@fonoster/apiserver 0.30.0 → 0.31.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 (159) hide show
  1. package/dist/applications/buildService.d.ts +1 -1
  2. package/dist/applications/buildService.js +4 -3
  3. package/dist/applications/createCreateApplication.js +6 -3
  4. package/dist/applications/createCreateTestToken.d.ts +3 -1
  5. package/dist/applications/createCreateTestToken.js +18 -13
  6. package/dist/applications/createGetFnUtil.d.ts +1 -1
  7. package/dist/applications/createUpdateApplication.js +6 -4
  8. package/dist/applications/evalKeys.d.ts +7 -1
  9. package/dist/applications/evalKeys.js +9 -3
  10. package/dist/applications/session/appModel.d.ts +28 -4
  11. package/dist/applications/session/appModel.js +74 -35
  12. package/dist/billing/buildService.d.ts +24 -0
  13. package/dist/billing/buildService.js +116 -0
  14. package/dist/{migration/cli.js → bin/usage.js} +46 -22
  15. package/dist/calls/buildService.d.ts +1 -20
  16. package/dist/calls/buildService.js +50 -10
  17. package/dist/calls/createCall.d.ts +16 -2
  18. package/dist/calls/createCall.js +29 -6
  19. package/dist/calls/createCallPublisher.d.ts +6 -4
  20. package/dist/calls/createCallPublisher.js +6 -5
  21. package/dist/calls/createTrackCall.d.ts +16 -13
  22. package/dist/calls/createTrackCall.js +78 -55
  23. package/dist/calls/getCall.d.ts +3 -3
  24. package/dist/calls/getCall.js +2 -3
  25. package/dist/calls/listCalls.d.ts +4 -4
  26. package/dist/calls/listCalls.js +2 -3
  27. package/dist/calls/types.d.ts +2 -1
  28. package/dist/capabilities/createGetCapabilities.d.ts +3 -0
  29. package/dist/capabilities/createGetCapabilities.js +2 -1
  30. package/dist/config/index.js +1 -3
  31. package/dist/config/schema.d.ts +106 -102
  32. package/dist/config/schema.js +39 -47
  33. package/dist/core/applyCatalog.d.ts +3 -3
  34. package/dist/core/applyCatalog.js +5 -4
  35. package/dist/core/regionHooks.d.ts +1 -0
  36. package/dist/core/runServices.js +25 -4
  37. package/dist/core/services.d.ts +25 -1
  38. package/dist/core/services.js +35 -11
  39. package/dist/core/testTokenConfig.js +2 -2
  40. package/dist/core/upsertRoomrPeer.d.ts +6 -0
  41. package/dist/core/{upsertMediaNodePeer.js → upsertRoomrPeer.js} +9 -9
  42. package/dist/envs.d.ts +30 -16
  43. package/dist/envs.js +49 -31
  44. package/dist/index.js +23 -22
  45. package/dist/outbound/createNodeDirectory.d.ts +35 -13
  46. package/dist/outbound/createNodeDirectory.js +54 -20
  47. package/dist/outbound/index.d.ts +1 -0
  48. package/dist/outbound/index.js +1 -0
  49. package/dist/outbound/placeOutboundCall.d.ts +53 -13
  50. package/dist/outbound/placeOutboundCall.js +135 -88
  51. package/dist/outbound/placementSweep.d.ts +56 -0
  52. package/dist/outbound/placementSweep.js +127 -0
  53. package/dist/outbound/runOutboundCalls.d.ts +18 -14
  54. package/dist/outbound/runOutboundCalls.js +46 -34
  55. package/dist/providers/createProvidersHandlers.d.ts +1 -10
  56. package/dist/providers/createProvidersHandlers.js +20 -25
  57. package/dist/providers/index.d.ts +2 -2
  58. package/dist/providers/index.js +2 -2
  59. package/dist/providers/registryUsage.d.ts +2 -2
  60. package/dist/providers/registryUsage.js +5 -5
  61. package/dist/records/createIndexRecord.d.ts +26 -3
  62. package/dist/records/createIndexRecord.js +37 -10
  63. package/dist/records/createRecordsRouter.js +4 -2
  64. package/dist/records/createSearchRecords.d.ts +4 -3
  65. package/dist/records/createSearchRecords.js +9 -21
  66. package/dist/records/maintenance.d.ts +1 -1
  67. package/dist/records/maintenance.js +1 -1
  68. package/dist/records/runCallRecords.d.ts +2 -0
  69. package/dist/records/runCallRecords.js +1 -1
  70. package/dist/records/types.d.ts +2 -0
  71. package/dist/regions/configSync.d.ts +5 -5
  72. package/dist/regions/configSync.js +9 -9
  73. package/dist/regions/createRegionsRouter.d.ts +6 -6
  74. package/dist/regions/createRegionsRouter.js +5 -5
  75. package/dist/regions/link.js +1 -1
  76. package/dist/regions/runRegions.d.ts +2 -0
  77. package/dist/regions/runRegions.js +4 -0
  78. package/dist/regions/service.js +4 -4
  79. package/dist/regions/sources.d.ts +1 -1
  80. package/dist/regions/sources.js +4 -4
  81. package/dist/regions/status.js +5 -4
  82. package/dist/regions/types.d.ts +2 -2
  83. package/dist/usage/buildService.d.ts +16 -0
  84. package/dist/{calls/influxdb.js → usage/buildService.js} +16 -9
  85. package/dist/{events/createPerCallCache.d.ts → usage/createGetUsage.d.ts} +7 -7
  86. package/dist/usage/createGetUsage.js +118 -0
  87. package/dist/usage/ingestUsage.d.ts +7 -0
  88. package/dist/usage/ingestUsage.js +87 -0
  89. package/dist/usage/publishRecordedUsage.d.ts +52 -0
  90. package/dist/usage/publishRecordedUsage.js +103 -0
  91. package/dist/usage/publishUsage.d.ts +29 -0
  92. package/dist/usage/publishUsage.js +50 -0
  93. package/dist/usage/rebuildUsage.d.ts +48 -0
  94. package/dist/usage/rebuildUsage.js +104 -0
  95. package/dist/usage/runUsageConsumer.d.ts +22 -0
  96. package/dist/usage/runUsageConsumer.js +78 -0
  97. package/dist/usage/snapshotStorage.d.ts +14 -0
  98. package/dist/usage/snapshotStorage.js +95 -0
  99. package/dist/usage/types.d.ts +36 -0
  100. package/dist/voice/stt/types.js +1 -1
  101. package/dist/webhooks/lostCalls.d.ts +35 -12
  102. package/dist/webhooks/lostCalls.js +86 -48
  103. package/dist/webhooks/nodeCallEvents.d.ts +73 -0
  104. package/dist/webhooks/nodeCallEvents.js +177 -0
  105. package/dist/webhooks/runWebhookFanout.d.ts +10 -4
  106. package/dist/webhooks/runWebhookFanout.js +41 -39
  107. package/package.json +17 -19
  108. package/dist/applications/migration/PrismaApplicationStore.d.ts +0 -55
  109. package/dist/applications/migration/PrismaApplicationStore.js +0 -92
  110. package/dist/applications/migration/convertLegacyApplication.d.ts +0 -11
  111. package/dist/applications/migration/convertLegacyApplication.js +0 -112
  112. package/dist/applications/migration/index.d.ts +0 -22
  113. package/dist/applications/migration/index.js +0 -38
  114. package/dist/applications/migration/migrateApplications.d.ts +0 -43
  115. package/dist/applications/migration/migrateApplications.js +0 -87
  116. package/dist/applications/migration/types.d.ts +0 -92
  117. package/dist/applications/migration/types.js +0 -20
  118. package/dist/calls/createFetchCalls.d.ts +0 -22
  119. package/dist/calls/createFetchCalls.js +0 -88
  120. package/dist/calls/createFetchSingleCall.d.ts +0 -22
  121. package/dist/calls/createFetchSingleCall.js +0 -54
  122. package/dist/calls/influxdb.d.ts +0 -2
  123. package/dist/core/upsertMediaNodePeer.d.ts +0 -6
  124. package/dist/events/callRefs.d.ts +0 -29
  125. package/dist/events/callRefs.js +0 -103
  126. package/dist/events/createCdrWriter.d.ts +0 -25
  127. package/dist/events/createCdrWriter.js +0 -95
  128. package/dist/events/createInfluxDbPub.d.ts +0 -10
  129. package/dist/events/createInfluxDbPub.js +0 -46
  130. package/dist/events/createPerCallCache.js +0 -46
  131. package/dist/events/mapCallDirectionToEnum.d.ts +0 -21
  132. package/dist/events/mapCallDirectionToEnum.js +0 -37
  133. package/dist/events/nats.d.ts +0 -44
  134. package/dist/events/nats.js +0 -93
  135. package/dist/events/transformEvent.d.ts +0 -4
  136. package/dist/events/transformEvent.js +0 -87
  137. package/dist/events/types.d.ts +0 -26
  138. package/dist/migration/argv.d.ts +0 -22
  139. package/dist/migration/argv.js +0 -42
  140. package/dist/migration/catalogMapping.d.ts +0 -30
  141. package/dist/migration/catalogMapping.js +0 -53
  142. package/dist/migration/index.d.ts +0 -27
  143. package/dist/migration/index.js +0 -43
  144. package/dist/migration/migrateAssistants.d.ts +0 -8
  145. package/dist/migration/migrateAssistants.js +0 -169
  146. package/dist/migration/migrateCredentials.d.ts +0 -4
  147. package/dist/migration/migrateCredentials.js +0 -107
  148. package/dist/migration/migrateIntegrations.d.ts +0 -32
  149. package/dist/migration/migrateIntegrations.js +0 -136
  150. package/dist/migration/migrateLegacy.d.ts +0 -41
  151. package/dist/migration/migrateLegacy.js +0 -76
  152. package/dist/migration/providerKeys.d.ts +0 -14
  153. package/dist/migration/providerKeys.js +0 -61
  154. package/dist/migration/seedCatalog.d.ts +0 -2
  155. package/dist/migration/seedCatalog.js +0 -160
  156. package/dist/migration/types.d.ts +0 -42
  157. package/dist/migration/types.js +0 -31
  158. /package/dist/{migration/cli.d.ts → bin/usage.d.ts} +0 -0
  159. /package/dist/{events → usage}/types.js +0 -0
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.APPBRIDGE_LOST_REASON = void 0;
3
+ exports.LOST_CALL_FORGET_MS = exports.APP_GONE_GRACE_MS = exports.APPBRIDGE_LOST_REASON = void 0;
4
4
  exports.lostCallEnded = lostCallEnded;
