waveterm/pkg/wshrpc/wshclient/wshclientutil.go

90 lines
2.2 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"
2024-11-21 03:05:13 +01:00
"github.com/wavetermdev/waveterm/pkg/panichandler"
2024-09-05 23:25:45 +02:00
"github.com/wavetermdev/waveterm/pkg/util/utilfn"
"github.com/wavetermdev/waveterm/pkg/wshrpc"
"github.com/wavetermdev/waveterm/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() {
2024-11-21 03:05:13 +01:00
defer panichandler.PanicHandler("wshclientutil:rtnErr")
2024-08-19 06:26:44 +02:00
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
}
2024-08-20 00:44:30 +02:00
opts.StreamCancelFn = func() {
// TODO coordinate the cancel with the for loop below
reqHandler.SendCancel()
}
go func() {
2024-11-21 03:05:13 +01:00
defer panichandler.PanicHandler("sendRpcRequestResponseStreamHelper")
2024-08-20 00:44:30 +02:00
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
}