• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 12292179806

12 Dec 2024 08:00AM UTC coverage: 49.544% (+0.004%) from 49.54%
12292179806

Pull #9342

github

ellemouton
docs: add release notes entry
Pull Request #9342: protofsm: update GR Manager usage and start using structured logging

0 of 62 new or added lines in 2 files covered. (0.0%)

78 existing lines in 14 files now uncovered.

100377 of 202602 relevant lines covered (49.54%)

2.06 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/protofsm/state_machine.go
1
package protofsm
2

3
import (
4
        "context"
5
        "fmt"
6
        "sync"
7
        "time"
8

9
        "github.com/btcsuite/btcd/btcec/v2"
10
        "github.com/btcsuite/btcd/chaincfg/chainhash"
11
        "github.com/btcsuite/btcd/wire"
12
        "github.com/btcsuite/btclog/v2"
13
        "github.com/lightningnetwork/lnd/chainntnfs"
14
        "github.com/lightningnetwork/lnd/fn/v2"
15
        "github.com/lightningnetwork/lnd/lnutils"
16
        "github.com/lightningnetwork/lnd/lnwire"
17
)
18

19
const (
20
        // pollInterval is the interval at which we'll poll the SendWhen
21
        // predicate if specified.
22
        pollInterval = time.Millisecond * 100
23
)
24

25
var (
26
        // ErrStateMachineShutdown occurs when trying to feed an event to a
27
        // StateMachine that has been asked to Stop.
28
        ErrStateMachineShutdown = fmt.Errorf("StateMachine is shutting down")
29
)
30

31
// EmittedEvent is a special type that can be emitted by a state transition.
32
// This can container internal events which are to be routed back to the state,
33
// or external events which are to be sent to the daemon.
34
type EmittedEvent[Event any] struct {
35
        // InternalEvent is an optional internal event that is to be routed
36
        // back to the target state. This enables state to trigger one or many
37
        // state transitions without a new external event.
38
        InternalEvent []Event
39

40
        // ExternalEvent is an optional external event that is to be sent to
41
        // the daemon for dispatch. Usually, this is some form of I/O.
42
        ExternalEvents DaemonEventSet
43
}
44

45
// StateTransition is a state transition type. It denotes the next state to go
46
// to, and also the set of events to emit.
47
type StateTransition[Event any, Env Environment] struct {
48
        // NextState is the next state to transition to.
49
        NextState State[Event, Env]
50

51
        // NewEvents is the set of events to emit.
52
        NewEvents fn.Option[EmittedEvent[Event]]
53
}
54

55
// Environment is an abstract interface that represents the environment that
56
// the state machine will execute using. From the PoV of the main state machine
57
// executor, we just care about being able to clean up any resources that were
58
// allocated by the environment.
59
type Environment interface {
60
        // Name returns the name of the environment. This is used to uniquely
61
        // identify the environment of related state machines.
62
        Name() string
63
}
64

65
// State defines an abstract state along, namely its state transition function
66
// that takes as input an event and an environment, and returns a state
67
// transition (next state, and set of events to emit). As state can also either
68
// be terminal, or not, a terminal event causes state execution to halt.
69
type State[Event any, Env Environment] interface {
70
        // ProcessEvent takes an event and an environment, and returns a new
71
        // state transition. This will be iteratively called until either a
72
        // terminal state is reached, or no further internal events are
73
        // emitted.
74
        ProcessEvent(event Event, env Env) (*StateTransition[Event, Env], error)
75

76
        // IsTerminal returns true if this state is terminal, and false
77
        // otherwise.
78
        IsTerminal() bool
79

80
        // TODO(roasbeef): also add state serialization?
81
}
82

