@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
package/dist/envs.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
2
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.SMTP_PORT = exports.SMTP_HOST = exports.SMTP_AUTH_USER = exports.SMTP_AUTH_PASS = exports.ROUTR_MEDIA_NODE_PEER = exports.ROUTR_API_ENDPOINT = exports.OWNER_PASSWORD = exports.OWNER_NAME = exports.OWNER_EMAIL = exports.NATS = exports.NATS_CONNECTION = exports.NATS_URL = exports.EVALUATIONS = exports.INFLUXDB_USERNAME = exports.INFLUXDB_URL = exports.INFLUXDB_TOKEN = exports.INFLUXDB_PASSWORD = exports.INFLUXDB_ORG = exports.AUTHZ_SERVICE_METHODS = exports.AUTHZ_SERVICE_PORT = exports.AUTHZ_SERVICE_HOST = exports.AUTHZ_SERVICE_ENABLED = exports.IDENTITY_DATABASE_URL = exports.IDENTITY_WORKSPACE_INVITE_URL = exports.IDENTITY_WORKSPACE_INVITE_EXPIRATION = exports.IDENTITY_WORKSPACE_INVITE_FAIL_URL = exports.IDENTITY_REFRESH_TOKEN_EXPIRES_IN = exports.IDENTITY_PUBLIC_KEY = exports.IDENTITY_PRIVATE_KEY = exports.IDENTITY_OAUTH2_GITHUB_CLIENT_SECRET = exports.IDENTITY_OAUTH2_GITHUB_CLIENT_ID = exports.IDENTITY_OAUTH2_GITHUB_ENABLED = exports.IDENTITY_TWO_FACTOR_AUTHENTICATION_REQUIRED = exports.IDENTITY_CONTACT_VERIFICATION_REQUIRED = exports.IDENTITY_ISSUER = exports.IDENTITY_ID_TOKEN_EXPIRES_IN = exports.IDENTITY_AUDIENCE = exports.IDENTITY_ACCESS_TOKEN_EXPIRES_IN = exports.HTTP_BRIDGE_PORT = exports.DEFAULT_NATS_QUEUE_GROUP = exports.DATABASE_URL = exports.CLOAK_ENCRYPTION_KEY = exports.NODE_HEARTBEAT_WILDCARD = exports.CALL_EVENTS_WILDCARD = exports.callEventsSubject = exports.CALLS_CREATE_SUBJECT = exports.APP_URL = exports.APISERVER_SIGNALING_SERVER = exports.APISERVER_HOST = exports.APISERVER_BIND_ADDR = void 0;
5
- exports.DOMAIN = exports.REGIONS = exports.REGISTRY = exports.WEBHOOKS = exports.SESSION_APPS = exports.CALL_RECORDS = exports.TWILIO_PHONE_NUMBER = exports.TWILIO_AUTH_TOKEN = exports.TWILIO_ACCOUNT_SID = exports.TEMPLATES_DIR = exports.SMTP_SENDER = exports.SMTP_SECURE = void 0;
4
+ exports.SMTP_PORT = exports.SMTP_HOST = exports.SMTP_AUTH_USER = exports.SMTP_AUTH_PASS = exports.ROUTR_SIP_PROXY = exports.ROUTR_ROOMR_PEER = exports.ROUTR_API_ENDPOINT = exports.OWNER_PASSWORD = exports.OWNER_NAME = exports.OWNER_EMAIL = exports.NATS = exports.NATS_CONNECTION = exports.NATS_URL = exports.EVALUATIONS = exports.AUTHZ_SERVICE_METHODS = exports.AUTHZ_SERVICE_PORT = exports.AUTHZ_SERVICE_HOST = exports.AUTHZ_SERVICE_ENABLED = exports.BILLING_ADDRESS = exports.BILLING_ENABLED = exports.IDENTITY_DATABASE_URL = exports.IDENTITY_WORKSPACE_INVITE_URL = exports.IDENTITY_WORKSPACE_INVITE_EXPIRATION = exports.IDENTITY_WORKSPACE_INVITE_FAIL_URL = exports.IDENTITY_REFRESH_TOKEN_EXPIRES_IN = exports.IDENTITY_PUBLIC_KEY = exports.IDENTITY_PRIVATE_KEY = exports.IDENTITY_OAUTH2_GITHUB_CLIENT_SECRET = exports.IDENTITY_OAUTH2_GITHUB_CLIENT_ID = exports.IDENTITY_OAUTH2_GITHUB_ENABLED = exports.IDENTITY_TWO_FACTOR_AUTHENTICATION_REQUIRED = exports.IDENTITY_CONTACT_VERIFICATION_REQUIRED = exports.IDENTITY_ISSUER = exports.IDENTITY_ID_TOKEN_EXPIRES_IN = exports.IDENTITY_AUDIENCE = exports.IDENTITY_ACCESS_TOKEN_EXPIRES_IN = exports.HTTP_BRIDGE_PORT = exports.DEFAULT_NATS_QUEUE_GROUP = exports.DATABASE_URL = exports.CLOAK_ENCRYPTION_KEY = exports.NODE_HEARTBEAT_WILDCARD = exports.MEDIA_CALL_EVENTS_WILDCARD = exports.mediaCallEventsSubject = exports.CALL_EVENTS_WILDCARD = exports.callEventsSubject = exports.CALLS_CREATE_SUBJECT = exports.APP_URL = exports.APISERVER_SIGNALING_SERVER = exports.APISERVER_HOST = exports.APISERVER_BIND_ADDR = void 0;
5
+ exports.DOMAIN_NAMES_ROOT = exports.TRUNK_NAMES_ROOT = exports.SIP_ROOT = exports.PSTN_ROOT = exports.DOMAIN = exports.REGIONS = exports.WEBHOOKS = exports.SESSION_APPS = exports.CALL_RECORDS = exports.TWILIO_PHONE_NUMBER = exports.TWILIO_AUTH_TOKEN = exports.TWILIO_ACCOUNT_SID = exports.TEMPLATES_DIR = exports.SMTP_SENDER = exports.SMTP_SECURE = void 0;
6
6
  /**
7
7
  * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
8
8
  * http://github.com/fonoster/fonoster
@@ -37,16 +37,24 @@ exports.APISERVER_SIGNALING_SERVER = (0, config_1.getSignalingServer)(config);
37
37
  exports.APP_URL = (0, config_1.getAppUrl)(config);
38
38
  exports.CALLS_CREATE_SUBJECT = "calls.create";
39
39
  /**
40
- * A call's status events, keyed by the call (TrackCall on any replica subscribes to them all):
41
- * TRYING and FAILED from the control plane that places the call, and the media node's
42
- * call.progress, call.answered and room.ended for the call's room.
40
+ * The control plane's own status of a call it places (TRYING, the node that took it, FAILED),
41
+ * keyed by the call, so TrackCall on any replica sees it.
43
42
  */
