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

lightningnetwork / lnd / 14388908780

10 Apr 2025 07:39PM UTC coverage: 56.811% (-12.3%) from 69.08%
14388908780

Pull #9702

github

web-flow
Merge f006bbf4d into b732525a9
Pull Request #9702: multi: make payment address mandatory

28 of 42 new or added lines in 11 files covered. (66.67%)

23231 existing lines in 283 files now uncovered.

107286 of 188846 relevant lines covered (56.81%)

22749.28 hits per line

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

75.84
/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
        "github.com/lightningnetwork/lnd/msgmux"
18
)
19

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

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

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

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

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

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

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

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

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

81
        // String returns a human readable string that represents the state.
82
        String() string
83
}
84

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

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

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

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

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

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

136
        log btclog.Logger
137

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

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

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

150
        gm   fn.GoroutineManager
151
        quit chan struct{}
152

153
        startOnce sync.Once
154
        stopOnce  sync.Once
155
}
156

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

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

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

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

179
        // Env is the environment that the state machine will use to execute.
180
        Env Env
181

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

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

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

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

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

217
// Start starts the state machine. This will spawn a goroutine that will drive
218
// the state machine to completion.
219
func (s *StateMachine[Event, Env]) Start(ctx context.Context) {
46✔
220
        s.startOnce.Do(func() {
92✔
221
                _ = s.gm.Go(ctx, func(ctx context.Context) {
92✔
222
                        s.driveMachine(ctx)
46✔
223
                })
46✔
224
        })
225
}
226

227
// Stop stops the state machine. This will block until the state machine has
228
// reached a stopping point.
229
func (s *StateMachine[Event, Env]) Stop() {
60✔
230
        s.stopOnce.Do(func() {
106✔
231
                close(s.quit)
46✔
232
                s.gm.Stop()
46✔
233
        })
46✔
234
}
235

236
// SendEvent sends a new event to the state machine.
237
//
238
// TODO(roasbeef): bool if processed?
239
func (s *StateMachine[Event, Env]) SendEvent(ctx context.Context, event Event) {
57✔
240
        s.log.Debugf("Sending event %T", event)
57✔
241

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

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

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

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

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

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

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

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

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

294
        return processed
1✔
295
}
296

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

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

307
        return fn.RecvOrTimeout(query.CurrentState, time.Second)
25✔
308
}
309

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

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

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

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

46✔
323
        s.newStateEvents.RegisterSubscriber(subscriber)
46✔
324

46✔
325
        return subscriber
46✔
326
}
46✔
327

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

46✔
333
        _ = s.newStateEvents.RemoveSubscriber(sub)
46✔
334
}
46✔
335

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

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

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

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

2✔
367
                                                s.SendEvent(ctx, event)
2✔
368
                                        },
2✔
369
                                )
370

371
                                if !launched {
2✔
372
                                        return ErrStateMachineShutdown
×
373
                                }
×
374

375
                                return nil
2✔
376
                        })
377
                }
378

379
                canSend := func() bool {
23✔
380
                        return fn.MapOptionZ(
4✔
381
                                daemonEvent.SendWhen,
4✔
382
                                func(pred SendPredicate) bool {
8✔
383
                                        return pred()
4✔
384
                                },
4✔
385
                        )
386
                }
387

388
                // If this doesn't have a SendWhen predicate, or if it's already
389
                // true, then we can just send it off right away.
390
                if !daemonEvent.SendWhen.IsSome() || canSend() {
36✔
391
                        return sendAndCleanUp()
17✔
392
                }
17✔
393

394
                // Otherwise, this has a SendWhen predicate, so we'll need
395
                // launch a goroutine to poll the SendWhen, then send only once
396
                // the predicate is true.
397
                launched := s.gm.Go(ctx, func(ctx context.Context) {
4✔
398
                        predicateTicker := time.NewTicker(
2✔
399
                                s.cfg.CustomPollInterval.UnwrapOr(pollInterval),
2✔
400
                        )
2✔
401
                        defer predicateTicker.Stop()
2✔
402

2✔
403
                        s.log.InfoS(ctx, "Waiting for send predicate to be true")
2✔
404

2✔
405
                        for {
4✔
406
                                select {
2✔
407
                                case <-predicateTicker.C:
1✔
408
                                        if canSend() {
2✔
409
                                                s.log.InfoS(ctx, "Send active predicate")
1✔
410

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

416
                                                return
1✔
417
                                        }
418

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

425
                if !launched {
2✔
426
                        return ErrStateMachineShutdown
×
427
                }
×
428

429
                return nil
2✔
430

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

10✔
437
                err := s.cfg.Daemon.BroadcastTransaction(
10✔
438
                        daemonEvent.Tx, daemonEvent.Label,
10✔
439
                )
10✔
440
                if err != nil {
10✔
UNCOV
441
                        log.Errorf("unable to broadcast txn: %v", err)
×
UNCOV
442
                }
×
443

444
                return nil
10✔
445

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

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

460
                launched := s.gm.Go(ctx, func(ctx context.Context) {
84✔
461
                        for {
84✔
462
                                select {
42✔
UNCOV
463
                                case spend, ok := <-spendEvent.Spend:
×
UNCOV
464
                                        if !ok {
×
UNCOV
465
                                                return
×
UNCOV
466
                                        }
×
467

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

UNCOV
477
                                        return
×
478

479
                                case <-ctx.Done():
42✔
480
                                        return
42✔
481
                                }
482
                        }
483
                })
484

485
                if !launched {
42✔
486
                        return ErrStateMachineShutdown
×
487
                }
×
488

489
                return nil
42✔
490

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

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

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

521
                                        return
×
522

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

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

533
                return nil
×
534
        }
535

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

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

57✔
546
        eventQueue := fn.NewQueue(newEvent)
57✔
547

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

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

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

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

10✔
590
                                        eventQueue.Enqueue(inEvent)
10✔
591
                                }
10✔
592

593
                                return nil
31✔
594
                        })
595
                        if err != nil {
53✔
596
                                return err
×
597
                        }
×
598

599
                        s.log.InfoS(ctx, "State transition",
53✔
600
                                btclog.Fmt("from_state", "%v", currentState),
53✔
601
                                btclog.Fmt("to_state", "%v", transition.NextState))
53✔
602

53✔
603
                        // With our events processed, we'll now update our
53✔
604
                        // internal state.
53✔
605
                        currentState = transition.NextState
53✔
606

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

53✔
613
                        return nil
53✔
614
                })
615
                if err != nil {
81✔
616
                        return currentState, err
14✔
617
                }
14✔
618
        }
619

620
        return currentState, nil
43✔
621
}
622

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

46✔
629
        currentState := s.cfg.InitialState
46✔
630

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

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

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

14✔
657
                                s.log.ErrorS(ctx, "Unable to apply event", err)
14✔
658

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

14✔
663
                                return
14✔
664
                        }
14✔
665

666
                        currentState = newState
43✔
667

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

675
                case <-s.gm.Done():
32✔
676
                        return
32✔
677
                }
678
        }
679
}
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