eyevinn-channel-engine 5.1.2 → 5.2.0

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.
Files changed (97) hide show
  1. package/.github/workflows/nodejs.yml +1 -1
  2. package/.github/workflows/publish.yml +1 -1
  3. package/.github/workflows/rc.yml +1 -1
  4. package/CONTRIBUTING.md +40 -0
  5. package/Dockerfile +1 -1
  6. package/README.md +70 -8
  7. package/dist/engine/chaos_monkey.d.ts +1 -1
  8. package/dist/engine/chaos_monkey.js +1 -0
  9. package/dist/engine/event_stream.d.ts +1 -6
  10. package/dist/engine/event_stream.js +2 -0
  11. package/dist/engine/memcached_state_store.d.ts +1 -13
  12. package/dist/engine/memcached_state_store.js +4 -0
  13. package/dist/engine/memory_state_store.d.ts +1 -13
  14. package/dist/engine/memory_state_store.js +5 -0
  15. package/dist/engine/playhead_state.d.ts +0 -26
  16. package/dist/engine/playhead_state.js +9 -0
  17. package/dist/engine/preflight.d.ts +1 -1
  18. package/dist/engine/preflight.js +1 -0
  19. package/dist/engine/redis_state_store.d.ts +1 -19
  20. package/dist/engine/redis_state_store.js +5 -0
  21. package/dist/engine/server.d.ts +27 -0
  22. package/dist/engine/server.js +140 -6
  23. package/dist/engine/session.d.ts +1 -148
  24. package/dist/engine/session.js +398 -11
  25. package/dist/engine/session_live.d.ts +1 -181
  26. package/dist/engine/session_live.js +19 -4
  27. package/dist/engine/session_live_state.d.ts +0 -23
  28. package/dist/engine/session_live_state.js +5 -0
  29. package/dist/engine/session_state.d.ts +0 -45
  30. package/dist/engine/session_state.js +10 -0
  31. package/dist/engine/shared_state_store.d.ts +1 -25
  32. package/dist/engine/shared_state_store.js +10 -0
  33. package/dist/engine/state_store_types.d.ts +32 -0
  34. package/dist/engine/state_store_types.js +5 -0
  35. package/dist/engine/stream_switcher.d.ts +1 -40
  36. package/dist/engine/stream_switcher.js +108 -20
  37. package/dist/engine/subtitle_slicer.d.ts +1 -8
  38. package/dist/engine/subtitle_slicer.js +1 -0
  39. package/dist/engine/util.d.ts +1 -29
  40. package/dist/engine/util.js +2 -1
  41. package/dist/examples/adbreak.d.ts +1 -0
  42. package/dist/examples/adbreak.js +104 -0
  43. package/dist/index.d.ts +1 -1
  44. package/dist/package.json +20 -4
  45. package/docs/design/mixing-muxed-demuxed-audio.md +153 -0
  46. package/docs/design/subtitles-live-mix-demux.md +135 -0
  47. package/docs/reference.md +67 -0
  48. package/engine/chaos_monkey.ts +17 -0
  49. package/engine/{event_stream.js → event_stream.ts} +5 -3
  50. package/engine/{memcached_state_store.js → memcached_state_store.ts} +19 -12
  51. package/engine/memory_state_store.ts +71 -0
  52. package/engine/{playhead_state.js → playhead_state.ts} +92 -82
  53. package/engine/{preflight.js → preflight.ts} +1 -1
  54. package/engine/{redis_state_store.js → redis_state_store.ts} +216 -208
  55. package/engine/server.ts +210 -8
  56. package/engine/{session.js → session.ts} +421 -22
  57. package/engine/{session_live.js → session_live.ts} +54 -31
  58. package/engine/{session_live_state.js → session_live_state.ts} +129 -120
  59. package/engine/{session_state.js → session_state.ts} +269 -248
  60. package/engine/{shared_state_store.js → shared_state_store.ts} +31 -19
  61. package/engine/state_store_types.ts +35 -0
  62. package/engine/{stream_switcher.js → stream_switcher.ts} +133 -34
  63. package/engine/{subtitle_slicer.js → subtitle_slicer.ts} +10 -8
  64. package/engine/{util.js → util.ts} +28 -24
  65. package/examples/adbreak.ts +115 -0
  66. package/index.ts +2 -0
  67. package/package.json +20 -4
  68. package/spec/engine/custom_vod_request_params_spec.ts +99 -0
  69. package/spec/engine/drm_spec.ts +128 -0
  70. package/spec/engine/{engine_spec.js → engine_spec.ts} +44 -1
  71. package/spec/engine/{ha_spec.js → ha_spec.ts} +7 -4
  72. package/spec/engine/{init_switching_spec.js → init_switching_spec.ts} +10 -6
  73. package/spec/engine/{interface_spec.js → interface_spec.ts} +16 -4
  74. package/spec/engine/{playhead_live_spec.js → playhead_live_spec.ts} +2 -1
  75. package/spec/engine/{playhead_spec.js → playhead_spec.ts} +15 -8
  76. package/spec/engine/session_spec.ts +800 -0
  77. package/spec/engine/stream_switcher_audio_reconcile_spec.ts +158 -0
  78. package/spec/engine/{stream_switcher_spec.js → stream_switcher_spec.ts} +111 -13
  79. package/spec/engine/subtitle_missing_language_spec.ts +196 -0
  80. package/spec/engine/{subtitle_spec.js → subtitle_spec.ts} +28 -27
  81. package/spec/helpers/ts-resolve.js +65 -0
  82. package/spec/support/jasmine.json +1 -1
  83. package/spec/testvectors/hls_subs_no_language/config.subtitleTracks.json +12 -0
  84. package/spec/testvectors/hls_subs_no_language/evidence_dummy_segments_name_mismatch.m3u8 +24 -0
  85. package/spec/testvectors/hls_subs_no_language/evidence_real_cues_name_match.m3u8 +24 -0
  86. package/spec/testvectors/hls_subs_no_language/french.m3u8 +9 -0
  87. package/spec/testvectors/hls_subs_no_language/master.m3u8 +11 -0
  88. package/spec/testvectors/hls_subs_no_language/video.m3u8 +25 -0
  89. package/spec/testvectors/slate/master.m3u8 +3 -0
  90. package/spec/testvectors/slate/media.m3u8 +9 -0
  91. package/tsconfig.json +21 -4
  92. package/tsconfig.spec.json +16 -0
  93. package/engine/chaos_monkey.js +0 -17
  94. package/engine/memory_state_store.js +0 -63
  95. package/spec/engine/session_spec.js +0 -116
  96. /package/spec/engine/{session_live_spec.js → session_live_spec.ts} +0 -0
  97. /package/spec/engine/{util_spec.js → util_spec.ts} +0 -0