44
43
  const callEventsSubject = (ref) => `calls.${ref}.events`;
45
44
  exports.callEventsSubject = callEventsSubject;
46
- /** Every call's status events (TrackCall's subscription). */
45
+ /** Every call's control-plane status (TrackCall's subscription). */
47
46
  exports.CALL_EVENTS_WILDCARD = "calls.*.events";
48
- /** Every media node's heartbeat and node.down (TrackCall ends the calls of a lost node). */
49
- exports.NODE_HEARTBEAT_WILDCARD = "media.*.heartbeat";
47
+ /**
48
+ * A call's events from its Roomr node (media-control "Events on NATS are keyed by call"):
49
+ * call.started, call.ringing, call.answered, call.ended and the call's participant and operation
50
+ * events, each with node_ref, seq and metadata.
51
+ */
52
+ const mediaCallEventsSubject = (ref) => `roomr.events.${ref}`;
53
+ exports.mediaCallEventsSubject = mediaCallEventsSubject;
54
+ /** Every call's media events (TrackCall's subscription; room events are roomr.events.room.*). */
55
+ exports.MEDIA_CALL_EVENTS_WILDCARD = "roomr.events.*";
56
+ /** Every Roomr node's heartbeat and node.down (TrackCall ends the calls of a lost node). */
57
+ exports.NODE_HEARTBEAT_WILDCARD = "roomr.nodes.*.heartbeat";
50
58
  // Other configurations
51
59
  exports.CLOAK_ENCRYPTION_KEY = config.encryption.key;
52
60
  exports.DATABASE_URL = config.database.url;
@@ -69,18 +77,16 @@ exports.IDENTITY_WORKSPACE_INVITE_FAIL_URL = identity.workspaceInviteFailUrl;
69
77
  exports.IDENTITY_WORKSPACE_INVITE_EXPIRATION = identity.workspaceInviteExpiration;
70
78
  exports.IDENTITY_WORKSPACE_INVITE_URL = identity.workspaceInviteUrl;
71
79
  exports.IDENTITY_DATABASE_URL = identity.dbUrl;
80
+ /** Billing is on (Cloud): stored usage is published for the billing service (add-billing-service D2). */
81
+ exports.BILLING_ENABLED = config.features.billing.enabled;
82
+ /** Where the Billing API is served (the billing service). */
83
+ exports.BILLING_ADDRESS = (_c = config.features.billing.address) !== null && _c !== void 0 ? _c : `${config.authz.host}:50073`;
72
84
  // Authz configurations
73
85
  exports.AUTHZ_SERVICE_ENABLED = config.authz.enabled;
74
86
  exports.AUTHZ_SERVICE_HOST = config.authz.host;
75
87
  exports.AUTHZ_SERVICE_PORT = config.authz.port;
