-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinspector.go
More file actions
344 lines (297 loc) · 9.11 KB
/
inspector.go
File metadata and controls
344 lines (297 loc) · 9.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package debug
import (
"fmt"
"sort"
"strings"
"go.klarlabs.de/statekit"
"go.klarlabs.de/statekit/internal/ir"
)
// Inspector provides debugging and inspection capabilities for a state machine.
// It allows examining the machine configuration, available transitions, and
// simulating transitions without side effects.
type Inspector[C any] struct {
interp *statekit.Interpreter[C]
machine *ir.MachineConfig[C]
}
// NewInspector creates a new Inspector for the given interpreter.
// The machine parameter is required for accessing machine configuration.
// Note: The machine parameter accepts *ir.MachineConfig[C] which is returned by
// the builder's Build() method. The statekit.MachineConfig[C] type alias is
// equivalent but Go's generic type inference requires the exact type.
func NewInspector[C any](interp *statekit.Interpreter[C], machine *ir.MachineConfig[C]) *Inspector[C] {
return &Inspector[C]{
interp: interp,
machine: machine,
}
}
// CurrentState returns the current state ID of the interpreter.
func (i *Inspector[C]) CurrentState() statekit.StateID {
return i.interp.State().Value
}
// CurrentContext returns the current context.
func (i *Inspector[C]) CurrentContext() C {
return i.interp.State().Context
}
// IsDone returns true if the machine is in a final state.
func (i *Inspector[C]) IsDone() bool {
return i.interp.Done()
}
// MachineID returns the machine's ID.
func (i *Inspector[C]) MachineID() string {
return i.machine.ID
}
// InitialState returns the machine's initial state.
func (i *Inspector[C]) InitialState() statekit.StateID {
return i.machine.Initial
}
// AllStates returns all state IDs defined in the machine.
func (i *Inspector[C]) AllStates() []statekit.StateID {
states := make([]statekit.StateID, 0, len(i.machine.States))
for id := range i.machine.States {
states = append(states, id)
}
sort.Slice(states, func(a, b int) bool {
return states[a] < states[b]
})
return states
}
// StateInfo returns detailed information about a specific state.
func (i *Inspector[C]) StateInfo(stateID statekit.StateID) *StateInfo {
config := i.machine.GetState(stateID)
if config == nil {
return nil
}
info := &StateInfo{
ID: config.ID,
Type: config.Type.String(),
Parent: config.Parent,
Initial: config.Initial,
Children: config.Children,
Entry: actionsToStrings(config.Entry),
Exit: actionsToStrings(config.Exit),
}
// Collect transitions
for _, t := range config.Transitions {
info.Transitions = append(info.Transitions, TransitionInfo{
Event: t.Event,
Target: t.Target,
Guard: t.Guard,
Actions: actionsToStrings(t.Actions),
Delay: t.Delay.String(),
})
}
return info
}
// AvailableEvents returns all events that the current state can handle.
// This includes events handled by ancestor states (due to event bubbling).
func (i *Inspector[C]) AvailableEvents() []statekit.EventType {
currentState := i.interp.State().Value
eventSet := make(map[statekit.EventType]bool)
// Collect events from current state and all ancestors
stateID := currentState
for stateID != "" {
config := i.machine.GetState(stateID)
if config == nil {
break
}
for _, t := range config.Transitions {
// Skip delayed transitions (they fire automatically)
if t.Delay > 0 {
continue
}
eventSet[t.Event] = true
}
stateID = config.Parent
}
events := make([]statekit.EventType, 0, len(eventSet))
for e := range eventSet {
events = append(events, e)
}
sort.Slice(events, func(a, b int) bool {
return events[a] < events[b]
})
return events
}
// CanTransition checks if the given event would cause a transition.
// This evaluates guards but does not execute actions.
func (i *Inspector[C]) CanTransition(eventType statekit.EventType) bool {
_, canTransition := i.SimulateTransition(statekit.Event{Type: eventType})
return canTransition
}
// CanTransitionWithPayload checks if the given event with payload would cause a transition.
func (i *Inspector[C]) CanTransitionWithPayload(event statekit.Event) bool {
_, canTransition := i.SimulateTransition(event)
return canTransition
}
// SimulateTransition simulates sending an event without executing actions.
// Returns the target state and whether a transition would occur.
func (i *Inspector[C]) SimulateTransition(event statekit.Event) (statekit.StateID, bool) {
currentState := i.interp.State().Value
ctx := i.interp.State().Context
// Find matching transition starting from current state
stateID := currentState
for stateID != "" {
config := i.machine.GetState(stateID)
if config == nil {
break
}
for _, t := range config.Transitions {
if t.Event != event.Type {
continue
}
// Check guard if present
if t.Guard != "" {
guard := i.machine.GetGuard(t.Guard)
if guard != nil && !guard(ctx, event) {
continue // Guard failed, try next
}
}
// Found matching transition
target := t.Target
if target == "" {
// Self-transition with no explicit target
return currentState, false
}
// Resolve to leaf state
resolvedTarget := i.machine.GetInitialLeaf(target)
return resolvedTarget, true
}
stateID = config.Parent
}
return currentState, false
}
// TransitionsFrom returns all possible transitions from the given state.
func (i *Inspector[C]) TransitionsFrom(stateID statekit.StateID) []TransitionInfo {
config := i.machine.GetState(stateID)
if config == nil {
return nil
}
var transitions []TransitionInfo
for _, t := range config.Transitions {
transitions = append(transitions, TransitionInfo{
Event: t.Event,
Target: t.Target,
Guard: t.Guard,
Actions: actionsToStrings(t.Actions),
Delay: t.Delay.String(),
})
}
return transitions
}
// Ancestors returns all ancestor states of the current state.
func (i *Inspector[C]) Ancestors() []statekit.StateID {
return i.machine.GetAncestors(i.interp.State().Value)
}
// Path returns the full path from root to current state.
func (i *Inspector[C]) Path() []statekit.StateID {
return i.machine.GetPath(i.interp.State().Value)
}
// Dump returns a human-readable string representation of the current machine state.
func (i *Inspector[C]) Dump() string {
var sb strings.Builder
fmt.Fprintf(&sb, "Machine: %s\n", i.machine.ID)
fmt.Fprintf(&sb, "Current State: %s\n", i.interp.State().Value)
fmt.Fprintf(&sb, "Is Done: %v\n", i.interp.Done())
sb.WriteString("\n")
// Path
path := i.Path()
fmt.Fprintf(&sb, "Path: %s\n", strings.Join(toStringSlice(path), " -> "))
sb.WriteString("\n")
// Available events
events := i.AvailableEvents()
sb.WriteString("Available Events:\n")
if len(events) == 0 {
sb.WriteString(" (none)\n")
}
for _, e := range events {
canTransition := i.CanTransition(e)
target, _ := i.SimulateTransition(statekit.Event{Type: e})
marker := ""
if canTransition {
marker = fmt.Sprintf(" -> %s", target)
} else {
marker = " (blocked by guard)"
}
fmt.Fprintf(&sb, " - %s%s\n", e, marker)
}
return sb.String()
}
// DumpMachine returns a complete dump of the machine configuration.
func (i *Inspector[C]) DumpMachine() string {
var sb strings.Builder
fmt.Fprintf(&sb, "Machine: %s\n", i.machine.ID)
fmt.Fprintf(&sb, "Initial: %s\n", i.machine.Initial)
fmt.Fprintf(&sb, "States: %d\n", len(i.machine.States))
sb.WriteString("\n")
// List all states
states := i.AllStates()
for _, stateID := range states {
info := i.StateInfo(stateID)
fmt.Fprintf(&sb, "State: %s\n", info.ID)
fmt.Fprintf(&sb, " Type: %s\n", info.Type)
if info.Parent != "" {
fmt.Fprintf(&sb, " Parent: %s\n", info.Parent)
}
if info.Initial != "" {
fmt.Fprintf(&sb, " Initial: %s\n", info.Initial)
}
if len(info.Children) > 0 {
fmt.Fprintf(&sb, " Children: %s\n", strings.Join(toStringSlice(info.Children), ", "))
}
if len(info.Entry) > 0 {
fmt.Fprintf(&sb, " Entry: %s\n", strings.Join(info.Entry, ", "))
}
if len(info.Exit) > 0 {
fmt.Fprintf(&sb, " Exit: %s\n", strings.Join(info.Exit, ", "))
}
if len(info.Transitions) > 0 {
sb.WriteString(" Transitions:\n")
for _, t := range info.Transitions {
fmt.Fprintf(&sb, " %s -> %s", t.Event, t.Target)
if t.Guard != "" {
fmt.Fprintf(&sb, " [%s]", t.Guard)
}
if len(t.Actions) > 0 {
fmt.Fprintf(&sb, " / %s", strings.Join(t.Actions, ", "))
}
sb.WriteString("\n")
}
}
sb.WriteString("\n")
}
return sb.String()
}
// StateInfo contains detailed information about a state.
type StateInfo struct {
ID statekit.StateID
Type string
Parent statekit.StateID
Initial statekit.StateID
Children []statekit.StateID
Entry []string
Exit []string
Transitions []TransitionInfo
}
// TransitionInfo contains information about a transition.
type TransitionInfo struct {
Event statekit.EventType
Target statekit.StateID
Guard statekit.GuardType
Actions []string
Delay string
}
// Helper functions
func actionsToStrings(actions []ir.ActionType) []string {
result := make([]string, len(actions))
for i, a := range actions {
result[i] = string(a)
}
return result
}
func toStringSlice[T ~string](slice []T) []string {
result := make([]string, len(slice))
for i, s := range slice {
result[i] = string(s)
}
return result
}