83
// DaemonAdapters is a set of methods that server as adapters to bridge the
84
// pure world of the FSM to the real world of the daemon. These will be used to
85
// do things like broadcast transactions, or send messages to peers.
86
type DaemonAdapters interface {
87
        // SendMessages sends the target set of messages to the target peer.
88
        SendMessages(btcec.PublicKey, []lnwire.Message) error
89

90
        // BroadcastTransaction broadcasts a transaction with the target label.
91
        BroadcastTransaction(*wire.MsgTx, string) error
92

93
        // RegisterConfirmationsNtfn registers an intent to be notified once
94
        // txid reaches numConfs confirmations. We also pass in the pkScript as
95
        // the default light client instead needs to match on scripts created
96
        // in the block. If a nil txid is passed in, then not only should we
97
        // match on the script, but we should also dispatch once the
98
        // transaction containing the script reaches numConfs confirmations.
99
        // This can be useful in instances where we only know the script in
100
        // advance, but not the transaction containing it.
101
        //
102
        // TODO(roasbeef): could abstract further?
103
        RegisterConfirmationsNtfn(txid *chainhash.Hash, pkScript []byte,
104
                numConfs, heightHint uint32,
105
                opts ...chainntnfs.NotifierOption,
106
        ) (*chainntnfs.ConfirmationEvent, error)
107

108
        // RegisterSpendNtfn registers an intent to be notified once the target
109
        // outpoint is successfully spent within a transaction. The script that
110
        // the outpoint creates must also be specified. This allows this
111
        // interface to be implemented by BIP 158-like filtering.
112
        RegisterSpendNtfn(outpoint *wire.OutPoint, pkScript []byte,
113
                heightHint uint32) (*chainntnfs.SpendEvent, error)
114
}
115

116
// stateQuery is used by outside callers to query the internal state of the
117
// state machine.
118
type stateQuery[Event any, Env Environment] struct {
119
        // CurrentState is a channel that will be sent the current state of the
120
        // state machine.
121
        CurrentState chan State[Event, Env]
122
}
123

124
// StateMachine represents an abstract FSM that is able to process new incoming
125
// events and drive a state machine to termination. This implementation uses
126
// type params to abstract over the types of events and environment. Events
127
// trigger new state transitions, that use the environment to perform some
128
// action.
129
//
130
// TODO(roasbeef): terminal check, daemon event execution, init?
131
type StateMachine[Event any, Env Environment] struct {
132
        cfg StateMachineCfg[Event, Env]
133

134
        log btclog.Logger
135

136
        // events is the channel that will be used to send new events to the
137
        // FSM.
138
        events chan Event
139

140
        // newStateEvents is an EventDistributor that will be used to notify
141
        // any relevant callers of new state transitions that occur.
142
        newStateEvents *fn.EventDistributor[State[Event, Env]]
143

144
        // stateQuery is a channel that will be used by outside callers to
145
        // query the internal state machine state.
146
        stateQuery chan stateQuery[Event, Env]
147

148
        wg   *fn.GoroutineManager
149
        quit chan struct{}
150

151
        startOnce sync.Once
152
        stopOnce  sync.Once
153
}
154

155
// ErrorReporter is an interface that's used to report errors that occur during
156
// state machine execution.
157
type ErrorReporter interface {
158
        // ReportError is a method that's used to report an error that occurred
159
        // during state machine execution.
160
        ReportError(err error)
161
}
162

163
// StateMachineCfg is a configuration struct that's used to create a new state
164
// machine.
165
type StateMachineCfg[Event any, Env Environment] struct {
166
        // ErrorReporter is used to report errors that occur during state
167
        // transitions.
168
        ErrorReporter ErrorReporter
169

170
        // Daemon is a set of adapters that will be used to bridge the FSM to
171
        // the daemon.
172
        Daemon DaemonAdapters
173

174
        // InitialState is the initial state of the state machine.
175
        InitialState State[Event, Env]
176

177
        // Env is the environment that the state machine will use to execute.
178
        Env Env
179

180
        // InitEvent is an optional event that will be sent to the state
181
        // machine as if it was emitted at the onset of the state machine. This
182
        // can be used to set up tracking state such as a txid confirmation
183
        // event.
184
        InitEvent fn.Option[DaemonEvent]
185

186
        // MsgMapper is an optional message mapper that can be used to map
187
        // normal wire messages into FSM events.
188
        MsgMapper fn.Option[MsgMapper[Event]]
189

190
        // CustomPollInterval is an optional custom poll interval that can be
191
        // used to set a quicker interval for tests.
192
        CustomPollInterval fn.Option[time.Duration]
193
}
194