76
88
  exports.AUTHZ_SERVICE_METHODS = config.authz.methods;
77
- // InfluxDB configurations
78
- exports.INFLUXDB_ORG = config.influxdb.org;
79
- exports.INFLUXDB_PASSWORD = config.influxdb.password;
80
- exports.INFLUXDB_TOKEN = config.influxdb.token;
81
- exports.INFLUXDB_URL = config.influxdb.url;
82
- exports.INFLUXDB_USERNAME = config.influxdb.username;
83
- // Platform model keys for assistant evaluations, by credentialRef (rework-autopilot 8.2).
89
+ // Platform model keys for agent evaluations, by credentialRef (rework-autopilot 8.2).
84
90
  exports.EVALUATIONS = config.evaluations;
85
91
  exports.NATS_URL = config.nats.url;
86
92
  /** The `nats` setting itself (URL, user, password), for helpers that take a NatsTarget. */
@@ -88,31 +94,43 @@ exports.NATS_CONNECTION = config.nats;
88
94
  /** nats.js connect options: the URL plus the apiserver's NATS user, when set (add-platform 4.1). */
89
95
  exports.NATS = (0, common_1.natsConnectOptions)(config.nats);
90
96
  // Default owner (if identity.owner is set, the system creates a user and a workspace)
91
- exports.OWNER_EMAIL = (_c = config.identity.owner) === null || _c === void 0 ? void 0 : _c.email;
92
- exports.OWNER_NAME = (_e = (_d = config.identity.owner) === null || _d === void 0 ? void 0 : _d.name) !== null && _e !== void 0 ? _e : "Admin";
93
- exports.OWNER_PASSWORD = (_f = config.identity.owner) === null || _f === void 0 ? void 0 : _f.password;
97
+ exports.OWNER_EMAIL = (_d = config.identity.owner) === null || _d === void 0 ? void 0 : _d.email;
98
+ exports.OWNER_NAME = (_f = (_e = config.identity.owner) === null || _e === void 0 ? void 0 : _e.name) !== null && _f !== void 0 ? _f : "Admin";
99
+ exports.OWNER_PASSWORD = (_g = config.identity.owner) === null || _g === void 0 ? void 0 : _g.password;
94
100
  exports.ROUTR_API_ENDPOINT = config.routr.apiEndpoint;
95
- // The media-node peer every app-linked number points at (add-media-node 4.1)
96
- exports.ROUTR_MEDIA_NODE_PEER = config.routr.mediaNodePeer;
101
+ // The roomr peer every app-linked number points at (add-roomr 4.1)
102
+ exports.ROUTR_ROOMR_PEER = config.routr.roomrPeer;
103
+ /** Routr's SIP address: API-originated calls are dialed through it (Roomr CreateCall). */
104
+ exports.ROUTR_SIP_PROXY = config.routr.sipProxy;
97
105
  // SMTP configurations (optional; email features fail clearly without it)
98
- exports.SMTP_AUTH_PASS = (_g = config.smtp) === null || _g === void 0 ? void 0 : _g.password;
99
- exports.SMTP_AUTH_USER = (_h = config.smtp) === null || _h === void 0 ? void 0 : _h.user;
100
- exports.SMTP_HOST = (_j = config.smtp) === null || _j === void 0 ? void 0 : _j.host;
101
- exports.SMTP_PORT = (_l = (_k = config.smtp) === null || _k === void 0 ? void 0 : _k.port) !== null && _l !== void 0 ? _l : 587;
102
- exports.SMTP_SECURE = (_o = (_m = config.smtp) === null || _m === void 0 ? void 0 : _m.secure) !== null && _o !== void 0 ? _o : false;
103
- exports.SMTP_SENDER = (_p = config.smtp) === null || _p === void 0 ? void 0 : _p.sender;
106
+ exports.SMTP_AUTH_PASS = (_h = config.smtp) === null || _h === void 0 ? void 0 : _h.password;
107
+ exports.SMTP_AUTH_USER = (_j = config.smtp) === null || _j === void 0 ? void 0 : _j.user;
108
+ exports.SMTP_HOST = (_k = config.smtp) === null || _k === void 0 ? void 0 : _k.host;
109
+ exports.SMTP_PORT = (_m = (_l = config.smtp) === null || _l === void 0 ? void 0 : _l.port) !== null && _m !== void 0 ? _m : 587;
110
+ exports.SMTP_SECURE = (_p = (_o = config.smtp) === null || _o === void 0 ? void 0 : _o.secure) !== null && _p !== void 0 ? _p : false;
111
+ exports.SMTP_SENDER = (_q = config.smtp) === null || _q === void 0 ? void 0 : _q.sender;
104
112
  // Custom templates
105
113
  exports.TEMPLATES_DIR = config.templatesDir;
106
114
  // Twilio configurations
