waveterm/pkg/wshrpc/wshclient/wshclientutil.go

84 lines
2.0 KiB
Go
Raw Normal View History

// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
package wshclient
import (
2024-08-19 06:26:44 +02:00
"errors"
"github.com/wavetermdev/thenextwave/pkg/util/utilfn"
"github.com/wavetermdev/thenextwave/pkg/wshrpc"
"github.com/wavetermdev/thenextwave/pkg/wshutil"
)
func sendRpcRequestCallHelper[T any](w *wshutil.WshRpc, command string, data interface{}, opts *wshrpc.RpcOpts) (T, error) {
if opts == nil {
opts = &wshrpc.RpcOpts{}
}
var respData T
2024-08-19 06:26:44 +02:00
if w == nil {
return respData, errors.New("nil wshrpc passed to wshclient")
}
if opts.NoResponse {
err := w.SendCommand(command, data, opts)
if err != nil {
return respData, err
}
return respData, nil
}
resp, err := w.SendRpcRequest(command, data, opts)
if err != nil {
return respData, err
}
err = utilfn.ReUnmarshal(&respData, resp)
if err != nil {
return respData, err
}
return respData, nil
}
2024-08-19 06:26:44 +02:00
func rtnErr[T any](ch chan wshrpc.RespOrErrorUnion[T], err error) {
go func() {
ch <- wshrpc.RespOrErrorUnion[T]{Error: err}
close(ch)
}()
}
func sendRpcRequestResponseStreamHelper[T any](w *wshutil.WshRpc, command string, data interface{}, opts *wshrpc.RpcOpts) chan wshrpc.RespOrErrorUnion[T] {
if opts == nil {
opts = &wshrpc.RpcOpts{}
}
respChan := make(chan wshrpc.RespOrErrorUnion[T])
2024-08-19 06:26:44 +02:00
if w == nil {
rtnErr(respChan, errors.New("nil wshrpc passed to wshclient"))
return respChan
}
reqHandler, err := w.SendComplexRequest(command, data, opts)
if err != nil {
2024-08-19 06:26:44 +02:00
rtnErr(respChan, err)
return respChan
} else {
go func() {
defer close(respChan)
for {
if reqHandler.ResponseDone() {
break
}
resp, err := reqHandler.NextResponse()
if err != nil {
respChan <- wshrpc.RespOrErrorUnion[T]{Error: err}
break
}
var respData T
err = utilfn.ReUnmarshal(&respData, resp)
if err != nil {
respChan <- wshrpc.RespOrErrorUnion[T]{Error: err}
break
}
respChan <- wshrpc.RespOrErrorUnion[T]{Response: respData}
}
}()
}
return respChan
}