195
// NewStateMachine creates a new state machine given a set of daemon adapters,
196
// an initial state, an environment, and an event to process as if emitted at
197
// the onset of the state machine. Such an event can be used to set up tracking
198
// state such as a txid confirmation event.
199
func NewStateMachine[Event any, Env Environment](
NEW
200
        cfg StateMachineCfg[Event, Env]) StateMachine[Event, Env] {
×
201

×
202
        return StateMachine[Event, Env]{
×
NEW
203
                cfg: cfg,
×
NEW
204
                log: log.WithPrefix(
×
NEW
205
                        fmt.Sprintf("FSM(%v)", cfg.Env.Name()),
×
NEW
206
                ),
×
207
                events:         make(chan Event, 1),
×
208
                stateQuery:     make(chan stateQuery[Event, Env]),
×
NEW
209
                wg:             fn.NewGoroutineManager(),
×
210
                newStateEvents: fn.NewEventDistributor[State[Event, Env]](),
×
211
                quit:           make(chan struct{}),
×
212
        }
×
213
}
×
214

215
// Start starts the state machine. This will spawn a goroutine that will drive
216
// the state machine to completion.
NEW
217
func (s *StateMachine[Event, Env]) Start(ctx context.Context) {
×
218
        s.startOnce.Do(func() {
×
NEW
219
                _ = s.wg.Go(ctx, func(ctx context.Context) {
×
NEW
220
                        s.driveMachine(ctx)
×
UNCOV
221
                })
×
222
        })
223
}
224

225
// Stop stops the state machine. This will block until the state machine has
226
// reached a stopping point.
227
func (s *StateMachine[Event, Env]) Stop() {
×
228
        s.stopOnce.Do(func() {
×
229
                close(s.quit)
×
230
                s.wg.Stop()
×
231
        })
×
232
}
233

234
// SendEvent sends a new event to the state machine.
235
//
236
// TODO(roasbeef): bool if processed?
NEW
237
func (s *StateMachine[Event, Env]) SendEvent(ctx context.Context, event Event) {
×
NEW
238
        s.log.DebugS(ctx, "Sending event",
×
NEW
239
                "event", lnutils.SpewLogClosure(event))
×
240

×
241
        select {
×
242
        case s.events <- event:
×
NEW
243
        case <-ctx.Done():
×
NEW
244
                return
×
245
        case <-s.quit:
×
246
                return
×
247
        }
248
}
249

250
// CanHandle returns true if the target message can be routed to the state
251
// machine.
252
func (s *StateMachine[Event, Env]) CanHandle(msg lnwire.Message) bool {
×
253
        cfgMapper := s.cfg.MsgMapper
×
254
        return fn.MapOptionZ(cfgMapper, func(mapper MsgMapper[Event]) bool {
×
255
                return mapper.MapMsg(msg).IsSome()
×
256
        })
×
257
}
258

259
// Name returns the name of the state machine's environment.
260
func (s *StateMachine[Event, Env]) Name() string {
×
261
        return s.cfg.Env.Name()
×
262
}
×
263

264
// SendMessage attempts to send a wire message to the state machine. If the
265
// message can be mapped using the default message mapper, then true is
266
// returned indicating that the message was processed. Otherwise, false is
267
// returned.
268
func (s *StateMachine[Event, Env]) SendMessage(ctx context.Context,
NEW
269
        msg lnwire.Message) bool {
×
NEW
270

×
271
        // If we have no message mapper, then return false as we can't process
×
272
        // this message.
×
273
        if !s.cfg.MsgMapper.IsSome() {
×
274
                return false
×
275
        }
×
276

NEW
277
        s.log.DebugS(ctx, "Sending msg", "msg", lnutils.SpewLogClosure(msg))
×
278

×
279
        // Otherwise, try to map the message using the default message mapper.
×
280
        // If we can't extract an event, then we'll return false to indicate
×
281
        // that the message wasn't processed.
×
282
        var processed bool
×
283
        s.cfg.MsgMapper.WhenSome(func(mapper MsgMapper[Event]) {
×
284
                event := mapper.MapMsg(msg)
×
285

×
286
                event.WhenSome(func(event Event) {
×
NEW
287
                        s.SendEvent(ctx, event)
×
288

×
289
                        processed = true
×
290
                })
×
291
        })
292

293
        return processed
×
294
}
295

