Repository navigation
Expand file tree
/
Copy pathnode_client.go
More file actions
406 lines (346 loc) · 10.1 KB
/
Copy pathnode_client.go
File metadata and controls
406 lines (346 loc) · 10.1 KB
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
package node
import (
"context"
"errors"
"fmt"
"os"
"slices"
"time"
amhelp "github.com/pancsta/asyncmachine-go/pkg/helpers"
am "github.com/pancsta/asyncmachine-go/pkg/machine"
"github.com/pancsta/asyncmachine-go/pkg/node/states"
arpc "github.com/pancsta/asyncmachine-go/pkg/rpc"
ssrpc "github.com/pancsta/asyncmachine-go/pkg/rpc/states"
ampipe "github.com/pancsta/asyncmachine-go/pkg/states/pipes"
)
var ssC = states.ClientStates
// Client is a node client, connecting to a supervisor and then a worker.
type Client struct {
*am.ExceptionHandler
Mach *am.Machine
Name string
SuperAddr string
LogEnabled bool
// LeaveSuper is a flag to leave the supervisor after connecting to the
// worker. TODO
LeaveSuper bool
// ConnTimeout is the time to wait for an outbound connection to be
// established. Default is 5 seconds.
ConnTimeout time.Duration
// network
RpcSuper *arpc.Client
RpcWorker *arpc.Client
// internal
// current nodes list (set by Start)
nodeList []string
schemaClient am.Schema
schemaWorker am.Schema
}
// implement ConsumerHandlers
var _ ssrpc.ConsumerHandlers = &Client{}
// NewClient creates a new Client instance with the provided context, id,
// workerKind, state dependencies, and options. Returns a pointer to the Client
// instance and an error if any validation or initialization fails.
//
// workerKind: any string used to build IDs and address workers
func NewClient(ctx context.Context, clientId string, workerKind string,
workerSchema am.Schema, opts *ClientOpts,
) (*Client, error) {
// defaults
if opts == nil {
opts = &ClientOpts{}
}
if opts.ClientSchema == nil {
opts.ClientSchema = states.ClientSchema
}
if opts.ClientStates == nil {
opts.ClientStates = states.ClientStates.Names()
}
// validate
if clientId == "" {
return nil, errors.New("client: clientId required")
}
if workerSchema == nil {
return nil, errors.New("client: workerSchema required")
}
if workerKind == "" {
return nil, errors.New("client: workerKind required")
}
err := amhelp.SchemaImplements(workerSchema, states.WorkerStates.Names())
if err != nil {
err := fmt.Errorf(
"worker has to implement am/node/states/WorkerStates: %w", err,
)
return nil, err
}
name := fmt.Sprintf("%s-%s-%s", workerKind, clientId,
time.Now().Format("150405"))
c := &Client{
Name: name,
ConnTimeout: 5 * time.Second,
LogEnabled: os.Getenv(EnvAmNodeLogClient) != "",
schemaClient: opts.ClientSchema,
schemaWorker: workerSchema,
}
if amhelp.IsDebug() {
c.ConnTimeout = 10 * c.ConnTimeout
}
mach, err := am.NewCommon(ctx, "nc-"+name, c.schemaClient,
opts.ClientStates, c, opts.Parent, &am.Opts{
Tags: slices.Concat([]string{"node-client"}, opts.Tags),
})
if err != nil {
return nil, err
}
mach.SemLogger().SetArgsMapper(amhelp.LogArgsMapper)
c.Mach = mach
_ = amhelp.MachDebugEnv(mach)
// check base states
err = amhelp.Implements(mach.StateNames(), ssC.Names())
if err != nil {
err := fmt.Errorf(
"client has to implement am/node/states/ClientStates: %w", err,
)
return nil, err
}
return c, nil
}
// ///// ///// /////
var _ = ssC.Start
// ///// HANDLERS
// ///// ///// /////
func (c *Client) StartEnter(e *am.Event) bool {
a := am.ParseArgs[A](e.Args)
return a != nil && len(a.NodesList) > 0
}
func (c *Client) StartState(e *am.Event) {
var err error
ctx := c.Mach.NewStateCtx(ssC.Start)
args := am.ParseArgs[A](e.Args)
addr := args.NodesList[0]
c.nodeList = args.NodesList
// init super rpc (but dont connect just yet)
c.RpcSuper, err = arpc.NewClient(ctx, addr, GetSuperClientId(c.Name),
states.SupervisorSchema, &arpc.ClientOpts{
Parent: c.Mach,
Consumer: c.Mach,
})
if err != nil {
err := fmt.Errorf("failed to connect to the Supervisor: %w", err)
AddErrRpc(e, c.Mach, err, nil)
return
}
// bind to super rpc
_, err1 := ampipe.BindConnected(c.RpcSuper.Mach, c.Mach,
ssC.SuperDisconnected,
ssC.SuperConnecting, ssC.SuperConnected, ssC.SuperDisconnecting)
_, err2 := ampipe.BindErr(c.RpcSuper.Mach, c.Mach, ssC.ErrSupervisor)
_, err3 := ampipe.BindReady(c.RpcSuper.Mach, c.Mach, ssC.SuperReady, "")
err = errors.Join(err1, err2, err3)
if err != nil {
c.Mach.AddErr(err, nil)
return
}
// unblock
go func() {
// try all nodes TODO randomize
for i, addr := range args.NodesList {
if ctx.Err() != nil {
return // expired
}
c.Mach.Log("trying node %d: %s", i, addr)
// (re)start and wait
// TODO handle in ExceptionState when SuperConnecting active
c.Mach.Remove1(am.StateException, nil)
c.RpcSuper.Addr = addr
// fewer retries, bc of fallbacks
// TODO config via a composable RetryPolicy from rpc-c
c.RpcSuper.ConnRetries = 3
c.RpcSuper.Start(e)
err := amhelp.WaitForAny(
ctx, c.ConnTimeout,
c.Mach.When1(ssC.SuperReady, nil),
c.RpcSuper.Mach.WhenNot1(ssrpc.ClientStates.Start, nil),
)
if ctx.Err() != nil {
return // expired
}
// stopped rpc client is an error
if c.RpcSuper.Mach.Not1(ssrpc.ClientStates.Start) {
// TODO blacklist the node for X time
// re-start
c.RpcSuper.Stop(ctx, e, false)
c.Mach.Remove1(ssC.Exception, nil)
continue
}
if err != nil {
err := errors.Join(err, c.RpcSuper.Mach.Err())
AddErrRpc(e, c.Mach, err, nil)
return
}
}
}()
}
var _ = ssC.Start
func (c *Client) StartEnd(e *am.Event) {
if c.RpcSuper != nil {
c.RpcSuper.Stop(context.TODO(), e, true)
}
if c.RpcWorker != nil {
c.RpcWorker.Stop(context.TODO(), e, true)
}
}
var _ = ssC.WorkerRequested
func (c *Client) WorkerRequestedEnter(e *am.Event) bool {
return c.RpcSuper.NetMach.Is1(ssS.WorkersAvailable)
}
func (c *Client) WorkerRequestedState(e *am.Event) {
// supervisor needs IDs of RPC clients for routing and ACL
c.RpcSuper.NetMach.Add1(ssS.ProvideWorker, Pass(&ARpc{
SuperRpcId: c.RpcSuper.Mach.Id(),
WorkerRpcId: arpc.GetClientId(GetWorkerClientId(c.Name)),
}))
}
var _ = ssC.ServerPayload
func (c *Client) ServerPayloadEnter(e *am.Event) bool {
a := am.ParseArgs[arpc.AServerPayload](e.Args)
return a != nil && a.Name != "" && a.Payload != nil
}
// ServerPayloadState handles both Supervisor and Worker inbound payloads, but
// this shared code only deals with [ssC.ClientStatesDef.WorkerRequested].
func (c *Client) ServerPayloadState(e *am.Event) {
c.Mach.Remove1(ssC.ServerPayload, nil)
args := am.ParseArgs[arpc.AServerPayload](e.Args)
c.log("worker %s delivered: %s", args.Payload.Source, args.Name)
if args.Name != ssS.ProvideWorker {
// worker impl will handle
return
}
if c.Mach.Not1(ssC.WorkerRequested) {
c.log("worker not requested")
return
}
ctx := c.Mach.NewStateCtx(ssC.WorkerRequested)
ctxStart := c.Mach.NewStateCtx(ssC.Start)
addr, ok := args.Payload.Data.(string)
if !ok || addr == "" {
err := errors.New("invalid worker address")
c.Mach.AddErrState(ssC.ErrSupervisor, err, nil)
return
}
c.log("connecting to worker: %s", addr)
// unblock
go func() {
// connect to the worker
var err error
c.RpcWorker, err = arpc.NewClient(ctxStart, addr, GetWorkerClientId(c.Name),
c.schemaWorker, &arpc.ClientOpts{
Parent: c.Mach,
Consumer: c.Mach,
})
if err != nil {
err := fmt.Errorf("failed to connect to the NetworkMachine: %w", err)
AddErrRpc(e, c.Mach, err, nil)
return
}
// delay for rpc/Mux
c.RpcWorker.HelloDelay = 100 * time.Millisecond
// bind to worker rpc
_, err1 := ampipe.BindConnected(c.RpcWorker.Mach, c.Mach,
ssC.WorkerDisconnected,
ssC.WorkerConnecting, ssC.WorkerConnected, ssC.WorkerDisconnecting)
_, err2 := ampipe.BindErr(c.RpcWorker.Mach, c.Mach, ssC.ErrWorker)
_, err3 := ampipe.BindReady(c.RpcWorker.Mach, c.Mach, ssC.WorkerReady, "")
err = errors.Join(err1, err2, err3)
if err != nil {
c.Mach.AddErr(err, nil)
return
}
// start and wait
c.RpcWorker.Start(e)
err = amhelp.WaitForAny(
ctx, c.ConnTimeout,
c.Mach.When1(ssC.WorkerReady, nil),
c.RpcWorker.Mach.WhenErr(ctxStart),
)
// TODO retry
if err != nil {
c.Mach.Remove1(ssC.WorkerRequested, nil)
return
}
}()
}
// ///// ///// /////
// ///// METHODS
// ///// ///// /////
// Start initializes the client with a list of node addresses to connect to.
func (c *Client) Start(nodesList []string) {
// TODO event
c.Mach.Add1(ssC.Start, Pass(&A{
NodesList: nodesList,
}))
}
// Stop halts the client's connection to both the supervisor and worker RPCs,
// and removes the client state from the state machine.
func (c *Client) Stop(ctx context.Context) {
// TODO event
if c.RpcSuper != nil {
c.RpcSuper.Stop(ctx, nil, false)
}
if c.RpcWorker != nil {
c.RpcWorker.Stop(ctx, nil, false)
}
c.Mach.Remove1(ssC.Start, nil)
}
// ReqWorker sends a request to add a "WorkerRequested" state to the client's
// state machine and waits for "WorkerReady" state.
func (c *Client) ReqWorker(ctx context.Context) error {
// failsafe worker request
_, err := amhelp.NewReqAdd1(c.Mach, ssC.WorkerRequested, nil).Run(ctx)
if err != nil {
return err
}
err = amhelp.WaitForAll(ctx, c.ConnTimeout,
c.Mach.When1(ssC.WorkerReady, nil))
if err != nil {
return err
}
c.log("worker connected: %s", c.RpcWorker.NetMach.Id())
return nil
}
// Dispose deallocates resources and stops the client's RPC connections.
func (c *Client) Dispose(ctx context.Context) {
c.Stop(ctx)
c.RpcSuper = nil
c.RpcWorker = nil
c.Mach.Dispose()
}
func (c *Client) log(msg string, args ...any) {
if !c.LogEnabled {
return
}
c.Mach.Log(msg, args...)
}
// ///// ///// /////
// ///// MISC
// ///// ///// /////
// ClientOpts provides configuration options for creating a new client state
// machine.
type ClientOpts struct {
// Parent is a parent state machine for a new client state machine. See
// [am.Opts].
Parent am.Api
Tags []string
// Optional schema for the client. Should extend [states.ClientStatesDef].
ClientSchema am.Schema
// Optional state names for ClientSchema.
ClientStates am.S
}
// GetWorkerClientId returns a Node Client machine ID from a name.
func GetWorkerClientId(name string) string {
return "nc-worker-" + name
}
// GetSuperClientId returns a Node Supervisor machine ID from a name.
func GetSuperClientId(name string) string {
return "nc-super-" + name
}