-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
132 lines (99 loc) · 2.55 KB
/
main.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"sync/atomic"
"syscall"
"github.com/pojntfx/panrpc/go/pkg/rpc"
)
type local struct{}
func (s *local) Println(ctx context.Context, msg string) error {
log.Println("Printing message", msg, "for remote with ID", rpc.GetRemoteID(ctx))
fmt.Println(msg)
return nil
}
type remote struct {
Increment func(ctx context.Context, delta int64) (int64, error)
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var clients atomic.Int64
registry := rpc.NewRegistry[remote, json.RawMessage](
&local{},
&rpc.RegistryHooks{
OnClientConnect: func(remoteID string) {
log.Printf("%v clients connected", clients.Add(1))
},
OnClientDisconnect: func(remoteID string) {
log.Printf("%v clients connected", clients.Add(-1))
},
},
)
log.Printf(`Run one of the following commands to run a function on the remote(s):
- kill -SIGHUP %v: Increment remote counter by one
- kill -SIGUSR2 %v: Decrement remote counter by one`, os.Getpid(), os.Getpid())
go func() {
done := make(chan os.Signal, 1)
signal.Notify(done, syscall.SIGHUP)
<-done
if err := registry.ForRemotes(func(remoteID string, remote remote) error {
log.Println("Calling functions for remote with ID", remoteID)
new, err := remote.Increment(ctx, 1)
if err != nil {
log.Println("Got error for Increment func:", err)
return nil
}
log.Println(new)
return nil
}); err != nil {
panic(err)
}
}()
go func() {
done := make(chan os.Signal, 1)
signal.Notify(done, syscall.SIGUSR2)
<-done
if err := registry.ForRemotes(func(remoteID string, remote remote) error {
log.Println("Calling functions for remote with ID", remoteID)
new, err := remote.Increment(ctx, -1)
if err != nil {
log.Println("Got error for Increment func:", err)
return nil
}
log.Println(new)
return nil
}); err != nil {
panic(err)
}
}()
log.Println("Connected to stdin and stdout")
encoder := json.NewEncoder(os.Stdout)
decoder := json.NewDecoder(os.Stdin)
if err := registry.LinkStream(
ctx,
func(v rpc.Message[json.RawMessage]) error {
return encoder.Encode(v)
},
func(v *rpc.Message[json.RawMessage]) error {
return decoder.Decode(v)
},
func(v any) (json.RawMessage, error) {
b, err := json.Marshal(v)
if err != nil {
return nil, err
}
return json.RawMessage(b), nil
},
func(data json.RawMessage, v any) error {
return json.Unmarshal([]byte(data), v)
},
nil,
); err != nil {
panic(err)
}
}