@fonoster/apiserver 0.33.0 → 0.34.2

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.
@@ -73,16 +73,16 @@ export declare const sessionAppInputSchema: z.ZodObject<{
73
73
  fallbackMessage: z.ZodEffects<z.ZodOptional<z.ZodString>, string, unknown>;
74
74
  listeners: z.ZodEffects<z.ZodArray<z.ZodObject<{
75
75
  url: z.ZodString;
76
- tracks: z.ZodEffects<z.ZodDefault<z.ZodEnum<["inbound", "outbound", "both"]>>, "outbound" | "inbound" | "both", unknown>;
76
+ tracks: z.ZodEffects<z.ZodDefault<z.ZodEnum<["inbound", "outbound", "both"]>>, "inbound" | "outbound" | "both", unknown>;
77
77
  }, "strip", z.ZodTypeAny, {
78
78
  url?: string;
79
- tracks?: "outbound" | "inbound" | "both";
79
+ tracks?: "inbound" | "outbound" | "both";
80
80
  }, {
81
81
  url?: string;
82
82
  tracks?: unknown;
83
83
  }>, "many">, {
84
84
  url?: string;
85
- tracks?: "outbound" | "inbound" | "both";
85
+ tracks?: "inbound" | "outbound" | "both";
86
86
  }[], unknown>;
87
87
  recording: z.ZodEffects<z.ZodOptional<z.ZodEnum<["off", "on", "consent"]>>, "on" | "off" | "consent", unknown>;
88
88
  amd: z.ZodEffects<z.ZodOptional<z.ZodObject<{
@@ -133,7 +133,7 @@ export declare const sessionAppInputSchema: z.ZodObject<{
133
133
  fallbackMessage?: string;
134
134
  listeners?: {
135
135
  url?: string;
136
- tracks?: "outbound" | "inbound" | "both";
136
+ tracks?: "inbound" | "outbound" | "both";
137
137
  }[];
138
138
  amd?: {
139
139
  enabled?: boolean;
@@ -193,7 +193,7 @@ export declare function toAppColumns(db: AppsDb, request: Record<string, unknown
193
193
  };
194
194
  listeners: {
195
195
  url?: string;
196
- tracks?: "outbound" | "inbound" | "both";
196
+ tracks?: "inbound" | "outbound" | "both";
197
197
  }[];
198
198
  fallbackAppRef: string;
199
199
  fallbackMessage: string;
@@ -8,9 +8,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.buildService = buildService;
16
13
  /**
@@ -33,7 +30,6 @@ exports.buildService = buildService;
33
30
  */
34
31
  const authz_1 = require("@fonoster/authz");
35
32
  const logger_1 = require("@fonoster/logger");
36
- const sdk_1 = __importDefault(require("@routr/sdk"));
37
33
  const nats_1 = require("nats");
38
34
  const db_1 = require("../core/db");
39
35
  const routrConfig_1 = require("../core/routrConfig");
@@ -82,7 +78,7 @@ function buildService() {
82
78
  proto: "calls.proto"
83
79
  },
84
80
  handlers: {
85
- createCall: (0, createCall_1.createCall)(db_1.prisma, callPublisher, (0, createIsWorkspaceNumber_1.createIsWorkspaceNumber)(new sdk_1.default.Numbers(routrConfig_1.routrConfig)), authzAdmission()),
81
+ createCall: (0, createCall_1.createCall)(db_1.prisma, callPublisher, (0, createIsWorkspaceNumber_1.createIsWorkspaceNumber)((0, routrConfig_1.routrNumbers)()), authzAdmission()),
86
82
  // Call history from the call-record index (add-call-record 7.1).
87
83
  listCalls: (0, listCalls_1.listCalls)((0, records_1.createFetchCallsFromIndex)(db_1.prisma)),
88
84
  getCall: (0, getCall_1.getCall)((0, records_1.createFetchSingleCallFromIndex)(db_1.prisma)),
@@ -16,26 +16,13 @@
16
16
  * See the License for the specific language governing permissions and
17
17
  * limitations under the License.
18
18
  */
19
- /** One page of Routr's numbers (the Routr SDK's listNumbers). */
20
- type NumbersPage = {
21
- items?: {
22
- telUrl?: string;
23
- extended?: Record<string, unknown> | null;
24
- }[];
25
- nextPageToken?: string;
26
- };
27
- type NumbersLister = {
28
- listNumbers(request: {
29
- pageSize: number;
30
- pageToken?: string;
31
- }): Promise<NumbersPage>;
32
- };
19
+ import { NumbersLister } from "../utils/someRoutrNumber";
33
20
  /** Whether `e164` (CreateCall's `from`) is a Number of the workspace `accessKeyId`. */
34
21
  type IsWorkspaceNumber = (accessKeyId: string, e164: string) => Promise<boolean>;
35
22
  /**
36
23
  * CreateCall's `from` becomes X-Dod-Number, which Routr uses to pick the Number's trunk, so it
37
- * must be one of the caller's own Numbers (security review C2). Routr has no lookup by telUrl in
38
- * its API, so this pages through the Numbers and matches `tel:<from>` and the workspace.
24
+ * must be one of the caller's own Numbers (security review C2). It asks Routr every time (no
25
+ * cache: a Number just removed is refused), matching `tel:<from>` and the workspace.
39
26
  */
40
27
  declare function createIsWorkspaceNumber(numbers: NumbersLister): IsWorkspaceNumber;
41
28
  export { createIsWorkspaceNumber, IsWorkspaceNumber, NumbersLister };
@@ -10,30 +10,35 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.createIsWorkspaceNumber = createIsWorkspaceNumber;
13
- const PAGE_SIZE = 200;
14
- const MAX_PAGES = 100;
13
+ /**
14
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
15
+ * http://github.com/fonoster/fonoster
16
+ *
17
+ * This file is part of Fonoster
18
+ *
19
+ * Licensed under the MIT License (the "License");
20
+ * you may not use this file except in compliance with
21
+ * the License. You may obtain a copy of the License at
22
+ *
23
+ * https://opensource.org/licenses/MIT
24
+ *
25
+ * Unless required by applicable law or agreed to in writing, software
26
+ * distributed under the License is distributed on an "AS IS" BASIS,
27
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28
+ * See the License for the specific language governing permissions and
29
+ * limitations under the License.
30
+ */
31
+ const someRoutrNumber_1 = require("../utils/someRoutrNumber");
15
32
  /**
16
33
  * CreateCall's `from` becomes X-Dod-Number, which Routr uses to pick the Number's trunk, so it
17
- * must be one of the caller's own Numbers (security review C2). Routr has no lookup by telUrl in
18
- * its API, so this pages through the Numbers and matches `tel:<from>` and the workspace.
34
+ * must be one of the caller's own Numbers (security review C2). It asks Routr every time (no
35
+ * cache: a Number just removed is refused), matching `tel:<from>` and the workspace.
19
36
  */
20
37
  function createIsWorkspaceNumber(numbers) {
21
38
  return (accessKeyId, e164) => __awaiter(this, void 0, void 0, function* () {
22
- var _a, _b;
23
39
  if (!accessKeyId || !e164)
24
40
  return false;
25
41
  const telUrl = `tel:${e164}`;
26
- let pageToken;
27
- for (let page = 0; page < MAX_PAGES; page++) {
28
- const res = yield numbers.listNumbers({ pageSize: PAGE_SIZE, pageToken });
29
- for (const n of (_a = res.items) !== null && _a !== void 0 ? _a : []) {
30
- if (n.telUrl === telUrl && ((_b = n.extended) === null || _b === void 0 ? void 0 : _b.accessKeyId) === accessKeyId)
31
- return true;
32
- }
33
- if (!res.nextPageToken || res.nextPageToken === pageToken)
34
- return false;
35
- pageToken = res.nextPageToken;
36
- }
37
- return false;
42
+ return (0, someRoutrNumber_1.someRoutrNumber)(numbers, (n) => { var _a; return n.telUrl === telUrl && ((_a = n.extended) === null || _a === void 0 ? void 0 : _a.accessKeyId) === accessKeyId; });
38
43
  });
39
44
  }
@@ -25,6 +25,7 @@ exports.toTrackMessage = toTrackMessage;
25
25
  const common_1 = require("@fonoster/common");
26
26
  const logger_1 = require("@fonoster/logger");
27
27
  const envs_1 = require("../envs");
28
+ const failureStatus_1 = require("../records/failureStatus");
28
29
  const FINAL_STATUSES = [
29
30
  common_1.DialStatus.BUSY,
30
31
  common_1.DialStatus.FAILED,
@@ -56,7 +57,7 @@ const UNANSWERED = {
56
57
  * unknown event types).
57
58
  */
58
59
  function toTrackMessage(event, subject = "") {
59
- var _a, _b, _c, _d;
60
+ var _a, _b, _c, _d, _e;
60
61
  const tokens = subject.split(".");
61
62
  const fromSubject = tokens[0] === "roomr" ? tokens[2] : tokens[1];
62
63
  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 : "");
@@ -75,11 +76,15 @@ function toTrackMessage(event, subject = "") {
75
76
  case "call.ended":
76
77
  // An answered call just ends; an unanswered one ends with its dial status.
77
78
  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);
79
+ ? Object.assign({ ref, final: true }, node) : Object.assign({ ref, status: (_d = UNANSWERED[String(event.cause)]) !== null && _d !== void 0 ? _d : common_1.DialStatus.FAILED,
80
+ // The call's record says the same (its failure reason is the node's cause).
81
+ hangupCause: (0, failureStatus_1.failureStatus)(String((_e = event.cause) !== null && _e !== void 0 ? _e : "")), final: true }, node);
79
82
  case undefined:
80
83
  // The control plane's {ref, status}, {ref, final} and {ref, node_ref} (a node took it).
81
84
  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)
85
+ ? Object.assign(Object.assign(Object.assign(Object.assign({ ref }, (event.status !== undefined ? { status: event.status } : {})), (event.final === true ? { final: true } : {})), node), (event.status === common_1.DialStatus.FAILED
86
+ ? { hangupCause: (0, failureStatus_1.failureStatus)() }
87
+ : {}))
83
88
  : undefined;
84
89
  default:
85
90
  return undefined;
@@ -120,13 +125,20 @@ function createTrackCallHandler(nc, options = {}) {
120
125
  tracked.delete(t.ref);
121
126
  return true;
122
127
  };
123
- /** Ends a stream that got no final status: FAILED, then the end. */
128
+ /**
129
+ * Ends a stream that got no final status: FAILED (why: SERVICE_UNAVAILABLE, the record's word
130
+ * for a call that failed for no reason of its own), then the end.
131
+ */
124
132
  const fail = (t, why) => {
125
133
  if (!untrack(t))
126
134
  return;
127
135
  logger.warn(`TrackCall ${t.ref}: ${why}; ending with FAILED`);
128
136
  try {
129
- t.stream.write({ ref: t.ref, status: common_1.DialStatus.FAILED });
137
+ t.stream.write({
138
+ ref: t.ref,
139
+ status: common_1.DialStatus.FAILED,
140
+ hangupCause: (0, failureStatus_1.failureStatus)()
141
+ });
130
142
  t.stream.end();
131
143
  }
132
144
  catch (_a) {
@@ -135,7 +147,7 @@ function createTrackCallHandler(nc, options = {}) {
135
147
  };
136
148
  /** Writes one message; returns true when the stream is done. */
137
149
  const deliver = (t, message) => {
138
- const { ref, status } = message;
150
+ const { ref, status, hangupCause } = message;
139
151
  if (message.nodeRef && message.nodeRef !== t.nodeRef) {
140
152
  t.nodeRef = message.nodeRef;
141
153
  }
@@ -143,7 +155,7 @@ function createTrackCallHandler(nc, options = {}) {
143
155
  if (t.nodeRef)
144
156
  t.nodeAt = now();
145
157
  if (status)
146
- t.stream.write({ ref, status });
158
+ t.stream.write(Object.assign({ ref, status }, (hangupCause ? { hangupCause } : {})));
147
159
  const done = message.final === true || (!!status && FINAL_STATUSES.includes(status));
148
160
  if (done) {
149
161
  untrack(t);
@@ -51,6 +51,8 @@ declare class CallPlacementError extends Error {
51
51
  type TrackCallResponse = {
52
52
  ref: string;
53
53
  status: DialStatus;
54
+ /** Why the dial ended, on the message that ends an unanswered or failed call (as its record says). */
55
+ hangupCause?: CallStatus;
54
56
  };
55
57
  type CallStream = {
56
58
  write: (data: TrackCallResponse | GrpcErrorMessage) => void;
@@ -2,4 +2,6 @@ declare const routrConfig: {
2
2
  endpoint: string;
3
3
  insecure: boolean;
4
4
  };
5
- export { routrConfig };
5
+ /** The apiserver's one client for Routr's Numbers (CreateCall's check, the records' trunks). */
6
+ declare const routrNumbers: () => import("@routr/sdk/dist/numbers").default;
7
+ export { routrConfig, routrNumbers };
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.routrConfig = void 0;
6
+ exports.routrNumbers = exports.routrConfig = void 0;
4
7
  /**
5
8
  * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
6
9
  * http://github.com/fonoster/fonoster
@@ -19,9 +22,14 @@ exports.routrConfig = void 0;
19
22
  * See the License for the specific language governing permissions and
20
23
  * limitations under the License.
21
24
  */
25
+ const sdk_1 = __importDefault(require("@routr/sdk"));
22
26
  const envs_1 = require("../envs");
23
27
  const routrConfig = {
24
28
  endpoint: envs_1.ROUTR_API_ENDPOINT,
25
29
  insecure: true
26
30
  };
27
31
  exports.routrConfig = routrConfig;
32
+ let numbers;
33
+ /** The apiserver's one client for Routr's Numbers (CreateCall's check, the records' trunks). */
34
+ const routrNumbers = () => (numbers !== null && numbers !== void 0 ? numbers : (numbers = new sdk_1.default.Numbers(routrConfig)));
35
+ exports.routrNumbers = routrNumbers;
@@ -87,6 +87,7 @@ const httpBridge_1 = require("./httpBridge");
87
87
  const identityConfig_1 = require("./identityConfig");
88
88
  const loadServices_1 = __importDefault(require("./loadServices"));
89
89
  const regionHooks_1 = require("./regionHooks");
90
+ const routrConfig_1 = require("./routrConfig");
90
91
  const services_1 = __importDefault(require("./services"));
91
92
  const telemetry_1 = require("./telemetry");
92
93
  const telemetryInterceptor_1 = require("./telemetryInterceptor");
@@ -146,7 +147,8 @@ function runServices() {
146
147
  db: db_1.prisma,
147
148
  relay: { regionOf: regions.regionOf, client: regions.relay },
148
149
  onConfigChange: regions.onConfigChange,
149
- usage: { directory: () => regionHooks_1.workspaceRegionHooks.directory() }
150
+ usage: { directory: () => regionHooks_1.workspaceRegionHooks.directory() },
151
+ trunkOf: (0, records_1.createTrunkOfNumber)((0, routrConfig_1.routrNumbers)())
150
152
  });
151
153
  // The dashboard's cookie session (M4): refresh token in an httpOnly cookie on its origin
152
154
  const session = {
@@ -1,5 +1,6 @@
1
1
  import { NatsConnection } from "nats";
2
2
  import { UsageDirectory } from "../usage/types";
3
+ import { TrunkOfNumber } from "./createTrunkOfNumber";
3
4
  import { RecordIndexEntry, RecordsDb } from "./types";
4
5
  /** Where a call's usage lines go: owners come from Identity's workspaces once attached. */
5
6
  export type IndexUsageDeps = {
@@ -21,12 +22,14 @@ export declare function usageEvents(entry: RecordIndexEntry, workspaceRef: strin
21
22
  model?: string;
22
23
  keySource?: "platform" | "workspace";
23
24
  }[];
25
+ /** How long indexing waits for a call's trunk before indexing it without one. */
26
+ export declare const TRUNK_LOOKUP_TIMEOUT_MS = 2000;
24
27
  /**
25
28
  * Upserts a record's index entry. Entries arrive at least once and possibly out of order, so a
26
29
  * lower version never overwrites a higher one. An erased record keeps its row, without numbers.
27
30
  * The call's usage lines are stored in the same transaction as the row (add-usage-metering D1).
28
31
  */
29
- export declare function createIndexRecord(db: RecordsDb, usage?: IndexUsageDeps): (entry: RecordIndexEntry) => Promise<boolean>;
32
+ export declare function createIndexRecord(db: RecordsDb, usage?: IndexUsageDeps, trunkOf?: TrunkOfNumber, trunkTimeoutMs?: number): (entry: RecordIndexEntry) => Promise<boolean>;
30
33
  /** The work queue that captures the AppBridge replicas' index entries and its durable consumer (ST-2). */
31
34
  export declare const RECORD_INDEX_STREAM = "FONOSTER_RECORD_INDEX";
32
35
  export declare const RECORD_INDEX_DURABLE = "apiserver-call-records";
@@ -39,4 +42,5 @@ export declare const RECORD_INDEX_DURABLE = "apiserver-call-records";
39
42
  export declare function subscribeRecordIndex(nc: NatsConnection, db: RecordsDb, options?: {
40
43
  ackWaitMs?: number;
41
44
  usage?: IndexUsageDeps;
45
+ trunkOf?: TrunkOfNumber;
42
46
  }): Promise<() => Promise<void> | void>;
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.RECORD_INDEX_DURABLE = exports.RECORD_INDEX_STREAM = void 0;
12
+ exports.RECORD_INDEX_DURABLE = exports.RECORD_INDEX_STREAM = exports.TRUNK_LOOKUP_TIMEOUT_MS = void 0;
13
13
  exports.usageEvents = usageEvents;
14
14
  exports.createIndexRecord = createIndexRecord;
15
15
  exports.subscribeRecordIndex = subscribeRecordIndex;
@@ -50,14 +50,50 @@ function usageEvents(entry, workspaceRef) {
50
50
  return (Object.assign(Object.assign(Object.assign(Object.assign({}, line), { id: common_1.Usage.usageId(entry.callRef, line), workspaceRef }), (entry.appRef ? { appRef: entry.appRef } : {})), { callRef: entry.callRef, region: entry.region, regionKind: (0, types_1.isPrivateRegionRef)(entry.region) ? "private" : "public", origin, occurredAt: new Date((_a = entry.endedAt) !== null && _a !== void 0 ? _a : entry.startedAt).toISOString() }));
51
51
  });
52
52
  }
53
+ /**
54
+ * The trunk the call used, by name: the trunk of the workspace's Number on the call (the callee
55
+ * of an inbound call, the caller of an outbound one). Undefined when unknown, e.g. for an internal
56
+ * call or when Routr can't be reached or doesn't answer within `timeoutMs`; indexing never fails
57
+ * or stalls for it (the entry must be acknowledged within the consumer's ack wait).
58
+ */
59
+ function trunkNameOf(entry, workspaceRef, trunkOf, timeoutMs) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ var _a;
62
+ const number = entry.direction === "inbound"
63
+ ? entry.to
64
+ : entry.direction === "outbound"
65
+ ? entry.from
66
+ : undefined;
67
+ if (!trunkOf || !workspaceRef || !number)
68
+ return undefined;
69
+ let timer;
70
+ try {
71
+ return yield Promise.race([
72
+ trunkOf(workspaceRef, number),
73
+ new Promise((_, reject) => {
74
+ timer = setTimeout(() => reject(new Error(`Routr did not answer in ${timeoutMs} ms`)), timeoutMs);
75
+ })
76
+ ]);
77
+ }
78
+ catch (e) {
79
+ logger.warn(`no trunk for ${entry.callRef}: ${(_a = e.message) !== null && _a !== void 0 ? _a : e}`);
80
+ return undefined;
81
+ }
82
+ finally {
83
+ clearTimeout(timer);
84
+ }
85
+ });
86
+ }
87
+ /** How long indexing waits for a call's trunk before indexing it without one. */
88
+ exports.TRUNK_LOOKUP_TIMEOUT_MS = 2000;
53
89
  /**
54
90
  * Upserts a record's index entry. Entries arrive at least once and possibly out of order, so a
55
91
  * lower version never overwrites a higher one. An erased record keeps its row, without numbers.
56
92
  * The call's usage lines are stored in the same transaction as the row (add-usage-metering D1).
57
93
  */
58
- function createIndexRecord(db, usage) {
94
+ function createIndexRecord(db, usage, trunkOf, trunkTimeoutMs = exports.TRUNK_LOOKUP_TIMEOUT_MS) {
59
95
  return (entry) => __awaiter(this, void 0, void 0, function* () {
60
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
96
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
61
97
  const existing = yield db.callRecord.findUnique({
62
98
  where: { callRef: entry.callRef }
63
99
  });
@@ -72,25 +108,34 @@ function createIndexRecord(db, usage) {
72
108
  return false;
73
109
  }
74
110
  const erased = entry.status === "erased";
111
+ const accessKeyId = (_b = (_a = existing === null || existing === void 0 ? void 0 : existing.accessKeyId) !== null && _a !== void 0 ? _a : entry.workspaceRef) !== null && _b !== void 0 ? _b : null;
112
+ // Resolved once, when the call is first indexed: later versions keep what was stored, a
113
+ // null included, so a Number moved to another trunk since never renames the call's.
114
+ const trunkName = existing
115
+ ? ((_c = existing.trunkName) !== null && _c !== void 0 ? _c : null)
116
+ : erased
117
+ ? null
118
+ : ((_d = (yield trunkNameOf(entry, accessKeyId, trunkOf, trunkTimeoutMs))) !== null && _d !== void 0 ? _d : null);
75
119
  const data = {
76
- accessKeyId: (_b = (_a = existing === null || existing === void 0 ? void 0 : existing.accessKeyId) !== null && _a !== void 0 ? _a : entry.workspaceRef) !== null && _b !== void 0 ? _b : null,
77
- appRef: erased ? ((_c = existing === null || existing === void 0 ? void 0 : existing.appRef) !== null && _c !== void 0 ? _c : null) : entry.appRef,
120
+ accessKeyId,
121
+ appRef: erased ? ((_e = existing === null || existing === void 0 ? void 0 : existing.appRef) !== null && _e !== void 0 ? _e : null) : entry.appRef,
78
122
  fromNumber: erased ? null : entry.from,
79
123
  toNumber: erased ? null : entry.to,
80
- direction: erased ? ((_d = existing === null || existing === void 0 ? void 0 : existing.direction) !== null && _d !== void 0 ? _d : null) : entry.direction,
124
+ direction: erased ? ((_f = existing === null || existing === void 0 ? void 0 : existing.direction) !== null && _f !== void 0 ? _f : null) : entry.direction,
81
125
  status: entry.status,
82
- endReason: erased ? ((_e = existing === null || existing === void 0 ? void 0 : existing.endReason) !== null && _e !== void 0 ? _e : null) : entry.endReason,
126
+ endReason: erased ? ((_g = existing === null || existing === void 0 ? void 0 : existing.endReason) !== null && _g !== void 0 ? _g : null) : entry.endReason,
83
127
  failureReason: entry.failureReason,
84
128
  sipStatus: entry.sipStatus,
85
- amdStatus: erased ? null : ((_f = entry.amdStatus) !== null && _f !== void 0 ? _f : null),
129
+ amdStatus: erased ? null : ((_h = entry.amdStatus) !== null && _h !== void 0 ? _h : null),
130
+ trunkName,
86
131
  startedAt: erased && existing ? existing.startedAt : new Date(entry.startedAt),
87
132
  endedAt: erased
88
- ? ((_g = existing === null || existing === void 0 ? void 0 : existing.endedAt) !== null && _g !== void 0 ? _g : null)
133
+ ? ((_j = existing === null || existing === void 0 ? void 0 : existing.endedAt) !== null && _j !== void 0 ? _j : null)
89
134
  : entry.endedAt
90
135
  ? new Date(entry.endedAt)
91
136
  : null,
92
137
  durationSeconds: erased
93
- ? ((_h = existing === null || existing === void 0 ? void 0 : existing.durationSeconds) !== null && _h !== void 0 ? _h : 0)
138
+ ? ((_k = existing === null || existing === void 0 ? void 0 : existing.durationSeconds) !== null && _k !== void 0 ? _k : 0)
94
139
  : entry.durationSeconds,
95
140
  region: entry.region,
96
141
  location: entry.location,
@@ -106,7 +151,7 @@ function createIndexRecord(db, usage) {
106
151
  };
107
152
  const directory = usage === null || usage === void 0 ? void 0 : usage.directory();
108
153
  const workspaceRef = data.accessKeyId;
109
- if (!erased && directory && workspaceRef && ((_j = entry.usage) === null || _j === void 0 ? void 0 : _j.length)) {
154
+ if (!erased && directory && workspaceRef && ((_l = entry.usage) === null || _l === void 0 ? void 0 : _l.length)) {
110
155
  const events = usageEvents(entry, workspaceRef);
111
156
  yield db.$transaction((tx) => __awaiter(this, void 0, void 0, function* () {
112
157
  yield tx.callRecord.upsert(upsert);
@@ -114,7 +159,7 @@ function createIndexRecord(db, usage) {
114
159
  }));
115
160
  return true;
116
161
  }
117
- if (!erased && !directory && ((_k = entry.usage) === null || _k === void 0 ? void 0 : _k.length))
162
+ if (!erased && !directory && ((_m = entry.usage) === null || _m === void 0 ? void 0 : _m.length))
118
163
  logger.warn(`usage for ${entry.callRef} not stored: no workspace directory yet`);
119
164
  yield db.callRecord.upsert(upsert);
120
165
  return true;
@@ -131,7 +176,7 @@ exports.RECORD_INDEX_DURABLE = "apiserver-call-records";
131
176
  */
132
177
  function subscribeRecordIndex(nc_1, db_1) {
133
178
  return __awaiter(this, arguments, void 0, function* (nc, db, options = {}) {
134
- const index = createIndexRecord(db, options.usage);
179
+ const index = createIndexRecord(db, options.usage, options.trunkOf);
135
180
  const handle = (data, headers) => __awaiter(this, void 0, void 0, function* () {
136
181
  var _a;
137
182
  let entry;
@@ -46,7 +46,9 @@ export type RecordsRouterDeps = {
46
46
  * The records API (call-record "Records are available through the API and the dashboard",
47
47
  * tasks 5.1 and 4.2), on the apiserver's HTTP port so recordings download as files:
48
48
  *
49
- * GET /api/records search: after, before, number, appRef, status
49
+ * GET /api/records search: after, before, number, appRef, status;
50
+ * a page of records; the first page
51
+ * also has the query's total
50
52
  * GET /api/records/:callRef the record (redacted; ?original=true, ?version=n)
51
53
  * GET /api/records/:callRef/recording the recording (WAV)
52
54
  * GET /api/records/:callRef/audit deletions of this record (owner, admin)
@@ -46,7 +46,9 @@ exports.UNREDACTED_ROLES = ["WORKSPACE_OWNER", "WORKSPACE_ADMIN"];
46
46
  * The records API (call-record "Records are available through the API and the dashboard",
47
47
  * tasks 5.1 and 4.2), on the apiserver's HTTP port so recordings download as files:
48
48
  *
49
- * GET /api/records search: after, before, number, appRef, status
49
+ * GET /api/records search: after, before, number, appRef, status;
50
+ * a page of records; the first page
51
+ * also has the query's total
50
52
  * GET /api/records/:callRef the record (redacted; ?original=true, ?version=n)
51
53
  * GET /api/records/:callRef/recording the recording (WAV)
52
54
  * GET /api/records/:callRef/audit deletions of this record (owner, admin)
@@ -85,7 +87,7 @@ function createRecordsRouter(deps) {
85
87
  router.use(express_1.default.json());
86
88
  router.use(auth);
87
89
  const view = (row) => {
88
- var _a, _b, _c;
90
+ var _a, _b, _c, _d;
89
91
  return ({
90
92
  callRef: row.callRef,
91
93
  appRef: row.appRef,
@@ -97,8 +99,9 @@ function createRecordsRouter(deps) {
97
99
  failureReason: row.failureReason,
98
100
  sipStatus: row.sipStatus,
99
101
  amdStatus: (_a = row.amdStatus) !== null && _a !== void 0 ? _a : null,
102
+ trunkName: (_b = row.trunkName) !== null && _b !== void 0 ? _b : null,
100
103
  startedAt: row.startedAt.toISOString(),
101
- endedAt: (_c = (_b = row.endedAt) === null || _b === void 0 ? void 0 : _b.toISOString()) !== null && _c !== void 0 ? _c : null,
104
+ endedAt: (_d = (_c = row.endedAt) === null || _c === void 0 ? void 0 : _c.toISOString()) !== null && _d !== void 0 ? _d : null,
102
105
  durationSeconds: row.durationSeconds,
103
106
  region: row.region,
104
107
  version: row.version,
@@ -117,10 +120,11 @@ function createRecordsRouter(deps) {
117
120
  status: q.status,
118
121
  pageSize: q.pageSize ? Number(q.pageSize) : undefined,
119
122
  pageToken: q.pageToken
120
- });
123
+ }, { total: true });
121
124
  res.json({
122
125
  items: result.items.map(view),
123
- nextPageToken: result.nextPageToken
126
+ nextPageToken: result.nextPageToken,
127
+ total: result.total
124
128
  });
125
129
  })));
126
130
  router.get("/retention", handle((_req, res) => __awaiter(this, void 0, void 0, function* () {
@@ -30,14 +30,19 @@ export type RecordSearch = {
30
30
  direction?: string;
31
31
  status?: string;
32
32
  pageSize?: number;
33
- /** The previous page's last startedAt (ms). */
33
+ /** Where the previous page ended: `<startedAt ms>:<callRef>` (a bare startedAt ms is read too). */
34
34
  pageToken?: string;
35
35
  };
36
36
  /**
37
37
  * Searches the index within one workspace (call-record "Fetch and search": time range, number,
38
38
  * app, direction and status; records from other workspaces are never returned). Newest first.
39
+ * With `total`, the first page (no page token) also counts every record the query matches, on
40
+ * all pages (#1069); later pages don't count again.
39
41
  */
40
- export declare function createSearchRecords(db: RecordsDb): (accessKeyId: string, search: RecordSearch) => Promise<{
42
+ export declare function createSearchRecords(db: RecordsDb): (accessKeyId: string, search: RecordSearch, options?: {
43
+ total?: boolean;
44
+ }) => Promise<{
45
+ total?: number;
41
46
  items: CallRecordRow[];
42
47
  nextPageToken: string;
43
48
  }>;
@@ -32,59 +32,73 @@ exports.createFetchSingleCallFromIndex = createFetchSingleCallFromIndex;
32
32
  * limitations under the License.
33
33
  */
34
34
  const types_1 = require("@fonoster/types");
35
+ const failureStatus_1 = require("./failureStatus");
36
+ /** A page token: the last record's startedAt and callRef, so records that share a time are not skipped. */
37
+ function pageTokenOf(row) {
38
+ return `${row.startedAt.getTime()}:${row.callRef}`;
39
+ }
40
+ /** The records after a page token, in the list's order (startedAt, then callRef, descending). */
41
+ function afterToken(pageToken) {
42
+ const sep = pageToken.indexOf(":");
43
+ const at = new Date(Number(sep < 0 ? pageToken : pageToken.slice(0, sep)));
44
+ // An older token (a bare startedAt) keeps its meaning: strictly before it.
45
+ if (sep < 0)
46
+ return { startedAt: { lt: at } };
47
+ return {
48
+ OR: [
49
+ { startedAt: { lt: at } },
50
+ { startedAt: at, callRef: { lt: pageToken.slice(sep + 1) } }
51
+ ]
52
+ };
53
+ }
35
54
  /**
36
55
  * Searches the index within one workspace (call-record "Fetch and search": time range, number,
37
56
  * app, direction and status; records from other workspaces are never returned). Newest first.
57
+ * With `total`, the first page (no page token) also counts every record the query matches, on
58
+ * all pages (#1069); later pages don't count again.
38
59
  */
39
60
  function createSearchRecords(db) {
40
- return (accessKeyId, search) => __awaiter(this, void 0, void 0, function* () {
61
+ return (accessKeyId_1, search_1, ...args_1) => __awaiter(this, [accessKeyId_1, search_1, ...args_1], void 0, function* (accessKeyId, search, options = {}) {
41
62
  const startedAt = {};
42
63
  if (search.after)
43
64
  startedAt.gte = new Date(search.after);
44
65
  if (search.before)
45
66
  startedAt.lt = new Date(search.before);
46
- if (search.pageToken) {
47
- const token = new Date(Number(search.pageToken));
48
- if (!startedAt.lt || token < startedAt.lt)
49
- startedAt.lt = token;
50
- }
51
67
  const where = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ accessKeyId, erasedAt: null }, (Object.keys(startedAt).length ? { startedAt } : {})), (search.from ? { fromNumber: search.from } : {})), (search.to ? { toNumber: search.to } : {})), (search.appRef ? { appRef: search.appRef } : {})), (search.direction ? { direction: search.direction } : {})), (search.status ? { status: search.status } : {})), (search.number
52
68
  ? {
53
69
  OR: [{ fromNumber: search.number }, { toNumber: search.number }]
54
70
  }
55
71
  : {}));
72
+ // The page token only moves the page: the total counts the query without it.
73
+ const pageWhere = search.pageToken
74
+ ? { AND: [where, afterToken(search.pageToken)] }
75
+ : where;
56
76
  const pageSize = Math.min(Math.max(search.pageSize || 50, 1), 500);
57
- const items = yield db.callRecord.findMany({
58
- where,
59
- orderBy: { startedAt: "desc" },
60
- take: pageSize
61
- });
62
- return {
63
- items,
64
- nextPageToken: items.length === pageSize
65
- ? String(items[items.length - 1].startedAt.getTime())
66
- : ""
67
- };
77
+ const [items, total] = yield Promise.all([
78
+ db.callRecord.findMany({
79
+ where: pageWhere,
80
+ orderBy: [{ startedAt: "desc" }, { callRef: "desc" }],
81
+ take: pageSize
82
+ }),
83
+ options.total && !search.pageToken
84
+ ? db.callRecord.count({ where })
85
+ : undefined
86
+ ]);
87
+ return Object.assign({ items, nextPageToken: items.length === pageSize ? pageTokenOf(items[items.length - 1]) : "" }, (total !== undefined ? { total } : {}));
68
88
  });
69
89
  }
70
- const FAILURE_STATUS = {
71
- busy: types_1.CallStatus.USER_BUSY,
72
- no_answer: types_1.CallStatus.NO_ANSWER,
73
- rejected: types_1.CallStatus.CALL_REJECTED,
74
- no_app: types_1.CallStatus.NO_ROUTE_DESTINATION
75
- };
76
90
  /** A call detail record (the existing Calls API shape) from an index row. */
77
91
  function toCallDetailRecord(row) {
78
- var _a, _b, _c, _d, _e, _f, _g;
92
+ var _a, _b, _c, _d, _e;
79
93
  const status = row.status === "failed"
80
- ? ((_b = FAILURE_STATUS[(_a = row.failureReason) !== null && _a !== void 0 ? _a : ""]) !== null && _b !== void 0 ? _b : types_1.CallStatus.SERVICE_UNAVAILABLE)
94
+ ? (0, failureStatus_1.failureStatus)(row.failureReason)
81
95
  : types_1.CallStatus.NORMAL_CLEARING;
82
96
  // The Calls API carries times as epoch seconds (int32 on the wire; the SDK multiplies by 1000).
83
- return Object.assign({ ref: row.callRef, accessKeyId: (_c = row.accessKeyId) !== null && _c !== void 0 ? _c : "", callId: row.callRef, direction: row.direction === "outbound"
97
+ return Object.assign({ ref: row.callRef, accessKeyId: (_a = row.accessKeyId) !== null && _a !== void 0 ? _a : "", callId: row.callRef, direction: row.direction === "outbound"
84
98
  ? types_1.CallDirection.TO_PSTN
85
99
  : types_1.CallDirection.FROM_PSTN, type: row.direction === "outbound"
86
100
  ? types_1.CallType.API_ORIGINATED
87
- : types_1.CallType.SIP_ORIGINATED, status, startedAt: Math.floor(row.startedAt.getTime() / 1000), endedAt: Math.floor(((_d = row.endedAt) !== null && _d !== void 0 ? _d : row.startedAt).getTime() / 1000), from: (_e = row.fromNumber) !== null && _e !== void 0 ? _e : "", to: (_f = row.toNumber) !== null && _f !== void 0 ? _f : "", duration: row.durationSeconds, appRef: (_g = row.appRef) !== null && _g !== void 0 ? _g : "" }, (row.amdStatus ? { amdStatus: row.amdStatus.toUpperCase() } : {}));
101
+ : types_1.CallType.SIP_ORIGINATED, status, startedAt: Math.floor(row.startedAt.getTime() / 1000), endedAt: Math.floor(((_b = row.endedAt) !== null && _b !== void 0 ? _b : row.startedAt).getTime() / 1000), from: (_c = row.fromNumber) !== null && _c !== void 0 ? _c : "", to: (_d = row.toNumber) !== null && _d !== void 0 ? _d : "", duration: row.durationSeconds, appRef: (_e = row.appRef) !== null && _e !== void 0 ? _e : "" }, (row.amdStatus ? { amdStatus: row.amdStatus.toUpperCase() } : {}));
88
102
  }
89
103
  const STATUS_FILTER = {
90
104
  [types_1.CallStatus.NORMAL_CLEARING]: { status: "completed" },
@@ -0,0 +1,40 @@
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 { NumbersLister } from "../utils/someRoutrNumber";
20
+ /** The name of the trunk of the workspace's Number, or undefined when it has none. */
21
+ type TrunkOfNumber = (accessKeyId: string, number: string) => Promise<string | undefined>;
22
+ /**
23
+ * A number as a lookup key: `tel:+1555…`, `sip:+1555…@host;params`, `+1555…` and `1555…` are
24
+ * the same Number (Routr keeps telUrls; a call's legs may carry a URI or bare digits).
25
+ */
26
+ declare function numberKey(number: string): string;
27
+ /**
28
+ * Resolves a call's trunk from its Number when the call's record is indexed (#1069): Routr routes
29
+ * a Number's calls through the Number's trunk, both ways. Routr has no lookup by telUrl, so the
30
+ * Numbers are listed once and kept for `ttlMs`. A number not in the list lists them again, at
31
+ * most every `missMs`, so a Number added since is found; one still missing after that is kept
32
+ * as unknown until the next listing. One listing runs at a time, and a failed one is not
33
+ * retried for `missMs`.
34
+ */
35
+ declare function createTrunkOfNumber(numbers: NumbersLister, options?: {
36
+ ttlMs?: number;
37
+ missMs?: number;
38
+ now?: () => number;
39
+ }): TrunkOfNumber;
40
+ export { createTrunkOfNumber, numberKey, TrunkOfNumber };
@@ -0,0 +1,88 @@
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.createTrunkOfNumber = createTrunkOfNumber;
13
+ exports.numberKey = numberKey;
14
+ /**
15
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
16
+ * http://github.com/fonoster/fonoster
17
+ *
18
+ * This file is part of Fonoster
19
+ *
20
+ * Licensed under the MIT License (the "License");
21
+ * you may not use this file except in compliance with
22
+ * the License. You may obtain a copy of the License at
23
+ *
24
+ * https://opensource.org/licenses/MIT
25
+ *
26
+ * Unless required by applicable law or agreed to in writing, software
27
+ * distributed under the License is distributed on an "AS IS" BASIS,
28
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29
+ * See the License for the specific language governing permissions and
30
+ * limitations under the License.
31
+ */
32
+ const someRoutrNumber_1 = require("../utils/someRoutrNumber");
33
+ /**
34
+ * A number as a lookup key: `tel:+1555…`, `sip:+1555…@host;params`, `+1555…` and `1555…` are
35
+ * the same Number (Routr keeps telUrls; a call's legs may carry a URI or bare digits).
36
+ */
37
+ function numberKey(number) {
38
+ const user = number
39
+ .trim()
40
+ .replace(/^<?(tel|sips?):/i, "")
41
+ .split(/[@;>]/)[0];
42
+ return /^\d+$/.test(user) ? `+${user}` : user;
43
+ }
44
+ /**
45
+ * Resolves a call's trunk from its Number when the call's record is indexed (#1069): Routr routes
46
+ * a Number's calls through the Number's trunk, both ways. Routr has no lookup by telUrl, so the
47
+ * Numbers are listed once and kept for `ttlMs`. A number not in the list lists them again, at
48
+ * most every `missMs`, so a Number added since is found; one still missing after that is kept
49
+ * as unknown until the next listing. One listing runs at a time, and a failed one is not
50
+ * retried for `missMs`.
51
+ */
52
+ function createTrunkOfNumber(numbers, options = {}) {
53
+ var _a, _b, _c;
54
+ const ttlMs = (_a = options.ttlMs) !== null && _a !== void 0 ? _a : 60000;
55
+ const missMs = (_b = options.missMs) !== null && _b !== void 0 ? _b : 10000;
56
+ const now = (_c = options.now) !== null && _c !== void 0 ? _c : Date.now;
57
+ // By workspace and number: the trunk's name, or null for a Number without one or an unknown number.
58
+ let trunks = new Map();
59
+ let loadedAt = -Infinity;
60
+ let triedAt = -Infinity;
61
+ let loading;
62
+ const load = () => (loading !== null && loading !== void 0 ? loading : (loading = (() => __awaiter(this, void 0, void 0, function* () {
63
+ triedAt = now();
64
+ const next = new Map();
65
+ yield (0, someRoutrNumber_1.someRoutrNumber)(numbers, (n) => {
66
+ var _a, _b;
67
+ const accessKeyId = (_a = n.extended) === null || _a === void 0 ? void 0 : _a.accessKeyId;
68
+ if (n.telUrl && typeof accessKeyId === "string")
69
+ next.set(`${accessKeyId} ${numberKey(n.telUrl)}`, ((_b = n.trunk) === null || _b === void 0 ? void 0 : _b.name) || null);
70
+ });
71
+ trunks = next;
72
+ loadedAt = now();
73
+ }))().finally(() => (loading = undefined))));
74
+ return (accessKeyId, number) => __awaiter(this, void 0, void 0, function* () {
75
+ var _a;
76
+ if (!accessKeyId || !number)
77
+ return undefined;
78
+ const key = `${accessKeyId} ${numberKey(number)}`;
79
+ const age = now() - loadedAt;
80
+ const due = age >= ttlMs || (!trunks.has(key) && age >= missMs);
81
+ if (due && (loading || now() - triedAt >= missMs)) {
82
+ yield load();
83
+ if (!trunks.has(key))
84
+ trunks.set(key, null);
85
+ }
86
+ return (_a = trunks.get(key)) !== null && _a !== void 0 ? _a : undefined;
87
+ });
88
+ }
@@ -0,0 +1,25 @@
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 { CallStatus } from "@fonoster/types";
20
+ /**
21
+ * Why a failed call ended, as a CallStatus: what GetCall and ListCalls report for it and what
22
+ * TrackCall ends its stream with. Any other reason (node_error, removed, canceled, a call that
23
+ * never got placed) is SERVICE_UNAVAILABLE.
24
+ */
25
+ export declare function failureStatus(reason?: string | null): CallStatus;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.failureStatus = failureStatus;
4
+ /**
5
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
6
+ * http://github.com/fonoster/fonoster
7
+ *
8
+ * This file is part of Fonoster
9
+ *
10
+ * Licensed under the MIT License (the "License");
11
+ * you may not use this file except in compliance with
12
+ * the License. You may obtain a copy of the License at
13
+ *
14
+ * https://opensource.org/licenses/MIT
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */
22
+ const types_1 = require("@fonoster/types");
23
+ /** Failure reasons of a call record → the Calls API's CallStatus names. */
24
+ const FAILURE_STATUS = {
25
+ busy: types_1.CallStatus.USER_BUSY,
26
+ no_answer: types_1.CallStatus.NO_ANSWER,
27
+ rejected: types_1.CallStatus.CALL_REJECTED,
28
+ no_app: types_1.CallStatus.NO_ROUTE_DESTINATION
29
+ };
30
+ /**
31
+ * Why a failed call ended, as a CallStatus: what GetCall and ListCalls report for it and what
32
+ * TrackCall ends its stream with. Any other reason (node_error, removed, canceled, a call that
33
+ * never got placed) is SERVICE_UNAVAILABLE.
34
+ */
35
+ function failureStatus(reason) {
36
+ var _a;
37
+ return (_a = FAILURE_STATUS[reason !== null && reason !== void 0 ? reason : ""]) !== null && _a !== void 0 ? _a : types_1.CallStatus.SERVICE_UNAVAILABLE;
38
+ }
@@ -19,6 +19,7 @@
19
19
  export * from "./createIndexRecord";
20
20
  export * from "./createRecordsRouter";
21
21
  export * from "./createSearchRecords";
22
+ export * from "./createTrunkOfNumber";
22
23
  export * from "./maintenance";
23
24
  export * from "./runCallRecords";
24
25
  export * from "./stores";
@@ -35,6 +35,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
35
35
  __exportStar(require("./createIndexRecord"), exports);
36
36
  __exportStar(require("./createRecordsRouter"), exports);
37
37
  __exportStar(require("./createSearchRecords"), exports);
38
+ __exportStar(require("./createTrunkOfNumber"), exports);
38
39
  __exportStar(require("./maintenance"), exports);
39
40
  __exportStar(require("./runCallRecords"), exports);
40
41
  __exportStar(require("./stores"), exports);
@@ -21,6 +21,7 @@ import { NatsTarget } from "@fonoster/common";
21
21
  import { Router } from "express";
22
22
  import { IndexUsageDeps } from "./createIndexRecord";
23
23
  import { RecordsRouterDeps } from "./createRecordsRouter";
24
+ import { TrunkOfNumber } from "./createTrunkOfNumber";
24
25
  import { RecordsDb } from "./types";
25
26
  export type CallRecordsConfig = {
26
27
  enabled: boolean;
@@ -40,6 +41,8 @@ export declare function runCallRecords(config: CallRecordsConfig, deps: {
40
41
  relay?: RecordsRouterDeps["relay"];
41
42
  onConfigChange?: (accessKeyId: string) => void;
42
43
  usage?: IndexUsageDeps;
44
+ /** Names the trunk of a call's Number when its record is indexed. */
45
+ trunkOf?: TrunkOfNumber;
43
46
  }): Promise<{
44
47
  routers: {
45
48
  path: string;
@@ -27,7 +27,10 @@ function runCallRecords(config, deps) {
27
27
  if (!config.enabled)
28
28
  return { routers: [] };
29
29
  const nc = yield (0, nats_1.connect)(Object.assign(Object.assign({}, (0, common_1.natsConnectOptions)(deps.natsUrl)), { maxReconnectAttempts: -1 }));
30
- yield (0, createIndexRecord_1.subscribeRecordIndex)(nc, deps.db, { usage: deps.usage });
30
+ yield (0, createIndexRecord_1.subscribeRecordIndex)(nc, deps.db, {
31
+ usage: deps.usage,
32
+ trunkOf: deps.trunkOf
33
+ });
31
34
  const maintenance = (0, maintenance_1.natsMaintenanceClient)(nc, config.maintenanceTimeoutMs);
32
35
  const retention = setInterval(() => void (0, maintenance_1.runRetention)(deps.db, maintenance)
33
36
  .then((done) => done.length &&
@@ -30,6 +30,8 @@ export type CallRecordRow = {
30
30
  sipStatus: number | null;
31
31
  /** Who answered, by AMD (human, voicemail, ivr, machine, unknown); null when it didn't run. */
32
32
  amdStatus?: string | null;
33
+ /** The trunk of the workspace's number on the call, by name; null when unknown. */
34
+ trunkName?: string | null;
33
35
  startedAt: Date;
34
36
  endedAt: Date | null;
35
37
  durationSeconds: number;
@@ -67,6 +69,7 @@ export interface RecordsDb {
67
69
  };
68
70
  }): Promise<CallRecordRow | null>;
69
71
  findMany(args: Record<string, unknown>): Promise<CallRecordRow[]>;
72
+ count(args: Record<string, unknown>): Promise<number>;
70
73
  upsert(args: Record<string, unknown>): Promise<unknown>;
71
74
  update(args: Record<string, unknown>): Promise<unknown>;
72
75
  };
@@ -0,0 +1,42 @@
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
+ /** A Number as Routr's listNumbers has it: its telUrl, its trunk and its workspace. */
20
+ type RoutrNumber = {
21
+ telUrl?: string;
22
+ trunk?: {
23
+ name?: string;
24
+ } | null;
25
+ extended?: Record<string, unknown> | null;
26
+ };
27
+ /** Routr's Numbers API (the Routr SDK's Numbers), as far as listing goes. */
28
+ type NumbersLister = {
29
+ listNumbers(request: {
30
+ pageSize: number;
31
+ pageToken?: string;
32
+ }): Promise<{
33
+ items?: RoutrNumber[];
34
+ nextPageToken?: string;
35
+ }>;
36
+ };
37
+ /**
38
+ * Pages through Routr's Numbers until `visit` returns true, and says whether it did. Routr has no
39
+ * lookup by telUrl in its API, so whoever needs a Number by telUrl lists them.
40
+ */
41
+ declare function someRoutrNumber(numbers: NumbersLister, visit: (n: RoutrNumber) => boolean | void): Promise<boolean>;
42
+ export { NumbersLister, RoutrNumber, someRoutrNumber };
@@ -0,0 +1,34 @@
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.someRoutrNumber = someRoutrNumber;
13
+ const PAGE_SIZE = 200;
14
+ const MAX_PAGES = 100;
15
+ /**
16
+ * Pages through Routr's Numbers until `visit` returns true, and says whether it did. Routr has no
17
+ * lookup by telUrl in its API, so whoever needs a Number by telUrl lists them.
18
+ */
19
+ function someRoutrNumber(numbers, visit) {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ var _a;
22
+ let pageToken;
23
+ for (let page = 0; page < MAX_PAGES; page++) {
24
+ const res = yield numbers.listNumbers({ pageSize: PAGE_SIZE, pageToken });
25
+ for (const n of (_a = res.items) !== null && _a !== void 0 ? _a : [])
26
+ if (visit(n))
27
+ return true;
28
+ if (!res.nextPageToken || res.nextPageToken === pageToken)
29
+ return false;
30
+ pageToken = res.nextPageToken;
31
+ }
32
+ return false;
33
+ });
34
+ }
@@ -1,10 +1,30 @@
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
+ */
1
19
  import { Sessions, Webhooks } from "@fonoster/common";
2
20
  /** `call.ended`'s `endReason` when AppBridge that owned the call died mid-call. */
3
21
  export declare const APPBRIDGE_LOST_REASON = "appbridge-lost";
4
22
  /**
5
23
  * The `call.ended` the control plane sends for a call whose AppBridge is gone (the node ended it
6
- * 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
7
- * stores one delivery per endpoint (delivery ids depend on the event id): delivered once.
24
+ * with cause `app_gone`). Its id depends on the call only (`Webhooks.callEndedId`), so every
25
+ * replica that detects the loss builds the same event, and so does an AppBridge that sent its own
26
+ * `call.ended` just before it died: the fan-out stores one delivery per endpoint (delivery ids
27
+ * depend on the event id) and the first one wins.
8
28
  */
9
29
  export declare function lostCallEnded(call: Record<string, unknown>, lastSeenAt: number): Webhooks.WebhookEvent | undefined;
10
30
  /** How long after the node's `app_gone` an AppBridge's own end of the call may still show up. */
@@ -21,14 +21,15 @@ exports.createLostCalls = createLostCalls;
21
21
  * See the License for the specific language governing permissions and
22
22
  * limitations under the License.
23
23
  */
24
- const crypto_1 = require("crypto");
25
24
  const common_1 = require("@fonoster/common");
26
25
  /** `call.ended`'s `endReason` when AppBridge that owned the call died mid-call. */
27
26
  exports.APPBRIDGE_LOST_REASON = "appbridge-lost";
28
27
  /**
29
28
  * 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
- * stores one delivery per endpoint (delivery ids depend on the event id): delivered once.
29
+ * with cause `app_gone`). Its id depends on the call only (`Webhooks.callEndedId`), so every
30
+ * replica that detects the loss builds the same event, and so does an AppBridge that sent its own
31
+ * `call.ended` just before it died: the fan-out stores one delivery per endpoint (delivery ids
32
+ * depend on the event id) and the first one wins.
32
33
  */
33
34
  function lostCallEnded(call, lastSeenAt) {
34
35
  const str = (v) => (typeof v === "string" ? v : "");
@@ -38,7 +39,7 @@ function lostCallEnded(call, lastSeenAt) {
38
39
  if (!callRef || !appRef)
39
40
  return undefined;
40
41
  const startedAt = Date.parse(str(call.startedAt));
41
- const event = common_1.Webhooks.callEnded("", {
42
+ return common_1.Webhooks.callEnded("", {
42
43
  callRef,
43
44
  appRef,
44
45
  from: str(call.from),
@@ -49,11 +50,6 @@ function lostCallEnded(call, lastSeenAt) {
49
50
  : 0,
50
51
  endReason: exports.APPBRIDGE_LOST_REASON
51
52
  });
52
- const digest = (0, crypto_1.createHash)("sha256")
53
- .update(`appbridge-lost\n${callRef}`)
54
- .digest("hex")
55
- .slice(0, 32);
56
- return Object.assign(Object.assign({}, event), { id: `evt_lost_${digest}` });
57
53
  }
58
54
  /** How long after the node's `app_gone` an AppBridge's own end of the call may still show up. */
59
55
  exports.APP_GONE_GRACE_MS = 2000;
@@ -94,7 +94,7 @@ function runWebhookFanout(config, deps) {
94
94
  if (!resolved)
95
95
  return;
96
96
  yield store.refreshEndpoints(resolved.workspaceRef);
97
- const created = yield store.insertDeliveries(dispatcher.plan(resolved));
97
+ const created = yield dispatcher.publishOnce(resolved);
98
98
  if (created.length)
99
99
  void runDue();
100
100
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fonoster/apiserver",
3
- "version": "0.33.0",
3
+ "version": "0.34.2",
4
4
  "description": "APIServer for Fonoster",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/fonoster#readme",
@@ -22,14 +22,14 @@
22
22
  "fonoster-usage": "./dist/bin/usage.js"
23
23
  },
24
24
  "dependencies": {
25
- "@fonoster/authz": "^0.33.0",
26
- "@fonoster/autopilot": "^0.33.0",
27
- "@fonoster/callrecord": "^0.33.0",
28
- "@fonoster/common": "^0.33.0",
29
- "@fonoster/identity": "^0.33.0",
30
- "@fonoster/logger": "^0.33.0",
31
- "@fonoster/sipnet": "^0.33.0",
32
- "@fonoster/types": "^0.33.0",
25
+ "@fonoster/authz": "^0.34.2",
26
+ "@fonoster/autopilot": "^0.34.2",
27
+ "@fonoster/callrecord": "^0.34.1",
28
+ "@fonoster/common": "^0.34.2",
29
+ "@fonoster/identity": "^0.34.2",
30
+ "@fonoster/logger": "^0.34.1",
31
+ "@fonoster/sipnet": "^0.34.2",
32
+ "@fonoster/types": "^0.34.1",
33
33
  "@grpc/grpc-js": "~1.14.6",
34
34
  "@prisma/client": "^6.19.1",
35
35
  "@routr/common": "^2.24.0",
@@ -66,7 +66,7 @@
66
66
  "@types/uuid": "^10.0.0",
67
67
  "@types/validator": "^13.15.10"
68
68
  },
69
- "gitHead": "ab449441e5e628169680422c66b8cc3474ad9bf9",
69
+ "gitHead": "e7d99a0fdd2b1242b38e22f3e3b3cc5aa4448ffe",
70
70
  "prisma": {
71
71
  "seed": "tsx src/core/seed.ts"
72
72
  }