forked from ignite/cli
/
tsrelayer.go
69 lines (56 loc) · 1.56 KB
/
tsrelayer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package tsrelayer
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"github.com/gorilla/rpc/v2/json2"
"golang.org/x/sync/errgroup"
"github.com/notional-labs/tinyport/tinyport/pkg/cmdrunner"
"github.com/notional-labs/tinyport/tinyport/pkg/cmdrunner/step"
"github.com/notional-labs/tinyport/tinyport/pkg/nodetime"
)
// Call calls a method in the ts relayer wrapper lib with args and fills reply from the returned value.
func Call(ctx context.Context, method string, args, reply interface{}) error {
command, cleanup, err := nodetime.Command(nodetime.CommandXRelayer)
if err != nil {
return err
}
defer cleanup()
req, err := json2.EncodeClientRequest(method, args)
if err != nil {
return err
}
resr, resw := io.Pipe()
g := errgroup.Group{}
g.Go(func() error {
defer resw.Close()
return cmdrunner.New().Run(
ctx,
step.New(
step.Exec(command[0], command[1:]...),
step.Write(req),
step.Stdout(resw),
),
)
})
// regular logs can be printed to the stdout by the other process before a jsonrpc response is emitted.
// differentiate both kinds and simulate printing regular logs if there are any.
sc := bufio.NewScanner(resr)
for sc.Scan() {
err = json2.DecodeClientResponse(bytes.NewReader(sc.Bytes()), reply)
var e *json2.Error
if errors.As(err, &e) || errors.Is(err, json2.ErrNullResult) { // jsonrpc returned with a server-side error.
return err
}
if err != nil { // a line printed to the stdout by the other process.
fmt.Println(sc.Text())
}
}
if err := sc.Err(); err != nil {
return err
}
return g.Wait()
}