296
// CurrentState returns the current state of the state machine.
297
func (s *StateMachine[Event, Env]) CurrentState() (State[Event, Env], error) {
×
298
        query := stateQuery[Event, Env]{
×
299
                CurrentState: make(chan State[Event, Env], 1),
×
300
        }
×
301

×
302
        if !fn.SendOrQuit(s.stateQuery, query, s.quit) {
×
303
                return nil, ErrStateMachineShutdown
×
304
        }
×
305

306
        return fn.RecvOrTimeout(query.CurrentState, time.Second)
×
307
}
308

309
// StateSubscriber represents an active subscription to be notified of new
310
// state transitions.
311
type StateSubscriber[E any, F Environment] *fn.EventReceiver[State[E, F]]
312

313
// RegisterStateEvents registers a new event listener that will be notified of
314
// new state transitions.
315
func (s *StateMachine[Event, Env]) RegisterStateEvents() StateSubscriber[
316
        Event, Env] {
×
317

×
318
        subscriber := fn.NewEventReceiver[State[Event, Env]](10)
×
319

×
320
        // TODO(roasbeef): instead give the state and the input event?
×
321

×
322
        s.newStateEvents.RegisterSubscriber(subscriber)
×
323

×
324
        return subscriber
×
325
}
×
326

327
// RemoveStateSub removes the target state subscriber from the set of active
328
// subscribers.
329
func (s *StateMachine[Event, Env]) RemoveStateSub(sub StateSubscriber[
330
        Event, Env]) {
×
331

×
332
        _ = s.newStateEvents.RemoveSubscriber(sub)
×
333
}
×
334

