@fonoster/apiserver 0.30.0 → 0.31.1

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
@@ -61,35 +61,59 @@ Object.defineProperty(exports, "__esModule", { value: true });
61
61
  * See the License for the specific language governing permissions and
62
62
  * limitations under the License.
63
63
  */
64
- const fs = __importStar(require("fs"));
65
- const migration_1 = require("../applications/migration");
66
- const argv_1 = require("./argv");
67
- const migrateLegacy_1 = require("./migrateLegacy");
68
- // fonoster-migrate-legacy: the one-time cutover migration (docs/operators/cutover.md, section 2).
69
- // Dry run by default; --apply writes. Secrets never go on the command line or in the output.
70
- const USAGE = `usage: fonoster-migrate-legacy [--apply] --autopilot-url <wss://...>
71
- [--autopilot-secret-env <ENV>] [--app <ref>]... [--default-voice <id>] [--default-language <tag>]
72
- [--fallback-message <text>] [--gateway-apps <file>] [--allow-insecure-webhooks]
73
- [--integrations <integrations.json> --credentials-out <file> [--secrets-dir <dir>]]`;
74
- function main(argv) {
64
+ /**
65
+ * fonoster-usage: maintenance for the usage ledger (add-usage-metering D7).
66
+ *
67
+ * fonoster-usage rebuild --from <YYYY-MM-DD> --to <YYYY-MM-DD> [--from-records]
68
+ *
69
+ * rebuild recomputes usage_daily for the days from usage_events. With --from-records it first
70
+ * re-reads the sealed call records of those days and stores usage that never reached the ledger.
71
+ */
72
+ const identity_1 = require("@fonoster/identity");
73
+ const identityConfig_1 = require("../core/identityConfig");
74
+ const envs_1 = require("../envs");
75
+ const stores_1 = require("../records/stores");
76
+ const rebuildUsage_1 = require("../usage/rebuildUsage");
77
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
78
+ const USAGE = "usage: fonoster-usage rebuild --from <YYYY-MM-DD> --to <YYYY-MM-DD> [--from-records]";
79
+ function option(args, name) {
80
+ const i = args.indexOf(name);
81
+ return i >= 0 ? args[i + 1] : undefined;
82
+ }
83
+ function main(args) {
75
84
  return __awaiter(this, void 0, void 0, function* () {
76
- if (argv.includes("--help") || argv.includes("-h")) {
77
- console.log(USAGE);
78
- return;
85
+ const from = option(args, "--from");
86
+ const to = option(args, "--to");
87
+ if (args[0] !== "rebuild" ||
88
+ !from ||
89
+ !to ||
90
+ !DAY.test(from) ||
91
+ !DAY.test(to) ||
92
+ from > to) {
93
+ console.error(USAGE);
94
+ return 2;
79
95
  }
80
- const options = (0, argv_1.optionsFromArgv)(argv);
81
- // Loaded lazily: the database client reads fonoster.yaml (and the encryption key).
82
96
  const { prisma } = yield Promise.resolve().then(() => __importStar(require("../core/db")));
83
- const report = yield (0, migrateLegacy_1.migrateLegacy)(prisma, options);
84
- const gatewayApps = (0, argv_1.arg)(argv, "--gateway-apps");
85
- if (gatewayApps) {
86
- fs.writeFileSync(gatewayApps, JSON.stringify({ apps: (0, migration_1.toGatewayApps)(report.apps) }, null, 2), { mode: 0o600 });
97
+ const db = prisma;
98
+ if (args.includes("--from-records")) {
99
+ const identity = (0, identity_1.createPrismaClient)(identityConfig_1.identityConfig.dbUrl, identityConfig_1.identityConfig.encryptionKey);
100
+ const recovered = yield (0, rebuildUsage_1.recoverUsageFromRecords)({
101
+ db,
102
+ directory: (0, identity_1.createWorkspaceDirectory)(identity),
103
+ storeFor: (0, stores_1.createStoreResolver)(envs_1.CALL_RECORDS.stores),
104
+ fromDay: from,
105
+ toDay: to
106
+ });
107
+ console.log(`recovered ${recovered} usage lines from records`);
108
+ yield identity.$disconnect();
87
109
  }
88
- console.log(JSON.stringify({ applied: !options.dryRun, steps: report.steps }, null, 2));
110
+ const totals = yield (0, rebuildUsage_1.rebuildUsageDaily)(db, from, to);
111
+ console.log(`rebuilt ${totals} daily totals for ${from}..${to}`);
89
112
  yield prisma.$disconnect();
113
+ return 0;
90
114
  });
91
115
  }
92
- main(process.argv.slice(2)).catch((e) => {
116
+ main(process.argv.slice(2)).then((code) => process.exit(code), (e) => {
93
117
  console.error(e.message);
94
118
  process.exit(1);
95
119
  });
@@ -1,23 +1,4 @@
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 { InfluxDBClient } from "@fonoster/common";
20
- declare function buildService(influxdb: InfluxDBClient): Promise<{
1
+ declare function buildService(): Promise<{
21
2
  definition: {
22
3
  serviceName: string;
23
4
  pckg: string;
@@ -13,6 +13,26 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.buildService = buildService;
16
+ /**
17
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
18
+ * http://github.com/fonoster/fonoster
19
+ *
20
+ * This file is part of Fonoster
21
+ *
22
+ * Licensed under the MIT License (the "License");
23
+ * you may not use this file except in compliance with
24
+ * the License. You may obtain a copy of the License at
25
+ *
26
+ * https://opensource.org/licenses/MIT
27
+ *
28
+ * Unless required by applicable law or agreed to in writing, software
29
+ * distributed under the License is distributed on an "AS IS" BASIS,
30
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31
+ * See the License for the specific language governing permissions and
32
+ * limitations under the License.
33
+ */
34
+ const authz_1 = require("@fonoster/authz");
35
+ const logger_1 = require("@fonoster/logger");
16
36
  const sdk_1 = __importDefault(require("@routr/sdk"));
17
37
  const nats_1 = require("nats");
18
38
  const db_1 = require("../core/db");
@@ -25,7 +45,32 @@ const createIsWorkspaceNumber_1 = require("./createIsWorkspaceNumber");
25
45
  const createTrackCall_1 = require("./createTrackCall");
26
46
  const getCall_1 = require("./getCall");
27
47
  const listCalls_1 = require("./listCalls");
28
- function buildService(influxdb) {
48
+ const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
49
+ /** An answer slower than this admits the call (add-billing-service D7). */
50
+ const ADMISSION_TIMEOUT_MS = 500;
51
+ /** Outbound admission from the authorization service, when it is enabled. */
52
+ function authzAdmission() {
53
+ if (!envs_1.AUTHZ_SERVICE_ENABLED)
54
+ return undefined;
55
+ const client = new authz_1.AuthzClient(`${envs_1.AUTHZ_SERVICE_HOST}:${envs_1.AUTHZ_SERVICE_PORT}`);
56
+ return (request) => client
57
+ .checkSession({
58
+ accessKeyId: request.accessKeyId,
59
+ appRef: request.appRef,
60
+ callRef: request.callRef,
61
+ callerNumber: request.from,
62
+ ingressNumber: request.to,
63
+ callDirection: "TO_PSTN"
64
+ }, ADMISSION_TIMEOUT_MS)
65
+ .catch((e) => {
66
+ logger.warn("call admitted without an answer from authorization", {
67
+ callRef: request.callRef,
68
+ error: e.message
69
+ });
70
+ return { authorized: true };
71
+ });
72
+ }
73
+ function buildService() {
29
74
  return __awaiter(this, void 0, void 0, function* () {
30
75
  const callPublisher = yield (0, createCallPublisher_1.createCallPublisher)(envs_1.NATS_CONNECTION);
31
76
  const nc = yield (0, nats_1.connect)(Object.assign(Object.assign({}, envs_1.NATS), { maxReconnectAttempts: -1 }));
@@ -37,15 +82,10 @@ function buildService(influxdb) {
37
82
  proto: "calls.proto"
38
83
  },
39
84
  handlers: {
40
- createCall: (0, createCall_1.createCall)(db_1.prisma, callPublisher, (0, createIsWorkspaceNumber_1.createIsWorkspaceNumber)(new sdk_1.default.Numbers(routrConfig_1.routrConfig))),
41
- // Call history from the call-record index (add-call-record 7.1) when the flag is on; the
42
- // InfluxDB CDR path stays until the migration is done.
43
- listCalls: envs_1.CALL_RECORDS.listCallsFromIndex
44
- ? (0, listCalls_1.listCalls)(influxdb, (0, records_1.createFetchCallsFromIndex)(db_1.prisma))
45
- : (0, listCalls_1.listCalls)(influxdb),
46
- getCall: envs_1.CALL_RECORDS.listCallsFromIndex
47
- ? (0, getCall_1.getCall)(influxdb, (0, records_1.createFetchSingleCallFromIndex)(db_1.prisma))
48
- : (0, getCall_1.getCall)(influxdb),
85
+ createCall: (0, createCall_1.createCall)(db_1.prisma, callPublisher, (0, createIsWorkspaceNumber_1.createIsWorkspaceNumber)(new sdk_1.default.Numbers(routrConfig_1.routrConfig)), authzAdmission()),
86
+ // Call history from the call-record index (add-call-record 7.1).
87
+ listCalls: (0, listCalls_1.listCalls)((0, records_1.createFetchCallsFromIndex)(db_1.prisma)),
88
+ getCall: (0, getCall_1.getCall)((0, records_1.createFetchSingleCallFromIndex)(db_1.prisma)),
49
89
  trackCall: (0, createTrackCall_1.createTrackCall)(nc)
50
90
  }
51
91
  };
@@ -20,7 +20,21 @@ import { GrpcErrorMessage } from "@fonoster/common";
20
20
  import { Prisma } from "../core/db";
21
21
  import { IsWorkspaceNumber } from "./createIsWorkspaceNumber";
22
22
  import { CallPublisher } from "./types";
23
- declare function createCall(prisma: Prisma, publisher: CallPublisher, isWorkspaceNumber: IsWorkspaceNumber): (call: {
23
+ /**
24
+ * Asks whether an outbound call may start (add-billing-service D7). A refusal names its reason;
25
+ * an unanswered or failed check admits the call.
26
+ */
27
+ type AdmitCall = (request: {
28
+ callRef: string;
29
+ appRef: string;
30
+ accessKeyId: string;
31
+ from: string;
32
+ to: string;
33
+ }) => Promise<{
34
+ authorized: boolean;
35
+ reason?: string;
36
+ }>;
37
+ declare function createCall(prisma: Prisma, publisher: CallPublisher, isWorkspaceNumber: IsWorkspaceNumber, admitCall?: AdmitCall): (call: {
24
38
  request: unknown;
25
39
  }, callback: (error?: import("@fonoster/common").GrpcErrorMessage, response?: unknown) => void) => Promise<void>;
26
- export { createCall };
40
+ export { AdmitCall, createCall };
@@ -36,8 +36,9 @@ const uuid_1 = require("uuid");
36
36
  const notFoundError_1 = require("../core/notFoundError");
37
37
  const types_1 = require("./types");
38
38
  const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
39
- function createCall(prisma, publisher, isWorkspaceNumber) {
39
+ function createCall(prisma, publisher, isWorkspaceNumber, admitCall) {
40
40
  const fn = (call, callback) => __awaiter(this, void 0, void 0, function* () {
41
+ var _a, _b;
41
42
  const { request } = call;
42
43
  const { from, to, appRef, timeout, metadata } = request;
43
44
  const ref = (0, uuid_1.v4)();
@@ -60,7 +61,26 @@ function createCall(prisma, publisher, isWorkspaceNumber) {
60
61
  });
61
62
  return;
62
63
  }
63
- // Placement answers once a media node has accepted the call, so a call with no capacity
64
+ // Admission before any SIP (voice-session, "Calls are admitted before they start").
65
+ if (admitCall) {
66
+ const decision = yield admitCall({
67
+ callRef: ref,
68
+ appRef,
69
+ accessKeyId,
70
+ from,
71
+ to
72
+ });
73
+ if (!decision.authorized) {
74
+ const reason = (_a = decision.reason) !== null && _a !== void 0 ? _a : "not_authorized";
75
+ logger.info("call refused", { ref, reason });
76
+ callback({
77
+ code: grpc_js_1.status.FAILED_PRECONDITION,
78
+ message: `The call was refused: ${reason}`
79
+ });
80
+ return;
81
+ }
82
+ }
83
+ // Placement answers once a Roomr node has accepted the call, so a call with no capacity
64
84
  // fails here (RESOURCE_EXHAUSTED) instead of TrackCall reporting FAILED later.
65
85
  try {
66
86
  yield publisher.publishCall({
@@ -77,11 +97,14 @@ function createCall(prisma, publisher, isWorkspaceNumber) {
77
97
  if (!(e instanceof types_1.CallPlacementError))
78
98
  throw e;
79
99
  logger.warn("call not placed", { ref, code: e.code, message: e.message });
100
+ const code = (_b = {
101
+ no_capacity: grpc_js_1.status.RESOURCE_EXHAUSTED,
102
+ invalid_argument: grpc_js_1.status.INVALID_ARGUMENT,
103
+ already_exists: grpc_js_1.status.ALREADY_EXISTS
104
+ }[e.code]) !== null && _b !== void 0 ? _b : grpc_js_1.status.UNAVAILABLE;
80
105
  callback({
81
- code: e.code === "no_capacity"
82
- ? grpc_js_1.status.RESOURCE_EXHAUSTED
83
- : grpc_js_1.status.UNAVAILABLE,
84
- message: e.code === "no_capacity"
106
+ code,
107
+ message: code === grpc_js_1.status.RESOURCE_EXHAUSTED
85
108
  ? `No capacity to place the call: ${e.message}`
86
109
  : `The call could not be placed: ${e.message}`
87
110
  });
@@ -22,8 +22,9 @@ import { CreateCallRequest } from "./types";
22
22
  declare function createCallPublisher(nats: NatsTarget): Promise<{
23
23
  /**
24
24
  * Asks the outbound placement (any replica's `calls.create` queue group) to place the call,
25
- * and resolves once a media node has accepted its room. Rejects with a CallPlacementError:
26
- * `no_capacity` when no node took it, `unavailable` when no replica answered.
25
+ * and resolves once a Roomr node has accepted CreateCall. Rejects with a CallPlacementError:
26
+ * `no_capacity` when no node took it, `invalid_argument` or `already_exists` as the node
27
+ * said, `unavailable` otherwise (no replica answered included).
27
28
  */
28
29
  publishCall: (request: CreateCallRequest & {
29
30
  ref: string;
@@ -33,8 +34,9 @@ declare function createCallPublisher(nats: NatsTarget): Promise<{
33
34
  declare function callPublisher(nc: NatsConnection): {
34
35
  /**
35
36
  * Asks the outbound placement (any replica's `calls.create` queue group) to place the call,
36
- * and resolves once a media node has accepted its room. Rejects with a CallPlacementError:
37
- * `no_capacity` when no node took it, `unavailable` when no replica answered.
37
+ * and resolves once a Roomr node has accepted CreateCall. Rejects with a CallPlacementError:
38
+ * `no_capacity` when no node took it, `invalid_argument` or `already_exists` as the node
39
+ * said, `unavailable` otherwise (no replica answered included).
38
40
  */
39
41
  publishCall: (request: CreateCallRequest & {
40
42
  ref: string;
@@ -37,10 +37,10 @@ const types_1 = require("./types");
37
37
  const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
38
38
  const sc = (0, nats_1.StringCodec)();
39
39
  /**
40
- * How long CreateCall waits for a node to accept the call's room: up to three nodes at the
41
- * media-control reply timeout (2 s) each, plus margin.
40
+ * How long CreateCall waits for the placement: CreateRoom (a retry on a timeout, up to three
41
+ * nodes), AppBridge's claim and CreateCall (a retry on a timeout), 2 s each, plus margin.
42
42
  */
43
- const PLACE_TIMEOUT_MS = 8000;
43
+ const PLACE_TIMEOUT_MS = 15000;
44
44
  function createCallPublisher(nats) {
45
45
  return __awaiter(this, void 0, void 0, function* () {
46
46
  const options = (0, common_1.natsConnectOptions)(nats);
@@ -54,8 +54,9 @@ function callPublisher(nc) {
54
54
  return {
55
55
  /**
56
56
  * Asks the outbound placement (any replica's `calls.create` queue group) to place the call,
57
- * and resolves once a media node has accepted its room. Rejects with a CallPlacementError:
58
- * `no_capacity` when no node took it, `unavailable` when no replica answered.
57
+ * and resolves once a Roomr node has accepted CreateCall. Rejects with a CallPlacementError:
58
+ * `no_capacity` when no node took it, `invalid_argument` or `already_exists` as the node
59
+ * said, `unavailable` otherwise (no replica answered included).
59
60
  */
60
61
  publishCall: (request) => __awaiter(this, void 0, void 0, function* () {
61
62
  var _a, _b;
@@ -3,11 +3,11 @@ import { NatsConnection } from "nats";
3
3
  import { TrackCallResponse } from "./types";
4
4
  /** Timings of TrackCall's own end of a call (control-plane, "TrackCall always ends"). */
5
5
  export declare const TRACK_CALL_DEFAULTS: {
6
- /** A stream whose call never reached a media node (no node in this long) ends FAILED. */
6
+ /** A stream whose call never reached a Roomr node (no node in this long) ends FAILED. */
7
7
  noNodeMs: number;
8
- /** The call's media node is gone after this long without its heartbeat (3 beats of 2 s). */
8
+ /** The call's Roomr node is gone after this long without its heartbeat (3 beats of 2 s). */
9
9
  nodeStaleMs: number;
10
- /** No call outlives the media node's MaxDuration (4 h); a stream ends FAILED after this. */
10
+ /** No call outlives the Roomr node's MaxDuration (4 h); a stream ends FAILED after this. */
11
11
  maxMs: number;
12
12
  /** How often open streams are checked. */
13
13
  sweepMs: number;
@@ -19,26 +19,29 @@ type TrackMessage = Partial<TrackCallResponse> & {
19
19
  ref: string;
20
20
  /** The call is over (the room ended): close the stream. */
21
21
  final?: boolean;
22
- /** The media node that holds the call's room, when the message says. */
23
- nodeId?: string;
22
+ /** The Roomr node that holds the call, when the message says. */
23
+ nodeRef?: string;
24
24
  };
25
25
  /**
26
- * One message on `calls.<ref>.events` as a TrackCall message: the control plane's `{ref,
27
- * status}` as is, and the media node's call.progress, call.answered and room.ended translated.
28
- * Undefined for anything else.
26
+ * One message as a TrackCall message: the control plane's `{ref, status}` (on
27
+ * `calls.<ref>.events`) as is, and the Roomr node's call.ringing, call.answered and call.ended
28
+ * (on `roomr.events.<call_ref>`) translated. Undefined for anything else (receivers ignore
29
+ * unknown event types).
29
30
  */
30
31
  declare function toTrackMessage(event: Record<string, unknown>, subject?: string): TrackMessage | undefined;
31
32
  /**
32
- * TrackCall: status updates of an API-originated call, from the call's own subject
33
- * `calls.<ref>.events`. The replica that placed the call publishes TRYING (and FAILED), and the
34
- * media node publishes the room's call events there, so any replica serves TrackCall for any
33
+ * TrackCall: status updates of an API-originated call, from the call's own subjects. The replica
34
+ * that placed the call publishes TRYING (and FAILED) on `calls.<ref>.events`, and the Roomr node
35
+ * publishes the call's events on `roomr.events.<ref>`, so any replica serves TrackCall for any
35
36
  * call, even after the placing replica is gone. The SDK subscribes right after CreateCall
36
37
  * returns, and the first statuses can come before that, so each call's messages are kept for a
37
38
  * while and replayed (also to a second TrackCall for the same call).
38
39
  *
39
40
  * Every stream ends: on the call's final status, when the client goes away, with FAILED when
40
- * the call's media node stops sending heartbeats (or says node.down) before the final, when no
41
- * node ever takes the call, or after `maxMs` at most.
41
+ * the call's Roomr node stops sending heartbeats before the final, when no node ever takes the
42
+ * call, or after `maxMs` at most. `node.down` alone does not fail a call: a draining node says it
43
+ * and keeps its live calls, so a call fails after `node.down` only when nothing (no heartbeat, no
44
+ * event of the call) comes from its node for `nodeStaleMs`, i.e. the node exited.
42
45
  */
43
46
  declare function createTrackCallHandler(nc: NatsConnection, options?: TrackCallOptions): {
44
47
  trackCall: (call: {
@@ -35,63 +35,69 @@ const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filen
35
35
  const KEEP_MS = 120000;
36
36
  /** Timings of TrackCall's own end of a call (control-plane, "TrackCall always ends"). */
37
37
  exports.TRACK_CALL_DEFAULTS = {
38
- /** A stream whose call never reached a media node (no node in this long) ends FAILED. */
38
+ /** A stream whose call never reached a Roomr node (no node in this long) ends FAILED. */
39
39
  noNodeMs: 30000,
40
- /** The call's media node is gone after this long without its heartbeat (3 beats of 2 s). */
40
+ /** The call's Roomr node is gone after this long without its heartbeat (3 beats of 2 s). */
41
41
  nodeStaleMs: 6000,
42
- /** No call outlives the media node's MaxDuration (4 h); a stream ends FAILED after this. */
42
+ /** No call outlives the Roomr node's MaxDuration (4 h); a stream ends FAILED after this. */
43
43
  maxMs: 4 * 60 * 60000 + 5 * 60000,
44
44
  /** How often open streams are checked. */
45
45
  sweepMs: 1000
46
46
  };
47
- /** media-control `call.progress` statuses → the Calls API's DialStatus names. */
48
- const PROGRESS = {
49
- ringing: common_1.DialStatus.PROGRESS,
47
+ /** call.ended causes of an unanswered call → the Calls API's DialStatus names (else FAILED). */
48
+ const UNANSWERED = {
50
49
  busy: common_1.DialStatus.BUSY,
51
- no_answer: common_1.DialStatus.NOANSWER,
52
- failed: common_1.DialStatus.FAILED
50
+ no_answer: common_1.DialStatus.NOANSWER
53
51
  };
54
52
  /**
55
- * One message on `calls.<ref>.events` as a TrackCall message: the control plane's `{ref,
56
- * status}` as is, and the media node's call.progress, call.answered and room.ended translated.
57
- * Undefined for anything else.
53
+ * One message as a TrackCall message: the control plane's `{ref, status}` (on
54
+ * `calls.<ref>.events`) as is, and the Roomr node's call.ringing, call.answered and call.ended
55
+ * (on `roomr.events.<call_ref>`) translated. Undefined for anything else (receivers ignore
56
+ * unknown event types).
58
57
  */
59
58
  function toTrackMessage(event, subject = "") {
60
59
  var _a, _b, _c, _d;
61
- const fromSubject = subject.split(".")[1];
62
- const ref = String((_c = (_b = (_a = event.ref) !== null && _a !== void 0 ? _a : event.callRef) !== null && _b !== void 0 ? _b : fromSubject) !== null && _c !== void 0 ? _c : "");
60
+ const tokens = subject.split(".");
61
+ const fromSubject = tokens[0] === "roomr" ? tokens[2] : tokens[1];
62
+ const ref = String((_c = (_b = (_a = event.ref) !== null && _a !== void 0 ? _a : event.call_ref) !== null && _b !== void 0 ? _b : fromSubject) !== null && _c !== void 0 ? _c : "");
63
63
  if (!ref)
64
64
  return undefined;
65
- const node = typeof event.nodeId === "string" && event.nodeId
66
- ? { nodeId: event.nodeId }
65
+ const node = typeof event.node_ref === "string" && event.node_ref
66
+ ? { nodeRef: event.node_ref }
67
67
  : {};
68
68
  switch (event.type) {
69
- case "call.progress":
70
- return Object.assign({ ref, status: (_d = PROGRESS[String(event.status)]) !== null && _d !== void 0 ? _d : common_1.DialStatus.FAILED }, node);
69
+ case "call.started":
70
+ return node.nodeRef ? Object.assign({ ref }, node) : undefined;
71
+ case "call.ringing":
72
+ return Object.assign({ ref, status: common_1.DialStatus.PROGRESS }, node);
71
73
  case "call.answered":
72
74
  return Object.assign({ ref, status: common_1.DialStatus.ANSWER }, node);
73
- case "room.ended":
74
- return Object.assign({ ref, final: true }, node);
75
+ case "call.ended":
76
+ // An answered call just ends; an unanswered one ends with its dial status.
77
+ return event.answered === true
78
+ ? Object.assign({ ref, final: true }, node) : Object.assign({ ref, status: (_d = UNANSWERED[String(event.cause)]) !== null && _d !== void 0 ? _d : common_1.DialStatus.FAILED, final: true }, node);
75
79
  case undefined:
76
- // The control plane's {ref, status}, {ref, final} and {ref, nodeId} (the room exists).
77
- return event.status !== undefined || event.final === true || node.nodeId
78
- ? Object.assign(Object.assign({}, event), { ref })
80
+ // The control plane's {ref, status}, {ref, final} and {ref, node_ref} (a node took it).
81
+ return event.status !== undefined || event.final === true || node.nodeRef
82
+ ? Object.assign(Object.assign(Object.assign({ ref }, (event.status !== undefined ? { status: event.status } : {})), (event.final === true ? { final: true } : {})), node)
79
83
  : undefined;
80
84
  default:
81
85
  return undefined;
82
86
  }
83
87
  }
84
88
  /**
85
- * TrackCall: status updates of an API-originated call, from the call's own subject
86
- * `calls.<ref>.events`. The replica that placed the call publishes TRYING (and FAILED), and the
87
- * media node publishes the room's call events there, so any replica serves TrackCall for any
89
+ * TrackCall: status updates of an API-originated call, from the call's own subjects. The replica
90
+ * that placed the call publishes TRYING (and FAILED) on `calls.<ref>.events`, and the Roomr node
91
+ * publishes the call's events on `roomr.events.<ref>`, so any replica serves TrackCall for any
88
92
  * call, even after the placing replica is gone. The SDK subscribes right after CreateCall
89
93
  * returns, and the first statuses can come before that, so each call's messages are kept for a
90
94
  * while and replayed (also to a second TrackCall for the same call).
91
95
  *
92
96
  * Every stream ends: on the call's final status, when the client goes away, with FAILED when
93
- * the call's media node stops sending heartbeats (or says node.down) before the final, when no
94
- * node ever takes the call, or after `maxMs` at most.
97
+ * the call's Roomr node stops sending heartbeats before the final, when no node ever takes the
98
+ * call, or after `maxMs` at most. `node.down` alone does not fail a call: a draining node says it
99
+ * and keeps its live calls, so a call fails after `node.down` only when nothing (no heartbeat, no
100
+ * event of the call) comes from its node for `nodeStaleMs`, i.e. the node exited.
95
101
  */
96
102
  function createTrackCallHandler(nc, options = {}) {
97
103
  var _a, _b;
@@ -100,9 +106,12 @@ function createTrackCallHandler(nc, options = {}) {
100
106
  const tracked = new Map();
101
107
  /** Recent messages per call (insertion order is first-seen order). */
102
108
  const recent = new Map();
103
- /** Last heartbeat per media node. */
109
+ /** Last heartbeat per Roomr node. */
104
110
  const beats = new Map();
111
+ /** When each Roomr node said node.down (cleared by its next heartbeat). */
112
+ const downAt = new Map();
105
113
  const subscription = nc.subscribe(envs_1.CALL_EVENTS_WILDCARD);
114
+ const mediaEvents = nc.subscribe(envs_1.MEDIA_CALL_EVENTS_WILDCARD);
106
115
  const untrack = (t) => {
107
116
  const set = tracked.get(t.ref);
108
117
  if (!(set === null || set === void 0 ? void 0 : set.delete(t)))
@@ -127,10 +136,12 @@ function createTrackCallHandler(nc, options = {}) {
127
136
  /** Writes one message; returns true when the stream is done. */
128
137
  const deliver = (t, message) => {
129
138
  const { ref, status } = message;
130
- if (message.nodeId && message.nodeId !== t.nodeId) {
131
- t.nodeId = message.nodeId;
132
- t.nodeAt = now();
139
+ if (message.nodeRef && message.nodeRef !== t.nodeRef) {
140
+ t.nodeRef = message.nodeRef;
133
141
  }
142
+ // Any message of the call proves its node is still there (a draining node sends no heartbeats).
143
+ if (t.nodeRef)
144
+ t.nodeAt = now();
134
145
  if (status)
135
146
  t.stream.write({ ref, status });
136
147
  const done = message.final === true || (!!status && FINAL_STATUSES.includes(status));
@@ -140,8 +151,8 @@ function createTrackCallHandler(nc, options = {}) {
140
151
  }
141
152
  return done;
142
153
  };
143
- subscription.callback = (err, msg) => {
144
- var _a, _b;
154
+ const onEvent = (err, msg) => {
155
+ var _a, _b, _c;
145
156
  // We can't do much more than log the error
146
157
  if (err) {
147
158
  logger.error("call to subscription.callback", { err });
@@ -149,21 +160,30 @@ function createTrackCallHandler(nc, options = {}) {
149
160
  }
150
161
  let message;
151
162
  try {
152
- message = toTrackMessage(msg === null || msg === void 0 ? void 0 : msg.json(), msg === null || msg === void 0 ? void 0 : msg.subject);
163
+ const event = msg === null || msg === void 0 ? void 0 : msg.json();
164
+ // Any event of a call, status or not, shows its node is still there (a draining node
165
+ // sends no heartbeats).
166
+ const eventRef = typeof (event === null || event === void 0 ? void 0 : event.call_ref) === "string" ? event.call_ref : "";
167
+ for (const t of (_a = tracked.get(eventRef)) !== null && _a !== void 0 ? _a : [])
168
+ if (t.nodeRef && t.nodeRef === event.node_ref)
169
+ t.nodeAt = now();
170
+ message = toTrackMessage(event, msg === null || msg === void 0 ? void 0 : msg.subject);
153
171
  }
154
- catch (_c) {
172
+ catch (_d) {
155
173
  return; // not JSON
156
174
  }
157
175
  if (!message)
158
176
  return;
159
177
  const { ref, status } = message;
160
178
  logger.verbose("call to subscription.callback", { ref, status });
161
- const kept = (_a = recent.get(ref)) !== null && _a !== void 0 ? _a : { at: now(), messages: [] };
179
+ const kept = (_b = recent.get(ref)) !== null && _b !== void 0 ? _b : { at: now(), messages: [] };
162
180
  kept.messages.push(message);
163
181
  recent.set(ref, kept);
164
- for (const t of [...((_b = tracked.get(ref)) !== null && _b !== void 0 ? _b : [])])
182
+ for (const t of [...((_c = tracked.get(ref)) !== null && _c !== void 0 ? _c : [])])
165
183
  deliver(t, message);
166
184
  };
185
+ subscription.callback = onEvent;
186
+ mediaEvents.callback = onEvent;
167
187
  const onHeartbeat = (err, msg) => {
168
188
  if (err)
169
189
  return;
@@ -174,46 +194,48 @@ function createTrackCallHandler(nc, options = {}) {
174
194
  catch (_a) {
175
195
  return;
176
196
  }
177
- const nodeId = typeof (event === null || event === void 0 ? void 0 : event.nodeId) === "string" ? event.nodeId : "";
178
- if (!nodeId)
197
+ const nodeRef = typeof (event === null || event === void 0 ? void 0 : event.node_ref) === "string" ? event.node_ref : "";
198
+ if (!nodeRef)
179
199
  return;
180
- if (event.type === "node.heartbeat")
181
- beats.set(nodeId, now());
200
+ if (event.type === "node.heartbeat") {
201
+ beats.set(nodeRef, now());
202
+ downAt.delete(nodeRef);
203
+ }
182
204
  else if (event.type === "node.down") {
183
- beats.delete(nodeId);
184
- for (const set of [...tracked.values()])
185
- for (const t of [...set])
186
- if (t.nodeId === nodeId)
187
- fail(t, `media node ${nodeId} is down`);
205
+ // Only a mark: the node may be draining with live calls (see the sweep).
206
+ downAt.set(nodeRef, now());
188
207
  }
189
208
  };
190
209
  const heartbeats = nc.subscribe(envs_1.NODE_HEARTBEAT_WILDCARD, {
191
210
  callback: onHeartbeat
192
211
  });
193
212
  const sweep = () => {
194
- var _a, _b;
213
+ var _a, _b, _c;
195
214
  const at = now();
196
215
  for (const [ref, kept] of recent) {
197
216
  if (at - kept.at <= KEEP_MS)
198
217
  break;
199
218
  recent.delete(ref);
200
219
  }
201
- for (const [nodeId, seen] of beats)
220
+ for (const [nodeRef, seen] of beats)
202
221
  if (at - seen > KEEP_MS)
203
- beats.delete(nodeId);
222
+ beats.delete(nodeRef);
223
+ for (const [nodeRef, down] of downAt)
224
+ if (at - down > KEEP_MS)
225
+ downAt.delete(nodeRef);
204
226
  for (const set of [...tracked.values()])
205
227
  for (const t of [...set]) {
206
228
  if (at - t.startedAt > o.maxMs) {
207
229
  fail(t, "no final status in time");
208
230
  }
209
- else if (!t.nodeId) {
231
+ else if (!t.nodeRef) {
210
232
  if (at - t.startedAt > o.noNodeMs)
211
- fail(t, "no media node took the call");
233
+ fail(t, "no Roomr node took the call");
212
234
  }
213
235
  else {
214
- const seen = Math.max((_a = beats.get(t.nodeId)) !== null && _a !== void 0 ? _a : 0, (_b = t.nodeAt) !== null && _b !== void 0 ? _b : 0);
236
+ const seen = Math.max((_a = beats.get(t.nodeRef)) !== null && _a !== void 0 ? _a : 0, (_b = downAt.get(t.nodeRef)) !== null && _b !== void 0 ? _b : 0, (_c = t.nodeAt) !== null && _c !== void 0 ? _c : 0);
215
237
  if (at - seen > o.nodeStaleMs)
216
- fail(t, `media node ${t.nodeId} missed its heartbeats`);
238
+ fail(t, `Roomr node ${t.nodeRef} missed its heartbeats`);
217
239
  }
218
240
  }
219
241
  };
@@ -242,10 +264,11 @@ function createTrackCallHandler(nc, options = {}) {
242
264
  size: () => [...tracked.values()].reduce((n, s) => n + s.size, 0),
243
265
  sweep,
244
266
  stop() {
245
- var _a, _b;
267
+ var _a, _b, _c;
246
268
  clearInterval(timer);
247
269
  (_a = subscription.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(subscription);
248
- (_b = heartbeats.unsubscribe) === null || _b === void 0 ? void 0 : _b.call(heartbeats);
270
+ (_b = mediaEvents.unsubscribe) === null || _b === void 0 ? void 0 : _b.call(mediaEvents);
271
+ (_c = heartbeats.unsubscribe) === null || _c === void 0 ? void 0 : _c.call(heartbeats);
249
272
  }
250
273
  };
251
274
  }