Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1685 lines (1518 loc) · 60.6 KB
/
Copy pathindex.js
File metadata and controls
1685 lines (1518 loc) · 60.6 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
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
import pino from 'pino'
import {strictEqual, ok} from 'node:assert'
import {EventEmitter} from 'node:events'
import {createServer as createHttpServer} from 'node:http'
import {x} from 'xastscript'
import {CLIENT_CALLS, SERVER_CALLS, ALL_CALLS} from './lib/calls.js'
import {openInMemoryStorage} from './lib/in-memory-storage.js'
import {
createSendRequest,
BESTAETIGUNG,
Vdv453HttpError, Vdv453ApiError,
} from './lib/send-request.js'
import {createServer} from './lib/server.js'
import {SERVICES} from './lib/services.js'
import {isProgrammerError} from './lib/is-programmer-error.js'
import {getZst} from './lib/zst.js'
import {
PARSED_LINIENFAHRPLAN_CHILDREN,
parseRefAusSollFahrt,
} from './lib/parse-ref-aus-sollfahrt.js'
import {parseAusIstFahrt} from './lib/parse-aus-istfahrt.js'
const {
DFI,
// REF_DFI,
// ANS,
// REF_ANS,
// > Dieser Dienst wird derzeit nicht von der VBB Datendrehscheibe unterstützt.
// VIS,
// > Dieser Dienst wird derzeit nicht von der VBB Datendrehscheibe unterstützt.
// AND,
REF_AUS,
AUS,
} = SERVICES
const {
STATUS,
ABO_VERWALTEN,
DATEN_ABRUFEN,
} = CLIENT_CALLS
const {
CLIENT_STATUS,
DATEN_BEREIT,
} = SERVER_CALLS
// > 5.1.2.1 Abonnementsanfrage (AboAnfrage)
// > Definition AboAnfrage:
// > […]
// > AboASBRef: […] Abonniert Referenzdaten für die Anschlusssicherung.
// > AboASB: […] Abonniert Prozessdaten für die Anschlusssicherung.
// > AboAZBRef: […] Abonniert Referenzdaten für die Fahrgastinformation.
// > AboAZB: […] Abonniert Prozessdaten für die Fahrgastinformation.
// > AboVIS: […] Abonniert Prozessdaten für die Visualisierung.
// > AboAND: […] Abonniert Prozessdaten des Nachrichtendienstes.
// > […]
const ABO_ANFRAGE_ROOT_SUB_TAGS_BY_SERVICE = new Map([
[DFI, 'AboAZB'],
// [REF_DFI, 'AboAZBRef'],
[REF_AUS, 'AboAUSRef'],
[AUS, 'AboAUS'],
])
// > 5.1.4.2 Daten übertragen (DatenAbrufenAntwort)
// > Definition DatenAbrufenAntwort:
// > […]
// > Zubringernachricht: […] Enthält Nachrichten des Zubringers im Dienst Anschlusssicherung.
// > Abbringernachricht: […] Enthält Nachrichten des Abbringers im Dienst Anschlusssicherung.
// > AZBNachricht: […] Enthält Nachrichten über auf einen Anzeigebereich zulaufende Fremdfahrzeuge.
// > VISNachricht: […] Enthält Informationen zu Fahrten, die in einer Fremdleitstelle visualisiert werden sollen.
// > ANDNachricht: […] Enthält Informationen zu aktuellen Betriebsereignissen, die in einer Fremdleitstelle einem Disponenten mitgeteilt werden sollen.
// > […]
// VDV 454 spec:
// > 5.1.2 Daten übermitteln (AUSNachricht)
// > Alle Datenübermittlungen zu einem Abonnement (Planungdaten, Istdaten und Anschlussinformationen) werden in dem Element AUSNachricht übermittelt.
const DATEN_ABRUFEN_ANTWORT_ROOT_SUB_TAGS_BY_SERVICE = new Map([
[DFI, 'AZBNachricht'],
// [REF_DFI, 'AZBNachricht'],
// Because a single AUSNachricht may have (unpredictably) much data (with the VBB API it usually is at most ~1mb, but we can't rely on that), we only parse its children (i.e. Linienfahrplan) into XML trees.
// todo: how to handle other AUSNachricht children: SollUmlauf, FahrtVerband, GesAnschluss?
// todo: parse AUSNachricht.AboID and expose it?
// todo:
// > Falls ein Datenlieferant eine DatenAbrufenAnfrage erhält, die Daten aber noch nicht bereit hat, soll eine leere DatenAbrufenAntwort (das verpflichtende Element Bestaetigung ist enthalten, das optionale Element AUSNachricht fehlt jedoch) gesendet werden. Der Datenkonsument darf in diesem Fall keine Rückschlüsse auf irgendwelche Linienfahrpläne ziehen, weil die Antwort darüber nichts aussagt.
[REF_AUS, 'Linienfahrplan'], // Linienfahrplan is a child of AUSNachricht
[AUS, 'AUSNachricht'],
])
const SECOND = 1000
const MINUTE = 60 * SECOND
const HOUR = 60 * MINUTE
const DAY = 24 * HOUR
// > When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.
// https://nodejs.org/docs/latest-v20.x/api/timers.html#settimeoutcallback-delay-args
const SETTIMEOUT_MAX_DELAY = 2147483647
const DFI_DEFAULT_SUBSCRIPTION_TTL = 1 * HOUR
const REF_AUS_DEFAULT_SUBSCRIPTION_TTL = 1 * DAY
const AUS_DEFAULT_SUBSCRIPTION_TTL = 1 * HOUR
const SUBSCRIPTION_EXPIRED_MSG = 'subscription expired'
const UNSUBSCRIBED_MANUALLY_MSG = 'unsubscribed manually'
const SUBSCRIPTION_CANCELED_BY_SERVER_MSG = 'subscription canceled by the server'
const STORAGE_TTL_STARTDIENSTZST = 3 * DAY
const STORAGE_KEY_STARTDIENSTZST = 'startdienstzst'
const STORAGE_TTL_SERVER_STATE = 3 * DAY
// $STORAGE_PREFIX_LATEST_SERVER_STARTDIENSTZST:$service -> latest known (parsed!) StartDienstZst
const STORAGE_PREFIX_LATEST_SERVER_STARTDIENSTZST = 'server-latest-startdienstzst:'
// $STORAGE_PREFIX_LATEST_SERVER_DATENVERSIONID:$service -> latest known DatenVersionID
const STORAGE_PREFIX_LATEST_SERVER_DATENVERSIONID = 'server-latest-datenversionid:'
// $STORAGE_PREFIX_SUBSCRIPTIONS:$service:$aboID -> expiresAt
const STORAGE_PREFIX_SUBSCRIPTIONS = 'subs:'
const waitFor = async (ms, abortSignal) => {
await new Promise((resolve) => {
const timer = setTimeout(resolve, ms)
const onAbort = () => {
abortSignal.removeEventListener('abort', onAbort)
clearTimeout(timer)
resolve()
}
abortSignal.addEventListener('abort', onAbort)
})
}
// adapted from https://github.com/sindresorhus/p-retry/blob/0b1e29877422c40b59cad4a4c938dcf44fe512ce/index.js#L52-L60
const createGetExpDelay = (factor, minTimeout, maxTimeout) => {
let retries = 0
const getExpDelay = () => {
const attempt = Math.max(1, retries++ + 1)
const random = 1 + Math.random() / 5
return Math.min(
Math.round(random * minTimeout * (factor ** (attempt - 1))),
maxTimeout,
)
}
return getExpDelay
}
// This implementation follows the VDV 453 spec, as documented in the "VDV-453 Ist-Daten-Schnittstelle – Version 2.4" document. It also supports the VDV 454 extension, as documented in the "VDV-454 Ist-Daten-Schnittstelle – Fahrplanauskunft – Version 2.0".
// https://web.archive.org/web/20240221234602/https://www.vdv.de/453v24-sds.pdfx?forced=false
// https://web.archive.org/web/20240222010651/https://www.vdv.de/454v2.0-sd.pdfx?forced=false
// https://web.archive.org/web/20231205141847/https://www.vdv.de/vdv453-incl-454-v2015.a-ohne-siri-20150630.zipx?forced=true
// see also https://web.archive.org/web/20231208122259/https://www.vdv.de/i-d-s-downloads.aspx
const createClient = async (cfg, opt = {}) => {
const {
leitstelle,
theirLeitstelle,
} = cfg
strictEqual(typeof leitstelle, 'string', 'cfg.leitstelle must be a string')
ok(leitstelle, 'cfg.leitstelle must not be empty')
strictEqual(typeof theirLeitstelle, 'string', 'cfg.theirLeitstelle must be a string')
ok(theirLeitstelle, 'cfg.theirLeitstelle must not be empty')
const {
logger,
requestsLogger,
fetchSubscriptionsDataPeriodically,
fetchNewDataCooldownAfterFailure,
openStorage,
onDatenBereitAnfrage,
onClientStatusAnfrage,
onStatusAntwort,
onServerXSDVersionID,
onSubscriptionCreated,
onSubscriptionRestored,
onSubscriptionExpired,
onSubscriptionCanceled,
onSubscriptionsResetByServer,
onSubscriptionManualFetchStarted,
onSubscriptionManualFetchSucceeded,
onSubscriptionManualFetchFailed,
onDatenAbrufenAntwort,
onDataFetchStarted,
onDataFetchSucceeded,
onDataFetchFailed,
onRefAusFetchStarted,
onRefAusFetchSucceeded,
onRefAusFetchFailed,
onAusFetchStarted,
onAusFetchSucceeded,
onAusFetchFailed,
} = {
logger: pino({
level: process.env.LOG_LEVEL || 'info',
}),
// separate logger for network requests, they are too noisy usually
requestsLogger: pino({
level: process.env.LOG_LEVEL_REQUESTS || 'info',
// todo: remove some fields from logs, e.g.
// - clientRequest.agent
// - clientRequest.res
// - serverResponse._readableState
// - serverResponse.client
// - serverResponse.req
}),
// Some VDV-453 systems may not notify us about new/changed data (see _handleDatenBereitAnfrage), so we fetch the data "manually" periodically.
// todo [breaking]: default to false
fetchSubscriptionsDataPeriodically: true,
// While fetching new data iteratively (and continuously, depending on the usage), the number of milliseconds that the client should wait after a failure.
fetchNewDataCooldownAfterFailure: 1000, // 1s
openStorage: openInMemoryStorage,
// hooks for debugging/metrics/etc.
onDatenBereitAnfrage: (svc, datenBereitAnfrage) => {},
onClientStatusAnfrage: (svc, clientStatusAnfrage) => {},
onStatusAntwort: (svc, statusAntwort, {timePassed}) => {},
onServerXSDVersionID: (svc, xsdVersionID) => {},
onSubscriptionCreated: (svc, {aboId, expiresAt, aboSubTag, aboSubChildren}, bestaetigung, subStats) => {},
onSubscriptionRestored: (svc, {aboId, expiresAt}) => {},
onSubscriptionExpired: (svc, {aboId, aboSubTag, aboSubChildren}, subStats) => {},
onSubscriptionCanceled: (svc, {aboId, aboSubTag, aboSubChildren}, reason, subStats) => {},
onSubscriptionsResetByServer: (svc, subStats) => {},
onSubscriptionManualFetchStarted: (svc, {aboId, aboSubTag, aboSubChildren}) => {},
onSubscriptionManualFetchSucceeded: (svc, {aboId, aboSubTag, aboSubChildren}, {timePassed}) => {},
onSubscriptionManualFetchFailed: (svc, {aboId, aboSubTag, aboSubChildren}) => {},
onDatenAbrufenAntwort: (svc, {datensatzAlle, weitereDaten, itLevel, bestaetigung}) => {},
onDataFetchStarted: (svc, {datensatzAlle}) => {},
onDataFetchSucceeded: (svc, {datensatzAlle}, {nrOfFetches, totalDataItems, timePassed}) => {},
onDataFetchFailed: (svc, {datensatzAlle}, err, {nrOfFetches, totalDataItems, timePassed}) => {},
onRefAusFetchStarted: ({datensatzAlle}) => {},
onRefAusFetchSucceeded: ({datensatzAlle}, {nrOfSollFahrts}) => {},
onRefAusFetchFailed: ({datensatzAlle}, err, {nrOfSollFahrts}) => {},
onAusFetchStarted: ({datensatzAlle}) => {},
onAusFetchSucceeded: ({datensatzAlle}, {nrOfIstFahrts}) => {},
onAusFetchFailed: ({datensatzAlle}, err, {nrOfIstFahrts}) => {},
...opt,
}
ok('object' === typeof logger && logger, 'opt.logger must be an object')
cfg = {
...cfg,
logger,
}
// When fetching all new data from the server, the maximum number of batches to fetch. The number of items per batch depends on the server and service.
const datenAbrufenMaxBatches = {
default: 10,
[AUS]: 300,
[REF_AUS]: 1000,
...(opt.datenAbrufenMaxBatches ?? {}),
}
const {
remoteEndpointId,
sendRequest,
} = createSendRequest({
...cfg,
logger: requestsLogger,
}, opt)
const {router, errorHandler} = createServer({
...cfg,
logger: requestsLogger,
}, opt)
// todo: serve basic information about the service on /
const data = new EventEmitter()
// ----------------------------------
// todo: move to lib/server.js?
const _onRequest = (service, call, handleRequest) => {
const path = '/' + [
theirLeitstelle,
service,
call,
].map(part => encodeURIComponent(part)).join('/')
logger.trace({
service,
path,
}, 'adding HTTP POST request handler')
router.post(path, async (req, res, next) => {
try {
await handleRequest(req, res, next)
} catch (err) {
next(err)
}
})
}
const _handleClientStatusAnfrage = (service) => {
_onRequest(service, CLIENT_STATUS, async (req, res) => {
const logCtx = {
service,
}
const clientStatusAnfrage = await req.parseWholeRoot('ClientStatusAnfrage')
logCtx.clientStatusAnfrage = clientStatusAnfrage
logger.debug(logCtx, 'received ClientStatusAnfrage')
res.respondWithResponse({
ok: true, // todo: are we ever not okay?
status: true, // send Status element
children: [
x('StartDienstZst', {}, startDienstZst),
// todo: provide AktiveAbos if `clientStatusAnfrage.$.MitAbos` has value `true`
// > 5.1.8.3 ClientStatusAnfrage
// > Beispiel 3: Antwort des Clients: Dienst verfügbar, Client initialisiert gerade und will keine Auskunft zu den aktiven Abonnements geben:
// > 5.1.8.3 ClientStatusAnfrage
// > […]
// > Stellt der Server einen Unterschied zwischen seiner Abonnementliste und der Liste vom Client, kann der Server entweder stillschweigend den Unterschied beseitigen indem er die nicht aus der Clientsicht aktiven Abonnements löscht und die aus der Clientsicht aktiven Abonnements registriert und anfängt für diese Daten bereitzustellen oder er setzt den StartDienstZst in seiner StatusAntwort auf die aktuelle Zeit und erzwingt somit die Neuinitiali- sierung des Clients. Der zweite Weg wird empfohlen.
// > Ist die Struktur AktiveAbos leer, hat der Client keine aktiven Abonnements. Falls der Server doch welche kennt, sollen diese stillschweigend deaktiviert werden.
],
})
await onClientStatusAnfrage(service, clientStatusAnfrage)
try {
await _checkClientStatusAnfrage(service, clientStatusAnfrage)
} catch (err) {
logger.warn({
...logCtx,
err,
}, `failed to check ClientStatusAnfrage: ${err.message}`)
}
})
}
const _sendStatusAnfrage = async (service) => {
const logCtx = {
service,
}
const t0 = performance.now()
const {
clientRequest: req,
serverResponse: res,
parseResponse,
assertStatusAntwortOk,
} = await sendRequest(
service,
STATUS,
// todo: move "StatusAnfrage" into constant?
'StatusAnfrage',
[],
)
const timePassed = performance.now() - t0
const tags = parseResponse([
// todo: move "StatusAntwort" into constant?
{tag: 'StatusAntwort', preserve: true},
])
for await (const el of tags) {
const tag = el.$name
if (tag === 'StatusAntwort') {
assertStatusAntwortOk(el, logCtx)
const datenBereit = el.DatenBereit?.$text?.trim() === 'true'
const startDienstZst = el.StartDienstZst?.$text || null
const datenVersionID = el.DatenVersionID?.$text || null
logger.debug({
...logCtx,
datenBereit,
startDienstZst,
datenVersionID,
timePassed,
}, 'received StatusAntwort')
await onStatusAntwort(service, el, {timePassed})
try {
await _checkServerStatusAntwort(service, el)
} catch (err) {
logger.warn({
...logCtx,
err,
}, `failed to check server StatusAntwort: ${err.message}`)
}
return {
datenBereit,
startDienstZst,
datenVersionID,
statusAntwort: el,
}
}
// todo: otherwise warn-log unexpected tag?
}
throw new Vdv453ApiError(
service,
'StatusAnfrage',
`server's reponse body does not contain a StatusAntwort`,
'?',
req,
null, // reqOpts
null, // reqBody
res,
)
}
// > 5.1.7 Wiederaufsetzen nach Absturz
// > […]
// > Verliert der Server seine Abonnement-Daten, so ist dies zunächst vom Client aus nicht feststellbar. DatenBereitAnfragen bleiben zwar aus, aber dies kann nicht vom normalen Betrieb unterschieden und somit der Absturz des Servers nicht festgestellt werden. Um diesen Fall zu erkennen, sind zusätzliche, zyklische Anfragen vom Typ StatusAnfrage (5.1.8.1) zum Server zu senden. Innerhalb der StatusAntwort (5.1.8.2) gibt der Server den Zeitstempel des Dienststarts an. Fand der Dienststart nach der Einrichtung der Abonnements statt, so muss vom Verlust der Abonnements ausgegangen werden. Es ist nun zu verfahren wie beim Client-Datenverlust: Löschen und Neueinrichtung aller Abonnements.
// > […]
// > 5.1.8 Alive-Handling
// > […]
// > 5.1.8.2 Antwort (StatusAntwort, Status)
// > Sobald der Server in einer StatusAntwort einen aktualisierten Wert von StartDienstZst und DatenVersionID mitteilt (oder DatenVersionID vom System noch nicht unterstützt wird), muss der Client davon ausgehen, dass der Server-Dienst neu gestartet wurde und die Datenversorgung inkl. der Abonnements verloren gegangen ist.
// > Wenn der Server eine neue Datenversion signalisieren will, muss er dies dem Client durch eine gleichzeitige Aktualisierung von StartDienstZst und DatenVersionID mitteilen.
// > Sobald der Server in einer StatusAntwort einen aktualisierten Wert des StartDienstZst mitteilt, die DatenVersionID jedoch unverändert bleibt, kann der Client davon ausgehen, dass der Server-Dienst neu gestartet wurde, die bestehende Datenversorgung inkl. der Abonnement aber weiterhin vorliegt. Der Client muss die auf diesen Dienst bezogenen Daten und Abonnements daher *nicht* löschen. Eine Erneuerung der Abonnements und neu Abrufen der Daten ist in dem Fall nicht notwendig.
const _checkStartDienstZstAndDatenVersionID = async (service, startDienstZst, datenVersionID) => {
const tStartDienstZst = Date.parse(startDienstZst)
ok(Number.isInteger(tStartDienstZst), 'StartDienstZst not parsable as ISO 8601')
const logCtx = {
service,
tStartDienstZst,
datenVersionID,
}
// todo [breaking]: call onSubscriptionsResetByServer() even in this case, with `prevTStartDienstZst: null`!
if (!await storage.has(STORAGE_PREFIX_LATEST_SERVER_STARTDIENSTZST + service)) {
logger.trace({
...logCtx,
tStartDienstZst,
}, 'previously unknown server StartDienstZst')
await storage.set(
STORAGE_PREFIX_LATEST_SERVER_STARTDIENSTZST + service,
String(tStartDienstZst),
STORAGE_TTL_SERVER_STATE,
)
return;
}
// todo [breaking]: call onSubscriptionsResetByServer() even in this case, with `prevDatenVersionID: null`!
if (!await storage.has(STORAGE_PREFIX_LATEST_SERVER_DATENVERSIONID + service)) {
logger.trace({
...logCtx,
tStartDienstZst,
}, 'previously unknown server DatenVersionID')
await storage.set(
STORAGE_PREFIX_LATEST_SERVER_DATENVERSIONID + service,
datenVersionID,
STORAGE_TTL_SERVER_STATE,
)
return;
}
const prevTStartDienstZst = parseInt(await storage.get(STORAGE_PREFIX_LATEST_SERVER_STARTDIENSTZST + service))
const prevDatenVersionID = await storage.get(STORAGE_PREFIX_LATEST_SERVER_DATENVERSIONID + service)
if (tStartDienstZst !== prevTStartDienstZst) {
logger.trace({
...logCtx,
prevTStartDienstZst,
}, 'server StartDienstZst has changed')
}
if (datenVersionID !== prevDatenVersionID) {
logger.trace({
...logCtx,
prevDatenVersionID,
}, 'server DatenVersionID has changed')
}
const subscriptionsReset = tStartDienstZst !== prevTStartDienstZst && datenVersionID !== prevDatenVersionID
await storage.set(
STORAGE_PREFIX_LATEST_SERVER_STARTDIENSTZST + service,
String(tStartDienstZst),
STORAGE_TTL_SERVER_STATE,
)
await storage.set(
STORAGE_PREFIX_LATEST_SERVER_DATENVERSIONID + service,
datenVersionID,
STORAGE_TTL_SERVER_STATE,
)
if (subscriptionsReset) {
logger.info({
...logCtx,
prevTStartDienstZst,
prevDatenVersionID,
}, 'server StartDienstZst and DatenVersionID have changed')
for await (const {aboId} of _readSubscriptions(service)) {
await _abortSubscription(service, aboId, SUBSCRIPTION_CANCELED_BY_SERVER_MSG)
}
await onSubscriptionsResetByServer(service, await _getSubStats(service))
// todo: silently recreate all subscriptions? or leave this to the caller?
}
}
const _checkServerStatusAntwort = async (service, statusAntwort) => {
const startDienstZst = statusAntwort.StartDienstZst?.$text || null
ok(startDienstZst !== null, 'missing StatusAntwort.StartDienstZst')
const datenVersionID = statusAntwort.DatenVersionID?.$text || null
ok(datenVersionID !== null, 'missing StatusAntwort.DatenVersionID')
await _checkStartDienstZstAndDatenVersionID(service, startDienstZst, datenVersionID)
}
const _checkClientStatusAnfrage = async (service, clientStatusAfrage) => {
const startDienstZst = clientStatusAfrage.StartDienstZst?.$text || null
ok(startDienstZst !== null, 'missing ClientStatusAnfrage.StartDienstZst')
const datenVersionID = clientStatusAfrage.DatenVersionID?.$text || null
ok(datenVersionID !== null, 'missing ClientStatusAnfrage.DatenVersionID')
await _checkStartDienstZstAndDatenVersionID(service, startDienstZst, datenVersionID)
}
// ----------------------------------
const _sendAboAnfrage = async (service, aboParams) => {
// todo: validate arguments
const {
parseResponse,
assertBestaetigungOk,
} = await sendRequest(
service,
ABO_VERWALTEN,
// todo: move "AboAnfrage" into constant?
'AboAnfrage',
aboParams,
)
let result = null
const tags = parseResponse([
{tag: 'AboAntwort', preserve: true},
{tag: BESTAETIGUNG, preserve: true},
// todo: support `BestaetigungMitAboID` for >1 subscriptions in one call? – see also "5.1.2.2.1 Vorgehen für mehrfache BestaetigungMitAboID einer AboAnfrage"
// > 5.1.2.2 Abonnementsbestätigung (AboAntwort)
// > […]
// > (Unterelement, alternativ, mehrfach) Enthält für jedes Abonement (AboID) separate Informationen zur Fehlerbehandlung.
// > […]
// > Seit den Standard-Versionen VDV453 v2.4 und VDV454 v2.0 kann eine AboAnfrage mit mehreren Abonnements durch einer AboAntwort mit mehrfachen dedizierten AboBestaetigungMitAboID sowie Fehlermeldungen für jedes Abonnement (AboID) beantwortet werden.
])
for await (const el of tags) {
const tag = el.$name
// > 5.1.2.2 Abonnementsbestätigung (AboAntwort)
// > […]
// > Mit dem optionalen Element XSDVersionID in AboAnfrage und AboAntwort tauschen Client und Server die Versionskennung der Schnittstelle aus, die jeder von ihnen verwendet. Damit können beide Seiten Kompatibilitätsprüfungen vornehmen. Die aktuelle Version ist im XML-Schema im Attribut Version angegeben (Dateiname des XSD-Files, z.B. `xsd_2015a`).
if (tag === 'AboAntwort') {
const xsdVersionID = el.$.XSDVersionID ?? null
if (xsdVersionID !== null) {
await onServerXSDVersionID(service, xsdVersionID)
}
continue
}
if (tag === BESTAETIGUNG) {
assertBestaetigungOk(el)
// todo: warn if DatenGueltigBis < aboParams.VerfallZst?
// > (optional) Ende des Datenhorizontes des Datenproduzenten. Entfällt, wenn Anfrage vollständig im Datenhorizont liegt.
// todo: add hook onAboAntwort()?
result = el
continue
}
// todo: otherwise warn-log unexpected tag?
}
return result
}
const _nrOfSubscriptions = async (service) => {
let _nr = 0
// todo: add `storage` method for more efficient calculation?
for await (const _ of _readSubscriptions(service)) {
_nr++
}
return _nr
}
const _getSubStats = async (service) => ({
nrOfSubscriptions: await _nrOfSubscriptions(service),
})
const _abortSubscription = async (service, aboId, reason) => {
const subscriptionAbortController = subscriptionAbortControllers[service].get(aboId)
ok(subscriptionAbortController, `invalid abo ID "${aboId}" for service ${service}`)
// Note: We delete from `subscriptions` before abort()-ing.
await storage.del(STORAGE_PREFIX_SUBSCRIPTIONS + service + ':' + aboId)
subscriptionAbortControllers[service].delete(aboId)
subscriptionAbortController.abort(reason)
}
const _readSubscriptions = async function* (service = null, readExpiresAt = false) {
const prefix = STORAGE_PREFIX_SUBSCRIPTIONS + (service === null ? '' : service + ':')
const entries = await storage[readExpiresAt ? 'entries' : 'keys'](prefix)
for (const entry of entries) {
const key = readExpiresAt ? entry[0] : entry
const val = readExpiresAt ? entry[1] : null
const [_, service, aboId] = key.split(':')
const expiresAt = readExpiresAt ? parseInt(val) : null
yield {service, aboId, expiresAt}
}
}
const getAllSubscriptions = async () => {
const _subscriptions = Object.create(null)
for await (const {service, aboId, expiresAt} of _readSubscriptions(null, true)) {
if (!(service in _subscriptions)) {
_subscriptions[service] = new Map()
}
_subscriptions[service].set(aboId, expiresAt)
}
return _subscriptions
}
const _ensureSubscriptionWillExpire = async (service, aboId, expiresIn) => {
const logCtx = {
service,
aboId,
}
ok(expiresIn <= SETTIMEOUT_MAX_DELAY, 'expiresIn is too large')
const subscriptionAbortController = new AbortController()
subscriptionAbortControllers[service].set(aboId, subscriptionAbortController)
// on abort, call hooks
const markSubscriptionAsExpiredOrCanceled = async () => {
const subStats = await _getSubStats(service)
if (subscriptionAbortController.signal.reason === SUBSCRIPTION_EXPIRED_MSG) {
try {
await onSubscriptionExpired(service, logCtx, subStats)
} catch (err) {
logger.warn({
...logCtx,
subStats,
}, 'onSubscriptionExpired() hook failed')
if (isProgrammerError(err)) {
throw err
}
}
} else {
try {
await onSubscriptionCanceled(service, logCtx, subscriptionAbortController.signal.reason, subStats)
} catch (err) {
logger.warn({
...logCtx,
abortReason: subscriptionAbortController.signal.reason,
subStats,
}, 'onSubscriptionCanceled() hook failed')
if (isProgrammerError(err)) {
throw err
}
}
}
}
subscriptionAbortController.signal.addEventListener('abort', () => {
markSubscriptionAsExpiredOrCanceled()
.catch((err) => {
logger.error({
...logCtx,
err,
}, `failed to mark subscription as expired or canceled: ${err.message}`)
})
})
// expiration timer fires -> abort subscription
// subscription aborted externally -> clear expiration timer
{
const expireSubClientSide = () => {
logger.trace(logCtx, 'expiring subscription client-side')
_abortSubscription(service, aboId, SUBSCRIPTION_EXPIRED_MSG)
.catch((err) => {
logger.warn({
...logCtx,
err,
}, `failed to expire subscription client-side: ${err.message}`)
})
}
// clear old expiration timer if applicable, set up a new one
if (_expirationTimersBySubAbortController.has(subscriptionAbortController)) {
const oldExpirationTimer = _expirationTimersBySubAbortController.get(subscriptionAbortController)
clearTimeout(oldExpirationTimer)
}
const expirationTimer = setTimeout(expireSubClientSide, expiresIn)
expirationTimer.unref()
_expirationTimersBySubAbortController.set(subscriptionAbortController, expirationTimer)
// clear expiration timer on external subscription abort
// If the subscription got aborted externally (i.e. not because it has expired but for some other reason), we should clear the timeout.
// Also, we clear the subscription abort listener as soon as the expiration timer fires.
{
const cancelExpirationTimer = () => {
logger.trace(logCtx, `subscription aborted: "${subscriptionAbortController.signal.reason}"`)
// de-listen self, a.k.a. once()
subscriptionAbortController.signal.removeEventListener('abort', cancelExpirationTimer)
const expirationTimer = _expirationTimersBySubAbortController.get(subscriptionAbortController)
clearTimeout(expirationTimer)
}
subscriptionAbortController.signal.addEventListener('abort', cancelExpirationTimer)
}
}
return {
subscriptionAbortController,
}
}
// subscriptionAbortController -> timer
const _expirationTimersBySubAbortController = new WeakMap()
const _subscribe = async (service, aboSubChildren, expiresAt, fetchNewDataUntilNoMoreAvailable, fetchInterval) => {
// todo: validate arguments
ok(
ABO_ANFRAGE_ROOT_SUB_TAGS_BY_SERVICE.has(service),
`invalid/unknown tag of root sub element for service "${service}"`
)
const aboSubTag = ABO_ANFRAGE_ROOT_SUB_TAGS_BY_SERVICE.get(service)
// todo: handle BigInt?
ok(Number.isInteger(expiresAt), 'expiresAt must be a UNIX timestamp')
// todo: what if the server has a different date/time configured?
const expiresIn = expiresAt - Date.now()
ok(expiresIn > 0, 'expiresAt must be in the future')
// todo: consider using e.g. https://github.com/trs/set-long-timeout/issues/2#issue-1912020818 here?
ok(expiresIn <= SETTIMEOUT_MAX_DELAY, `expiresAt must not be greater than ${SETTIMEOUT_MAX_DELAY}`)
const aboId = getNextAboId()
const logCtx = {
service,
aboId,
expiresAt,
fetchInterval,
}
logger.debug({
...logCtx,
aboSubTag,
aboSubChildren,
}, 'subscribing to items')
const aboParams = [
x(aboSubTag, {
AboID: aboId,
VerfallZst: getZst(expiresAt),
// todo: support attributes!
}, aboSubChildren)
]
// keep track of the subscription using the `aboID`
// We do this before sending the request because we might crash while the request is in-flight.
await storage.set(STORAGE_PREFIX_SUBSCRIPTIONS + service + ':' + aboId, String(expiresAt), expiresIn)
let bestaetigung
try {
bestaetigung = await _sendAboAnfrage(
service,
aboParams,
)
} catch (err) {
await storage.del(STORAGE_PREFIX_SUBSCRIPTIONS + service + ':' + aboId)
throw err
}
const {
subscriptionAbortController,
} = await _ensureSubscriptionWillExpire(service, aboId, expiresIn)
await onSubscriptionCreated(
service,
{
aboId,
expiresAt,
aboSubTag,
aboSubChildren,
},
bestaetigung,
await _getSubStats(service),
)
if (fetchSubscriptionsDataPeriodically) {
ok(Number.isInteger(fetchInterval), 'fetchInterval must be an integer')
const fetchPeriodicallyAndLogErrors = async () => {
// Usually subscriptions get created on client startup, so wait a bit for the server to notify us about new data (DatenBereitAnfrage) *if it supports that*. Only when it hasn't done that (quickly enough), we fetch manually.
const fetchIntervalInitialWait = Math.max(fetchInterval / 30, 2_000) // 2 seconds minimum
await new Promise(resolve => setTimeout(resolve, fetchIntervalInitialWait))
while (!subscriptionAbortController.signal.aborted) {
logger.debug(logCtx, 'manually fetching data')
await onSubscriptionManualFetchStarted(service, logCtx)
// `subscriptionAbortController` controls the periodic fetching, `fetchAbortController` controls an individual fetch. The former aborts the latter, but not vice versa.
const fetchAbortController = new AbortController()
const cancelFetch = () => {
fetchAbortController.abort(subscriptionAbortController.signal.reason)
}
subscriptionAbortController.signal.addEventListener('abort', cancelFetch)
try {
const t0 = performance.now()
// Note: The server might also notify us of new data, to which we react with fetching new data (see _handleDatenBereitAnfrage()), so just doing it "manually" here nonetheless would result in fetching the twice in parallel. Therefore we use _fetch*NewDataUntilNoMoreAvailable() instead of _fetchNew*DataOnce(), because the former ensures it only ever runs once in parallel.
await fetchNewDataUntilNoMoreAvailable()
const timePassed = performance.now() - t0
await onSubscriptionManualFetchSucceeded(service, logCtx, {
timePassed,
})
logger.debug({
...logCtx,
timePassed,
}, 'successfully fetched data manually')
} catch (err) {
// todo: error-log programmer errors!
logger.warn({
...logCtx,
err,
}, `failed to fetch & process data: ${err.message}`)
await onSubscriptionManualFetchFailed(service, logCtx, err)
} finally {
subscriptionAbortController.signal.removeEventListener('abort', cancelFetch)
}
// todo: make configurable based on previous fetch's success & duration
await waitFor(fetchInterval, subscriptionAbortController.signal)
}
}
fetchPeriodicallyAndLogErrors()
.catch((err) => {
logger.error({
service,
err,
}, `failed to fetch data periodically: ${err.message}`)
})
}
// todo: move this up, above the fetchPeriodicallyAndLogErrors() loop
logger.trace({
...logCtx,
bestaetigung,
}, 'successfully subscribed')
return {
aboId,
// todo: pass `subscriptionAbortController.signal` to allow client to witness expiration/cancelation?
}
}
const _unsubscribe = async (service, aboIds, silenceSubscriptionNotFoundError = false) => {
const logCtx = {
service,
aboIds,
}
logger.debug(logCtx, 'unsubscribing from subscriptions')
try {
const aboParams = aboIds.map(aboId => x('AboLoeschen', {}, aboId))
const bestaetigung = await _sendAboAnfrage(
service,
aboParams,
)
logCtx.bestaetigung = bestaetigung
} catch (err) {
const match = /zu löschenden Abonnements (\d+(, \d+)?) wurden nicht gefunden/i.exec(err.message)
if (match && match[1]) {
err.isSubscriptionNotFoundError = true
if (silenceSubscriptionNotFoundError) {
logCtx.notFoundAboIds = match[1].split(', ')
return;
}
}
throw err
}
for (const aboId of aboIds) {
const abortController = subscriptionAbortControllers[service].get(aboId)
if (!abortController) {
continue
}
await _abortSubscription(service, aboId, UNSUBSCRIBED_MANUALLY_MSG)
}
logger.debug(logCtx, 'successfully unsubscribed from subscriptions')
}
const _unsubscribeAll = async (service) => {
const logCtx = {
service,
}
logger.debug(logCtx, 'unsubscribing from all subscriptions')
const aboParams = [
x('AboLoeschenAlle', {}, 'true'),
]
const bestaetigung = await _sendAboAnfrage(
service,
aboParams,
)
logCtx.bestaetigung = bestaetigung
for await (const {aboId} of _readSubscriptions(service)) {
await _abortSubscription(service, aboId, UNSUBSCRIBED_MANUALLY_MSG)
}
logger.debug(logCtx, 'successfully unsubscribed from all subscriptions')
}
const unsubscribeAllOwned = async () => {
const _subscriptions = Object.create(null)
for await (const {service, aboId} of _readSubscriptions()) {
if (!(service in _subscriptions)) {
_subscriptions[service] = [aboId]
} else {
_subscriptions[service].push(aboId)
}
}
await Promise.all(Object.entries(_subscriptions).map(async ([service, aboIds]) => {
await _unsubscribe(service, aboIds, true)
}))
}
// ----------------------------------
// service -> true/false
const isFetchingData = {}
// service -> true/false
// - set to true by _processDatenBereitAnfrage() at any point in time
// - set to false by _fetchNewDataUntilNoMoreAvailable() before fetching
const datenBereitAnfrageReceivedWhileFetching = {}
// The server should notify the client of new/changed data, so that the latter can then request it.
// > 5.1.3.1 Datenbereitstellung signalisieren (DatenBereitAnfrage)
// > Ist das Abonnement eingerichtet und sind die Daten bereitgestellt, wird der Datenkonsument durch eine DatenBereitAnfrage über das Vorhandensein aktualisierter Daten informiert. Dies geschieht bei jeder Änderung der Daten die dem Abonnement zugeordnet sind. Die Signalisierung bezieht sich auf alle Abonnements eines Dienstes.
// The VDV API is constantly notifying us via `DatenBereitAnfrage`s when any IstFahrt(s) has changed, even while we're currently fetching. Because of the latency between us and the API, it's essentially a distributed system of two parties that try to sync their state: We do't know if the newly changed IstFahrt is already included in the batch currently being fetched.
// This is why we just fetch again afterwards whenever we have received a DatenBereitAnfrage while fetching.
const _fetchNewDataUntilNoMoreAvailable = async (service, fetchNewDataOnce) => {
const logCtx = {
service,
}
if ((await _nrOfSubscriptions(service)) === 0) { // 0 subscriptions on `service`
logger.debug(logCtx, `not starting to fetch new ${service} data again, because there are no subscriptions (anymore)`)
return;
}
// Make sure there's only ever one of this function running.
if (isFetchingData[service]) {
logger.debug(logCtx, `not starting to fetch new ${service} data again, because we're already fetching`)
return;
}
logger.debug(logCtx, `starting to fetch new ${service} data until no new data is available anymore`)
isFetchingData[service] = true
let iterations = 0
const retryDelay = createGetExpDelay(2, fetchNewDataCooldownAfterFailure, fetchNewDataCooldownAfterFailure * 5)
try {
while (datenBereitAnfrageReceivedWhileFetching[service]) {
iterations++
datenBereitAnfrageReceivedWhileFetching[service] = false
// We must keep looping even with fetch failures, so we catch & log all errors.
try {
await fetchNewDataOnce({
// todo: allow this to get cancelled from the outside
abortController: new AbortController(),
})
} catch (err) {
// todo: throw ES errors: ReferenceError, TypeError, etc. – or only catch VDV errors?
logger.warn({
...logCtx,
iteration: iterations - 1,
err,
}, `failed to fetch new ${service} data: ${err.message}`)
// todo: `datenBereitAnfrageReceivedWhileFetching[service] = true` to cause a refetch? – prevent endless cycles!
// prevent DOS-ing the server
await new Promise(resolve => setTimeout(resolve, retryDelay()))
}
// todo: wait for a moment before refetching?
}
} finally {
isFetchingData[service] = false
logger.trace({
...logCtx,
iterations,
}, `done fetching new ${service} data`)
}
}
// todo: move into the subs section?
const _handleDatenBereitAnfrage = (service, fetchNewDataUntilNoMoreAvailable) => {
const _processDatenBereitAnfrage = async (req, res) => {
const logCtx = {
service,
}
if ((await _nrOfSubscriptions(service)) === 0) { // 0 subscriptions on `service`
logger.warn(logCtx, 'received DatenBereitAnfrage, even though we don\'t know about a subscription')
res.respondWithResponse({
ok: false,
bestaetigung: true, // send Bestaetigung element
})
return;
}
const datenBereitAnfrage = await req.parseWholeRoot('DatenBereitAnfrage')
logCtx.datenBereitAnfrage = datenBereitAnfrage
logger.debug(logCtx, 'received DatenBereitAnfrage')
res.respondWithResponse({
ok: true,
bestaetigung: true, // send Bestaetigung element
})
await onDatenBereitAnfrage(service, datenBereitAnfrage)