@rootintf/protocol-2phw 2.3.7-api.2 → 3.1.2-api.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/twoPhW.ts CHANGED
@@ -1,833 +1,865 @@
1
-
2
- import {
3
- definitions_2PhW as definitions_2PhW_,
4
- schema_MsgWarp as schema_MsgWarp_,
5
- schema_MsgEngage as schema_MsgEngage_,
6
- // schema_MsgOptions as schema_MsgOptions_,
7
- // schema_Options_delay as schema_Options_delay_,
8
- } from './validate-esm.mjs';
9
-
10
- // import { v4 as uuidv4 } from 'uuid'; // uuid is already a dep of JSON_Msg, so why not
11
- import { LOGR, lRef, l_merge, l_array, l_concat, l_LL } from '@knev/bitlogr';
12
- import { JSON_Msg, JSON_MsgEffect, JSON_MsgAck, logr as logr_json_msg_ } from '@rootintf/json-msg'
13
-
14
- import { EventLog, logr as logr_evtlog_ } from '@rootintf/eventlog'
15
-
16
- type t_msg = string;
17
-
18
- interface EventMinimal {
19
- dt : number;
20
- data : { msg : t_msg, json_msg };
21
- }
22
-
23
- // interface Event extends Required<EventMinimal> {
24
- // type : string;
25
- // id : string | number;
26
- // timeout_id : NodeJS.Timeout | null;
27
- // };
28
-
29
- const k_TTL= 20000;
30
-
31
- //-------------------------------------------------------------------------------------------------
32
-
33
- const obj_labels_merge_= l_merge(logr_evtlog_.lref.get(), logr_json_msg_.lref.get()); // VALIDATION : 4
34
- const obj_labels_concat_= l_concat(obj_labels_merge_, l_array(['HANDLERS', 'DROPS', 'PROTOCOL_STATE', 'RECVER', 'SENDER']) );
35
-
36
- const lref_= lRef(obj_labels_concat_);
37
- logr_json_msg_.lref= lref_;
38
- logr_evtlog_.lref= lref_;
39
-
40
- const LOGR_= LOGR.get_instance();
41
- const logr_= LOGR_.create(); // don't let create() make a new ref, assign lref_ from here
42
- logr_.lref= lref_;
43
-
44
- const l_= logr_.l;
45
-
46
- //-------------------------------------------------------------------------------------------------
47
-
48
- type t_callback = (msg : t_msg, json_msg) => boolean;
49
- type t_callback_void = (msg : t_msg, json_msg) => void;
50
-
51
- class Config {
52
- public _callback_msgWarp : t_callback
53
- public _callback_msgEngage : t_callback
54
- public _callback_msgAckWarp : t_callback
55
- public _callback_msgAckEngage : t_callback
56
- public _callback_msg_sent_expired : t_callback_void
57
- public _callback_msgOptions: () => void;
58
-
59
- constructor() {
60
- // Initialize callbacks as no-op functions
61
- this._callback_msgWarp = (_msg : t_msg, _json_msg) => {
62
- console.assert(false, 'callback_msgWarp uninitialized'); return false;
63
- };
64
- this._callback_msgEngage = (_msg : t_msg, _json_msg) => {
65
- console.assert(false, 'callback_msgEngage uninitialized'); return false;
66
- };
67
- this._callback_msgAckWarp = (_msg : t_msg, _json_msg) => {
68
- console.assert(false, 'callback_msgAckWarp uninitialized'); return false;
69
- };
70
- this._callback_msgAckEngage = (_msg : t_msg, _json_msg) => {
71
- console.assert(false, 'callback_msgAckEngage uninitialized'); return false;
72
- };
73
- this._callback_msg_sent_expired = (_msg : t_msg, _json_msg) => {
74
- console.assert(false, '_callback_msg_sent_expired uninitialized');
75
- };
76
- this._callback_msgOptions = () => {
77
- console.assert(false, 'callback_msgOptions uninitialized');
78
- };
79
- }
80
-
81
- receiver(callback_msgWarp : t_callback, callback_msgEngage : t_callback, callback_msg_sent_expired : t_callback_void) {
82
- this._callback_msgWarp= callback_msgWarp;
83
- this._callback_msgEngage= callback_msgEngage;
84
- this._callback_msg_sent_expired= callback_msg_sent_expired;
85
- }
86
- sender(callback_msgAckWarp : t_callback, callback_msgAckEngage : t_callback, callback_msg_sent_expired : t_callback_void ) {
87
- this._callback_msgAckWarp= callback_msgAckWarp;
88
- this._callback_msgAckEngage= callback_msgAckEngage;
89
- this._callback_msg_sent_expired= callback_msg_sent_expired;
90
- }
91
-
92
- set callback_msgOptions(callback) {
93
- this._callback_msgOptions= callback;
94
- }
95
- }
96
-
97
- // var config = (function() {
98
- // let _options;
99
-
100
- // return {
101
- // get callback_Abort() { return _options.callback_Abort; },
102
-
103
- // set options(obj) {
104
- // _options= obj;
105
- // if (_options.logr) // && options_.logr[ __name(l_) ] )
106
- // LOGR_.toggled= _options.logr
107
- // }
108
- // }
109
- // })();
110
-
111
- //-------------------------------------------------------------------------------------------------
112
-
113
- let k_VERSION= "2";
114
-
115
- // rtt_msec <= ttl_msec *2 => rtt_msec = ttl_msec *2
116
- // t_ttl_rtt_(TTL, RTT) = t_ttl_rtt_(TTL, TTL *2) = TTL *2 + TTL *2 = TTL *4 MAX
117
-
118
- function time_ttl_rtt_(ttl_msec: number | undefined, rtt_msec?: number): number | undefined {
119
- if (ttl_msec === undefined)
120
- return undefined;
121
- if (rtt_msec === undefined)
122
- return ttl_msec *2;
123
-
124
- console.assert(rtt_msec <= ttl_msec *2, `t_ttl_rtt_: INVALID rtt_msec ttl_msec[${ttl_msec}] rtt_msec[${rtt_msec}]`)
125
- return (ttl_msec *2) + rtt_msec;
126
- }
127
-
128
- var JSON_MsgOptions = (function() {
129
- return {
130
- create_with_cause_options : function(msg_cause, options) {
131
- return JSON_MsgEffect.create_with_msg_merge(msg_cause, {
132
- options: options,
133
- "2PhW": k_VERSION
134
- });
135
- },
136
- validate : function(json) {
137
- // if (! JSON_Msg_msg.validate(json))
138
- // return false;
139
- // if (! schema_MsgOptions_(json)) {
140
- // logr_.log(l_.VALIDATION, () => ['JSON_MsgOptions: schema_MsgOptions_: ', (schema_MsgOptions_ as any).errors])
141
- // return false;
142
- // }
143
- return true;
144
- }
145
- }
146
- })();
147
-
148
- var JSON_MsgWarp = (function() {
149
- return {
150
- create_with_id_user_hyperport : function(json_warp_id, json_user, json_hyperport, nr_ttl_msec) {
151
- return JSON_Msg.merge({
152
- warp : {
153
- id : json_warp_id,
154
- user : json_user,
155
- hyperport : json_hyperport,
156
- ttl_msec : nr_ttl_msec
157
- },
158
- "2PhW": k_VERSION
159
- });
160
- },
161
- compare : function(json_L, json_R) {
162
- if (json_L.dt !== json_R.dt)
163
- return false;
164
- if (json_L.warp.id !== json_R.warp.id)
165
- return false;
166
- if (json_L.referer[0] !== json_R.referer[0])
167
- return false;
168
- if (json_L.referer[1] !== json_R.referer[1])
169
- return false;
170
- return true;
171
- },
172
- validate : function(json_msg) {
173
- // if (! JSON_Msg.validate(json))
174
- // return false;
175
- if (! schema_MsgWarp_(json_msg)) {
176
- logr_.log(l_.VALIDATION, () => ['JSON_MsgWarp: schema_MsgWarp_: ', (schema_MsgWarp_ as any).errors])
177
- return false;
178
- }
179
- return true;
180
- }
181
- }
182
- })();
183
-
184
- var JSON_MsgEngage = (function() {
185
- return {
186
- create_with_Warp : function(json_msgWarp) {
187
- console.assert(json_msgWarp.ack === undefined, "Engage with a Warp, not an Ack");
188
- return JSON_MsgEffect.create_with_cause_merge(json_msgWarp, {
189
- engage : {
190
- "ok" : true,
191
- "rtt_msec" : Date.now() - Date.parse(json_msgWarp.dt)
192
- },
193
- "2PhW": k_VERSION
194
- });
195
- },
196
- validate : function(json_msgEffect) {
197
- // if (! JSON_Msg_msg.validate(json))
198
- // return false;
199
- if (! JSON_MsgWarp.validate(json_msgEffect._cause))
200
- return false;
201
- if (! schema_MsgEngage_(json_msgEffect)) {
202
- logr_.log(l_.VALIDATION, () => ['JSON_MsgEngage: schema_MsgEngage_: ', (schema_MsgEngage_ as any).errors])
203
- return false;
204
- }
205
- return true;
206
- }
207
- };
208
- })();
209
-
210
- var JSON_MsgAckWarp = (function() {
211
- return {
212
- // createWith_msgAck_msg : function(json_msgAck, _msg) {
213
- // const json_msgAckWarp= structuredClone(json_msgAck);
214
- // json_msgAckWarp._cause= _cause;
215
- // return json_msgAckWarp;
216
- // }
217
- create_with_Warp_Ok : function(json_msgWarp, b_ok= true) {
218
- const json_msgAck= JSON_MsgAck.create_with_cause_Ok(json_msgWarp, b_ok);
219
- json_msgAck["2PhW"]= k_VERSION;
220
- return json_msgAck;
221
- },
222
- // create_with_msgExpired : function( json_msgWarp ) {
223
- // const json_msgAck_msg= JSON_MsgAck_msg.create_with_msgExpired( json_msgWarp )
224
- // json_msgAck_msg["2PhW"]= k_VERSION;
225
- // return json_msgAck_msg;
226
- // },
227
- validate : function(json_msgAck) {
228
- // if (! JSON_MsgAck_msg.validate(json))
229
- // return false;
230
- if (! JSON_MsgWarp.validate(json_msgAck._cause))
231
- return false;
232
- return true;
233
- }
234
- }
235
- })();
236
-
237
- var JSON_MsgAckEngage = (function() {
238
- return {
239
- // createWith_msgAck_msg : function(json_msgAck, _msg) {
240
- // const json_msgAckEngage= structuredClone(json_msgAck);
241
- // json_msgAckEngage._cause= _cause;
242
- // return json_msgAckEngage;
243
- // }
244
- create_with_Engage_Ok : function(json_msgEngage, b_ok= true) {
245
- const json_msgAck= JSON_MsgAck.create_with_cause_Ok(json_msgEngage, b_ok);
246
- json_msgAck["2PhW"]= k_VERSION;
247
- return json_msgAck;
248
- },
249
- // create_with_msgExpired : function( json_msgEngage ) {
250
- // const json_msgAck_msg= JSON_MsgAck_msg.create_with_msgExpired( json_msgEngage )
251
- // json_msgAck_msg["2PhW"]= k_VERSION;
252
- // return json_msgAck_msg;
253
- // },
254
- validate : function(json_msgAck) {
255
- // if (! JSON_MsgAck_msg.validate(json_msgAck_msg))
256
- // return false;
257
- if (! JSON_MsgEngage.validate(json_msgAck._cause))
258
- return false;
259
- return true;
260
- }
261
- }
262
- })();
263
-
264
- //-------------------------------------------------------------------------------------------------
265
- // States
266
-
267
- class StateState {
268
- private _idx_event : number;
269
- private _event : EventMinimal;
270
- protected _statekeeper : ProtocolStateState;
271
-
272
- constructor(idx_event : number, event : EventMinimal) {
273
- this._statekeeper = null;
274
- this._idx_event = idx_event;
275
- this._event = event;
276
- }
277
- get protocol() {
278
- return this._statekeeper;
279
- }
280
- set protocol(parent) {
281
- this._statekeeper = parent;
282
- }
283
- get idx_event() {
284
- return this._idx_event;
285
- }
286
- get event() {
287
- return this._event;
288
- }
289
- get json_msg() {
290
- return this._event.data.json_msg;
291
- }
292
- changeState(state_new : StateState) {
293
- if (this.canChangeState(state_new))
294
- this.protocol.state = state_new;
295
- else
296
- this.protocol.state = new StateINVALID(state_new._idx_event, state_new._event);
297
- }
298
- canChangeState(_state_new : StateState) : boolean {
299
- throw new Error("Subclass must implement canChangeState()");
300
- }
301
- }
302
-
303
- class StateAckEngage extends StateState {
304
- constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
305
- get evt_AckEngage() { return this.event }
306
- get json_msgAckEngage() { return this.json_msg }
307
- canChangeState(_state_new : StateState) {
308
- return false;
309
- }
310
- }
311
-
312
- class StateEngage extends StateState {
313
- constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
314
- get evt_Engage() { return this.event }
315
- get json_msgEngage() { return this.json_msg }
316
- canChangeState(state_new : StateState) {
317
- if (false === state_new instanceof StateAckEngage)
318
- return false;
319
-
320
- // The Engage gets to live for THE WARP'S creation time + TTL*2 + RTT
321
- const json_msgWarp= this.json_msgEngage._cause;
322
- const timeout_ms= time_ttl_rtt_(json_msgWarp.warp.ttl_msec, this.json_msgEngage.engage.rtt_msec);
323
- logr_.log(l_.PROTOCOL_STATE, () => [`StateEngage: evt_AckEngage.dt@${state_new.evt_AckEngage.dt}, msgWarp.dt@${Date.parse(json_msgWarp.dt)} + ${timeout_ms}`])
324
- if (state_new.evt_AckEngage.dt >= Date.parse(json_msgWarp.dt) + timeout_ms)
325
- return false;
326
-
327
- return true;
328
- }
329
- }
330
-
331
- class StateAckWarp extends StateState {
332
- constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
333
- get evt_AckWarp() { return this.event }
334
- get json_msgAckWarp() { return this.json_msg }
335
- canChangeState(state_new : StateState) {
336
- if (false === state_new instanceof StateEngage)
337
- return false;
338
-
339
- if (! this.json_msgAckWarp.ack.ok)
340
- return false;
341
-
342
- if (this.json_msgAckWarp._cause.warp.instantaneous)
343
- return false;
344
-
345
- // The Ack gets to live for THE ACK'S creation time + TTL*2 + STT
346
- // +STT, so lines up with the Engage timeout
347
- // - Engage: T0 +2TTL +RTT; RTT= STT+STT
348
- // - AckWarp: TAckWarp +2TLL +STT; TAckWarp= T0 +STT;
349
- // - STT: Date of the Ack minus date of the Warp.
350
- const timeout_ms= time_ttl_rtt_(this.json_msgAckWarp._cause.warp.ttl_msec) + Date.parse(this.json_msgAckWarp.dt) - Date.parse(this.json_msgAckWarp._cause.dt);
351
- logr_.log(l_.PROTOCOL_STATE, () => [`StateAckWarp: evt_Engage.dt@${state_new.evt_Engage.dt}, msgAckWarp.dt@${Date.parse(this.json_msgAckWarp.dt)} + ${timeout_ms}`])
352
- if (state_new.evt_Engage.dt >= Date.parse(this.json_msgAckWarp.dt) + timeout_ms)
353
- return false;
354
-
355
- return true;
356
- }
357
- }
358
-
359
- class StateWarp extends StateState {
360
- constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
361
- get evt_Warp() { return this.event }
362
- get json_msgWarp() { return this.json_msg }
363
- canChangeState(state_new : StateState) {
364
- if (false === state_new instanceof StateAckWarp)
365
- return false;
366
-
367
- // The Warp gets to live for THE WARP'S creation time + TTL*2
368
- const timeout_ms= time_ttl_rtt_(this.json_msgWarp.warp.ttl_msec);
369
- logr_.log(l_.PROTOCOL_STATE, () => [`StateWarp: evt_AckWarp.dt@${state_new.evt_AckWarp.dt}, msgWarp.dt@${Date.parse(this.json_msgWarp.dt)} + ${timeout_ms}`])
370
- if (state_new.evt_AckWarp.dt >= Date.parse(this.json_msgWarp.dt) + timeout_ms)
371
- return false;
372
-
373
- return true;
374
- }
375
- }
376
-
377
- class StateINVALID extends StateState {
378
- constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
379
- canChangeState(_state_new : StateState) {
380
- // INVALID can't transition to any state
381
- return false;
382
- }
383
- }
384
-
385
- class StateInitialState extends StateState {
386
- constructor() { super(null, null); }
387
- canChangeState(state_new : StateState) {
388
- if (false === state_new instanceof StateWarp)
389
- return false;
390
-
391
- // The NEWLY created Warp only gets to live for its creation time + TTL
392
- const timeout_ms= state_new.json_msgWarp.warp.ttl_msec;
393
- logr_.log(l_.PROTOCOL_STATE, () => [`StateInitialState: evt_Warp.dt@${state_new.evt_Warp.dt}, msgWarp.dt@${Date.parse(state_new.json_msgWarp.dt)} + ${timeout_ms}`])
394
- if (state_new.evt_Warp.dt >= Date.parse(state_new.json_msgWarp.dt) + timeout_ms)
395
- return false;
396
-
397
- return true;
398
- }
399
- }
400
-
401
- //----
402
-
403
- class ProtocolStateState {
404
- private _state : StateState;
405
-
406
- constructor(state_initial? : StateState) {
407
- this.state = state_initial || new StateInitialState();
408
- }
409
-
410
- set state(state_new : StateState) {
411
- if (! (state_new instanceof StateState)) {
412
- throw new Error("initState must be an instance of StateState or its subclasses");
413
- }
414
- this._state = state_new;
415
- if (state_new && state_new.protocol !== this) {
416
- state_new.protocol = this;
417
- }
418
- }
419
- get state() : StateState {
420
- return this._state;
421
- }
422
-
423
- canChangeState(state_new : StateState) : boolean {
424
- return this._state.canChangeState(state_new);
425
- }
426
- }
427
-
428
- //-------------------------------------------------------------------------------------------------
429
-
430
- class TwoPhW_EventLog {
431
- private _eventLog : EventLog;
432
-
433
- constructor(eventLog : EventLog) {
434
- this._eventLog = eventLog;
435
- }
436
-
437
- _warp(json_msg) {
438
- const b_Ack = json_msg.ack !== undefined;
439
- const json = b_Ack ? json_msg["_cause"] : json_msg;
440
-
441
- if (json.warp) {
442
- return {
443
- str_type: `2PhW[JSON_Msg${b_Ack ? 'Ack' : ''}Warp]`,
444
- json_msgWarp: json
445
- };
446
- }
447
- if (json.engage) {
448
- return {
449
- str_type: `2PhW[JSON_Msg${b_Ack ? 'Ack' : ''}Engage]`,
450
- json_msgWarp: json["_cause"]
451
- };
452
- }
453
- return { str_type: null, json_msgWarp: null }; // Explicit default for invalid cases
454
- }
455
-
456
- // _addEvent(msg: t_msg, json_msg : JSON_Msg, timeout_ms? : number, timeout_callback? : ( args? : {idx_event : number, event : EventMinimal} ) => {}) {
457
- _addEvent(msg: t_msg, json_msg, timeout_ms? : number, timeout_callback? : () => void) {
458
- const { str_type, json_msgWarp }= this._warp(json_msg);
459
- const { idx }= this._eventLog.add_Event(str_type, json_msgWarp.warp.id, {msg, json_msg}, timeout_ms, timeout_callback);
460
- logr_.log(l_.PROTOCOL_STATE, () => [`_addEvent: [${idx}] timeout:${Date.now()}+${timeout_ms} `, json_msg]);
461
- }
462
-
463
- _dropEvent(json_msg) {
464
- const { json_msgWarp }= this._warp(json_msg);
465
- if (! json_msgWarp)
466
- return;
467
- this._eventLog.add_Event('2PhW[DROPPED!]', json_msgWarp.warp.id, json_msg);
468
- }
469
-
470
- _cancelTimeout(idx_event) {
471
- logr_.log(l_.PROTOCOL_STATE, () => [`_cancelTimeout: [${idx_event}] timeout cancelled`]);
472
- this._eventLog.cancel_timeout(idx_event);
473
- }
474
-
475
- traverse_State(json_msgWarp) {
476
- const protocolState = new ProtocolStateState();
477
-
478
- const arr_evts= this._eventLog.get_Events_by_id(json_msgWarp.warp.id, k_TTL);
479
- logr_.log(l_.EVENTS, () => ['traverse_State: arr_evts: ', arr_evts]);
480
- //TODO: what is the right TTL? should it be a constant or calculated
481
-
482
- for (let i = arr_evts.length - 1; i >= 0; i--) {
483
- const { idx, evt } = arr_evts[i];
484
-
485
- const json_msg= evt.data.json_msg;
486
- if (! JSON_MsgWarp.compare(json_msgWarp, this._warp(json_msg).json_msgWarp) )
487
- protocolState.state.changeState( new StateINVALID(idx, evt) );
488
-
489
- switch(evt.type) {
490
- case '2PhW[JSON_MsgWarp]' :
491
- protocolState.state.changeState( new StateWarp(idx, evt) );
492
- break;
493
- case '2PhW[JSON_MsgAckWarp]' :
494
- protocolState.state.changeState( new StateAckWarp(idx, evt) );
495
- break;
496
- case '2PhW[JSON_MsgEngage]' :
497
- protocolState.state.changeState( new StateEngage(idx, evt) );
498
- break;
499
- case '2PhW[JSON_MsgAckEngage]' :
500
- protocolState.state.changeState( new StateAckEngage(idx, evt) );
501
- break;
502
- default :
503
- break;
504
- }
505
-
506
- logr_.log(l_.PROTOCOL_STATE, () => ['traverse_State: type,state: ',
507
- evt.type,
508
- (protocolState.state.json_msg.ack?.ok === false) ? '--NACK--' : '',
509
- protocolState.state
510
- ]);
511
- }
512
- return protocolState;
513
- }
514
-
515
- }
516
-
517
- class TwoPhW {
518
- private _2PhW_eventLog : TwoPhW_EventLog;
519
- private _config : Config;
520
-
521
- constructor(eventLog : EventLog) {
522
- this._2PhW_eventLog = new TwoPhW_EventLog(eventLog);
523
- this._config= new Config();
524
- }
525
-
526
- get config() : Config {
527
- return this._config;
528
- }
529
-
530
- get eventLog() : TwoPhW_EventLog {
531
- return this._2PhW_eventLog;
532
- }
533
-
534
- //-------------------------------------------------------------------------------------------------
535
-
536
- _handler_msgOptions(cfg, msg, json_msgOptions) : boolean
537
- {
538
- logr_.log(l_.HANDLERS, () => ['handler_msgOptions_: ...']);
539
-
540
- /*
541
- if (! validate_Options_delay_(json_msgOptions.options))
542
- return false;
543
-
544
- if (JSON_MsgWarp.validate(json_msgOptions._cause)) {
545
- const json_msgWarp= json_msgOptions._cause;
546
-
547
- const ctx= get_ctx(json_msgWarp.id);
548
- if (!ctx )
549
- return false;
550
-
551
- const ttl_msec= json_msgOptions.options.ttl_msec_incr[0];
552
- const ttl_incr= json_msgOptions.options.ttl_msec_incr[1];
553
-
554
- //TODO: double check ttl_msec is the same as current accummulated ttl for idempotence.
555
-
556
- logr_.log(l_.HANDLERS, () => ['handler_msgOptions_: ', json_msgOptions]);
557
-
558
- ctx.protocol.delayTimeout(ttl_incr);
559
-
560
- if (cfg._callback_msgOptions)
561
- return cfg._callback_msgOptions(msg, json_msgOptions);
562
-
563
- return true;
564
- }
565
- */
566
-
567
- return false;
568
- }
569
-
570
- //-------------------------------------------------------------------------------------------------
571
- // sender Source (src)
572
-
573
- register_msgWarp(msg : t_msg, json_msgWarp) : boolean
574
- {
575
- logr_.log(l_.SENDER, () => ['register_msgWarp: ', json_msgWarp]);
576
-
577
- const protocolState= this.eventLog.traverse_State(json_msgWarp);
578
- const b_changeState= protocolState.canChangeState( new StateWarp(null, {
579
- dt: Date.now(),
580
- data: { msg, json_msg: json_msgWarp }
581
- }) );
582
-
583
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['register_msgWarp: protocolState.canChangeState ', b_changeState]);
584
- if (! b_changeState)
585
- return false;
586
-
587
- const timeout_ms= time_ttl_rtt_(json_msgWarp.warp.ttl_msec);
588
- const elapsed_ms= Date.now() - Date.parse(json_msgWarp.dt);
589
-
590
- this.eventLog._addEvent(msg, json_msgWarp, timeout_ms-elapsed_ms, () => { // pass { _idx, _evt}?
591
- this.config._callback_msg_sent_expired(msg, json_msgWarp);
592
- });
593
- }
594
-
595
- _handler_msgAckWarp(msg : t_msg, json_msgAckWarp) : boolean
596
- {
597
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckWarp: ', json_msgAckWarp]);
598
-
599
- const json_msgWarp= json_msgAckWarp._cause;
600
-
601
- const protocolState= this.eventLog.traverse_State(json_msgWarp);
602
- const b_changeState= protocolState.canChangeState( new StateAckWarp(null, {
603
- dt: Date.now(),
604
- data: { msg, json_msg: json_msgAckWarp }
605
- }) );
606
-
607
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckWarp: protocolState.canChangeState ', b_changeState]);
608
- if (! b_changeState)
609
- return false;
610
-
611
- this.eventLog._cancelTimeout(protocolState.state.idx_event);
612
- this.eventLog._addEvent(msg, json_msgAckWarp);
613
- return this.config._callback_msgAckWarp(msg, json_msgAckWarp);
614
- }
615
-
616
- register_msgEngage(msg : t_msg, json_msgEngage) : boolean
617
- {
618
- logr_.log(l_.SENDER, () => ['register_msgEngage: ', json_msgEngage]);
619
-
620
- const json_msgWarp= json_msgEngage._cause;
621
-
622
- const protocolState= this.eventLog.traverse_State(json_msgWarp);
623
- const b_changeState = protocolState.canChangeState( new StateEngage(null, {
624
- dt: Date.now(),
625
- data : { msg, json_msg: json_msgEngage }
626
- }) );
627
-
628
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['register_msgEngage: protocolState.canChangeState ', b_changeState]);
629
- if (! b_changeState)
630
- return false;
631
-
632
- const timeout_ms= time_ttl_rtt_(json_msgWarp.warp.ttl_msec, json_msgEngage.engage.rtt_msec);
633
- const elapsed_ms= Date.now() - Date.parse(json_msgWarp.dt);
634
-
635
- this.eventLog._addEvent(msg, json_msgEngage, timeout_ms-elapsed_ms, () => {
636
- this.config._callback_msg_sent_expired(msg, json_msgEngage);
637
- });
638
- }
639
-
640
- _handler_msgAckEngage(msg : t_msg, json_msgAckEngage) : boolean
641
- {
642
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckEngage: ', json_msgAckEngage]);
643
-
644
- const json_msgWarp= json_msgAckEngage._cause._cause;
645
-
646
- const protocolState= this.eventLog.traverse_State(json_msgWarp);
647
- const b_changeState= protocolState.canChangeState( new StateAckEngage(null, {
648
- dt: Date.now(),
649
- data : { msg, json_msg: json_msgAckEngage }
650
- }) );
651
-
652
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckEngage_: protocolState.canChangeState ', b_changeState]);
653
- if (! b_changeState)
654
- return false;
655
-
656
- this.eventLog._cancelTimeout(protocolState.state.idx_event);
657
- this.eventLog._addEvent(msg, json_msgAckEngage);
658
- return this.config._callback_msgAckEngage(msg, json_msgAckEngage)
659
- }
660
-
661
- //-------------------------------------------------------------------------------------------------
662
- // receiver Destination (dst)
663
-
664
- _handler_msgWarp(msg : t_msg, json_msgWarp) : boolean
665
- {
666
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_msgWarp: ', json_msgWarp]);
667
-
668
- const protocolState= this.eventLog.traverse_State(json_msgWarp);
669
- const b_changeState= protocolState.canChangeState( new StateWarp(null, {
670
- dt: Date.now(),
671
- data: { msg, json_msg: json_msgWarp }
672
- }) );
673
-
674
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_msgWarp: protocolState.canChangeState: ', b_changeState]);
675
- if (! b_changeState)
676
- return false;
677
-
678
- this.eventLog._addEvent(msg, json_msgWarp);
679
- return this.config._callback_msgWarp(msg, json_msgWarp)
680
- }
681
-
682
- register_msgAckWarp(msg: t_msg, json_msgAckWarp) : boolean
683
- {
684
- logr_.log(l_.RECVER, () => ['register_msgAckWarp: ', json_msgAckWarp]);
685
-
686
- const json_msgWarp= json_msgAckWarp._cause;
687
-
688
- const protocolState= this.eventLog.traverse_State(json_msgWarp);
689
- const b_changeState= protocolState.canChangeState( new StateAckWarp(null, {
690
- dt: Date.now(),
691
- data: { msg, json_msg: json_msgAckWarp }
692
- }) );
693
-
694
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['register_msgAckWarp: protocolState.canChangeState: ', b_changeState]);
695
- if (! b_changeState)
696
- return false;
697
-
698
- const elapsed_ms= Date.now() - Date.parse(json_msgAckWarp.dt);
699
- const timeout_ms= time_ttl_rtt_(json_msgWarp.warp.ttl_msec) + Date.parse(json_msgAckWarp.dt) - Date.parse(json_msgWarp.dt);
700
-
701
- this.eventLog._addEvent(msg, json_msgAckWarp, timeout_ms-elapsed_ms, () => { // pass { _idx, _evt} ?
702
- this.config._callback_msg_sent_expired(msg, json_msgAckWarp);
703
- });
704
- }
705
-
706
- _handler_msgEngage(msg : t_msg, json_msgEngage) : boolean
707
- {
708
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_msgEngage: ', json_msgEngage]);
709
-
710
- const json_msgWarp= json_msgEngage._cause;
711
-
712
- const protocolState= this.eventLog.traverse_State(json_msgWarp);
713
- const b_changeState= protocolState.canChangeState( new StateEngage(null, {
714
- dt: Date.now(),
715
- data: { msg, json_msg: json_msgEngage }
716
- }) );
717
-
718
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_msgEngage: protocolState.canChangeState: ', b_changeState]);
719
- if (! b_changeState)
720
- return false;
721
-
722
- this.eventLog._cancelTimeout(protocolState.state.idx_event);
723
- this.eventLog._addEvent(msg, json_msgEngage);
724
- return this.config._callback_msgEngage(msg, json_msgEngage)
725
- }
726
-
727
- register_msgAckEngage(msg : t_msg, json_msgAckEngage) : boolean
728
- {
729
- logr_.log(l_.RECVER, () => ['register_msgAckEngage: ', json_msgAckEngage]);
730
-
731
- const json_msgWarp= json_msgAckEngage._cause._cause;
732
-
733
- const protocolState= this.eventLog.traverse_State(json_msgWarp);
734
- const b_changeState= protocolState.canChangeState( new StateAckEngage(null, {
735
- dt: Date.now(),
736
- data: { msg, json_msg: json_msgAckEngage }
737
- }) );
738
-
739
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['register_msgAckEngage: protocolState.canChangeState: ', b_changeState]);
740
- if (! b_changeState)
741
- return false;
742
-
743
- this.eventLog._addEvent(msg, json_msgAckEngage);
744
- }
745
-
746
- //-------------------------------------------------------------------------------------------------
747
-
748
- handler_json_msgAck(msg : t_msg, json_msgAck) : boolean
749
- {
750
- logr_.log(l_.HANDLERS, () => ['TwoPhW: handler_json_msgAck: ', json_msgAck]);
751
-
752
- if (JSON_MsgAckWarp.validate(json_msgAck) && this._handler_msgAckWarp(msg, json_msgAck) )
753
- return true;
754
-
755
- if (JSON_MsgAckEngage.validate(json_msgAck) && this._handler_msgAckEngage(msg, json_msgAck) )
756
- return true;
757
-
758
- return false;
759
- }
760
-
761
- handler_json_msgEffect(msg : t_msg, json_msgEffect) : boolean
762
- {
763
- logr_.log(l_.HANDLERS, () => ['TwoPhW: handler_json_msgEffect: ', json_msgEffect]);
764
-
765
- // if (JSON_MsgAck.validate(json_msgEffect) && this.handler_json_msgAck(msg, json_msgEffect) )
766
- // return true;
767
-
768
- if (JSON_MsgEngage.validate(json_msgEffect) && this._handler_msgEngage(msg, json_msgEffect) )
769
- return true;
770
-
771
- // if (JSON_MsgOptions.validate(json_msg) && this.handler_msgOptions_(this._config, msg, json_msg))
772
- // return true;
773
-
774
- return false;
775
- }
776
-
777
- handler_json_msg(msg : t_msg, json_msg) : boolean
778
- {
779
- logr_.log(l_.HANDLERS, () => ['TwoPhW: handler_json_msg: ', json_msg]);
780
-
781
- if (JSON_MsgWarp.validate(json_msg) && this._handler_msgWarp(msg, json_msg) )
782
- return true;
783
-
784
- // https://attacomsian.com/blog/javascript-iterate-objects
785
- // Object.keys(json_msg).forEach((key, index) => {
786
- // if (key == 'dt')
787
- // return;
788
- // if (key == 'referer')
789
- // return;
790
- // console.log(`${key}: ${json_msg[key]}`);
791
- // });
792
-
793
- return false;
794
- }
795
-
796
- // handler_json(msg : t_msg, json) : boolean
797
- // {
798
- // logr_.log(l_.HANDLERS, () => ['handler_json: ', json]);
799
-
800
- // if (JSON_MsgEffect.validate(json) && this.handler_json_msgEffect(msg, json) )
801
- // return true;
802
-
803
- // if (JSON_Msg.validate(json) && this.handler_json_msg(msg, json) )
804
- // return true;
805
-
806
- // return false;
807
- // }
808
-
809
- };
810
-
811
- //-------------------------------------------------------------------------------------------------
812
-
813
- export {
814
- time_ttl_rtt_ as t_ttl_rtt,
815
- TwoPhW,
816
- JSON_MsgOptions,
817
- JSON_MsgWarp,
818
- JSON_MsgEngage,
819
- JSON_MsgAckWarp,
820
- JSON_MsgAckEngage,
821
- logr_ as logr,
822
- JSON_Msg,
823
- JSON_MsgEffect,
824
- JSON_MsgAck,
825
- // -----
826
- StateAckEngage,
827
- StateEngage,
828
- StateAckWarp,
829
- StateWarp,
830
- StateINVALID,
831
- StateInitialState
832
- };
833
-
1
+
2
+ // The wire interface (validators, constructors, VERSION) is GENERATED by iface-gen from schema_TwoPhW.json
3
+ // -- in the HOST's project, never here. This package has no interface and no schema of its own: the host
4
+ // hands its generated interface to protocol_TwoPhW() (at the bottom of this file), which is what binds
5
+ // the two. So the package and the host cannot disagree about the wire, the version included.
6
+
7
+ // import { v4 as uuidv4 } from 'uuid'; // uuid is already a dep of JSON_Msg, so why not
8
+ import { LOGR, lRef, l_merge, l_array, l_concat, l_LL } from '@knev/bitlogr';
9
+ import { JSON_Msg, JSON_Eff, JSON_Ack, JSON_Hold, logr as logr_json_msg_ } from '@rootintf/json-msg'
10
+
11
+ import { EventLog, logr as logr_evtlog_ } from '@rootintf/eventlog'
12
+
13
+ type t_msg = string;
14
+
15
+ interface EventMinimal {
16
+ dt : number;
17
+ // b_sent: the step is one THIS participant sent (register_*), not one it received (handler_json_*)
18
+ data : { msg : t_msg, json_msg, b_sent : boolean };
19
+ }
20
+
21
+ // interface Event extends Required<EventMinimal> {
22
+ // type : string;
23
+ // id : string | number;
24
+ // timeout_id : NodeJS.Timeout | null;
25
+ // };
26
+
27
+ //-------------------------------------------------------------------------------------------------
28
+
29
+ const obj_labels_merge_= l_merge(logr_evtlog_.lref.get(), logr_json_msg_.lref.get()); // VALIDATION : 4
30
+ const obj_labels_concat_= l_concat(obj_labels_merge_, l_array(['HANDLERS', 'DROPS', 'PROTOCOL_STATE', 'RECVER', 'SENDER']) );
31
+
32
+ const lref_= lRef(obj_labels_concat_);
33
+ logr_json_msg_.lref= lref_;
34
+ logr_evtlog_.lref= lref_;
35
+
36
+ const LOGR_= LOGR.get_instance();
37
+ const logr_= LOGR_.create(); // don't let create() make a new ref, assign lref_ from here
38
+ logr_.lref= lref_;
39
+
40
+ const l_= logr_.l;
41
+
42
+ //-------------------------------------------------------------------------------------------------
43
+
44
+ type t_callback = (msg : t_msg, json_msg) => boolean;
45
+ type t_callback_void = (msg : t_msg, json_msg) => void;
46
+
47
+ class Config {
48
+ // A step's callback is what makes the step this participant's to handle: with no callback set,
49
+ // the step's handler refuses it (returns false) before anything is logged. Every participant on
50
+ // the ME hears every exchange, so "no callback" is the normal case for a role it does not play.
51
+ public _callback_msgWarp : t_callback | null = null;
52
+ public _callback_effEngage : t_callback | null = null;
53
+ public _callback_ackWarp : t_callback | null = null;
54
+ public _callback_ackEngage : t_callback | null = null;
55
+ // Optional, and not what makes a hold ours (that is the sender role, _callback_ackWarp): a hold
56
+ // moves the Warp's expiry whether or not anybody wants to be told about it.
57
+ public _callback_holdWarp : t_callback | null = null;
58
+ // "a step I sent was never answered inside its window", one per role: the sender's fires for its
59
+ // Warp / Engage, the receiver's for its AckWarp. A participant playing both roles keeps both.
60
+ public _callback_sender_sent_expired : t_callback_void
61
+ public _callback_receiver_sent_expired : t_callback_void
62
+
63
+ constructor() {
64
+ this._callback_sender_sent_expired = (_msg : t_msg, _json_msg) => {
65
+ console.assert(false, '_callback_sender_sent_expired uninitialized');
66
+ };
67
+ this._callback_receiver_sent_expired = (_msg : t_msg, _json_msg) => {
68
+ console.assert(false, '_callback_receiver_sent_expired uninitialized');
69
+ };
70
+ }
71
+
72
+ receiver(callback_msgWarp : t_callback, callback_effEngage : t_callback, callback_msg_sent_expired : t_callback_void) {
73
+ this._callback_msgWarp= callback_msgWarp;
74
+ this._callback_effEngage= callback_effEngage;
75
+ this._callback_receiver_sent_expired= callback_msg_sent_expired;
76
+ }
77
+ // callback_holdWarp: the receiver says it is working on our Warp (what it waits for, how far it is)
78
+ sender(callback_ackWarp : t_callback, callback_ackEngage : t_callback, callback_msg_sent_expired : t_callback_void, callback_holdWarp : t_callback | null = null) {
79
+ this._callback_ackWarp= callback_ackWarp;
80
+ this._callback_ackEngage= callback_ackEngage;
81
+ this._callback_sender_sent_expired= callback_msg_sent_expired;
82
+ this._callback_holdWarp= callback_holdWarp;
83
+ }
84
+ }
85
+
86
+ // var config = (function() {
87
+ // let _options;
88
+
89
+ // return {
90
+ // get callback_Abort() { return _options.callback_Abort; },
91
+
92
+ // set options(obj) {
93
+ // _options= obj;
94
+ // if (_options.logr) // && options_.logr[ __name(l_) ] )
95
+ // LOGR_.toggled= _options.logr
96
+ // }
97
+ // }
98
+ // })();
99
+
100
+ //-------------------------------------------------------------------------------------------------
101
+
102
+ // Timing. Every step is timed from the message it answers, by that message's own dt; no step looks further
103
+ // back than the message before it. Two durations:
104
+ // - TTL (warp.ttl_msec, set by the sender): the longest a message may take to travel ONE way. Network only.
105
+ // - the lease (hold.ttl_msec of a JSON_HoldWarp, set by the receiver): "my next word comes within this long".
106
+ // Work only.
107
+ // A message that hands the turn over (Warp, AckWarp, Engage) is answered within its dt + TTL*2, there and
108
+ // back. After a hold the next word is due within the hold's dt + its lease + TTL. Of several holds the one
109
+ // that ends latest counts; nothing is added up. The exchange as a whole has no limit: it stays open for as
110
+ // long as leases are renewed.
111
+
112
+ // the window in which a message that hands the turn over is answered: TTL there, TTL back
113
+ function window_msec_(nr_ttl_msec: number): number {
114
+ return nr_ttl_msec *2;
115
+ }
116
+
117
+ // Are these the same Warp? The identity of an exchange: the Warp's own dt, its warp.id and its sender.
118
+ function compare_msgWarp_(json_L, json_R) : boolean {
119
+ if (json_L.dt !== json_R.dt)
120
+ return false;
121
+ if (json_L.warp.id !== json_R.warp.id)
122
+ return false;
123
+ if (json_L.referer[0] !== json_R.referer[0])
124
+ return false;
125
+ if (json_L.referer[1] !== json_R.referer[1])
126
+ return false;
127
+ return true;
128
+ }
129
+
130
+ //-------------------------------------------------------------------------------------------------
131
+ // States
132
+
133
+ class StateState {
134
+ private _idx_event : number;
135
+ private _event : EventMinimal;
136
+ protected _statekeeper : ProtocolStateState;
137
+
138
+ constructor(idx_event : number, event : EventMinimal) {
139
+ this._statekeeper = null;
140
+ this._idx_event = idx_event;
141
+ this._event = event;
142
+ }
143
+ get protocol() {
144
+ return this._statekeeper;
145
+ }
146
+ set protocol(parent) {
147
+ this._statekeeper = parent;
148
+ }
149
+ get idx_event() {
150
+ return this._idx_event;
151
+ }
152
+ get event() {
153
+ return this._event;
154
+ }
155
+ get json_msg() {
156
+ return this._event.data.json_msg;
157
+ }
158
+ changeState(state_new : StateState) {
159
+ if (this.canChangeState(state_new))
160
+ this.protocol.state = state_new;
161
+ else
162
+ this.protocol.state = new StateINVALID(state_new._idx_event, state_new._event);
163
+ }
164
+ canChangeState(_state_new : StateState) : boolean {
165
+ throw new Error("Subclass must implement canChangeState()");
166
+ }
167
+ }
168
+
169
+ class StateAckEngage extends StateState {
170
+ constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
171
+ get evt_AckEngage() { return this.event }
172
+ get json_ackEngage() { return this.json_msg }
173
+ canChangeState(_state_new : StateState) {
174
+ return false;
175
+ }
176
+ }
177
+
178
+ class StateEngage extends StateState {
179
+ constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
180
+ get evt_Engage() { return this.event }
181
+ get json_effEngage() { return this.json_msg }
182
+ canChangeState(state_new : StateState) {
183
+ if (false === state_new instanceof StateAckEngage)
184
+ return false;
185
+
186
+ // The AckEngage is accepted until THE ENGAGE'S creation time + TTL*2
187
+ const timeout_ms= window_msec_(this.json_effEngage._cause.warp.ttl_msec);
188
+ logr_.log(l_.PROTOCOL_STATE, () => [`StateEngage: evt_AckEngage.dt@${state_new.evt_AckEngage.dt}, effEngage.dt@${Date.parse(this.json_effEngage.dt)} + ${timeout_ms}`])
189
+ if (state_new.evt_AckEngage.dt >= Date.parse(this.json_effEngage.dt) + timeout_ms)
190
+ return false;
191
+
192
+ return true;
193
+ }
194
+ }
195
+
196
+ // Can a JSON_EffEngage follow this JSON_AckWarp? Not after a nack (it ends the exchange), and not
197
+ // after the ack of an instantaneous warp (single phase: the ack concludes it).
198
+ function isEngageAwaited_(json_ackWarp) : boolean {
199
+ return !! json_ackWarp.ack.ok && ! json_ackWarp._cause.warp.instantaneous;
200
+ }
201
+
202
+ class StateAckWarp extends StateState {
203
+ constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
204
+ get evt_AckWarp() { return this.event }
205
+ get json_ackWarp() { return this.json_msg }
206
+ canChangeState(state_new : StateState) {
207
+ if (false === state_new instanceof StateEngage)
208
+ return false;
209
+
210
+ if (! isEngageAwaited_(this.json_ackWarp))
211
+ return false;
212
+
213
+ // The Engage is accepted until THE ACK'S creation time + TTL*2. Nothing of phase 1 enters it: how
214
+ // long the receiver took to acknowledge the Warp is not this phase's business.
215
+ const timeout_ms= window_msec_(this.json_ackWarp._cause.warp.ttl_msec);
216
+ logr_.log(l_.PROTOCOL_STATE, () => [`StateAckWarp: evt_Engage.dt@${state_new.evt_Engage.dt}, msgAckWarp.dt@${Date.parse(this.json_ackWarp.dt)} + ${timeout_ms}`])
217
+ if (state_new.evt_Engage.dt >= Date.parse(this.json_ackWarp.dt) + timeout_ms)
218
+ return false;
219
+
220
+ return true;
221
+ }
222
+ }
223
+
224
+ class StateWarp extends StateState {
225
+ // where the latest lease of a JSON_HoldWarp moved the end of the window to (epoch msec), and the event
226
+ // whose timer now guards it. null: no hold moved it.
227
+ private _nr_deadline_lease : number | null = null;
228
+ private _idx_event_timer : number | null = null;
229
+
230
+ constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
231
+ get evt_Warp() { return this.event }
232
+ get json_msgWarp() { return this.json_msg }
233
+
234
+ // Where a JSON_HoldWarp puts the end of the window: its OWN dt + its lease (hold.ttl_msec) + the
235
+ // warp's TTL (one for the next message to travel). NaN when its dt does not read: a lease with no anchor.
236
+ static deadline_holdWarp(json_holdWarp) : number {
237
+ const nr_lease= JSON_Hold.lease_epoch_msec(json_holdWarp);
238
+ return (nr_lease === null) ? NaN : nr_lease + json_holdWarp._cause.warp.ttl_msec;
239
+ }
240
+
241
+ // The last instant the JSON_AckWarp is accepted: THE WARP'S creation time + TTL*2, or where a hold
242
+ // moved it, whichever is later. The latest counts; nothing is added up.
243
+ get deadline_msec() : number {
244
+ const nr_deadline= Date.parse(this.json_msgWarp.dt) + window_msec_(this.json_msgWarp.warp.ttl_msec);
245
+ return (this._nr_deadline_lease !== null && this._nr_deadline_lease > nr_deadline) ? this._nr_deadline_lease : nr_deadline;
246
+ }
247
+
248
+ // the event that holds this Warp's expiry timer: the Warp's own, or the hold that last moved the window
249
+ get idx_event_timer() : number {
250
+ return (this._idx_event_timer !== null) ? this._idx_event_timer : this.idx_event;
251
+ }
252
+
253
+ // A hold on this Warp, logged as event idx_event. Returns whether it moved the end of the window:
254
+ // not when its lease ends no later than the window in force, nor when its dt does not read.
255
+ lease(idx_event : number, json_holdWarp) : boolean {
256
+ const nr_deadline= StateWarp.deadline_holdWarp(json_holdWarp);
257
+ if (! (nr_deadline > this.deadline_msec))
258
+ return false;
259
+
260
+ this._nr_deadline_lease= nr_deadline;
261
+ this._idx_event_timer= idx_event;
262
+ return true;
263
+ }
264
+
265
+ canChangeState(state_new : StateState) {
266
+ if (false === state_new instanceof StateAckWarp)
267
+ return false;
268
+
269
+ logr_.log(l_.PROTOCOL_STATE, () => [`StateWarp: evt_AckWarp.dt@${state_new.evt_AckWarp.dt}, deadline@${this.deadline_msec}`])
270
+ if (state_new.evt_AckWarp.dt >= this.deadline_msec)
271
+ return false;
272
+
273
+ return true;
274
+ }
275
+ }
276
+
277
+ class StateINVALID extends StateState {
278
+ constructor(idx_event : number, event : EventMinimal) { super(idx_event, event); }
279
+ canChangeState(_state_new : StateState) {
280
+ // INVALID can't transition to any state
281
+ return false;
282
+ }
283
+ }
284
+
285
+ class StateInitialState extends StateState {
286
+ constructor() { super(null, null); }
287
+ canChangeState(state_new : StateState) {
288
+ if (false === state_new instanceof StateWarp)
289
+ return false;
290
+
291
+ // The NEWLY created Warp only gets to live for its creation time + TTL
292
+ const timeout_ms= state_new.json_msgWarp.warp.ttl_msec;
293
+ logr_.log(l_.PROTOCOL_STATE, () => [`StateInitialState: evt_Warp.dt@${state_new.evt_Warp.dt}, msgWarp.dt@${Date.parse(state_new.json_msgWarp.dt)} + ${timeout_ms}`])
294
+ if (state_new.evt_Warp.dt >= Date.parse(state_new.json_msgWarp.dt) + timeout_ms)
295
+ return false;
296
+
297
+ return true;
298
+ }
299
+ }
300
+
301
+ //----
302
+
303
+ class ProtocolStateState {
304
+ private _state : StateState;
305
+
306
+ constructor(state_initial? : StateState) {
307
+ this.state = state_initial || new StateInitialState();
308
+ }
309
+
310
+ set state(state_new : StateState) {
311
+ if (! (state_new instanceof StateState)) {
312
+ throw new Error("initState must be an instance of StateState or its subclasses");
313
+ }
314
+ this._state = state_new;
315
+ if (state_new && state_new.protocol !== this) {
316
+ state_new.protocol = this;
317
+ }
318
+ }
319
+ get state() : StateState {
320
+ return this._state;
321
+ }
322
+
323
+ canChangeState(state_new : StateState) : boolean {
324
+ // Every window is measured from a message's own dt, and the schema only asks dt to be a string.
325
+ // A step whose dt does not read as a time has no window to be inside of: never legal. (Unchecked,
326
+ // it parses to NaN, every "is it past the deadline?" answers no, and it escapes all the windows.)
327
+ // Every logged step passed here, so the states can rely on the dt of the messages they wrap.
328
+ if (! Number.isFinite(Date.parse(state_new.json_msg.dt)))
329
+ return false;
330
+
331
+ // An exchange is a dialogue: a step we RECEIVE is only legal after a step we SENT, and vice
332
+ // versa. Every participant on the ME hears every exchange, so without this a warp we merely
333
+ // heard would be "answered" by the ack its real receiver sent, and we could answer our own step.
334
+ if (! (this._state instanceof StateInitialState) && this._state.event.data.b_sent === state_new.event.data.b_sent)
335
+ return false;
336
+
337
+ return this._state.canChangeState(state_new);
338
+ }
339
+ }
340
+
341
+ //-------------------------------------------------------------------------------------------------
342
+
343
+ const kstr_EVT_DROPPED_= '2PhW[DROPPED!]';
344
+ const kstr_EVT_HOLDWARP_= '2PhW[JSON_HoldWarp]';
345
+
346
+ class TwoPhW_EventLog {
347
+ private _eventLog : EventLog;
348
+
349
+ constructor(eventLog : EventLog) {
350
+ this._eventLog = eventLog;
351
+ }
352
+
353
+ _warp(json_msg) {
354
+ const b_Ack = json_msg.ack !== undefined;
355
+ const b_Hold = ! b_Ack && json_msg.hold !== undefined; // a message that carries both is an ack
356
+ const json = (b_Ack || b_Hold) ? json_msg["_cause"] : json_msg;
357
+
358
+ if (json.warp) {
359
+ return {
360
+ str_type: b_Ack ? '2PhW[JSON_AckWarp]' : (b_Hold ? kstr_EVT_HOLDWARP_ : '2PhW[JSON_MsgWarp]'),
361
+ json_msgWarp: json
362
+ };
363
+ }
364
+ if (json.engage) {
365
+ return {
366
+ str_type: b_Ack ? '2PhW[JSON_AckEngage]' : '2PhW[JSON_EffEngage]',
367
+ json_msgWarp: json["_cause"]
368
+ };
369
+ }
370
+ return { str_type: null, json_msgWarp: null }; // Explicit default for invalid cases
371
+ }
372
+
373
+ // _addEvent(msg: t_msg, json_msg : JSON_Msg, timeout_ms? : number, timeout_callback? : ( args? : {idx_event : number, event : EventMinimal} ) => {}) {
374
+ _addEvent(msg: t_msg, json_msg, b_sent : boolean, timeout_ms? : number, timeout_callback? : () => void) {
375
+ const { str_type, json_msgWarp }= this._warp(json_msg);
376
+ const { idx }= this._eventLog.add_Event(str_type, json_msgWarp.warp.id, {msg, json_msg, b_sent}, timeout_ms, timeout_callback);
377
+ logr_.log(l_.PROTOCOL_STATE, () => [`_addEvent: [${idx}] timeout:${Date.now()}+${timeout_ms} `, json_msg]);
378
+ }
379
+
380
+ // Record a message we refused, for forensics: under its exchange and in the shape of every other
381
+ // 2PhW event, but never a step -- traverse_State skips it.
382
+ _dropEvent(msg: t_msg, json_msg) {
383
+ const { json_msgWarp }= this._warp(json_msg);
384
+ if (! json_msgWarp)
385
+ return;
386
+ this._eventLog.add_Event(kstr_EVT_DROPPED_, json_msgWarp.warp.id, {msg, json_msg, b_sent: false});
387
+ }
388
+
389
+ _cancelTimeout(idx_event) {
390
+ logr_.log(l_.PROTOCOL_STATE, () => [`_cancelTimeout: [${idx_event}] timeout cancelled`]);
391
+ this._eventLog.cancel_timeout(idx_event);
392
+ }
393
+
394
+ traverse_State(json_msgWarp) {
395
+ const protocolState = new ProtocolStateState();
396
+
397
+ // Look back over the WHOLE exchange: to the Warp's own dt (+ TTL*2: a participant logs by its own
398
+ // clock). An exchange has no limit as a whole (holds keep it open for as long as they are renewed), so
399
+ // its age says nothing; whether it is still open is decided by its windows. A Warp whose dt does not
400
+ // read has no exchange to look back over, and is refused by every caller.
401
+ const nr_age_msec= Date.now() - Date.parse(json_msgWarp.dt);
402
+ const lookback_ms= window_msec_(json_msgWarp.warp.ttl_msec) + (Number.isFinite(nr_age_msec) ? Math.max(nr_age_msec, 0) : 0);
403
+ const arr_evts= this._eventLog.get_Events_by_id(json_msgWarp.warp.id, lookback_ms);
404
+
405
+ logr_.log(l_.EVENTS, () => ['traverse_State: arr_evts: ', arr_evts]);
406
+
407
+ for (let i = arr_evts.length - 1; i >= 0; i--) {
408
+ const { idx, evt } = arr_evts[i];
409
+
410
+ // a dropped message is not a step: not of this exchange, and it must not poison it either
411
+ // (it may well belong to ANOTHER exchange that reused the warp id -- that is why it was dropped)
412
+ if (evt.type === kstr_EVT_DROPPED_)
413
+ continue;
414
+
415
+ const json_msg= evt.data.json_msg;
416
+ if (! compare_msgWarp_(json_msgWarp, this._warp(json_msg).json_msgWarp) )
417
+ protocolState.state.changeState( new StateINVALID(idx, evt) );
418
+
419
+ switch(evt.type) {
420
+ case '2PhW[JSON_MsgWarp]' :
421
+ protocolState.state.changeState( new StateWarp(idx, evt) );
422
+ break;
423
+ case kstr_EVT_HOLDWARP_ :
424
+ // not a step: it changes no state, it moves the window of the Warp it is about
425
+ if (protocolState.state instanceof StateWarp)
426
+ protocolState.state.lease(idx, json_msg);
427
+ break;
428
+ case '2PhW[JSON_AckWarp]' :
429
+ protocolState.state.changeState( new StateAckWarp(idx, evt) );
430
+ break;
431
+ case '2PhW[JSON_EffEngage]' :
432
+ protocolState.state.changeState( new StateEngage(idx, evt) );
433
+ break;
434
+ case '2PhW[JSON_AckEngage]' :
435
+ protocolState.state.changeState( new StateAckEngage(idx, evt) );
436
+ break;
437
+ default :
438
+ break;
439
+ }
440
+
441
+ logr_.log(l_.PROTOCOL_STATE, () => ['traverse_State: type,state: ',
442
+ evt.type,
443
+ (protocolState.state.json_msg.ack?.ok === false) ? '--NACK--' : '',
444
+ protocolState.state
445
+ ]);
446
+ }
447
+ return protocolState;
448
+ }
449
+
450
+ }
451
+
452
+ class TwoPhW {
453
+ private _2PhW_eventLog : TwoPhW_EventLog;
454
+ private _config : Config;
455
+
456
+ constructor(eventLog : EventLog) {
457
+ this._2PhW_eventLog = new TwoPhW_EventLog(eventLog);
458
+ this._config= new Config();
459
+ }
460
+
461
+ get config() : Config {
462
+ return this._config;
463
+ }
464
+
465
+ get eventLog() : TwoPhW_EventLog {
466
+ return this._2PhW_eventLog;
467
+ }
468
+
469
+ //-------------------------------------------------------------------------------------------------
470
+ // The typed handlers (handler_json_<message>) are what the responder's base dispatch calls AFTER it
471
+ // validated the message as that type (generated: `JSON_AckWarp.validate(json_ack) &&
472
+ // this.handler_json_ackWarp(msg, json_ack)`). They do not validate again.
473
+
474
+ //-------------------------------------------------------------------------------------------------
475
+ // sender Source (src)
476
+
477
+ register_msgWarp(msg : t_msg, json_msgWarp) : boolean
478
+ {
479
+ logr_.log(l_.SENDER, () => ['register_msgWarp: ', json_msgWarp]);
480
+
481
+ const protocolState= this.eventLog.traverse_State(json_msgWarp);
482
+ const b_changeState= protocolState.canChangeState( new StateWarp(null, {
483
+ dt: Date.now(),
484
+ data: { msg, json_msg: json_msgWarp, b_sent: true }
485
+ }) );
486
+
487
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['register_msgWarp: protocolState.canChangeState ', b_changeState]);
488
+ if (! b_changeState)
489
+ return false;
490
+
491
+ // the first answer, a hold or the ack, is due within the Warp's dt + TTL*2
492
+ const timeout_ms= window_msec_(json_msgWarp.warp.ttl_msec);
493
+ const elapsed_ms= Date.now() - Date.parse(json_msgWarp.dt);
494
+
495
+ this.eventLog._addEvent(msg, json_msgWarp, true, timeout_ms-elapsed_ms, () => { // pass { _idx, _evt}?
496
+ this.config._callback_sender_sent_expired(msg, json_msgWarp);
497
+ });
498
+ return true;
499
+ }
500
+
501
+ handler_json_ackWarp(msg : t_msg, json_ackWarp) : boolean
502
+ {
503
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_ackWarp: ', json_ackWarp]);
504
+
505
+ // no callback for this step: not ours -- before anything is logged
506
+ if (! this.config._callback_ackWarp)
507
+ return false;
508
+
509
+ const json_msgWarp= json_ackWarp._cause;
510
+
511
+ const protocolState= this.eventLog.traverse_State(json_msgWarp);
512
+ const b_changeState= protocolState.canChangeState( new StateAckWarp(null, {
513
+ dt: Date.now(),
514
+ data: { msg, json_msg: json_ackWarp, b_sent: false }
515
+ }) );
516
+
517
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_ackWarp: protocolState.canChangeState ', b_changeState]);
518
+ if (! b_changeState)
519
+ return false;
520
+
521
+ // the Warp's own timer, or the one of the hold that last moved its window
522
+ this.eventLog._cancelTimeout((protocolState.state as StateWarp).idx_event_timer);
523
+ this.eventLog._addEvent(msg, json_ackWarp, false);
524
+ return this.config._callback_ackWarp(msg, json_ackWarp);
525
+ }
526
+
527
+ // The receiver says it is working on a Warp we sent and has not decided yet (JSON_HoldWarp). Not a step:
528
+ // the exchange stays where it is, waiting for the JSON_AckWarp. What changes is how long we wait for it:
529
+ // the expiry of the Warp moves to the end of the hold's lease.
530
+ handler_json_holdWarp(msg : t_msg, json_holdWarp) : boolean
531
+ {
532
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_holdWarp: ', json_holdWarp]);
533
+
534
+ // the sender role is not played here: not ours -- before anything is logged
535
+ if (! this.config._callback_ackWarp)
536
+ return false;
537
+
538
+ const json_msgWarp= json_holdWarp._cause;
539
+
540
+ // ours iff it is about a Warp WE sent that is still unanswered and still inside its window. Anything
541
+ // else (a Warp we only heard, one already acknowledged or expired) is somebody else's, or too late.
542
+ const state= this.eventLog.traverse_State(json_msgWarp).state;
543
+ if (! (state instanceof StateWarp) || ! state.event.data.b_sent)
544
+ return false;
545
+
546
+ const nr_now= Date.now();
547
+ if (nr_now >= state.deadline_msec)
548
+ return false;
549
+
550
+ const nr_deadline= StateWarp.deadline_holdWarp(json_holdWarp);
551
+ if (! Number.isFinite(nr_deadline))
552
+ return false; // a dt that does not read: a lease with no anchor
553
+
554
+ if (nr_deadline > state.deadline_msec) {
555
+ // the timer follows the window: the one in force is cancelled, this hold carries the new one.
556
+ // What expires is still the Warp: "the step I sent was never answered".
557
+ const { msg: msg_Warp, json_msg: json_msgWarp_sent }= state.event.data;
558
+ this.eventLog._cancelTimeout(state.idx_event_timer);
559
+ this.eventLog._addEvent(msg, json_holdWarp, false, nr_deadline - nr_now, () => {
560
+ this.config._callback_sender_sent_expired(msg_Warp, json_msgWarp_sent);
561
+ });
562
+ }
563
+ else
564
+ this.eventLog._addEvent(msg, json_holdWarp, false); // ends inside the window in force: logged, nothing moves
565
+
566
+ return this.config._callback_holdWarp ? this.config._callback_holdWarp(msg, json_holdWarp) : true;
567
+ }
568
+
569
+ register_effEngage(msg : t_msg, json_effEngage) : boolean
570
+ {
571
+ logr_.log(l_.SENDER, () => ['register_effEngage: ', json_effEngage]);
572
+
573
+ const json_msgWarp= json_effEngage._cause;
574
+
575
+ const protocolState= this.eventLog.traverse_State(json_msgWarp);
576
+ const b_changeState = protocolState.canChangeState( new StateEngage(null, {
577
+ dt: Date.now(),
578
+ data: { msg, json_msg: json_effEngage, b_sent: true }
579
+ }) );
580
+
581
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['register_effEngage: protocolState.canChangeState ', b_changeState]);
582
+ if (! b_changeState)
583
+ return false;
584
+
585
+ // the AckEngage is due within the Engage's own dt + TTL*2
586
+ const timeout_ms= window_msec_(json_msgWarp.warp.ttl_msec);
587
+ const elapsed_ms= Date.now() - Date.parse(json_effEngage.dt);
588
+
589
+ this.eventLog._addEvent(msg, json_effEngage, true, timeout_ms-elapsed_ms, () => {
590
+ this.config._callback_sender_sent_expired(msg, json_effEngage);
591
+ });
592
+ return true;
593
+ }
594
+
595
+ handler_json_ackEngage(msg : t_msg, json_ackEngage) : boolean
596
+ {
597
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_ackEngage: ', json_ackEngage]);
598
+
599
+ // no callback for this step: not ours -- before anything is logged
600
+ if (! this.config._callback_ackEngage)
601
+ return false;
602
+
603
+ const json_msgWarp= json_ackEngage._cause._cause;
604
+
605
+ const protocolState= this.eventLog.traverse_State(json_msgWarp);
606
+ const b_changeState= protocolState.canChangeState( new StateAckEngage(null, {
607
+ dt: Date.now(),
608
+ data: { msg, json_msg: json_ackEngage, b_sent: false }
609
+ }) );
610
+
611
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_ackEngage: protocolState.canChangeState ', b_changeState]);
612
+ if (! b_changeState)
613
+ return false;
614
+
615
+ this.eventLog._cancelTimeout(protocolState.state.idx_event);
616
+ this.eventLog._addEvent(msg, json_ackEngage, false);
617
+ return this.config._callback_ackEngage(msg, json_ackEngage)
618
+ }
619
+
620
+ //-------------------------------------------------------------------------------------------------
621
+ // receiver Destination (dst)
622
+
623
+ handler_json_msgWarp(msg : t_msg, json_msgWarp) : boolean
624
+ {
625
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_json_msgWarp: ', json_msgWarp]);
626
+
627
+ // no callback for this step: not ours -- before anything is logged
628
+ if (! this.config._callback_msgWarp)
629
+ return false;
630
+
631
+ const protocolState= this.eventLog.traverse_State(json_msgWarp);
632
+ const b_changeState= protocolState.canChangeState( new StateWarp(null, {
633
+ dt: Date.now(),
634
+ data: { msg, json_msg: json_msgWarp, b_sent: false }
635
+ }) );
636
+
637
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_json_msgWarp: protocolState.canChangeState: ', b_changeState]);
638
+ if (! b_changeState)
639
+ return false;
640
+
641
+ this.eventLog._addEvent(msg, json_msgWarp, false);
642
+ return this.config._callback_msgWarp(msg, json_msgWarp)
643
+ }
644
+
645
+ // Register a JSON_HoldWarp we are about to publish: "this Warp is being worked on, wait for the ack until
646
+ // my lease ends". Legal only for a Warp we RECEIVED, have not answered, and whose window is still open
647
+ // (a window that has closed cannot be reopened). It is what lets register_ackWarp succeed later than the
648
+ // Warp's own dt + TTL*2. Returns true, or false when it is not legal now: then do not publish it.
649
+ register_holdWarp(msg : t_msg, json_holdWarp) : boolean
650
+ {
651
+ logr_.log(l_.RECVER, () => ['register_holdWarp: ', json_holdWarp]);
652
+
653
+ const json_msgWarp= json_holdWarp._cause;
654
+
655
+ const state= this.eventLog.traverse_State(json_msgWarp).state;
656
+ if (! (state instanceof StateWarp) || state.event.data.b_sent)
657
+ return false;
658
+
659
+ if (Date.now() >= state.deadline_msec)
660
+ return false;
661
+
662
+ if (! Number.isFinite(StateWarp.deadline_holdWarp(json_holdWarp)))
663
+ return false;
664
+
665
+ this.eventLog._addEvent(msg, json_holdWarp, true);
666
+ return true;
667
+ }
668
+
669
+ register_ackWarp(msg: t_msg, json_ackWarp) : boolean
670
+ {
671
+ logr_.log(l_.RECVER, () => ['register_ackWarp: ', json_ackWarp]);
672
+
673
+ const json_msgWarp= json_ackWarp._cause;
674
+
675
+ const protocolState= this.eventLog.traverse_State(json_msgWarp);
676
+ const b_changeState= protocolState.canChangeState( new StateAckWarp(null, {
677
+ dt: Date.now(),
678
+ data: { msg, json_msg: json_ackWarp, b_sent: true }
679
+ }) );
680
+
681
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['register_ackWarp: protocolState.canChangeState: ', b_changeState]);
682
+ if (! b_changeState)
683
+ return false;
684
+
685
+ // The expiry means "the Engage I was waiting for never came". An ack no Engage can follow
686
+ // concludes the exchange and awaits nothing: logged, with no timer.
687
+ if (! isEngageAwaited_(json_ackWarp)) {
688
+ this.eventLog._addEvent(msg, json_ackWarp, true);
689
+ return true;
690
+ }
691
+
692
+ // the Engage is due within the ack's own dt + TTL*2
693
+ const elapsed_ms= Date.now() - Date.parse(json_ackWarp.dt);
694
+ const timeout_ms= window_msec_(json_msgWarp.warp.ttl_msec);
695
+
696
+ this.eventLog._addEvent(msg, json_ackWarp, true, timeout_ms-elapsed_ms, () => { // pass { _idx, _evt} ?
697
+ this.config._callback_receiver_sent_expired(msg, json_ackWarp);
698
+ });
699
+ return true;
700
+ }
701
+
702
+ handler_json_effEngage(msg : t_msg, json_effEngage) : boolean
703
+ {
704
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_json_effEngage: ', json_effEngage]);
705
+
706
+ // no callback for this step: not ours -- before anything is logged
707
+ if (! this.config._callback_effEngage)
708
+ return false;
709
+
710
+ const json_msgWarp= json_effEngage._cause;
711
+
712
+ const protocolState= this.eventLog.traverse_State(json_msgWarp);
713
+ const b_changeState= protocolState.canChangeState( new StateEngage(null, {
714
+ dt: Date.now(),
715
+ data: { msg, json_msg: json_effEngage, b_sent: false }
716
+ }) );
717
+
718
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_json_effEngage: protocolState.canChangeState: ', b_changeState]);
719
+ if (! b_changeState)
720
+ return false;
721
+
722
+ this.eventLog._cancelTimeout(protocolState.state.idx_event);
723
+ this.eventLog._addEvent(msg, json_effEngage, false);
724
+ return this.config._callback_effEngage(msg, json_effEngage)
725
+ }
726
+
727
+ register_ackEngage(msg : t_msg, json_ackEngage) : boolean
728
+ {
729
+ logr_.log(l_.RECVER, () => ['register_ackEngage: ', json_ackEngage]);
730
+
731
+ const json_msgWarp= json_ackEngage._cause._cause;
732
+
733
+ const protocolState= this.eventLog.traverse_State(json_msgWarp);
734
+ const b_changeState= protocolState.canChangeState( new StateAckEngage(null, {
735
+ dt: Date.now(),
736
+ data: { msg, json_msg: json_ackEngage, b_sent: true }
737
+ }) );
738
+
739
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['register_ackEngage: protocolState.canChangeState: ', b_changeState]);
740
+ if (! b_changeState)
741
+ return false;
742
+
743
+ this.eventLog._addEvent(msg, json_ackEngage, true);
744
+ return true;
745
+ }
746
+
747
+ };
748
+
749
+
750
+ //-------------------------------------------------------------------------------------------------
751
+ // The seam between this package and the interface
752
+
753
+ // What the host's generated 2PhW interface must offer (iface-gen, from schema_TwoPhW.json): the version
754
+ // and, per message, its validator and its constructor. Structural: this package names no generated type.
755
+ interface Iface_TwoPhW {
756
+ VERSION : string;
757
+ JSON_MsgWarp : { validate(msg) : boolean; merge(body) };
758
+ JSON_AckWarp : { validate(msg) : boolean };
759
+ JSON_HoldWarp : { validate(msg) : boolean; create_with_cause_ttl(cause, ttl_msec : number, hold?) };
760
+ JSON_EffEngage : { validate(msg) : boolean; create_with_cause_merge(cause, body) };
761
+ JSON_AckEngage : { validate(msg) : boolean };
762
+ }
763
+
764
+ // Bind the protocol to the HOST's generated interface. Called once, where the responder is set up:
765
+ //
766
+ // import * as iface_TwoPhW from '../generated/iface-TwoPhW';
767
+ // const { TwoPhW, JSON_MsgWarp, JSON_EffEngage, JSON_AckWarp, JSON_HoldWarp, JSON_AckEngage } = protocol_TwoPhW(iface_TwoPhW);
768
+ //
769
+ // Returns the state machine and, per message, the generated namespace (validate + merge /
770
+ // create_with_cause_merge; the validators are delta-only: the base is validated upstream, in the
771
+ // responder chain) extended with what the schema cannot express: the protocol's own constructors.
772
+ // Whatever is built through them carries the interface's own VERSION, so the package cannot speak
773
+ // another version of 2PhW than its host validates.
774
+ function protocol_TwoPhW<T extends Iface_TwoPhW>(iface_TwoPhW : T) {
775
+
776
+ // What was handed in is the host's to get right: a wrong import (the module's default export, another
777
+ // interface) must fail here, where it is made, not as an undefined deep inside an exchange.
778
+ const arr_str_missing= [
779
+ [ 'VERSION', typeof iface_TwoPhW?.VERSION === 'string' ],
780
+ [ 'JSON_MsgWarp.validate', typeof iface_TwoPhW?.JSON_MsgWarp?.validate === 'function' ],
781
+ [ 'JSON_MsgWarp.merge', typeof iface_TwoPhW?.JSON_MsgWarp?.merge === 'function' ],
782
+ [ 'JSON_AckWarp.validate', typeof iface_TwoPhW?.JSON_AckWarp?.validate === 'function' ],
783
+ [ 'JSON_HoldWarp.validate', typeof iface_TwoPhW?.JSON_HoldWarp?.validate === 'function' ],
784
+ [ 'JSON_HoldWarp.create_with_cause_ttl', typeof iface_TwoPhW?.JSON_HoldWarp?.create_with_cause_ttl === 'function' ],
785
+ [ 'JSON_EffEngage.validate', typeof iface_TwoPhW?.JSON_EffEngage?.validate === 'function' ],
786
+ [ 'JSON_EffEngage.create_with_cause_merge', typeof iface_TwoPhW?.JSON_EffEngage?.create_with_cause_merge === 'function' ],
787
+ [ 'JSON_AckEngage.validate', typeof iface_TwoPhW?.JSON_AckEngage?.validate === 'function' ]
788
+ ].filter(([ _str_member, b_present ]) => ! b_present).map(([ str_member ]) => str_member);
789
+ if (arr_str_missing.length)
790
+ throw new Error(`protocol_TwoPhW: not a generated 2PhW interface, it lacks: ${arr_str_missing.join(', ')}`);
791
+
792
+ const k_VERSION= iface_TwoPhW.VERSION;
793
+
794
+ const JSON_MsgWarp = {
795
+ ...iface_TwoPhW.JSON_MsgWarp,
796
+ create_with_id_user_hyperport : function(json_warp_id, json_user, json_hyperport, nr_ttl_msec) {
797
+ return iface_TwoPhW.JSON_MsgWarp.merge({
798
+ id : json_warp_id,
799
+ user : json_user,
800
+ hyperport : json_hyperport,
801
+ ttl_msec : nr_ttl_msec
802
+ });
803
+ },
804
+ compare : compare_msgWarp_
805
+ };
806
+
807
+ const JSON_EffEngage = {
808
+ ...iface_TwoPhW.JSON_EffEngage,
809
+ create_with_Warp : function(json_msgWarp) {
810
+ console.assert(json_msgWarp.ack === undefined, "Engage with a Warp, not an Ack");
811
+ return iface_TwoPhW.JSON_EffEngage.create_with_cause_merge(json_msgWarp, {
812
+ "ok" : true
813
+ });
814
+ }
815
+ };
816
+
817
+ // iface-gen emits no constructor for a JSON_Ack: build the base ack, stamp the protocol marker
818
+
819
+ const JSON_AckWarp = {
820
+ ...iface_TwoPhW.JSON_AckWarp,
821
+ create_with_Warp_Ok : function(json_msgWarp, b_ok= true) {
822
+ const json_ack= JSON_Ack.create_with_cause_Ok(json_msgWarp, b_ok);
823
+ json_ack["2PhW"]= k_VERSION;
824
+ return json_ack;
825
+ }
826
+ };
827
+
828
+ const JSON_AckEngage = {
829
+ ...iface_TwoPhW.JSON_AckEngage,
830
+ create_with_Engage_Ok : function(json_effEngage, b_ok= true) {
831
+ const json_ack= JSON_Ack.create_with_cause_Ok(json_effEngage, b_ok);
832
+ json_ack["2PhW"]= k_VERSION;
833
+ return json_ack;
834
+ }
835
+ };
836
+
837
+ return {
838
+ TwoPhW,
839
+ VERSION : k_VERSION,
840
+ JSON_MsgWarp,
841
+ JSON_EffEngage,
842
+ JSON_AckWarp,
843
+ JSON_HoldWarp : iface_TwoPhW.JSON_HoldWarp, // as generated: its constructor is built from the lease already
844
+ JSON_AckEngage
845
+ };
846
+ }
847
+
848
+ //-------------------------------------------------------------------------------------------------
849
+
850
+ export {
851
+ protocol_TwoPhW,
852
+ window_msec_ as window_msec,
853
+ logr_ as logr,
854
+ JSON_Msg,
855
+ JSON_Eff,
856
+ JSON_Ack,
857
+ // -----
858
+ StateAckEngage,
859
+ StateEngage,
860
+ StateAckWarp,
861
+ StateWarp,
862
+ StateINVALID,
863
+ StateInitialState
864
+ };
865
+ export type { Iface_TwoPhW, TwoPhW };