5
- exports.createLostCallSweep = createLostCallSweep;
5
+ exports.createLostCalls = createLostCalls;
6
6
  /**
7
7
  * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
8
8
  * http://github.com/fonoster/fonoster
@@ -23,11 +23,11 @@ exports.createLostCallSweep = createLostCallSweep;
23
23
  */
24
24
  const crypto_1 = require("crypto");
25
25
  const common_1 = require("@fonoster/common");
26
- /** `call.ended`'s `endReason` when the appbridge that owned the call died mid-call. */
26
+ /** `call.ended`'s `endReason` when AppBridge that owned the call died mid-call. */
27
27
  exports.APPBRIDGE_LOST_REASON = "appbridge-lost";
28
28
  /**
29
- * The `call.ended` the control plane sends for a call whose appbridge is gone. Its id depends on
30
- * the call only, so every replica that detects the loss builds the same event and the fan-out
29
+ * The `call.ended` the control plane sends for a call whose AppBridge is gone (the node ended it
30
+ * with cause `app_gone`). Its id depends on the call only, so every replica that detects the loss builds the same event and the fan-out
31
31
  * stores one delivery per endpoint (delivery ids depend on the event id): delivered once.
32
32
  */
33
33
  function lostCallEnded(call, lastSeenAt) {
@@ -55,55 +55,93 @@ function lostCallEnded(call, lastSeenAt) {
55
55
  .slice(0, 32);
56
56
  return Object.assign(Object.assign({}, event), { id: `evt_lost_${digest}` });
57
57
  }
58
+ /** How long after the node's `app_gone` an AppBridge's own end of the call may still show up. */
59
+ exports.APP_GONE_GRACE_MS = 2000;
58
60
  /**
59
- * Finds calls whose appbridge died mid-call, from the session registry: an appbridge rewrites its
60
- * `gateways.<ref>` entry and each of its `calls.<callRef>` entries every SESSIONS_REFRESH_MS and
61
- * deletes a call's entry when the call ends. A call entry not rewritten for `staleMs` (the lease
62
- * TTL) whose appbridge's entry is not rewritten either is a lost call: `emit` gets its
63
- * `call.ended` (reason `appbridge-lost`) and the call is forgotten. Times are when this replica
64
- * saw each write, so a replica that just started waits a full `staleMs` before judging.
61
+ * How long a call entry is remembered after its last write: an AppBridge rewrites its entries
62
+ * every SESSIONS_REFRESH_MS, and the node reports `app_gone` well within this after its AppBridge
63
+ * stops (stream break at once, keepalive or media timeout within seconds).
65
64
  */
66
- function createLostCallSweep(deps) {
67
- var _a, _b;
68
- const staleMs = (_a = deps.staleMs) !== null && _a !== void 0 ? _a : common_1.Sessions.SESSIONS_TTL_MS;
69
- const now = (_b = deps.now) !== null && _b !== void 0 ? _b : Date.now;
65
+ exports.LOST_CALL_FORGET_MS = 5 * 60000;
66
+ /**
67
+ * Calls whose AppBridge died mid-call (redesign-roomr 15.4, workspace-webhooks "AppBridge dies
68
+ * mid-call"). AppBridge writes `calls.<callRef>` (with the app and parties once the call reached
69
+ * an app) and deletes it when the call ends, right after it sent its own `call.ended`. When the
70
+ * Roomr node ends a call with cause `app_gone` (its control stream broke, or the app leg went
71
+ * silent), `onAppGone` waits `graceMs` for that delete and then, if the entry was not deleted (it
72
+ * is still there, or it expired with the AppBridge that kept it alive), `emit` gets the call's
73
+ * `call.ended` with `endReason` `appbridge-lost`. Its id depends on the call only, so the event is
74
+ * delivered once per endpoint across replicas; a call AppBridge ended itself gets none.
75
+ *
76
+ * Entries are remembered as this replica saw them on the registry watch (an entry that expires is
77
+ * not reported by the watch, so it stays here until `forgetMs` after its last write).
78
+ */
79
+ function createLostCalls(deps) {
80
+ var _a, _b, _c;
81
+ const graceMs = (_a = deps.graceMs) !== null && _a !== void 0 ? _a : exports.APP_GONE_GRACE_MS;
82
+ const forgetMs = (_b = deps.forgetMs) !== null && _b !== void 0 ? _b : exports.LOST_CALL_FORGET_MS;
83
+ const now = (_c = deps.now) !== null && _c !== void 0 ? _c : Date.now;
70
84
  const calls = new Map();
71
- const gateways = new Map();
85
+ /** Calls already reported here (a repeated app_gone sends nothing more). */
86
+ const reported = new Map();
87
+ const timers = new Set();
88
+ const forget = () => {
89
+ const at = now();
90
+ for (const [id, c] of calls)
91
+ if (at - c.seenAt > forgetMs)
92
+ calls.delete(id);
93
+ for (const [id, t] of reported)
94
+ if (at - t > forgetMs)
95
+ reported.delete(id);
96
+ };
97
+ /** One `calls.*` registry entry (a put, or a delete when the call ended normally). */
72
98
  const onEntry = (e) => {
73
- if (e.kind === "calls") {
74
- if (e.value)
75
- calls.set(e.id, { value: e.value, seenAt: now() });
76
- else
77
- calls.delete(e.id); // ended: its appbridge sent call.ended
78
- }
79
- else if (e.kind === "gateways") {
80
- if (e.value)
81
- gateways.set(e.id, now());
82
- else
83
- gateways.delete(e.id);
84
- }
99
+ if (e.kind !== "calls")
100
+ return;
101
+ if (e.value)
102
+ calls.set(e.id, { value: e.value, seenAt: now() });
103
+ else
104
+ calls.delete(e.id); // ended: its AppBridge sent call.ended
105
+ if (calls.size % 256 === 0)
106
+ forget();
85
107
  };
86
- const sweep = () => {
87
- var _a, _b;
88
- const at = now();
89
- const lost = [];
90
- for (const [id, c] of calls) {
91
- if (at - c.seenAt <= staleMs)
92
- continue;
93
- // Watched ids are the key after `gateways.` (sanitized like the key).
94
- const gatewayId = common_1.Sessions.sessionKey("gateways", String((_a = c.value.gatewayRef) !== null && _a !== void 0 ? _a : "")).slice("gateways.".length);
95
- const gatewaySeen = (_b = gateways.get(gatewayId)) !== null && _b !== void 0 ? _b : 0;
96
- // The appbridge is alive: it will rewrite the entry (or delete it when the call ends).
97
- if (at - gatewaySeen <= staleMs)
98
- continue;
99
- calls.delete(id);
100
- const event = lostCallEnded(c.value, c.seenAt);
101
- if (!event)
102
- continue;
103
- lost.push(event);
108
+ /** Reports the call now if its entry is still known; returns its event. */
109
+ const report = (callRef) => {
110
+ const id = common_1.Sessions.sessionKey("calls", callRef).slice("calls.".length);
111
+ const c = calls.get(id);
112
+ if (!c || reported.has(id))
113
+ return undefined;
114
+ calls.delete(id);
115
+ reported.set(id, now());
116
+ const event = lostCallEnded(c.value, now());
117
+ if (event)
104
118
  deps.emit(event);
119
+ return event;
120
+ };
121
+ return {
122
+ onEntry,
123
+ /**
124
+ * The node ended `callRef` with cause `app_gone`: after `graceMs` (an AppBridge that ended the
125
+ * call itself deletes its entry by then) the call's `call.ended` (appbridge-lost) is sent.
126
+ * Resolves with the event, or undefined when there is none to send.
127
+ */
128
+ onAppGone(callRef) {
129
+ if (graceMs <= 0)
130
+ return Promise.resolve(report(callRef));
131
+ return new Promise((resolve) => {
132
+ const t = setTimeout(() => {
133
+ timers.delete(t);
134
+ resolve(report(callRef));
135
+ }, graceMs);
136
+ timers.add(t);
137
+ });
138
+ },
139
+ /** Drops what is remembered past `forgetMs` (also done as entries arrive). */
140
+ forget,
141
+ size: () => calls.size,
142
+ stop() {
143
+ timers.forEach(clearTimeout);
144
+ timers.clear();
105
145
  }
106
- return lost;
107
146
  };
108
- return { onEntry, sweep, size: () => calls.size };
109
147
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
3
+ * http://github.com/fonoster/fonoster
4
+ *
5
+ * This file is part of Fonoster
6
+ *
7
+ * Licensed under the MIT License (the "License");
8
+ * you may not use this file except in compliance with
9
+ * the License. You may obtain a copy of the License at
10
+ *
11
+ * https://opensource.org/licenses/MIT
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ import { Webhooks } from "@fonoster/common";
20
+ import { NatsConnection } from "nats";
21
+ import { LostCalls } from "./lostCalls";
22
+ /** One replica handles each node event (core NATS queue group). */
23
+ export declare const NODE_EVENTS_QUEUE = "apiserver-roomr-events";
24
+ /** The minimal record of an unanswered outbound call, written where the region keeps records. */
25
+ export type FailedCallRecord = {
26
+ callRef: string;
27
+ workspaceRef: string | null;
28
+ /** The node's region (its heartbeat), where the record is written. */
29
+ region?: string;
30
+ entries: Record<string, unknown>[];
31
+ };
32
+ export type FailedCallRecords = (record: FailedCallRecord) => Promise<unknown>;
33
+ /** Where records go when the node reports no region (AppBridge's `callRecord.region` default). */
34
+ export declare const DEFAULT_RECORD_REGION = "default";
35
+ /**
36
+ * Writes failed-call records through the region's record maintenance subject
37
+ * (`callrecord.<region>.maintenance`, op `failed_call`, served by the AppBridge replicas that hold
38
+ * the region's signing key): the control plane never holds it.
39
+ */
40
+ export declare function natsFailedCallRecords(nc: NatsConnection, timeoutMs?: number): FailedCallRecords;
41
+ /** The minimal record's entries (as AppBridge wrote them for calls that never reached an app). */
42
+ export declare function failedCallEntries(call: Webhooks.UnansweredCall, workspaceRef: string | null): Record<string, unknown>[];
43
+ /**
44
+ * The control plane's reading of the Roomr nodes' call events (`roomr.events.<call_ref>`, one
45
+ * replica per event): what no AppBridge can report.
46
+ *
47
+ * - An outbound call the control plane placed (its `metadata.app_ref`) that ends unanswered
48
+ * (`call.ended` with `answered: false`: busy, no answer, rejected, node error, removed) reached
49
+ * no AppBridge: its minimal call record (call.started, call.progress, call.failed) is written
50
+ * (`records`) and `call.failed` goes to the fan-out (`intake`).
51
+ * - A call the node ended with cause `app_gone` lost its AppBridge: `lost` sends its `call.ended`
52
+ * (`appbridge-lost`) unless AppBridge ended the call itself.
53
+ *
54
+ * Events are best effort (media-control "Events are best effort while NATS is down"): one lost in
55
+ * an outage is never replayed; TrackCall's and the placement sweep's own sweeps close what it
56
+ * would have closed.
57
+ */
58
+ export declare function createNodeCallEvents(deps: {
59
+ lost?: LostCalls;
60
+ intake: (event: Webhooks.WebhookEvent) => Promise<unknown> | unknown;
61
+ records?: FailedCallRecords;
62
+ /** The workspace of an app (the record names it; the webhook resolves it itself). */
63
+ workspaceOfApp?: (appRef: string) => Promise<string | undefined>;
64
+ /** The region of a node from its heartbeats. */
65
+ regionOf?: (nodeRef: string) => string | undefined;
66
+ }): {
67
+ onEvent(subject: string, event: Record<string, unknown>): Promise<void>;
68
+ };
69
+ /**
70
+ * Subscribes to the nodes' call events (one replica per event) and their heartbeats (each node's
71
+ * region); returns a stop function.
72
+ */
73
+ export declare function subscribeNodeCallEvents(nc: NatsConnection, deps: Omit<Parameters<typeof createNodeCallEvents>[0], "regionOf">): () => void;
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DEFAULT_RECORD_REGION = exports.NODE_EVENTS_QUEUE = void 0;
13
+ exports.natsFailedCallRecords = natsFailedCallRecords;
14
+ exports.failedCallEntries = failedCallEntries;
15
+ exports.createNodeCallEvents = createNodeCallEvents;
16
+ exports.subscribeNodeCallEvents = subscribeNodeCallEvents;
17
+ /**
18
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
19
+ * http://github.com/fonoster/fonoster
20
+ *
21
+ * This file is part of Fonoster
22
+ *
23
+ * Licensed under the MIT License (the "License");
24
+ * you may not use this file except in compliance with
25
+ * the License. You may obtain a copy of the License at
26
+ *
27
+ * https://opensource.org/licenses/MIT
28
+ *
29
+ * Unless required by applicable law or agreed to in writing, software
30
+ * distributed under the License is distributed on an "AS IS" BASIS,
31
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
32
+ * See the License for the specific language governing permissions and
33
+ * limitations under the License.
34
+ */
35
+ const common_1 = require("@fonoster/common");
36
+ const logger_1 = require("@fonoster/logger");
37
+ const nats_1 = require("nats");
38
+ const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
39
+ const sc = (0, nats_1.StringCodec)();
40
+ /** One replica handles each node event (core NATS queue group). */
41
+ exports.NODE_EVENTS_QUEUE = "apiserver-roomr-events";
42
+ /** Where records go when the node reports no region (AppBridge's `callRecord.region` default). */
43
+ exports.DEFAULT_RECORD_REGION = "default";
44
+ /**
45
+ * Writes failed-call records through the region's record maintenance subject
46
+ * (`callrecord.<region>.maintenance`, op `failed_call`, served by the AppBridge replicas that hold
47
+ * the region's signing key): the control plane never holds it.
48
+ */
49
+ function natsFailedCallRecords(nc, timeoutMs = 5000) {
50
+ return (record) => __awaiter(this, void 0, void 0, function* () {
51
+ var _a;
52
+ const region = record.region || exports.DEFAULT_RECORD_REGION;
53
+ const msg = yield nc.request(`callrecord.${region}.maintenance`, sc.encode(JSON.stringify({
54
+ op: "failed_call",
55
+ callRef: record.callRef,
56
+ workspaceRef: record.workspaceRef,
57
+ entries: record.entries,
58
+ reason: "unanswered outbound call",
59
+ actor: "control-plane"
60
+ })), { timeout: timeoutMs });
61
+ const reply = JSON.parse(sc.decode(msg.data));
62
+ if ((reply === null || reply === void 0 ? void 0 : reply.type) !== "ack")
63
+ throw new Error(`record not written: ${(_a = reply === null || reply === void 0 ? void 0 : reply.code) !== null && _a !== void 0 ? _a : "error"}`);
64
+ return reply;
65
+ });
66
+ }
67
+ /** The minimal record's entries (as AppBridge wrote them for calls that never reached an app). */
68
+ function failedCallEntries(call, workspaceRef) {
69
+ const sip = call.sipStatus ? { sipStatus: call.sipStatus } : {};
70
+ return [
71
+ {
72
+ type: "call.started",
73
+ direction: "outbound",
74
+ appRef: call.appRef,
75
+ workspaceRef,
76
+ from: call.from,
77
+ to: call.to
78
+ },
79
+ Object.assign({ type: "call.progress", status: call.reason }, sip),
80
+ Object.assign({ type: "call.failed", reason: call.reason }, sip)
81
+ ];
82
+ }
83
+ /**
84
+ * The control plane's reading of the Roomr nodes' call events (`roomr.events.<call_ref>`, one
85
+ * replica per event): what no AppBridge can report.
86
+ *
87
+ * - An outbound call the control plane placed (its `metadata.app_ref`) that ends unanswered
88
+ * (`call.ended` with `answered: false`: busy, no answer, rejected, node error, removed) reached
89
+ * no AppBridge: its minimal call record (call.started, call.progress, call.failed) is written
90
+ * (`records`) and `call.failed` goes to the fan-out (`intake`).
91
+ * - A call the node ended with cause `app_gone` lost its AppBridge: `lost` sends its `call.ended`
92
+ * (`appbridge-lost`) unless AppBridge ended the call itself.
93
+ *
94
+ * Events are best effort (media-control "Events are best effort while NATS is down"): one lost in
95
+ * an outage is never replayed; TrackCall's and the placement sweep's own sweeps close what it
96
+ * would have closed.
97
+ */
98
+ function createNodeCallEvents(deps) {
99
+ return {
100
+ onEvent(subject, event) {
101
+ return __awaiter(this, void 0, void 0, function* () {
102
+ var _a, _b, _c, _d, _e;
103
+ if ((event === null || event === void 0 ? void 0 : event.type) !== "call.ended")
104
+ return;
105
+ if (event.cause === "app_gone" && typeof event.call_ref === "string") {
106
+ yield ((_a = deps.lost) === null || _a === void 0 ? void 0 : _a.onAppGone(event.call_ref));
107
+ }
108
+ const call = common_1.Webhooks.unansweredOutboundCall(subject, event);
109
+ if (!call)
110
+ return;
111
+ const workspaceRef = (_c = (yield ((_b = deps.workspaceOfApp) === null || _b === void 0 ? void 0 : _b.call(deps, call.appRef).catch(() => undefined)))) !== null && _c !== void 0 ? _c : null;
112
+ yield Promise.all([
113
+ (_d = deps
114
+ .records) === null || _d === void 0 ? void 0 : _d.call(deps, {
115
+ callRef: call.callRef,
116
+ workspaceRef,
117
+ region: (_e = deps.regionOf) === null || _e === void 0 ? void 0 : _e.call(deps, call.nodeRef),
118
+ entries: failedCallEntries(call, workspaceRef)
119
+ }).catch((e) => logger.warn(`call ${call.callRef}: minimal record not written: ${e.message}`)),
120
+ deps.intake(common_1.Webhooks.unansweredCallFailed(call))
121
+ ]);
122
+ });
123
+ }
124
+ };
125
+ }
126
+ /**
127
+ * Subscribes to the nodes' call events (one replica per event) and their heartbeats (each node's
128
+ * region); returns a stop function.
129
+ */
130
+ function subscribeNodeCallEvents(nc, deps) {
131
+ const regions = new Map();
132
+ const handler = createNodeCallEvents(Object.assign(Object.assign({}, deps), { regionOf: (nodeRef) => regions.get(nodeRef) }));
133
+ const parse = (data) => {
134
+ try {
135
+ const v = JSON.parse(sc.decode(data));
136
+ return v && typeof v === "object"
137
+ ? v
138
+ : undefined;
139
+ }
140
+ catch (_a) {
141
+ return undefined;
142
+ }
143
+ };
144
+ const events = nc.subscribe(common_1.Webhooks.ROOMR_CALL_EVENTS_SUBJECT, {
145
+ queue: exports.NODE_EVENTS_QUEUE,
146
+ callback: (err, msg) => {
147
+ if (err)
148
+ return;
149
+ const event = parse(msg.data);
150
+ if (!event)
151
+ return;
152
+ handler
153
+ .onEvent(msg.subject, event)
154
+ .catch((e) => logger.warn(`node call event failed: ${e.message}`));
155
+ }
156
+ });
157
+ const beats = nc.subscribe("roomr.nodes.*.heartbeat", {
158
+ callback: (err, msg) => {
159
+ if (err)
160
+ return;
161
+ const beat = parse(msg.data);
162
+ if ((beat === null || beat === void 0 ? void 0 : beat.type) === "node.heartbeat" &&
163
+ typeof beat.node_ref === "string" &&
164
+ typeof beat.region === "string" &&
165
+ beat.region) {
166
+ // Bounded: nodes come and go (a new node_ref per start).
167
+ if (regions.size >= 1024 && !regions.has(beat.node_ref))
168
+ regions.clear();
169
+ regions.set(beat.node_ref, beat.region);
170
+ }
171
+ }
172
+ });
173
+ return () => {
174
+ events.unsubscribe();
175
+ beats.unsubscribe();
176
+ };
177
+ }
@@ -12,8 +12,13 @@ export type WebhookFanoutConfig = {
12
12
  allowedDestinations?: string[];
13
13
  /** How long a replica may hold an event before another one gets it (default 30 s). */
14
14
  ackWaitMs?: number;
15
- /** How often calls of lost appbridges are looked for (default 5 s; 0 turns it off). */
16
- lostCallSweepMs?: number;
15
+ /**
16
+ * How long after a node's `app_gone` an AppBridge's own end of the call may still arrive before
17
+ * the control plane sends `call.ended` (appbridge-lost) (default 2 s; tests).
18
+ */
19
+ appGoneGraceMs?: number;
20
+ /** Whether minimal records of unanswered outbound calls are written (default true). */
21
+ failedCallRecords?: boolean;
17
22
  /** The session registry's bucket (default Sessions.SESSIONS_BUCKET; tests). */
18
23
  sessionsBucket?: string;
19
24
  };
@@ -22,8 +27,9 @@ export type WebhookFanoutDb = any;
22
27
  /**
23
28
  * Event fan-out from the bus (add-workspace-webhooks 2.2, build log LO-B1, ST-2): consumes
24
29
  * `webhooks.events` through a JetStream durable consumer (one replica per event), fills in the
25
- * workspace from the app when a producer did not know it (and takes media nodes' call.failed
26
- * reports from their own subject), reloads that workspace's endpoints,
30
+ * workspace from the app when a producer did not know it (and builds the events no AppBridge can
31
+ * send from the Roomr nodes' call events: call.failed of unanswered outbound calls and call.ended
32
+ * of calls whose AppBridge was lost), reloads that workspace's endpoints,
27
33
  * stores one delivery per subscribed endpoint and only then acknowledges the event, attempts the
28
34
  * new deliveries at once, and keeps retrying due deliveries (including ones adopted from replicas
29
35
  * that died). An event redelivered after a replica died finds the deliveries it already made
@@ -33,6 +33,7 @@ const common_1 = require("@fonoster/common");
33
33
  const logger_1 = require("@fonoster/logger");
34
34
  const durableConsumer_1 = require("../core/durableConsumer");
35
35
  const lostCalls_1 = require("./lostCalls");
36
+ const nodeCallEvents_1 = require("./nodeCallEvents");
36
37
  const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
37
38
  /** The work queue that captures `webhooks.events` and its one durable consumer (ST-2). */
38
39
  exports.WEBHOOK_EVENTS_STREAM = "FONOSTER_WEBHOOKS";
@@ -40,8 +41,9 @@ exports.WEBHOOK_EVENTS_DURABLE = "apiserver-webhooks";
40
41
  /**
41
42
  * Event fan-out from the bus (add-workspace-webhooks 2.2, build log LO-B1, ST-2): consumes
42
43
  * `webhooks.events` through a JetStream durable consumer (one replica per event), fills in the
43
- * workspace from the app when a producer did not know it (and takes media nodes' call.failed
44
- * reports from their own subject), reloads that workspace's endpoints,
44
+ * workspace from the app when a producer did not know it (and builds the events no AppBridge can
45
+ * send from the Roomr nodes' call events: call.failed of unanswered outbound calls and call.ended
46
+ * of calls whose AppBridge was lost), reloads that workspace's endpoints,
45
47
  * stores one delivery per subscribed endpoint and only then acknowledges the event, attempts the
46
48
  * new deliveries at once, and keeps retrying due deliveries (including ones adopted from replicas
47
49
  * that died). An event redelivered after a replica died finds the deliveries it already made
@@ -102,23 +104,19 @@ function runWebhookFanout(config, deps) {
102
104
  if (event)
103
105
  yield intakeEvent(event);
104
106
  });
105
- // Media nodes report calls no gateway claimed on their own subject (they may not publish
106
- // webhooks.events, M6); only a well-formed call.failed is accepted, its workspace from the app.
107
- // One replica per report (queue group); a repeated report has the same event id.
108
- const nodeReports = deps.nc.subscribe(common_1.Webhooks.NODE_CALL_FAILED_SUBJECT, {
109
- queue: "apiserver-node-call-failed",
110
- callback: (err, msg) => {
111
- if (err)
112
- return;
113
- const event = common_1.Webhooks.nodeCallFailedEvent(msg.subject, msg.data);
114
- if (!event)
115
- return;
116
- intakeEvent(event).catch((e) => logger.warn(`node call.failed fan-out failed: ${e.message}`));
117
- }
107
+ // What no AppBridge can report, from the nodes' call events (one replica per event; the
108
+ // events' ids depend on the call, so each endpoint gets one delivery): call.failed (and the
109
+ // minimal record) of unanswered outbound calls, call.ended (appbridge-lost) of calls whose
110
+ // AppBridge died.
111
+ const lost = yield watchLostCalls(config, deps.nc, (event) => intakeEvent(event).catch((e) => logger.warn(`lost call fan-out failed: ${e.message}`)));
112
+ const stopNodeEvents = (0, nodeCallEvents_1.subscribeNodeCallEvents)(deps.nc, {
113
+ lost: lost === null || lost === void 0 ? void 0 : lost.calls,
114
+ intake: (event) => intakeEvent(event).catch((e) => logger.warn(`node call event fan-out failed: ${e.message}`)),
115
+ records: config.failedCallRecords === false
116
+ ? undefined
117
+ : (0, nodeCallEvents_1.natsFailedCallRecords)(deps.nc),
118
+ workspaceOfApp
118
119
  });
119
- // Calls whose appbridge died mid-call get their call.ended (reason appbridge-lost) here: every
120
- // replica sweeps, and the event id depends on the call, so each endpoint gets one delivery.
121
- const stopLost = yield watchLostCalls(config, deps.nc, (event) => intakeEvent(event).catch((e) => logger.warn(`lost call fan-out failed: ${e.message}`)));
122
120
  let unsubscribe;
123
121
  try {
124
122
  unsubscribe = yield (0, durableConsumer_1.consumeDurable)(deps.nc, {
@@ -154,8 +152,8 @@ function runWebhookFanout(config, deps) {
154
152
  runDue,
155
153
  stop() {
156
154
  return __awaiter(this, void 0, void 0, function* () {
157
- nodeReports.unsubscribe();
158
- stopLost();
155
+ stopNodeEvents();
156
+ lost === null || lost === void 0 ? void 0 : lost.stop();
159
157
  yield unsubscribe();
160
158
  timers.forEach(clearInterval);
161
159
  yield running;
@@ -165,36 +163,40 @@ function runWebhookFanout(config, deps) {
165
163
  };
166
164
  });
167
165
  }
168
- /** Follows the session registry's calls and appbridges and sweeps for lost calls. */
166
+ /**
167
+ * Follows the session registry's `calls.*` entries (AppBridge's) for the calls whose AppBridge
168
+ * dies: the node's `app_gone` then sends their call.ended. Undefined without the registry.
169
+ */
169
170
  function watchLostCalls(config, nc, emit) {
170
171
  return __awaiter(this, void 0, void 0, function* () {
171
- var _a;
172
- const sweepMs = (_a = config.lostCallSweepMs) !== null && _a !== void 0 ? _a : 5000;
173
- if (sweepMs === 0)
174
- return () => undefined;
175
- const lost = (0, lostCalls_1.createLostCallSweep)({ emit });
176
- const stops = [];
172
+ const calls = (0, lostCalls_1.createLostCalls)({
173
+ emit: (event) => {
174
+ logger.warn(`call ${event.data.callRef}: its AppBridge is gone; call.ended (appbridge-lost)`);
175
+ return emit(event);
176
+ },
177
+ graceMs: config.appGoneGraceMs
178
+ });
179
+ let stopWatch;
177
180
  try {
178
181
  const kv = yield Promise.race([
179
182
  common_1.Sessions.openSessions(nc, { bucket: config.sessionsBucket }),
180
183
  new Promise((_, reject) => setTimeout(() => reject(new Error("timed out")), 5000).unref())
181
184
  ]);
182
- stops.push(yield common_1.Sessions.watchSessions(kv, "gateways", lost.onEntry));
183
- stops.push(yield common_1.Sessions.watchSessions(kv, "calls", lost.onEntry));
185
+ stopWatch = yield common_1.Sessions.watchSessions(kv, "calls", calls.onEntry);
184
186
  }
185
187
  catch (e) {
186
- stops.forEach((s) => s());
187
- logger.warn(`session registry unavailable; calls of lost appbridges get no call.ended: ${e.message}`);
188
- return () => undefined;
188
+ logger.warn(`session registry unavailable; calls of lost AppBridge replicas get no call.ended: ${e.message}`);
189
+ return undefined;
189
190
  }
190
- const timer = setInterval(() => {
191
- for (const event of lost.sweep())
192
- logger.warn(`call ${event.data.callRef}: its appbridge is gone; call.ended (appbridge-lost)`);
193
- }, sweepMs);
191
+ const timer = setInterval(() => calls.forget(), 60000);
194
192
  timer.unref();
195
- return () => {
196
- clearInterval(timer);
197
- stops.forEach((s) => s());
193
+ return {
194
+ calls,
195
+ stop() {
196
+ clearInterval(timer);
197
+ stopWatch();
198
+ calls.stop();
199
+ }
198
200
  };
199
201
  });
200
202
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fonoster/apiserver",
3
- "version": "0.30.0",
3
+ "version": "0.31.0",
4
4
  "description": "APIServer for Fonoster",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/fonoster#readme",
@@ -12,30 +12,28 @@
12
12
  "test": "test"
13
13
  },
14
14
  "scripts": {
15
- "prebuild": "rimraf ./dist tsconfig.tsbuildinfo",
15
+ "prebuild": "rimraf ./dist tsconfig.tsbuildinfo && npm run generate:prisma",
16
16
  "build": "tsc -b tsconfig.json",
17
- "clean": "rimraf ./dist node_modules tsconfig.tsbuildinfo"
17
+ "generate:prisma": "prisma generate --schema schema.prisma"
18
18
  },
19
19
  "bin": {
20
20
  "fonoster": "./dist/index.js",
21
21
  "fonoster-region-hub-setup": "./dist/bin/regionHubSetup.js",
22
- "fonoster-migrate-legacy": "./dist/migration/cli.js"
22
+ "fonoster-usage": "./dist/bin/usage.js"
23
23
  },
24
24
  "dependencies": {
25
- "@fonoster/authz": "^0.30.0",
26
- "@fonoster/autopilot": "^0.30.0",
27
- "@fonoster/callrecord": "^0.30.0",
28
- "@fonoster/common": "^0.30.0",
29
- "@fonoster/identity": "^0.30.0",
30
- "@fonoster/logger": "^0.30.0",
31
- "@fonoster/sipnet": "^0.30.0",
32
- "@fonoster/streams": "^0.30.0",
33
- "@fonoster/types": "^0.30.0",
25
+ "@fonoster/authz": "^0.31.0",
26
+ "@fonoster/autopilot": "^0.31.0",
27
+ "@fonoster/callrecord": "^0.31.0",
28
+ "@fonoster/common": "^0.31.0",
29
+ "@fonoster/identity": "^0.31.0",
30
+ "@fonoster/logger": "^0.31.0",
31
+ "@fonoster/sipnet": "^0.31.0",
32
+ "@fonoster/types": "^0.31.0",
34
33
  "@grpc/grpc-js": "~1.14.6",
35
- "@influxdata/influxdb-client": "^1.33.2",
36
34
  "@prisma/client": "^6.19.1",
37
- "@routr/common": "^2.15.2",
38
- "@routr/sdk": "^2.15.2",
35
+ "@routr/common": "^2.19.0",
36
+ "@routr/sdk": "^2.19.0",
39
37
  "express": "^5.0.1",
40
38
  "grpc-health-check": "^2.0.1",
41
39
  "jsonwebtoken": "^9.0.2",
@@ -68,8 +66,8 @@
68
66
  "@types/uuid": "^10.0.0",
69
67
  "@types/validator": "^13.15.10"
70
68
  },
71
- "gitHead": "b59b06a3ef325abe3f188c0fb87cc22d50ed5471",
72
- "optionalDependencies": {
73
- "@ai-coustics/aic-sdk": "^0.24.0"
69
+ "gitHead": "f0a5102dddeea0f70f659234108805bc10690f2e",
70
+ "prisma": {
71
+ "seed": "tsx src/core/seed.ts"
74
72
  }
75
73
  }