@@ -8,8 +8,8 @@ const fetch = require("node-fetch");
8
8
  const { m3u8Header, roundToThreeDecimals } = require("./util.js");
9
9
  const { AbortController } = require("abort-controller");
10
10
 
11
- const timer = (ms) => new Promise((res) => setTimeout(res, ms));
12
- const daterangeAttribute = (key, attr) => {
11
+ const timer = (ms: number) => new Promise((res) => setTimeout(res, ms));
12
+ const daterangeAttribute = (key: string, attr: any) => {
13
13
  if (key === "planned-duration" || key === "duration") {
14
14
  return key.toUpperCase() + "=" + `${attr.toFixed(3)}`;
15
15
  } else {
@@ -33,13 +33,22 @@ const PlaylistTypes = Object.freeze({
33
33
  SUBTITLE: 3,
34
34
  });
35
35
 
36
+ // Implicit globals assigned to (without a var/let/const declaration) inside
37
+ // class methods; declared ambiently here so the type-checker knows the names.
38
+ // `declare` emits no JavaScript, preserving the original runtime behavior
39
+ // (undeclared assignment / cross-call global) exactly.
40
+ declare let byteRangeOffset: any;
41
+ declare let list: any;
42
+
36
43
  /**
37
44
  * When we implement subtitle support in live-mix we should place it in its own file/or share it with audio
38
45
  * we should also remove audio implementation when we implement subtitles from this file so we don't get at 4000 line long file.
39
46
  */
40
47
 
41
48
  class SessionLive {
42
- constructor(config, sessionLiveStore) {
49
+ [key: string]: any;
50
+
51
+ constructor(config: any, sessionLiveStore: any) {
43
52
  this.sessionId = crypto.randomBytes(20).toString("hex");
44
53
  this.sessionLiveStateStore = sessionLiveStore.sessionLiveStateStore;
45
54
  this.instanceId = sessionLiveStore.instanceId;
@@ -239,7 +248,7 @@ class SessionLive {
239
248
  await timer(timerValueMs);
240
249
  } catch (err) {
241
250
  debug(`[${this.sessionId}]: SessionLive-Playhead consumer crashed`);
242
- console.error(`[${this.sessionId}]: ${err.message}`);
251
+ console.error(`[${this.sessionId}]: ${err instanceof Error ? err.message : err}`);
243
252
  debug(err);
244
253
  this.playheadState = PlayheadState.CRASHED;
245
254
  }
@@ -624,7 +633,7 @@ class SessionLive {
624
633
  }
625
634
 
626
635
  async getCurrentMediaAndDiscSequenceCount() {
627
- const counts = {
636
+ const counts: any = {
628
637
  mediaSeq: this.mediaSeqCountVideo,
629
638
  discSeq: this.discSeqCountVideo,
630
639
  };
@@ -747,7 +756,7 @@ class SessionLive {
747
756
  clearTimeout(timeout);
748
757
  }
749
758
 
750
- return new Promise((resolve, reject) => {
759
+ return new Promise<void>((resolve, reject) => {
751
760
  parser.on("m3u", (m3u) => {
752
761
  debug(`[${this.sessionId}]: ...Fetched a New Live Master Manifest from:\n${masterManifestURI}`);
753
762
  let baseUrl = "";
@@ -928,7 +937,7 @@ class SessionLive {
928
937
  break;
929
938
  }
930
939
  const segDur = this._getAnyFirstSegmentDurationMs() || DEFAULT_PLAYHEAD_INTERVAL_MS;
931
- const waitTimeMs = parseInt(segDur / 3, 10);
940
+ const waitTimeMs = parseInt((segDur / 3) as any, 10);
932
941
  debug(
933
942
  `[${this.sessionId}]: FOLLOWER: Leader has not put anything in store... Will check again in ${waitTimeMs}ms (Tries left=[${attempts}])`
934
943
  );
@@ -953,7 +962,7 @@ class SessionLive {
953
962
  break;
954
963
  }
955
964
  const segDur = this._getAnyFirstSegmentDurationMs() || DEFAULT_PLAYHEAD_INTERVAL_MS;
956
- const waitTimeMs = parseInt(segDur / 3, 10);
965
+ const waitTimeMs = parseInt((segDur / 3) as any, 10);
957
966
  debug(
958
967
  `[${this.sessionId}]: FOLLOWER: Leader has not put anything audio in store... Will check again in ${waitTimeMs}ms (Tries left=[${attempts}])`
959
968
  );
@@ -999,7 +1008,7 @@ class SessionLive {
999
1008
  );
1000
1009
  }
1001
1010
  const segDur = this._getAnyFirstSegmentDurationMs() || DEFAULT_PLAYHEAD_INTERVAL_MS;
1002
- const waitTimeMs = parseInt(segDur / 3, 10);
1011
+ const waitTimeMs = parseInt((segDur / 3) as any, 10);
1003
1012
  debug(`[${this.sessionId}]: FOLLOWER: Cannot find anything NEW in store... Will check again in ${waitTimeMs}ms (Tries left=[${attempts}])`);
1004
1013
  await timer(waitTimeMs);
1005
1014
  this.timerCompensation = false;
@@ -1171,6 +1180,9 @@ class SessionLive {
1171
1180
  audiotracksToSkipOnRetry = [];
1172
1181
  debug(`[${this.sessionId}]: Live Mseq counts=[${allStoredMediaSeqCountsVideo}]`);
1173
1182
  // Figure out what variants's are behind.
1183
+ // @ts-ignore -- pre-existing behavior: `HIGHEST_MEDIA_SEQUENCE_COUNT`
1184
+ // is a module-level `const`; this assignment throws at runtime if ever
1185
+ // reached. Preserved byte-for-byte (type-only migration, #374).
1174
1186
  HIGHEST_MEDIA_SEQUENCE_COUNT = Math.max(...allStoredMediaSeqCountsVideo);
1175
1187
  Object.keys(this.liveSourceM3Us).map((variantKey) => {
1176
1188
  if (this.liveSourceM3Us[variantKey].mediaSeq === HIGHEST_MEDIA_SEQUENCE_COUNT) {
@@ -1197,14 +1209,14 @@ class SessionLive {
1197
1209
  // Find Highest MSEQ
1198
1210
  let [ahead, behind] = Object.keys(this.liveSourceM3Us).map((v) => {
1199
1211
  const c = this.liveSourceM3Us[v].mediaSeq;
1200
- const a = [];
1201
- const b = [];
1212
+ const a: any[] = [];
1213
+ const b: any[] = [];
1202
1214
  if (c === HIGHEST_MEDIA_SEQUENCE_COUNT) {
1203
1215
  a.push({ c, v });
1204
1216
  } else {
1205
1217
  b.push({ c, v });
1206
1218
  }
1207
- });
1219
+ }) as any;
1208
1220
  // Find lowest bitrate with that highest MSEQ
1209
1221
  const variantToPaste = ahead.reduce((min, item) => (item.v < min.v ? item : min), list[0]);
1210
1222
  // Reassign that bitrate onto the one's originally planned for retry
@@ -1896,8 +1908,8 @@ class SessionLive {
1896
1908
  return null;
1897
1909
  }
1898
1910
 
1899
- _parseMediaManifest(m3u, mediaManifestUri, liveTargetBandwidth, isFirstBW, isLeader) {
1900
- return new Promise(async (resolve, reject) => {
1911
+ _parseMediaManifest(m3u: any, mediaManifestUri: any, liveTargetBandwidth: any, isFirstBW: any, isLeader: any) {
1912
+ return new Promise<void>(async (resolve, reject) => {
1901
1913
  try {
1902
1914
  if (!this.liveSegQueue[liveTargetBandwidth]) {
1903
1915
  this.liveSegQueue[liveTargetBandwidth] = [];
@@ -1940,8 +1952,8 @@ class SessionLive {
1940
1952
  });
1941
1953
  }
1942
1954
 
1943
- _parseAudioManifest(m3u, audioPlaylistUri, liveTargetAudiotrack, isFirstAT, isLeader) {
1944
- return new Promise(async (resolve, reject) => {
1955
+ _parseAudioManifest(m3u: any, audioPlaylistUri: any, liveTargetAudiotrack: any, isFirstAT: any, isLeader: any) {
1956
+ return new Promise<void>(async (resolve, reject) => {
1945
1957
  try {
1946
1958
  if (!this.liveSegQueueAudio[liveTargetAudiotrack]) {
1947
1959
  this.liveSegQueueAudio[liveTargetAudiotrack] = [];
@@ -2018,7 +2030,7 @@ class SessionLive {
2018
2030
  let timelinePosition = 0;
2019
2031
 
2020
2032
  for (let i = startIdx; i < playlistItems.length; i++) {
2021
- let seg = {};
2033
+ let seg: any = {};
2022
2034
  const playlistItem = playlistItems[i];
2023
2035
  let segmentUri;
2024
2036
  let byteRange = undefined;
@@ -2338,6 +2350,9 @@ class SessionLive {
2338
2350
  }
2339
2351
 
2340
2352
  if (!segAmounts.every((val, i, arr) => val === arr[0])) {
2353
+ // @ts-ignore -- pre-existing behavior: `console` is called as a function
2354
+ // here (not `console.log`), which throws at runtime if this path is hit.
2355
+ // Preserved byte-for-byte (type-only migration, #374).
2341
2356
  console(`[${this.sessionId}]: Cannot Generate audio Manifest! <${this.instanceId}> Not yet collected ALL segments from Live Source...`);
2342
2357
  return null;
2343
2358
  }
@@ -2505,8 +2520,8 @@ class SessionLive {
2505
2520
  // To only use profiles that the channel will actually need.
2506
2521
  _filterLiveProfiles() {
2507
2522
  const profiles = this.sessionLiveProfile;
2508
- const toKeep = new Set();
2509
- let newItem = {};
2523
+ const toKeep = new Set<any>();
2524
+ let newItem: any = {};
2510
2525
  profiles.forEach((profile) => {
2511
2526
  let bwToKeep = this._getNearestBandwidth(profile.bw, Object.keys(this.mediaManifestURIs));
2512
2527
  toKeep.add(bwToKeep);
@@ -2517,11 +2532,11 @@ class SessionLive {
2517
2532
  this.mediaManifestURIs = newItem;
2518
2533
  }
2519
2534
  _filterLiveProfilesAudio() {
2520
- const tracks = this.sessionAudioTracks.map((trackItem) => {
2535
+ const tracks = this.sessionAudioTracks.map((trackItem: any) => {
2521
2536
  return this._getTrackFromGroupAndLang(trackItem.groupId, trackItem.language);
2522
2537
  });
2523
- const toKeep = new Set();
2524
- let newItem = {};
2538
+ const toKeep = new Set<any>();
2539
+ let newItem: any = {};
2525
2540
  tracks.forEach((t) => {
2526
2541
  let atToKeep = this._findNearestAudiotrack(t, Object.keys(this.audioManifestURIs));
2527
2542
  toKeep.add(atToKeep);
@@ -2534,12 +2549,14 @@ class SessionLive {
2534
2549
 
2535
2550
  _filterLiveAudioTracks() {
2536
2551
  let audioTracks = this.sessionAudioTracks;
2537
- const toKeep = new Set();
2552
+ const toKeep = new Set<any>();
2538
2553
 
2539
- let newItemsAudio = {};
2540
- audioTracks.forEach((audioTrack) => {
2554
+ let newItemsAudio: any = {};
2555
+ audioTracks.forEach((audioTrack: any) => {
2541
2556
  let groupAndLangToKeep = this._findAudioGroupsForLang(audioTrack.language, this.audioManifestURIs);
2542
- toKeep.add(...groupAndLangToKeep);
2557
+ // Cast to a 1-tuple so the (behavior-preserving) spread type-checks against
2558
+ // Set.add's single parameter; runtime is unchanged (extra elements ignored).
2559
+ toKeep.add(...(groupAndLangToKeep as [any]));
2543
2560
  });
2544
2561
 
2545
2562
  toKeep.forEach((trackInfo) => {
@@ -2608,8 +2625,8 @@ class SessionLive {
2608
2625
  return false;
2609
2626
  }
2610
2627
 
2611
- _getGroupAndLangFromTrack(track) {
2612
- const GLItem = {
2628
+ _getGroupAndLangFromTrack(track: any) {
2629
+ const GLItem: any = {
2613
2630
  groupId: null,
2614
2631
  language: null,
2615
2632
  };
@@ -2623,11 +2640,13 @@ class SessionLive {
2623
2640
  return GLItem;
2624
2641
  }
2625
2642
  }
2643
+ // @ts-ignore -- pre-existing behavior: `g`/`l` are block-scoped to the
2644
+ // `if (match)` block above and are not in scope here. Preserved as-is.
2626
2645
  console.error(`Failed to extract GroupID and Language g=${g};l=${l}`);
2627
2646
  return GLItem;
2628
2647
  }
2629
2648
 
2630
- _getLangFromTrack(track) {
2649
+ _getLangFromTrack(track: any) {
2631
2650
  const match = track.match(/g:(.*?);l:(.*)/);
2632
2651
  if (match) {
2633
2652
  const g = match[1];
@@ -2636,11 +2655,13 @@ class SessionLive {
2636
2655
  return l;
2637
2656
  }
2638
2657
  }
2658
+ // @ts-ignore -- pre-existing behavior: `g`/`l` are block-scoped to the
2659
+ // `if (match)` block above and are not in scope here. Preserved as-is.
2639
2660
  console.error(`Failed to extract Language g=${g};l=${l}`);
2640
2661
  return null;
2641
2662
  }
2642
2663
 
2643
- _getGroupFromTrack(track) {
2664
+ _getGroupFromTrack(track: any) {
2644
2665
  const match = track.match(/g:(.*?);l:(.*)/);
2645
2666
  if (match) {
2646
2667
  const g = match[1];
@@ -2649,11 +2670,13 @@ class SessionLive {
2649
2670
  return g;
2650
2671
  }
2651
2672
  }
2673
+ // @ts-ignore -- pre-existing behavior: `g`/`l` are block-scoped to the
2674
+ // `if (match)` block above and are not in scope here. Preserved as-is.
2652
2675
  console.error(`Failed to extract Group ID g=${g};l=${l}`);
2653
2676
  return null;
2654
2677
  }
2655
2678
 
2656
- _getTrackFromGroupAndLang(g, l) {
2679
+ _getTrackFromGroupAndLang(g: any, l: any) {
2657
2680
  return `g:${g};l:${l}`;
2658
2681
  }
2659
2682
 
@@ -1,120 +1,129 @@
1
- const SharedStateStore = require('./shared_state_store.js');
2
- const debug = require("debug")("session-live-state-store");
3
-
4
- class SharedSessionLiveState {
5
- constructor(store, sessionId, instanceId, opts) {
6
- this.sessionId = sessionId;
7
- this.instanceId = instanceId;
8
- this.store = store;
9
- }
10
-
11
- async get(key) {
12
- return await this.store.get(this.sessionId, key);
13
- }
14
-
15
- async set(key, value) {
16
- if (await this.store.isLeader(this.instanceId)) {
17
- return await this.store.set(this.sessionId, key, value);
18
- } else {
19
- return await this.store.get(this.sessionId, key);
20
- }
21
- }
22
-
23
- async remove(key) {
24
- await this.store.remove(this.sessionId, key);
25
- }
26
- }
27
-
28
- class SessionLiveStateStore extends SharedStateStore {
29
- constructor(opts) {
30
- super("sessionLive", opts, {
31
- firstCounts: {
32
- liveSourceMseqCountVideo: null,
33
- liveSourceMseqCountAudio: null,
34
- mediaSeqCountVideo: null,
35
- mediaSeqCountAudio: null,
36
- discSeqCountVideo: null,
37
- discSeqCountAudio: null,
38
- },
39
- lastRequestedMediaSeqRawVideo: null,
40
- liveSegsForFollowers: null,
41
- transitSegs: null,
42
- });
43
-
44
- if (opts && opts.cacheTTL) {
45
- this.cacheTTL = opts.cacheTTL;
46
- }
47
- this.cache = {
48
- leader: {
49
- ts: 0,
50
- value: null
51
- }
52
- };
53
- }
54
-
55
- async ping(instanceId) {
56
- let t = Date.now();
57
- await this.setVolatile("", instanceId, t);
58
- }
59
-
60
- // Should only be called when Channel Engine starts.
61
- // This is due to the fact that we want to sync leaders between Session and SessionLive.
62
- async setLeader(instanceId) {
63
- if (!instanceId) {
64
- throw new Error("Cannot set leader without instance id");
65
- }
66
- debug(`[${instanceId}]: Taking the lead! ${instanceId}`);
67
- await this.set("", "leader", instanceId);
68
- this.cache.leader.ts = Date.now();
69
- this.cache.leader.value = instanceId;
70
- return instanceId;
71
- }
72
-
73
- async isLeader(instanceId) {
74
- if (!instanceId) {
75
- throw new Error("Cannot determine leader without instance id");
76
- }
77
- let leader;
78
- if (this.cache.leader.value && Date.now() < this.cache.leader.ts + this.cacheTTL) {
79
- leader = this.cache.leader.value;
80
- debug(`[${instanceId}]: reading 'leader' from cache: I am ${leader === instanceId ? "" : "NOT"} the leader!`);
81
- return leader === instanceId;
82
- }
83
- leader = await this.get("", "leader");
84
- if (!leader) {
85
- leader = instanceId;
86
- debug(`[${instanceId}]: We have a new leader! ${instanceId}`)
87
- await this.set("", "leader", instanceId);
88
- }
89
- // Check whether leader is actually alive only if I am not the leader
90
- if (leader !== instanceId) {
91
- debug(`[${instanceId}]: Checking whether leader ${leader} is alive`);
92
- const lastSeen = await this.get("", leader); // we don't have per session pings
93
- if (!lastSeen) {
94
- leader = instanceId;
95
- debug(`[${instanceId}]: Current leader is missing, taking the lead! ${leader}`);
96
- await this.set("", "leader", leader);
97
- } else {
98
- if (Date.now() - lastSeen > 30000) {
99
- leader = instanceId;
100
- debug(`[${instanceId}]: Current leader hasn't been seen for the last 30 sec, taking the lead! ${leader}`);
101
- await this.set("", "leader", leader);
102
- }
103
- }
104
- }
105
- debug(`[${instanceId}]: I am ${leader === instanceId ? "" : "NOT"} the leader!`);
106
- this.cache.leader.ts = Date.now();
107
- this.cache.leader.value = leader;
108
- return leader === instanceId;
109
- }
110
-
111
- async create(sessionId, instanceId) {
112
- debug(`[${sessionId}][${instanceId}]: creating SharedSessionLiveState`);
113
- await this.init(sessionId);
114
- return new SharedSessionLiveState(this, sessionId, instanceId, { cacheTTL: this.cacheTTL || 5000 });
115
- }
116
- }
117
-
118
- module.exports = {
119
- SessionLiveStateStore
120
- }
1
+ const SharedStateStore = require('./shared_state_store.js');
2
+ import type { ILeaderCache } from './state_store_types';
3
+ const debug = require("debug")("session-live-state-store");
4
+
5
+ // Type-only migration (#373): a faithful port of the original JS.
6
+
7
+ class SharedSessionLiveState {
8
+ sessionId: string;
9
+ instanceId: string;
10
+ store: SessionLiveStateStore;
11
+
12
+ constructor(store: SessionLiveStateStore, sessionId: string, instanceId: string, opts?: any) {
13
+ this.sessionId = sessionId;
14
+ this.instanceId = instanceId;
15
+ this.store = store;
16
+ }
17
+
18
+ async get(key: string): Promise<any> {
19
+ return await this.store.get(this.sessionId, key);
20
+ }
21
+
22
+ async set(key: string, value: any): Promise<any> {
23
+ if (await this.store.isLeader(this.instanceId)) {
24
+ return await this.store.set(this.sessionId, key, value);
25
+ } else {
26
+ return await this.store.get(this.sessionId, key);
27
+ }
28
+ }
29
+
30
+ async remove(key: string): Promise<void> {
31
+ await this.store.remove(this.sessionId, key);
32
+ }
33
+ }
34
+
35
+ class SessionLiveStateStore extends SharedStateStore {
36
+ declare cache: { leader: ILeaderCache };
37
+
38
+ constructor(opts?: any) {
39
+ super("sessionLive", opts, {
40
+ firstCounts: {
41
+ liveSourceMseqCountVideo: null,
42
+ liveSourceMseqCountAudio: null,
43
+ mediaSeqCountVideo: null,
44
+ mediaSeqCountAudio: null,
45
+ discSeqCountVideo: null,
46
+ discSeqCountAudio: null,
47
+ },
48
+ lastRequestedMediaSeqRawVideo: null,
49
+ liveSegsForFollowers: null,
50
+ transitSegs: null,
51
+ });
52
+
53
+ if (opts && opts.cacheTTL) {
54
+ this.cacheTTL = opts.cacheTTL;
55
+ }
56
+ this.cache = {
57
+ leader: {
58
+ ts: 0,
59
+ value: null
60
+ }
61
+ };
62
+ }
63
+
64
+ async ping(instanceId: string): Promise<void> {
65
+ let t = Date.now();
66
+ await this.setVolatile("", instanceId, t);
67
+ }
68
+
69
+ // Should only be called when Channel Engine starts.
70
+ // This is due to the fact that we want to sync leaders between Session and SessionLive.
71
+ async setLeader(instanceId: string): Promise<string> {
72
+ if (!instanceId) {
73
+ throw new Error("Cannot set leader without instance id");
74
+ }
75
+ debug(`[${instanceId}]: Taking the lead! ${instanceId}`);
76
+ await this.set("", "leader", instanceId);
77
+ this.cache.leader.ts = Date.now();
78
+ this.cache.leader.value = instanceId;
79
+ return instanceId;
80
+ }
81
+
82
+ async isLeader(instanceId: string): Promise<boolean> {
83
+ if (!instanceId) {
84
+ throw new Error("Cannot determine leader without instance id");
85
+ }
86
+ let leader;
87
+ if (this.cache.leader.value && Date.now() < this.cache.leader.ts + this.cacheTTL) {
88
+ leader = this.cache.leader.value;
89
+ debug(`[${instanceId}]: reading 'leader' from cache: I am ${leader === instanceId ? "" : "NOT"} the leader!`);
90
+ return leader === instanceId;
91
+ }
92
+ leader = await this.get("", "leader");
93
+ if (!leader) {
94
+ leader = instanceId;
95
+ debug(`[${instanceId}]: We have a new leader! ${instanceId}`)
96
+ await this.set("", "leader", instanceId);
97
+ }
98
+ // Check whether leader is actually alive only if I am not the leader
99
+ if (leader !== instanceId) {
100
+ debug(`[${instanceId}]: Checking whether leader ${leader} is alive`);
101
+ const lastSeen = await this.get("", leader); // we don't have per session pings
102
+ if (!lastSeen) {
103
+ leader = instanceId;
104
+ debug(`[${instanceId}]: Current leader is missing, taking the lead! ${leader}`);
105
+ await this.set("", "leader", leader);
106
+ } else {
107
+ if (Date.now() - lastSeen > 30000) {
108
+ leader = instanceId;
109
+ debug(`[${instanceId}]: Current leader hasn't been seen for the last 30 sec, taking the lead! ${leader}`);
110
+ await this.set("", "leader", leader);
111
+ }
112
+ }
113
+ }
114
+ debug(`[${instanceId}]: I am ${leader === instanceId ? "" : "NOT"} the leader!`);
115
+ this.cache.leader.ts = Date.now();
116
+ this.cache.leader.value = leader;
117
+ return leader === instanceId;
118
+ }
119
+
120
+ async create(sessionId: string, instanceId: string): Promise<SharedSessionLiveState> {
121
+ debug(`[${sessionId}][${instanceId}]: creating SharedSessionLiveState`);
122
+ await this.init(sessionId);
123
+ return new SharedSessionLiveState(this, sessionId, instanceId, { cacheTTL: this.cacheTTL || 5000 });
124
+ }
125
+ }
126
+
127
+ module.exports = {
128
+ SessionLiveStateStore
129
+ };