Repository navigation
Expand file tree
/
Copy pathnode_worker.go
More file actions
346 lines (284 loc) · 7.86 KB
/
Copy pathnode_worker.go
File metadata and controls
346 lines (284 loc) · 7.86 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
package node
import (
"context"
"errors"
"fmt"
"time"
"github.com/pancsta/asyncmachine-go/internal/utils"
amhelp "github.com/pancsta/asyncmachine-go/pkg/helpers"
am "github.com/pancsta/asyncmachine-go/pkg/machine"
"github.com/pancsta/asyncmachine-go/pkg/node/states"
"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 (
ssW = states.WorkerStates
sgW = states.WorkerGroups
)
type Worker struct {
*am.ExceptionHandler
Mach *am.Machine
Name string
Kind string
// AcceptClient is the ID of a client, passed by the supervisor. Worker should
// only accept connections from this client.
AcceptClient string
// ConnTimeout is the time to wait for an outbound connection to be
// established.
ConnTimeout time.Duration
DeliveryTimeout time.Duration
// BootAddr is the address of the bootstrap machine.
BootAddr string
// BootRpc is the RPC client connection to bootstrap machine, which passes
// connection info to the Supervisor.
BootRpc *rpc.Client
// LocalAddr is the address of the local RPC server.
LocalAddr string
// LocalRpc is the local RPC server, used by the Supervisor to connect.
LocalRpc *rpc.Server
// PublicAddr is the address of the public RPC server.
PublicAddr string
// PublicRpc is the public RPC server, used by the Client to connect.
PublicRpc *rpc.Server
}
// NewWorker initializes a new Worker instance and returns it, or an error if
// validation fails.
func NewWorker(ctx context.Context, kind string, workerStruct am.Schema,
stateNames am.S, opts *WorkerOpts,
) (*Worker, error) {
// validate
if kind == "" {
return nil, errors.New("worker: kind required")
}
if stateNames == nil {
return nil, errors.New("worker: stateNames required")
}
if workerStruct == nil {
return nil, errors.New("worker: workerStruct required")
}
if opts == nil {
opts = &WorkerOpts{}
}
name := fmt.Sprintf("%s-%s-%s", kind, utils.Hostname(), utils.RandId(6))
w := &Worker{
ConnTimeout: 5 * time.Second,
DeliveryTimeout: 5 * time.Second,
Name: name,
Kind: kind,
}
if amhelp.IsDebug() {
// increase timeouts using context.WithTimeout directly
w.DeliveryTimeout = 10 * w.DeliveryTimeout
}
mach, err := am.NewCommon(ctx, "nw-"+w.Name, workerStruct, stateNames, w,
opts.Parent, &am.Opts{Tags: []string{"node-worker"}})
if err != nil {
return nil, err
}
mach.SemLogger().SetArgsMapper(amhelp.LogArgsMapper)
w.Mach = mach
_ = amhelp.MachDebugEnv(mach)
// check base states
err = amhelp.Implements(mach.StateNames(), ssW.Names())
if err != nil {
err := fmt.Errorf(
"client has to implement am/node/states/WorkerStates: %w", err,
)
return nil, err
}
return w, nil
}
// ///// ///// /////
var _ = ssW.ErrNetwork
// ///// HANDLERS
// ///// ///// /////
func (w *Worker) ErrNetworkState(e *am.Event) {
// TODO handle RPC errors
}
var _ = ssW.Start
func (w *Worker) StartEnter(e *am.Event) bool {
a := am.ParseArgs[A](e.Args)
return a.LocalAddr != ""
}
var _ = ssW.Start
func (w *Worker) StartState(e *am.Event) {
var err error
ctx := w.Mach.NewStateCtx(ssW.Start)
args := am.ParseArgs[A](e.Args)
w.BootAddr = args.LocalAddr
// local RPC
opts := &rpc.ServerOpts{
Parent: w.Mach,
}
w.LocalRpc, err = rpc.NewServer(ctx, "localhost:0", "nw-loc-"+w.Name, w.Mach,
opts)
if err != nil {
AddErrRpc(e, w.Mach, err, nil)
return
}
w.LocalRpc.DeliveryTimeout = w.DeliveryTimeout
// bind to Ready state
_, err1 := rpc.BindServer(w.LocalRpc.Mach, w.Mach, ssW.LocalRpcReady,
ssW.SuperConnected)
// bind to err
_, err2 := ampipe.BindErr(w.LocalRpc.Mach, w.Mach, ssW.ErrSupervisor)
err = errors.Join(err1, err2)
if err != nil {
w.Mach.AddErr(err, nil)
return
}
// public RPC
opts = &rpc.ServerOpts{
Parent: w.Mach,
}
w.PublicRpc, err = rpc.NewServer(ctx, "0.0.0.0:0", "nw-pub-"+w.Name,
w.Mach, opts)
if err != nil {
AddErrRpc(e, w.Mach, err, nil)
return
}
w.PublicRpc.DeliveryTimeout = w.DeliveryTimeout
// bind to Ready state
_, err1 = rpc.BindServer(w.PublicRpc.Mach, w.Mach, ssW.PublicRpcReady,
ssW.ClientConnected)
// bind to err
_, err2 = ampipe.BindErr(w.PublicRpc.Mach, w.Mach, ssW.ErrClient)
err = errors.Join(err1, err2)
if err != nil {
w.Mach.AddErr(err, nil)
return
}
// start
if w.LocalRpc.Start(e) != am.Executed {
AddErrRpc(e, w.Mach, nil, nil)
return
}
if w.PublicRpc.Start(e) != am.Executed {
AddErrRpc(e, w.Mach, nil, nil)
return
}
}
var _ = ssW.Start
func (w *Worker) StartEnd(e *am.Event) {
args := am.ParseArgs[A](e.Args)
if w.PublicRpc != nil {
w.PublicRpc.Stop(e, true)
}
if w.LocalRpc != nil {
w.LocalRpc.Stop(e, true)
}
if w.BootRpc != nil {
// TODO ctx
go w.BootRpc.Stop(context.TODO(), e, true)
}
if args.Dispose {
w.Mach.Dispose()
}
}
var _ = ssW.LocalRpcReady
func (w *Worker) LocalRpcReadyState(e *am.Event) {
w.LocalAddr = w.LocalRpc.Addr
}
var _ = ssW.PublicRpcReady
func (w *Worker) PublicRpcReadyState(e *am.Event) {
w.PublicAddr = w.PublicRpc.Addr
}
var _ = ssW.RpcReady
func (w *Worker) RpcReadyState(e *am.Event) {
var err error
ctx := w.Mach.NewStateCtx(ssW.RpcReady)
w.Mach.EvAdd1(e, ssW.Ready, nil)
// connect to the bootstrap machine
opts := &rpc.ClientOpts{Parent: w.Mach}
w.BootRpc, err = rpc.NewClient(ctx, w.BootAddr, "nw-"+w.Name,
states.BootstrapSchema, opts)
if err != nil {
AddErrRpc(e, w.Mach, err, nil)
return
}
_, err = ampipe.BindErr(w.BootRpc.Mach, w.Mach, "")
if err != nil {
AddErrRpc(e, w.Mach, err, nil)
return
}
w.BootRpc.Start(e)
// unblock
go func() {
// wait for the bootstrap client to be ready
err := amhelp.WaitForAll(ctx, w.ConnTimeout,
w.BootRpc.Mach.When1(ssrpc.ClientStates.Ready, nil))
if ctx.Err() != nil {
return // expired
}
if err != nil {
AddErrRpc(e, w.Mach, err, nil)
return
}
// pass the local port to [bootstrap.WorkerAddState] via RPC
w.BootRpc.NetMach.EvAdd1(e, ssB.WorkerAddr, Pass(&ARpc{
LocalAddr: w.LocalAddr,
PublicAddr: w.PublicAddr,
Id: w.Mach.Id(),
}))
w.Mach.Log("Passed the local port to the bootstrap machine")
// dispose
go w.BootRpc.Stop(w.Mach.Context(), e, true)
}()
}
var _ = ssW.Healthcheck
func (w *Worker) HealthcheckState(e *am.Event) {
w.Mach.Remove1(ssW.Healthcheck, nil)
}
var _ = ssW.ServeClient
func (w *Worker) ServeClientEnter(e *am.Event) bool {
a := am.ParseArgs[ARpc](e.Args)
return a != nil && a.Id != ""
}
var _ = ssW.ServeClient
func (w *Worker) ServeClientState(e *am.Event) {
w.Mach.Remove1(ssW.ServeClient, nil)
args := am.ParseArgs[ARpc](e.Args)
w.AcceptClient = args.Id
w.PublicRpc.AllowedMachIds.Store(&[]string{w.AcceptClient})
}
var _ = ssW.ClientSendPayload
func (w *Worker) ClientSendPayloadEnter(e *am.Event) bool {
a := am.ParseArgs[rpc.AServerPayload](e.Args)
return a != nil && a.Name != "" && a.Payload != nil
}
func (w *Worker) ClientSendPayloadState(e *am.Event) {
w.Mach.Remove1(ssW.ClientSendPayload, nil)
args := am.ParseArgs[rpc.AServerPayload](e.Args)
ctx := w.Mach.NewStateCtx(ssW.Start)
// unblock
go func() {
ctx, cancel := context.WithTimeout(ctx, w.DeliveryTimeout)
defer cancel()
if err := w.PublicRpc.SendPayload(ctx, e, args.Payload); err != nil {
AddErrRpc(e, w.Mach, err, nil)
}
}()
}
// ///// ///// /////
// ///// METHODS
// ///// ///// /////
// Start connects the worker to the bootstrap RPC.
func (w *Worker) Start(bootAddr string) am.Result {
return w.Mach.Add1(ssW.Start, Pass(&A{LocalAddr: bootAddr}))
}
// Stop halts the worker's state machine and optionally disposes of its
// resources based on the dispose flag.
func (w *Worker) Stop(dispose bool) {
w.Mach.Remove1(ssW.Start, Pass(&A{Dispose: dispose}))
}
// ///// ///// /////
// ///// MISC
// ///// ///// /////
type WorkerOpts struct {
// Parent is a parent state machine for a new Worker state machine. See
// [am.Opts].
Parent am.Api
// TODO
Tags []string
}