107
- exports.TWILIO_ACCOUNT_SID = (_q = config.twilio) === null || _q === void 0 ? void 0 : _q.accountSid;
108
- exports.TWILIO_AUTH_TOKEN = (_r = config.twilio) === null || _r === void 0 ? void 0 : _r.authToken;
109
- exports.TWILIO_PHONE_NUMBER = (_s = config.twilio) === null || _s === void 0 ? void 0 : _s.phoneNumber;
115
+ exports.TWILIO_ACCOUNT_SID = (_r = config.twilio) === null || _r === void 0 ? void 0 : _r.accountSid;
116
+ exports.TWILIO_AUTH_TOKEN = (_s = config.twilio) === null || _s === void 0 ? void 0 : _s.authToken;
117
+ exports.TWILIO_PHONE_NUMBER = (_t = config.twilio) === null || _t === void 0 ? void 0 : _t.phoneNumber;
110
118
  // Call records (add-call-record): index, records API, retention, ListCalls from the index.
111
119
  exports.CALL_RECORDS = config.callRecords;
112
120
  // Session apps (rebuild: control): hosted Autopilot URL and signing secret, webhook URL policy
113
121
  exports.SESSION_APPS = config.apps;
114
122
  exports.WEBHOOKS = config.webhooks;
115
- exports.REGISTRY = config.registry;
116
123
  // Regions (add-private-regions): public regions, the region-signing key and the region hub
117
124
  exports.REGIONS = config.regions;
118
125
  exports.DOMAIN = config.domain;
126
+ /**
127
+ * The install's SIP roots, split as Twilio does: carriers reach trunks at
128
+ * `<label>.pstn.<domain>`, phones register on domains at `<label>.sip.<domain>`.
129
+ */
130
+ exports.PSTN_ROOT = `pstn.${config.domain}`;
131
+ exports.SIP_ROOT = `sip.${config.domain}`;
132
+ const strictNames = config.features.sip.names === "domain";
133
+ /** Where trunk inbound URIs must live, or undefined when features.sip.names is "any". */
134
+ exports.TRUNK_NAMES_ROOT = strictNames ? exports.PSTN_ROOT : undefined;
135
+ /** Where domains must live, or undefined when features.sip.names is "any". */
136
+ exports.DOMAIN_NAMES_ROOT = strictNames ? exports.SIP_ROOT : undefined;
package/dist/index.js CHANGED
@@ -53,10 +53,8 @@ const applyCatalog_1 = require("./core/applyCatalog");
53
53
  const db_1 = require("./core/db");
54
54
  const identityConfig_1 = require("./core/identityConfig");
55
55
  const runServices_1 = __importDefault(require("./core/runServices"));
56
- const upsertMediaNodePeer_1 = require("./core/upsertMediaNodePeer");
56
+ const upsertRoomrPeer_1 = require("./core/upsertRoomrPeer");
57
57
  const envs_1 = require("./envs");
58
- const createInfluxDbPub_1 = require("./events/createInfluxDbPub");
59
- const nats_1 = require("./events/nats");
60
58
  // Apply fonoster.yaml to the shared modules before serving. Loggers created
61
59
  // while the imports above ran switch to the file's settings here.
62
60
  const config = (0, config_1.getConfig)();
@@ -65,6 +63,7 @@ const config = (0, config_1.getConfig)();
65
63
  Promise.resolve().then(() => __importStar(require("./core/removeSwaggerNotice")));