335
// executeDaemonEvent executes a daemon event, which is a special type of event
336
// that can be emitted as part of the state transition function of the state
337
// machine. An error is returned if the type of event is unknown.
338
//
339
//nolint:funlen
340
func (s *StateMachine[Event, Env]) executeDaemonEvent(ctx context.Context,
341
        event DaemonEvent) error {
×
342

×
343
        switch daemonEvent := event.(type) {
×
344
        // This is a send message event, so we'll send the event, and also mind
345
        // any preconditions as well as post-send events.
346
        case *SendMsgEvent[Event]:
×
347
                sendAndCleanUp := func() error {
×
NEW
348
                        s.log.DebugS(ctx, "Sending message to target",
×
NEW
349
                                btclog.Hex6("target", daemonEvent.TargetPeer.SerializeCompressed()),
×
NEW
350
                                "messages", lnutils.SpewLogClosure(daemonEvent.Msgs))
×
351

×
352
                        err := s.cfg.Daemon.SendMessages(
×
353
                                daemonEvent.TargetPeer, daemonEvent.Msgs,
×
354
                        )
×
355
                        if err != nil {
×
356
                                return fmt.Errorf("unable to send msgs: %w",
×
357
                                        err)
×
358
                        }
×
359

360
                        // If a post-send event was specified, then we'll funnel
361
                        // that back into the main state machine now as well.
362
                        return fn.MapOptionZ(daemonEvent.PostSendEvent, func(event Event) error { //nolint:ll
×
NEW
363
                                launched := s.wg.Go(
×
NEW
364
                                        ctx, func(ctx context.Context) {
×
NEW
365
                                                s.log.DebugS(ctx, "Sending post-send event",
×
NEW
366
                                                        "event", lnutils.SpewLogClosure(event))
×
367

×
NEW
368
                                                s.SendEvent(ctx, event)
×
NEW
369
                                        },
×
370
                                )
371

372
                                if !launched {
×
373
                                        return ErrStateMachineShutdown
×
374
                                }
×
375

376
                                return nil
×
377
                        })
378
                }
379

380
                // If this doesn't have a SendWhen predicate, then we can just
381
                // send it off right away.
382
                if !daemonEvent.SendWhen.IsSome() {
×
383
                        return sendAndCleanUp()
×
384
                }
×
385

386
                // Otherwise, this has a SendWhen predicate, so we'll need
387
                // launch a goroutine to poll the SendWhen, then send only once
388
                // the predicate is true.
NEW
389
                launched := s.wg.Go(ctx, func(ctx context.Context) {
×
390
                        predicateTicker := time.NewTicker(
×
391
                                s.cfg.CustomPollInterval.UnwrapOr(pollInterval),
×
392
                        )
×
393
                        defer predicateTicker.Stop()
×
394

×
NEW
395
                        s.log.InfoS(ctx, "Waiting for send predicate to be true")
×
396

×
397
                        for {
×
398
                                select {
×
399
                                case <-predicateTicker.C:
×
400
                                        canSend := fn.MapOptionZ(
×
401
                                                daemonEvent.SendWhen,
×
402
                                                func(pred SendPredicate) bool {
×
403
                                                        return pred()
×
404
                                                },
×
405
                                        )
406

407
                                        if canSend {
×
NEW
408
                                                s.log.InfoS(ctx, "Send active predicate")
×
409

×
410
                                                err := sendAndCleanUp()
×
411
                                                if err != nil {
×
NEW
412
                                                        s.log.ErrorS(ctx, "Unable to send message", err)
×
413
                                                }
×
414

415
                                                return
×
416
                                        }
417

418
                                case <-ctx.Done():
×
419
                                        return
×
420
                                }
421
                        }
422
                })
423

424
                if !launched {
×
425
                        return ErrStateMachineShutdown
×
426
                }
×
427

428
                return nil
×
429

430
        // If this is a broadcast transaction event, then we'll broadcast with
431
        // the label attached.
432
        case *BroadcastTxn:
×
NEW
433
                s.log.DebugS(ctx, "Broadcasting txn",
×
NEW
434
                        "txid", daemonEvent.Tx.TxHash())
×
435

×
436
                err := s.cfg.Daemon.BroadcastTransaction(
×
437
                        daemonEvent.Tx, daemonEvent.Label,
×
438
                )
×
439
                if err != nil {
×
440
                        return fmt.Errorf("unable to broadcast txn: %w", err)
×
441
                }
×
442

443
                return nil
×
444

445
        // The state machine has requested a new event to be sent once a
446
        // transaction spending a specified outpoint has confirmed.
447
        case *RegisterSpend[Event]:
×
NEW
448
                s.log.DebugS(ctx, "Registering spend",
×
NEW
449
                        "outpoint", daemonEvent.OutPoint)
×
450

×
451
                spendEvent, err := s.cfg.Daemon.RegisterSpendNtfn(
×
452
                        &daemonEvent.OutPoint, daemonEvent.PkScript,
×
453
                        daemonEvent.HeightHint,
×
454
                )
×
455
                if err != nil {
×
456
                        return fmt.Errorf("unable to register spend: %w", err)
×
457
                }
×
458

NEW
459
                launched := s.wg.Go(ctx, func(ctx context.Context) {
×
460
                        for {
×
461
                                select {
×
462
                                case spend, ok := <-spendEvent.Spend:
×
463
                                        if !ok {
×
464
                                                return
×
465
                                        }
×
466

467
                                        // If there's a post-send event, then
468
                                        // we'll send that into the current
469
                                        // state now.
470
                                        postSpend := daemonEvent.PostSpendEvent
×
471
                                        postSpend.WhenSome(func(f SpendMapper[Event]) { //nolint:ll
×
472
                                                customEvent := f(spend)
×
NEW
473
                                                s.SendEvent(ctx, customEvent)
×
474
                                        })
×
475

476
                                        return
×
477

478
                                case <-ctx.Done():
×
479
                                        return
×
480
                                }
481
                        }
482
                })
483

484
                if !launched {
×
485
                        return ErrStateMachineShutdown
×
486
                }
×
487

488
                return nil
×
489

490
        // The state machine has requested a new event to be sent once a
491
        // specified txid+pkScript pair has confirmed.
492
        case *RegisterConf[Event]:
×
NEW
493
                s.log.DebugS(ctx, "Registering conf",
×
NEW
494
                        "txid", daemonEvent.Txid)
×
495

×
496
                numConfs := daemonEvent.NumConfs.UnwrapOr(1)
×
497
                confEvent, err := s.cfg.Daemon.RegisterConfirmationsNtfn(
×
498
                        &daemonEvent.Txid, daemonEvent.PkScript,
×
499
                        numConfs, daemonEvent.HeightHint,
×
500
                )
×
501
                if err != nil {
×
502
                        return fmt.Errorf("unable to register conf: %w", err)
×
503
                }
×
504

NEW
505
                launched := s.wg.Go(ctx, func(ctx context.Context) {
×
506
                        for {
×
507
                                select {
×
508
                                case <-confEvent.Confirmed:
×
509
                                        // If there's a post-conf event, then
×
510
                                        // we'll send that into the current
×
511
                                        // state now.
×
512
                                        //
×
513
                                        // TODO(roasbeef): refactor to
×
514
                                        // dispatchAfterRecv w/ above
×
515
                                        postConf := daemonEvent.PostConfEvent
×
516
                                        postConf.WhenSome(func(e Event) {
×
NEW
517
                                                s.SendEvent(ctx, e)
×
518
                                        })
×
519

520
                                        return
×
521

522
                                case <-ctx.Done():
×
523
                                        return
×
524
                                }
525
                        }
526
                })
527

528
                if !launched {
×
529
                        return ErrStateMachineShutdown
×
530
                }
×
531

532
                return nil
×
533
        }
534

535
        return fmt.Errorf("unknown daemon event: %T", event)
×
536
}
537

