-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhandleEvent.ts
More file actions
314 lines (263 loc) · 10.9 KB
/
Copy pathhandleEvent.ts
File metadata and controls
314 lines (263 loc) · 10.9 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
/*
* Copyright (c) 2022-2024 The Peacock Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test, handleActionsOnDraft } from "./index"
import { findNamedChild } from "./utils"
import {
HandleEventOptions,
HandleEventReturn,
InStateEventHandler,
StateMachineLike,
} from "./types"
import { create } from "mutative"
/**
* This function simulates an event happening, as if in game.
* Given a state machine definition, the event, and a few other things, you can inspect the results.
*
* @param definition The state machine definition.
* @param context The current context of the state machine.
* @param event The event object.
* @param options Various other settings and details needed for the implementation.
* @returns The state machine and related data after performing the operation.
*/
export function handleEvent<Context = unknown, Event = unknown>(
definition: StateMachineLike<Partial<Context>>,
context: Partial<Context>,
event: Event,
options: HandleEventOptions,
): HandleEventReturn<Partial<Context>> {
const log = options.logger || (() => {})
const { eventName, currentState = "Start" } = options
// (current state object - reduces code duplication)
let csObject = definition.States?.[currentState]
if (!csObject || (!csObject?.[eventName] && !csObject?.$timer)) {
log(
"disregard-event",
`SM in state ${currentState} disregarding ${eventName}`,
)
// we are here because either:
// - we have no handler for the current state
// - in this particular state, the state machine doesn't care about the current event
return {
context: context,
state: currentState,
}
}
const hasTimerState = !!csObject.$timer
// ensure no circular references are present, and that this won't update the param by accident
let newContext = context
const doEventHandler = (handler: InStateEventHandler) => {
// do we need to check conditions?
const shouldCheckConditions = !!handler.Condition
// does the event handler have any keys that look like actions?
// IOI sometimes puts the actions along-side keys like Transition and Condition,
// yet both still apply
const irregularEventKeys = Object.keys(handler).filter((k) =>
k.includes("$"),
)
const hasIrregularEventKeys = irregularEventKeys.length > 0
// do we need to perform actions?
const shouldPerformActions = !!handler.Actions || hasIrregularEventKeys
// do we need to perform a transition?
const shouldPerformTransition = !!handler.Transition
const constantKeys = Object.keys(definition.Constants || {})
let conditionResult = true
if (shouldCheckConditions) {
conditionResult = test(
handler.Condition,
{
...(newContext || {}),
...(options.contractId && {
ContractId: options.contractId,
}),
...(definition.Constants || {}),
Value: event,
},
{
pushUniqueAction(reference, item) {
const workingContext = {
...newContext,
...(definition.Constants || {}),
...(options.contractId && {
ContractId: options.contractId,
}),
Value: event,
}
const referenceArray = findNamedChild(reference, workingContext, true)
item = findNamedChild(item, workingContext, false)
log(
"action",
`Running pushUniqueAction on ${reference} with ${item}`,
)
if (!Array.isArray(referenceArray)) {
return false
}
if (referenceArray.includes(item)) {
return false
}
// Actually modify the context using Mutative
newContext = create(newContext, (draft) => {
const draftArray = findNamedChild(reference, draft, true)
if (Array.isArray(draftArray) && !draftArray.includes(item)) {
draftArray.push(item)
}
})
return true
},
logger: log,
timers: options.timers,
eventTimestamp: options.timestamp,
},
)
}
if (conditionResult && shouldPerformActions) {
let Actions = handler.Actions || []
if (!Array.isArray(Actions)) {
Actions = [Actions]
}
if (hasIrregularEventKeys) {
;(<unknown[]>Actions).push(
...irregularEventKeys.map((key) => {
return { [key]: handler[key] }
}),
)
}
// Special case: if the handler itself contains action keys and no Actions property,
// treat the handler as the actions
if (!handler.Actions && hasIrregularEventKeys) {
Actions = [handler]
}
// Create a working context with constants and event data
const workingContext = {
...newContext,
...(definition.Constants || {}),
...(options.contractId && {
ContractId: options.contractId,
}),
Value: event,
}
newContext = create(workingContext, (draft) => {
for (const actionSet of Actions as unknown[]) {
// For each action in the action set, apply it individually
for (const actionKey of Object.keys(actionSet)) {
handleActionsOnDraft(
{ [actionKey]: actionSet[actionKey] },
draft,
draft, // Use the draft for reading values so each action sees previous changes
{
originalContext: definition.Context ?? {}
}
)
}
}
// drop this specific event's value
if (draft.hasOwnProperty("Value")) {
delete draft.Value
}
// drop this specific event's ContractId
if (draft.hasOwnProperty("ContractId")) {
delete draft.ContractId
}
// drop the constants
for (const constantKey of constantKeys) {
delete draft[constantKey]
}
})
}
let state = currentState
if (conditionResult && shouldPerformTransition) {
state = handler.Transition
log(
"transition",
`${currentState} is performing a transition to ${state} - running its "-" event`,
)
// When transitioning, we have to reset all timers.
// Since this is pass-by-reference, we have to modify the existing array!
if (options.timers) {
while (options.timers.length > 0) {
options.timers.pop()
}
}
return handleEvent(
definition,
newContext,
{},
{
eventName: "-",
currentState: state,
logger: log,
timers: options.timers,
timestamp: options.timestamp,
contractId: options.contractId,
},
)
}
return {
context: newContext,
state,
}
}
type EHArray = InStateEventHandler[]
const doEventHandlers = (eventHandlers: EHArray) => {
for (const handler of eventHandlers) {
const out = doEventHandler(handler)
newContext = out.context
if (out.state !== currentState) {
// we swapped states while in a handler, so our work here is done
return {
context: newContext,
state: out.state,
}
}
}
return undefined
}
let eventHandlers = csObject[eventName]
if (!Array.isArray(eventHandlers)) {
// if we don't have a handler for the current event, but we do for the timer, it produces [undefined]
eventHandlers = [eventHandlers].filter(Boolean)
}
if (hasTimerState) {
const timerState = csObject.$timer
const timerEventHandlers: EHArray = []
// Timers will always have to be handled first.
// An expired timer might transition to another state and that has to happen as soon as possible.
if (Array.isArray(timerState)) {
timerEventHandlers.unshift(...timerState)
} else {
timerEventHandlers.unshift(timerState)
}
// Timers are a special snowflake, if they cause a state transition we have to continue processing normal events.
// Since the handlers don't know what they are processing and to prevent constantly checking for timers, we just run them separately.
const timerResult = doEventHandlers(timerEventHandlers)
// If the timer resulted in a state transition, we have to replay the current event again.
if (timerResult) {
log(
"timer",
"Timer caused a state transition, replaying current event with new state.",
)
options.currentState = timerResult.state
return handleEvent(definition, timerResult.context, event, options)
}
}
const result = doEventHandlers(eventHandlers)
if (result) {
return result
}
return {
state: currentState,
context: newContext,
}
}