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

lightningnetwork / lnd / 12313073348

13 Dec 2024 09:30AM UTC coverage: 58.666% (+1.2%) from 57.486%
12313073348

Pull #9344

github

ellemouton
htlcswitch+go.mod: use updated fn.ContextGuard

This commit updates the fn dep to the version containing the updates to
the ContextGuard implementation. Only the htlcswitch/link uses the guard
at the moment so this is updated to make use of the new implementation.
Pull Request #9344: htlcswitch+go.mod: use updated fn.ContextGuard

101 of 117 new or added lines in 4 files covered. (86.32%)

29 existing lines in 9 files now uncovered.

134589 of 229415 relevant lines covered (58.67%)

19278.57 hits per line

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

76.06
/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](
200
        cfg StateMachineCfg[Event, Env]) StateMachine[Event, Env] {
28✔
201

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

215
// Start starts the state machine. This will spawn a goroutine that will drive
216
// the state machine to completion.
217
func (s *StateMachine[Event, Env]) Start(ctx context.Context) {
28✔
218
        s.startOnce.Do(func() {
56✔
219
                _ = s.wg.Go(ctx, func(ctx context.Context) {
56✔
220
                        s.driveMachine(ctx)
28✔
221
                })
28✔
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() {
37✔
228
        s.stopOnce.Do(func() {
65✔
229
                close(s.quit)
28✔
230
                s.wg.Stop()
28✔
231
        })
28✔
232
}
233

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

38✔
241
        select {
38✔
242
        case s.events <- event:
38✔
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 {
2✔
253
        cfgMapper := s.cfg.MsgMapper
2✔
254
        return fn.MapOptionZ(cfgMapper, func(mapper MsgMapper[Event]) bool {
4✔
255
                return mapper.MapMsg(msg).IsSome()
2✔
256
        })
2✔
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,
269
        msg lnwire.Message) bool {
1✔
270

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

277
        s.log.DebugS(ctx, "Sending msg", "msg", lnutils.SpewLogClosure(msg))
1✔
278

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

1✔
286
                event.WhenSome(func(event Event) {
2✔
287
                        s.SendEvent(ctx, event)
1✔
288

1✔
289
                        processed = true
1✔
290
                })
1✔
291
        })
292

293
        return processed
1✔
294
}
295

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

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

306
        return fn.RecvOrTimeout(query.CurrentState, time.Second)
17✔
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] {
28✔
317

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

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

28✔
322
        s.newStateEvents.RegisterSubscriber(subscriber)
28✔
323

28✔
324
        return subscriber
28✔
325
}
28✔
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]) {
28✔
331

28✔
332
        _ = s.newStateEvents.RemoveSubscriber(sub)
28✔
333
}
28✔
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 {
47✔
342

47✔
343
        switch daemonEvent := event.(type) {
47✔
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]:
17✔
347
                sendAndCleanUp := func() error {
33✔
348
                        s.log.DebugS(ctx, "Sending message to target",
16✔
349
                                btclog.Hex6("target", daemonEvent.TargetPeer.SerializeCompressed()),
16✔
350
                                "messages", lnutils.SpewLogClosure(daemonEvent.Msgs))
16✔
351

16✔
352
                        err := s.cfg.Daemon.SendMessages(
16✔
353
                                daemonEvent.TargetPeer, daemonEvent.Msgs,
16✔
354
                        )
16✔
355
                        if err != nil {
16✔
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
19✔
363
                                launched := s.wg.Go(
3✔
364
                                        ctx, func(ctx context.Context) {
6✔
365
                                                s.log.DebugS(ctx, "Sending post-send event",
3✔
366
                                                        "event", lnutils.SpewLogClosure(event))
3✔
367

3✔
368
                                                s.SendEvent(ctx, event)
3✔
369
                                        },
3✔
370
                                )
371

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

376
                                return nil
3✔
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() {
29✔
383
                        return sendAndCleanUp()
12✔
384
                }
12✔
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.
389
                launched := s.wg.Go(ctx, func(ctx context.Context) {
10✔
390
                        predicateTicker := time.NewTicker(
5✔
391
                                s.cfg.CustomPollInterval.UnwrapOr(pollInterval),
5✔
392
                        )
5✔
393
                        defer predicateTicker.Stop()
5✔
394

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

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

407
                                        if canSend {
8✔
408
                                                s.log.InfoS(ctx, "Send active predicate")
4✔
409

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

415
                                                return
4✔
416
                                        }
417

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

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

428
                return nil
5✔
429

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

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

443
                return nil
6✔
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]:
24✔
448
                s.log.DebugS(ctx, "Registering spend",
24✔
449
                        "outpoint", daemonEvent.OutPoint)
24✔
450

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

459
                launched := s.wg.Go(ctx, func(ctx context.Context) {
48✔
460
                        for {
48✔
461
                                select {
24✔
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():
24✔
479
                                        return
24✔
480
                                }
481
                        }
482
                })
483

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

488
                return nil
24✔
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],
543
        error) {
38✔
544

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

38✔
548
        eventQueue := fn.NewQueue(newEvent)
38✔
549

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

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

570
                        newEvents := transition.NewEvents
37✔
571
                        err = fn.MapOptionZ(newEvents, func(events EmittedEvent[Event]) error { //nolint:ll
63✔
572
                                // With the event processed, we'll process any
26✔
573
                                // new daemon events that were emitted as part
26✔
574
                                // of this new state transition.
26✔
575
                                for _, dEvent := range events.ExternalEvents {
48✔
576
                                        err := s.executeDaemonEvent(
22✔
577
                                                ctx, dEvent,
22✔
578
                                        )
22✔
579
                                        if err != nil {
22✔
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 {
34✔
589
                                        s.log.DebugS(ctx, "Adding new internal event to queue",
8✔
590
                                                "event", lnutils.SpewLogClosure(inEvent))
8✔
591

8✔
592
                                        eventQueue.Enqueue(inEvent)
8✔
593
                                }
8✔
594

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

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

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

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

37✔
615
                        return nil
37✔
616
                })
617
                if err != nil {
55✔
618
                        return currentState, err
9✔
619
                }
9✔
620
        }
621

622
        return currentState, nil
29✔
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.
628
func (s *StateMachine[Event, Env]) driveMachine(ctx context.Context) {
28✔
629
        s.log.DebugS(ctx, "Starting state machine")
28✔
630

28✔
631
        currentState := s.cfg.InitialState
28✔
632

28✔
633
        // Before we start, if we have an init daemon event specified, then
28✔
634
        // we'll handle that now.
28✔
635
        err := fn.MapOptionZ(s.cfg.InitEvent, func(event DaemonEvent) error {
53✔
636
                return s.executeDaemonEvent(ctx, event)
25✔
637
        })
25✔
638
        if err != nil {
28✔
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)
28✔
646

28✔
647
        for {
102✔
648
                select {
74✔
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:
38✔
653
                        newState, err := s.applyEvents(
38✔
654
                                ctx, currentState, newEvent,
38✔
655
                        )
38✔
656
                        if err != nil {
47✔
657
                                s.cfg.ErrorReporter.ReportError(err)
9✔
658

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

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

9✔
665
                                return
9✔
666
                        }
9✔
667

668
                        currentState = newState
29✔
669

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

677
                case <-s.wg.Done():
19✔
678
                        return
19✔
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