538
// applyEvents applies a new event to the state machine. This will continue
539
// until no further events are emitted by the state machine. Along the way,
540
// we'll also ensure to execute any daemon events that are emitted.
541
func (s *StateMachine[Event, Env]) applyEvents(ctx context.Context,
542
        currentState State[Event, Env], newEvent Event) (State[Event, Env],
NEW
543
        error) {
×
NEW
544

×
NEW
545
        s.log.DebugS(ctx, "Applying new event",
×
NEW
546
                "event", lnutils.SpewLogClosure(newEvent))
×
547

×
548
        eventQueue := fn.NewQueue(newEvent)
×
549

×
550
        // Given the next event to handle, we'll process the event, then add
×
551
        // any new emitted internal events to our event queue. This continues
×
552
        // until we reach a terminal state, or we run out of internal events to
×
553
        // process.
×
554
        //
×
555
        //nolint:ll
×
556
        for nextEvent := eventQueue.Dequeue(); nextEvent.IsSome(); nextEvent = eventQueue.Dequeue() {
×
557
                err := fn.MapOptionZ(nextEvent, func(event Event) error {
×
NEW
558
                        s.log.DebugS(ctx, "Processing event",
×
NEW
559
                                "event", lnutils.SpewLogClosure(event))
×
560

×
561
                        // Apply the state transition function of the current
×
562
                        // state given this new event and our existing env.
×
563
                        transition, err := currentState.ProcessEvent(
×
564
                                event, s.cfg.Env,
×
565
                        )
×
566
                        if err != nil {
×
567
                                return err
×
568
                        }
×
569

570
                        newEvents := transition.NewEvents
×
571
                        err = fn.MapOptionZ(newEvents, func(events EmittedEvent[Event]) error { //nolint:ll
×
572
                                // With the event processed, we'll process any
×
573
                                // new daemon events that were emitted as part
×
574
                                // of this new state transition.
×
575
                                for _, dEvent := range events.ExternalEvents {
×
576
                                        err := s.executeDaemonEvent(
×
NEW
577
                                                ctx, dEvent,
×
578
                                        )
×
579
                                        if err != nil {
×
580
                                                return err
×
581
                                        }
×
582
                                }
583

584
                                // Next, we'll add any new emitted events to our
585
                                // event queue.
586
                                //
587
                                //nolint:ll
588
                                for _, inEvent := range events.InternalEvent {
×
NEW
589
                                        s.log.DebugS(ctx, "Adding new internal event to queue",
×
NEW
590
                                                "event", lnutils.SpewLogClosure(inEvent))
×
591

×
592
                                        eventQueue.Enqueue(inEvent)
×
593
                                }
×
594

595
                                return nil
×
596
                        })
597
                        if err != nil {
×
598
                                return err
×
599
                        }
×
600

NEW
601
                        s.log.InfoS(ctx, "State transition",
×
NEW
602
                                btclog.Fmt("from_state", "%T", currentState),
×
NEW
603
                                btclog.Fmt("to_state", "%T", transition.NextState))
×
604

×
605
                        // With our events processed, we'll now update our
×
606
                        // internal state.
×
607
                        currentState = transition.NextState
×
608

×
609
                        // Notify our subscribers of the new state transition.
×
610
                        //
×
611
                        // TODO(roasbeef): will only give us the outer state?
×
612
                        //  * let FSMs choose which state to emit?
×
613
                        s.newStateEvents.NotifySubscribers(currentState)
×
614

×
615
                        return nil
×
616
                })
617
                if err != nil {
×
618
                        return currentState, err
×
619
                }
×
620
        }
621

622
        return currentState, nil
×
623
}
624