66
64
  function main() {
67
65
  return __awaiter(this, void 0, void 0, function* () {
66
+ var _a;
68
67
  yield (0, identity_1.migratePasswordStorage)(identityConfig_1.identityConfig);
69
68
  if (envs_1.OWNER_EMAIL) {
70
69
  const user = {
@@ -77,30 +76,32 @@ function main() {
77
76
  // The provider catalog (add-self-host-installer D7): applied on every start, idempotent. A
78
77
  // configured file that can't be read or applied stops the server (IC-B2).
79
78
  if (config.catalog) {
80
- try {
81
- const lines = yield (0, applyCatalog_1.applyCatalog)(config.catalog.file, db_1.prisma);
82
- logger.info(lines[0] === "no changes"
83
- ? "catalog: no changes"
84
- : `catalog: ${lines.length} entries added or changed`, { file: config.catalog.file });
85
- }
86
- catch (e) {
87
- logger.error(`catalog: ${e.message}`);
88
- process.exit(1);
79
+ // `file`, then each of `files` (a stack's own catalogs, e.g. the fakes in dev and tests).
80
+ const files = [
81
+ { file: config.catalog.file, key: "catalog.file" },
82
+ ...((_a = config.catalog.files) !== null && _a !== void 0 ? _a : []).map((file, i) => ({
83
+ file,
84
+ key: `catalog.files[${i}]`
85
+ }))
86
+ ];
87
+ for (const { file, key } of files) {
88
+ try {
89
+ const lines = yield (0, applyCatalog_1.applyCatalog)(file, db_1.prisma, key);
90
+ logger.info(lines[0] === "no changes"
91
+ ? "catalog: no changes"
92
+ : `catalog: ${lines.length} entries added or changed`, { file });
93
+ }
94
+ catch (e) {
95
+ logger.error(`catalog: ${e.message}`);
96
+ process.exit(1);
97
+ }
89
98
  }
90
99
  }
91
- // The media-node peer every app-linked number points at (add-media-node 4.1). Runs in the
100
+ // The roomr peer every app-linked number points at (add-roomr 4.1). Runs in the
92
101
  // background: it waits for Routr, which may start after the API server.
93
- (0, upsertMediaNodePeer_1.upsertMediaNodePeer)().catch(logger.error);
102
+ (0, upsertRoomrPeer_1.upsertRoomrPeer)().catch(logger.error);
94
103
  // Start the gRPC server
95
104
  (0, runServices_1.default)().catch(logger.error);
96
- const pubToInfluxDb = (0, createInfluxDbPub_1.createInfluxDbPub)({
97
- url: envs_1.INFLUXDB_URL,
98
- token: envs_1.INFLUXDB_TOKEN,
99
- org: envs_1.INFLUXDB_ORG,
100
- bucket: common_1.INFLUXDB_CALLS_BUCKET
101
- });
102
- // Routr's call events become CDR points (one replica per event, refs shared: ST-1)
103
- (0, nats_1.watchNats)(envs_1.NATS_CONNECTION, pubToInfluxDb);
104
105
  });
105
106
  }
106
107
  const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
@@ -16,15 +16,26 @@
16
16
  * See the License for the specific language governing permissions and
17
17
  * limitations under the License.
18
18
  */
19
- /** One media node as its heartbeats describe it (media-control, node.heartbeat). */
20
- export type MediaNodeStatus = {
19
+ /** One Roomr node as its heartbeats describe it (media-control, node.heartbeat). */
20
+ export type RoomrStatus = {
21
+ /** The heartbeat's node_ref. */
21
22
  nodeId: string;
22
23
  rooms: number;
23
- /** The node's room limit (media-node "Call and room limits"); unset for nodes that report none. */
24
+ /** The node's room limit (max_rooms); unset for nodes that report none. */
24
25
  maxRooms?: number;
25
- draining: boolean;
26
+ /** The node's region; unset for nodes that report none. */
27
+ region?: string;
28
+ /**
29
+ * The node said `node.down` (it is draining or exiting) and has not sent a heartbeat since: it
30
+ * takes no new calls, but its live calls are not failed for it (see `live`).
31
+ */
32
+ down: boolean;
33
+ /** Where the node serves Roomr (the heartbeat's control_addr); unset: no calls placed on it. */
34
+ controlAddr?: string;
26
35
  seenAt: number;
27
36
  };
37
+ /** The room limit assumed for a node that reports none (the Roomr node's default). */
38
+ export declare const DEFAULT_MAX_ROOMS = 200;
28
39
  /** Heartbeats are every 2 s; a node silent for three of them is not offered new calls. */
29
40
  export declare const NODE_STALE_MS = 6000;
30
41
  /**
@@ -33,9 +44,11 @@ export declare const NODE_STALE_MS = 6000;
33
44
  */
34
45
  export declare const NODE_FORGET_MS = 60000;
35
46
  /**
36
- * The media nodes this replica knows, for placing outbound calls (add-media-node 3.3): fed by the
37
- * session registry's `nodes.` entries (JetStream KV, 3.2; read in full at start, so a restarted
38
- * replica places calls at once) and by `node.heartbeat` / `node.down` events.
47
+ * The Roomr nodes this replica knows, for placing outbound calls (add-roomr 3.3): fed by
48
+ * the `node.heartbeat` / `node.down` events on `roomr.nodes.<node_ref>.heartbeat` (core NATS;
49
+ * nodes write nothing else). `node.down` only takes the node out of placement: a draining node
50
+ * keeps its live rooms and sends no heartbeats, so it is "gone" only after it stays silent for
51
+ * `staleMs` past its `node.down`.
39
52
  */
40
53
  export declare function createNodeDirectory(options?: {
41
54
  staleMs?: number;
@@ -48,17 +61,26 @@ export declare function createNodeDirectory(options?: {
48
61
  */
49
62
  note(event: Record<string, unknown>, seenAt?: number): void;
50
63
  /**
51
- * The least-loaded eligible node (live, not draining, below its room limit), skipping the
52
- * nodes in `exclude` (already tried for this call); undefined when there is none.
64
+ * The eligible node with the most room to spare (control-plane): live, not down, below
65
+ * its room limit, with a control address and, when the call names a region, in that region; scored
66
+ * `1 - rooms / max_rooms`, highest wins. Skips the nodes in `exclude` (already tried for
67
+ * this call); undefined when there is none.
53
68
  */
54
- pick(exclude?: ReadonlySet<string>): string | undefined;
69
+ pick(exclude?: ReadonlySet<string>, region?: string): string | undefined;
55
70
  /**
56
- * A node refused a room because it is full or draining: no new call goes to it until its
57
- * next heartbeat says otherwise.
71
+ * A node refused a room because it is full or unavailable: no new call goes to it until
72
+ * its next heartbeat says otherwise.
58
73
  */
59
74
  refused(nodeId: string, code: string): void;
75
+ /**
76
+ * Whether the node is still there: a heartbeat, or its `node.down`, is fresh. A node that
77
+ * said `node.down` stays live for `staleMs` more; after that, silence means it exited.
78
+ */
79
+ live(nodeId: string): boolean;
80
+ /** The node's Roomr address (control_addr), if known. */
81
+ addressOf(nodeId: string): string | undefined;
60
82
  /** Counts a room placed on a node before its next heartbeat reports it. */
61
83
  placed(nodeId: string): void;
62
- list(): MediaNodeStatus[];
84
+ list(): RoomrStatus[];
63
85
  };
64
86
  export type NodeDirectory = ReturnType<typeof createNodeDirectory>;
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NODE_FORGET_MS = exports.NODE_STALE_MS = void 0;
3
+ exports.NODE_FORGET_MS = exports.NODE_STALE_MS = exports.DEFAULT_MAX_ROOMS = void 0;
4
4
  exports.createNodeDirectory = createNodeDirectory;
5
+ /** The room limit assumed for a node that reports none (the Roomr node's default). */
6
+ exports.DEFAULT_MAX_ROOMS = 200;
5
7
  /** Heartbeats are every 2 s; a node silent for three of them is not offered new calls. */
6
8
  exports.NODE_STALE_MS = 6000;
7
9
  /**
@@ -10,9 +12,11 @@ exports.NODE_STALE_MS = 6000;
10
12
  */
11
13
  exports.NODE_FORGET_MS = 60000;
12
14
  /**
13
- * The media nodes this replica knows, for placing outbound calls (add-media-node 3.3): fed by the
14
- * session registry's `nodes.` entries (JetStream KV, 3.2; read in full at start, so a restarted
15
- * replica places calls at once) and by `node.heartbeat` / `node.down` events.
15
+ * The Roomr nodes this replica knows, for placing outbound calls (add-roomr 3.3): fed by
16
+ * the `node.heartbeat` / `node.down` events on `roomr.nodes.<node_ref>.heartbeat` (core NATS;
17
+ * nodes write nothing else). `node.down` only takes the node out of placement: a draining node
18
+ * keeps its live rooms and sends no heartbeats, so it is "gone" only after it stays silent for
19
+ * `staleMs` past its `node.down`.
16
20
  */
17
21
  function createNodeDirectory(options = {}) {
18
22
  var _a, _b, _c;
@@ -38,11 +42,15 @@ function createNodeDirectory(options = {}) {
38
42
  */
39
43
  note(event, seenAt) {
40
44
  var _a;
41
- const nodeId = typeof event.nodeId === "string" ? event.nodeId : "";
45
+ const nodeId = typeof event.node_ref === "string" ? event.node_ref : "";
42
46
  if (!nodeId)
43
47
  return;
44
48
  if (event.type === "node.down") {
45
- nodes.delete(nodeId);
49
+ const known = nodes.get(nodeId);
50
+ if (known) {
51
+ known.down = true;
52
+ known.seenAt = seenAt !== null && seenAt !== void 0 ? seenAt : now();
53
+ }
46
54
  }
47
55
  else if (event.type === "node.heartbeat") {
48
56
  const at = seenAt !== null && seenAt !== void 0 ? seenAt : now();
@@ -50,49 +58,75 @@ function createNodeDirectory(options = {}) {
50
58
  // An older registry entry never replaces a fresher heartbeat.
51
59
  if (known && known.seenAt > at)
52
60
  return;
53
- const maxRooms = Number(event.maxRooms);
61
+ const maxRooms = Number(event.max_rooms);
54
62
  nodes.set(nodeId, {
55
63
  nodeId,
56
64
  rooms: Number((_a = event.rooms) !== null && _a !== void 0 ? _a : 0),
57
65
  maxRooms: Number.isFinite(maxRooms) && maxRooms > 0 ? maxRooms : undefined,
58
- draining: event.draining === true,
66
+ region: typeof event.region === "string" && event.region
67
+ ? event.region
68
+ : undefined,
69
+ down: false,
70
+ controlAddr: typeof event.control_addr === "string" && event.control_addr
71
+ ? event.control_addr
72
+ : undefined,
59
73
  seenAt: at
60
74
  });
61
75
  }
62
76
  forget();
63
77
  },
64
78
  /**
65
- * The least-loaded eligible node (live, not draining, below its room limit), skipping the
66
- * nodes in `exclude` (already tried for this call); undefined when there is none.
79
+ * The eligible node with the most room to spare (control-plane): live, not down, below
80
+ * its room limit, with a control address and, when the call names a region, in that region; scored
81
+ * `1 - rooms / max_rooms`, highest wins. Skips the nodes in `exclude` (already tried for
82
+ * this call); undefined when there is none.
67
83
  */
68
- pick(exclude = new Set()) {
84
+ pick(exclude = new Set(), region) {
85
+ var _a;
69
86
  let best;
70
87
  for (const n of nodes.values()) {
71
- if (exclude.has(n.nodeId) || n.draining)
88
+ if (exclude.has(n.nodeId) || n.down || !n.controlAddr)
72
89
  continue;
73
90
  if (now() - n.seenAt > staleMs)
74
91
  continue;
75
- if (n.maxRooms !== undefined && n.rooms >= n.maxRooms)
92
+ if (region && n.region !== region)
93
+ continue;
94
+ const limit = (_a = n.maxRooms) !== null && _a !== void 0 ? _a : exports.DEFAULT_MAX_ROOMS;
95
+ if (n.rooms >= limit)
76
96
  continue;
77
- if (!best || n.rooms < best.rooms)
78
- best = n;
97
+ const score = 1 - n.rooms / limit;
98
+ if (!best || score > best.score)
99
+ best = { node: n, score };
79
100
  }
80
- return best === null || best === void 0 ? void 0 : best.nodeId;
101
+ return best === null || best === void 0 ? void 0 : best.node.nodeId;
81
102
  },
82
103
  /**
83
- * A node refused a room because it is full or draining: no new call goes to it until its
84
- * next heartbeat says otherwise.
104
+ * A node refused a room because it is full or unavailable: no new call goes to it until
105
+ * its next heartbeat says otherwise.
85
106
  */
86
107
  refused(nodeId, code) {
87
108
  var _a;
88
109
  const n = nodes.get(nodeId);
89
110
  if (!n)
90
111
  return;
91
- if (code === "draining")
92
- n.draining = true;
112
+ if (code === "unavailable")
113
+ n.down = true;
93
114
  else
94
115
  n.maxRooms = Math.min((_a = n.maxRooms) !== null && _a !== void 0 ? _a : n.rooms, n.rooms);
95
116
  },
117
+ /**
118
+ * Whether the node is still there: a heartbeat, or its `node.down`, is fresh. A node that
119
+ * said `node.down` stays live for `staleMs` more; after that, silence means it exited.
120
+ */
121
+ live(nodeId) {
122
+ const n = nodes.get(nodeId);
123
+ return !!n && now() - n.seenAt <= staleMs;
124
+ },
125
+ /** The node's Roomr address (control_addr), if known. */
126
+ addressOf(nodeId) {
127
+ var _a;
128
+ return (_a = nodes.get(nodeId)) === null || _a === void 0 ? void 0 : _a.controlAddr;
129
+ },
96
130
  /** Counts a room placed on a node before its next heartbeat reports it. */
97
131
  placed(nodeId) {
98
132
  const n = nodes.get(nodeId);
@@ -18,4 +18,5 @@
18
18
  */
19
19
  export * from "./createNodeDirectory";
20
20
  export * from "./placeOutboundCall";
21
+ export * from "./placementSweep";
21
22
  export * from "./runOutboundCalls";
@@ -34,4 +34,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
34
34
  */
35
35
  __exportStar(require("./createNodeDirectory"), exports);
36
36
  __exportStar(require("./placeOutboundCall"), exports);
37
+ __exportStar(require("./placementSweep"), exports);
37
38
  __exportStar(require("./runOutboundCalls"), exports);
@@ -16,6 +16,7 @@
16
16
  * See the License for the specific language governing permissions and
17
17
  * limitations under the License.
18
18
  */
19
+ import { Roomr } from "@fonoster/common";
19
20
  import { NodeDirectory } from "./createNodeDirectory";
20
21
  /** The calls.create message the Calls service publishes (CreateCall). */
21
22
  export type OutboundCallRequest = {
@@ -26,31 +27,70 @@ export type OutboundCallRequest = {
26
27
  accessKeyId: string;
27
28
  timeout?: number;
28
29
  metadata?: Record<string, unknown>;
30
+ /** The call's region: only nodes whose heartbeat names it are eligible (unset: any node). */
31
+ region?: string;
32
+ };
33
+ /** Where API-originated calls are dialed: the SIP proxy and the digest identity it challenges. */
34
+ export type OutboundTarget = {
35
+ /** host:port of the SIP proxy (Routr); the INVITE goes there. */
36
+ proxy: string;
37
+ auth?: Roomr.SipAuth;
29
38
  };
30
- /** The slice of a NATS connection placement needs: JSON request and reply. */
31
- export type Requester = (subject: string, body: Record<string, unknown>, timeoutMs: number) => Promise<Record<string, unknown>>;
32
- /** The gateway subject that opens the app session when the callee answers (gateway B8). */
33
- export declare const GATEWAY_OUTBOUND_SUBJECT = "gateway.outbound";
34
39
  /** Nodes tried for one call before it fails with no_capacity. */
35
40
  export declare const MAX_PLACEMENT_ATTEMPTS = 3;
41
+ /**
42
+ * Attempts of CreateCall on the same node when the outcome is unknown (a timeout or a connection
43
+ * lost after sending): the same call_ref and parameters, so the node dedupes it.
44
+ */
45
+ export declare const SAME_NODE_ATTEMPTS = 3;
36
46
  /** The PlacementError code for "no node took the call" (CreateCall's RESOURCE_EXHAUSTED). */
37
47
  export declare const NO_CAPACITY = "no_capacity";
38
48
  export declare class PlacementError extends Error {
39
49
  readonly code: string;
40
50
  constructor(code: string, message: string);
41
51
  }
52
+ /** The Request-URI for a callee: a SIP URI as given, a number at the proxy's host. */
53
+ export declare function calleeUri(to: string, proxy: string): string;
54
+ /** The Roomr `metadata` of an API-originated call (AppBridge reads it at answer, 4.8). */
55
+ export declare function outboundMetadata(call: OutboundCallRequest): {
56
+ app_metadata?: string;
57
+ app_ref: string;
58
+ from: string;
59
+ to: string;
60
+ };
61
+ /**
62
+ * The CreateCall request for an API-originated call: dialed through the SIP proxy with the
63
+ * pass-through headers it routes on (`X-DOD-Number`, the caller id, picks the trunk; From is the
64
+ * node's own identity), `to.auth` for the proxy's challenge, and the app in `metadata.app_ref`.
65
+ */
66
+ export declare function createCallRequest(call: OutboundCallRequest, outbound: OutboundTarget): Roomr.CreateCallRequest;
42
67
  /**
43
- * Places an API-originated call (CreateCall) on the media nodes, replacing Asterisk's originate:
44
- * `room.create` on the least-loaded eligible node (the next one, up to MAX_PLACEMENT_ATTEMPTS
45
- * nodes, when a node is full, draining or silent), `gateway.outbound` so a gateway opens the app
46
- * session on `call.answered`, then `participant.dial` through Routr with the headers Routr
47
- * routes API-originated calls by (X-Dod-Number picks the trunk). The room carries the call's
48
- * ref, so the node also publishes the call's status events on `calls.<ref>.events` (TrackCall).
68
+ * Places an API-originated call (CreateCall) on a Roomr node over gRPC, at the heartbeat's
69
+ * `control_addr` (control-plane "Call creation picks the least-loaded Roomr node"):
70
+ *
71
+ * - `CreateCall` with the call's ref on the highest-scoring eligible node. The node dials the
72
+ * callee, creates the room on answer and opens the call's control stream to AppBridge, which
73
+ * finds the app in `metadata.app_ref`; a busy, unanswered or rejected call creates no room and
74
+ * ends with the node's `call.ended` (the control plane's minimal record and call.failed).
75
+ * - `RESOURCE_EXHAUSTED` or `UNAVAILABLE` sends the call to the next node, up to
76
+ * MAX_PLACEMENT_ATTEMPTS nodes, then `no_capacity` (synchronously: the API caller gets it).
77
+ * - A timeout or a lost connection is ambiguous (the INVITE may be out): CreateCall is repeated on
78
+ * the same node with the same call_ref and parameters (the node dedupes it), never on another;
79
+ * still no answer after SAME_NODE_ATTEMPTS fails the call, and EndCall is sent in case the node
80
+ * did take it.
81
+ *
82
+ * `onAttempt` is told each node before anything is sent to it (the session registry's
83
+ * `placements.<callRef>` entry, written before the RPC so a sweep can end the call if this
84
+ * replica dies mid-placement).
49
85
  */
50
- export declare function placeOutboundCall(request: Requester, nodes: NodeDirectory, call: OutboundCallRequest, hooks?: {
51
- /** Called once the room exists, before anything is dialed (e.g. to watch its events). */
52
- onRoom?: (nodeId: string, roomRef: string) => void;
86
+ export declare function placeOutboundCall(deps: {
87
+ roomr: Roomr.RoomrCalls;
88
+ nodes: NodeDirectory;
89
+ outbound: OutboundTarget;
90
+ }, call: OutboundCallRequest, hooks?: {
91
+ onAttempt?: (nodeId: string, controlAddr: string) => unknown;
53
92
  }): Promise<{
54
93
  nodeId: string;
55
94
  roomRef: string;
95
+ callRef: string;
56
96
  }>;