This repository has been archived by the owner on Apr 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
437 lines (352 loc) · 14.2 KB
/
index.js
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/* Copyright 2016 Simon `svvac` Wachter (_@svvac.net)
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENaze.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const aze = require('aze');
let _smcount = 0;
class StateMachine {
constructor(config) {
const smid = `SM${_smcount++}`;
this.$smid = smid;
this.$states_str = aze.get(config, 'states', []);
this.$states = {};
this.$states_str.forEach((s, i) => this.$states[s] = i);
this.$transition_whitelist = aze.get(config, 'transition_whitelist', null);
this.$cascade_handlers = aze.get(config, 'cascade_handlers', false);
if (aze.get(config, 'debug', false)) {
this.$$debug = function () {
console.log.apply(console, [ smid ].concat(Array.from(arguments)));
};
} else {
this.$$debug = () => null;
}
// For the user
this.state = {};
this.$$n = null;
this.$$np = null;
this.$$event_queue = [];
this.$$state_listeners = [];
this.$$state_listeners_map_down = {};
this.$$state_listeners_map_up = {};
this.$state = aze.get(config, 'init_state', 0);
this.$heartbeat = aze.get(config, 'heartbeat', false);
}
get $heartbeat() { return this.$$heartbeat_value; }
set $heartbeat(v) {
const tv = typeof v;
if (tv !== 'number' && tv !== 'boolean' && t !== null && t !== undefined) {
throw new TypeError('Invalid heartbeat interval')
}
if (!v || v < 1) v = false;
if (v == this.$$heartbeat_value) return;
this.$$debug('--', 'Setting heartbeat to', v);
this.$$heartbeat_value = v;
this.$$start_heartbeat();
}
$destruct() {
this.$$stop_heartbeat();
}
$timeout(duration, token) {
return this.$schedule(duration, '$timeout', token);
}
$schedule(duration, evt, payload) {
this.$$debug('--', 'Scheduling', evt, 'in', duration);
let timeout_cleared = false;
const t = setTimeout(() => {
timeout_cleared = true;
this.$push(evt, payload)
}, duration);
const f = () => {
if (timeout_cleared) return;
timeout_cleared = true;
clearTimeout(t);
this.$$debug('--', 'Canceled scheduled', evt);
};
f.evt = evt;
f.payload = payload;
f.duration = duration;
return f;
}
$$add_listener(states, cb, remove, revert) {
states = this.$$normalized_state_list(states);
let handle = this.$$state_listeners.indexOf(null);
if (handle < 0) handle = this.$$state_listeners.length;
this.$$state_listeners[handle] = {
cb: cb,
remove: !!remove,
triggered: false,
bound_to: states,
reversed: !!revert,
};
this.$$debug('--', 'Registered state change handler', handle);
const map = revert ? this.$$state_listeners_map_down
: this.$$state_listeners_map_up;
for (let state of states) {
if (!(state in map))
map[state] = [];
map[state].push(handle);
this.$$debug('--', 'Bound handler', handle, 'to', this.$states_str[state], revert ? 'down' : 'up');
}
return handle;
}
$remove_listener(handle) {
if (!(handle in this.$$state_listeners))
return null;
const h = this.$$state_listeners[handle];
for (let state of h.bound_to) {
const map = h.reversed ? this.$$state_listeners_map_down
: this.$$state_listeners_map_up;
let idx = map[state].indexOf(handle);
if (idx > -1) {
map[state].splice(idx, 1);
this.$$debug('--', 'Unbound handler', handle, 'from', this.$states_str[state], h.reversed ? 'down' : 'up');
}
}
this.$$state_listeners[handle] = null;
this.$$debug('--', 'Unregistered state change handler', handle);
this.$$debug('--', 'State change handler', handle, 'was called', Number(h.triggered), 'times');
return h;
}
$$process_state_change_events(prev, next) {
const handles = (prev in this.$$state_listeners_map_down ? this.$$state_listeners_map_down[prev] : [])
.concat(next in this.$$state_listeners_map_up ? this.$$state_listeners_map_up[next] : [])
for (let h of handles) {
const handler = this.$$state_listeners[h];
if (handler.remove && handler.triggered) continue;
this.$$debug('--', 'Triggering state change handler', h);
setImmediate(() => handler.cb.call(null, this, prev, next));
handler.triggered += 1;
if (handler.remove) {
this.$remove_listener(h);
}
}
}
$on(states, cb) {
return this.$$add_listener(states, cb, false, false)
}
$once(states, cb) {
return this.$$add_listener(states, cb, true, false);
}
$off(states, cb) {
return this.$$add_listener(states, cb, false, true);
}
$once_off(states, cb) {
return this.$$add_listener(states, cb, true, true);
}
$is(states) {
return this.$$state_is(this.$$n, arguments);
}
$$state_is(state, states) {
return this.$$normalized_state_list(states).indexOf(state) > -1;
}
$$normalized_state_list(states) {
if (typeof states === 'object' && 'callee' in states)
states = Array.isArray(states[0]) ? states[0] : Array.from(states);
if (!Array.isArray(states)) states = Array.from(arguments);
return states.map((s) => {
if (typeof s === 'number') {
if (s in this.$states_str) return s;
} else if (typeof s === 'string') {
if (s in this.$states) return this.$states[s];
}
throw new Error('Unknown state ' + s);
});
}
$push(evt, payload) {
this.$$debug('--', 'Queued', evt);
this.$$event_queue.push([ evt, payload ]);
this.$$flush_queue_();
}
$$flush_queue_() {
setImmediate(() => this.$$flush_queue());
}
$$flush_queue() {
if (this.$$event_queue.length) {
let e = this.$$event_queue.shift();
this.$$tick(e[0], e[1]);
}
}
$$start_heartbeat() {
const interval = this.$heartbeat;
this.$$stop_heartbeat();
if (!interval) return;
this.$$debug('--', 'Installing heartbeat');
this.$$heartbeat_interval_h = setInterval(() => this.$$tick(null), interval);
}
$$stop_heartbeat() {
if (!this.$$heartbeat_interval_h) return;
this.$$debug('--', 'Uninstalling heartbeat');
cancelInterval(this.$$heartbeat_interval_h);
this.$$heartbeat_interval_h = null;
}
get $state() { return this.$$n }
get $state_name() { return this.$states_str[this.$$n]; }
set $state(v) { return this.$transition(v); }
$transition(target) {
this.$$smexcep_check();
if (typeof target === 'string') {
if (target in this.$states) {
return this.$transition(this.$states[target]);
}
} else if (typeof target === 'number') {
if (target in this.$states_str) {
if (target === this.$$n) return this.$$n;
// Check if transition is allowed
if (this.$transition_whitelist) {
let valid = this.$transition_whitelist
.reduce((acc, trans) => acc
|| this.$$state_is(this.$$n, trans[0])
&& this.$$state_is(target, trans[1]), false);
if (!valid) {
this.$panic('Forbidden transition');
}
}
this.$$np = this.$$n;
this.$$n = target;
this.$$debug('Transitionning to', this.$states_str[target]);
this.$$process_state_change_events(this.$$np, this.$$n);
return this.$$n;
}
} else if (target === undefined) {
throw new Error('Can\'t transition to SMEXCEP: use .$panic()');
}
return this.$panic('Unknown state ' + target);
}
$$tick(evt, payload) {
// unedefined state means the state machine encountered an unhandled
// condition and therefore stopped since it will likely misbehave.
// Stop with a state machine exception.
if (this.$$n === undefined) {
// Ignore heartbeat events when in SMEXCEP.
if (evt === null) return;
return this.$panic();
}
// Keep track of time
//let time = process.hrtime();
//time = this.$time = time[0] * 1e3 + time[1] / 1e6; // ms
// Retrieve method, by order of preference:
//
// 1. __STATE_NAME__event_name() handles the event "event_name" when in
// state "STATE_NAME".
// 2. __STATE_NAME__() handles all events when in state "STATE_NAME".
// 3. ____event_name() handles all "event_name" events unless a more
// specific handler exists (e.g. 1. or 2.).
//
// The handler receives two parameters: the event identifier and the
// event payload. They can act upon the state appropriately. See return
// value requirements for handlers below.
//
// If an event was not explicitely handled by a handler, we still try
// these with lower specificity afterwards if this.$cascade_handlers is
// true
//
// By convention, state names are in caps, and event names in lowercase,
// but feel free to do whatever. Class properties and methods with a
// name starting in "$" and "$$" are reserved by this class so try not
// to blow everything up.
const method_list = [
this.$$get_method(`__${this.$state_name}__${evt}`),
this.$$get_method(`__${this.$state_name}__`),
this.$$get_method(`____${evt}`),
];
let ret;
try {
for (let method of method_list) {
if (!method) continue;
this.$$debug('Processing', evt, 'with', method.name);
ret = method.call(this, evt, payload);
// Test handling of the event
// If it was handled, stop processing
if (this.$$process_handler_return(ret, evt, payload)) {
return;
}
// Don't go further if not using cascading handlers
if (!this.$cascade_handlers) break;
}
} catch (e) {
console.error('Exception raised while in state', this.$state_name, 'handling event', evt);
console.error(e);
return this.$panic('Unhandled exception');
}
if (evt === null) {
return;
}
// Defensive programming
console.error('Unhandled condition for state', this.$state_name, 'with event', evt);
console.error('Returned', ret);
this.$panic();
}
$$process_handler_return(ret, evt, payload) {
// handler function MUST return something upon handling an
// event.
//
// * If it returns true, all good, we consider the event
// handled.
// * If it returns a string or an array, we consider that as an
// event to be immediately triggered on the state machine.
// * If false, immediately reemit the same event.
//
// Contrary to using $push(), the event is added at the
// top of the event queue so that it is the next event that will
// be fired on the state machine.
//
// Any other return value is invalid and will trigger a state
// machine exception.
if (ret === true) {
return true;
} else if (ret === false) {
this.$$debug('Zero-transition');
this.$$event_queue.unshift([ evt, payload ]);
this.$$flush_queue_();
return true;
} else if (typeof ret === 'string') {
this.$$debug('Zero-transition with event', ret);
this.$$event_queue.unshift([ ret ]);
this.$$flush_queue_();
return true;
} else if (Array.isArray(ret)) {
this.$$debug('Zero-transition with event', ret[0]);
this.$$event_queue.unshift(ret);
this.$$flush_queue_();
return true;
}
return false;
}
$panic(msg) {
if (this.$$n !== undefined) setImmediate(() => this.$panic_handler());
this.$$n = undefined;
this.$$stop_heartbeat();
throw new Error(msg || 'State machine exception');
}
$panic_handler() {
// user implemented
}
$$smexcep_check() {
if (this.$$n !== undefined) return;
this.$panic();
}
$$get_method(name, rec) {
if (typeof name === 'function') return name;
const res = this[name];
return typeof res === 'function' ? res
: rec !== false && typeof res === 'string' ? this.$$get_method(res)
: null;
}
// Convenience shorthand
pass() { return true; }
}
module.exports = StateMachine;