625
// driveMachine is the main event loop of the state machine. It accepts any new
626
// incoming events, and then drives the state machine forward until it reaches
627
// a terminal state.
NEW
628
func (s *StateMachine[Event, Env]) driveMachine(ctx context.Context) {
×
NEW
629
        s.log.DebugS(ctx, "Starting state machine")
×
630

×
631
        currentState := s.cfg.InitialState
×
632

×
633
        // Before we start, if we have an init daemon event specified, then
×
634
        // we'll handle that now.
×
635
        err := fn.MapOptionZ(s.cfg.InitEvent, func(event DaemonEvent) error {
×
NEW
636
                return s.executeDaemonEvent(ctx, event)
×
637
        })
×
638
        if err != nil {
×
NEW
639
                s.log.ErrorS(ctx, "Unable to execute init event", err)
×
640
                return
×
641
        }
×
642

643
        // We just started driving the state machine, so we'll notify our
644
        // subscribers of this starting state.
645
        s.newStateEvents.NotifySubscribers(currentState)
×
646

×
647
        for {
×
648
                select {
×
649
                // We have a new external event, so we'll drive the state
650
                // machine forward until we either run out of internal events,
651
                // or we reach a terminal state.
652
                case newEvent := <-s.events:
×
NEW
653
                        newState, err := s.applyEvents(
×
NEW
654
                                ctx, currentState, newEvent,
×
NEW
655
                        )
×
656
                        if err != nil {
×
657
                                s.cfg.ErrorReporter.ReportError(err)
×
658

×
NEW
659
                                s.log.ErrorS(ctx, "Unable to apply event", err)
×
660

×
661
                                // An error occurred, so we'll tear down the
×
662
                                // entire state machine as we can't proceed.
×
663
                                go s.Stop()
×
664

×
665
                                return
×
666
                        }
×
667

668
                        currentState = newState
×
669

670
                // An outside caller is querying our state, so we'll return the
671
                // latest state.
672
                case stateQuery := <-s.stateQuery:
×
673
                        if !fn.SendOrQuit(stateQuery.CurrentState, currentState, s.quit) { //nolint:ll
×
674
                                return
×
675
                        }
×
676

677
                case <-s.wg.Done():
×
678
                        return
×
679
                }
680
        }
681
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc