agl 43.6.0 → 43.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/changelog.md +27 -0
- package/dist_serve/bundle.js +1801 -1783
- package/dist_serve/bundle.js.map +2 -2
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/aglapi/interfaces.d.ts +35 -0
- package/dist_ts/aglapi/interfaces.js +9 -1
- package/dist_ts/classes.accountsactions.d.ts +3 -1
- package/dist_ts/classes.accountsactions.js +17 -1
- package/dist_ts/classes.apnsclient.d.ts +97 -0
- package/dist_ts/classes.apnsclient.js +363 -0
- package/dist_ts/classes.authmodels.js +19 -6
- package/dist_ts/classes.authstore.js +15 -2
- package/dist_ts/classes.cli.js +8 -1
- package/dist_ts/classes.controller.d.ts +33 -6
- package/dist_ts/classes.controller.js +254 -12
- package/dist_ts/classes.controllerdevices.d.ts +35 -7
- package/dist_ts/classes.controllerdevices.js +86 -13
- package/dist_ts/classes.controllerpush.d.ts +111 -0
- package/dist_ts/classes.controllerpush.js +299 -0
- package/dist_ts/classes.fcmclient.d.ts +78 -0
- package/dist_ts/classes.fcmclient.js +278 -0
- package/dist_ts/classes.inbox.d.ts +10 -2
- package/dist_ts/classes.inbox.js +9 -2
- package/dist_ts/classes.inferencerouter.d.ts +21 -3
- package/dist_ts/classes.inferencerouter.js +40 -17
- package/dist_ts/classes.inferenceservice.js +2 -2
- package/dist_ts/classes.mcpclient.d.ts +5 -0
- package/dist_ts/classes.mcpclient.js +18 -6
- package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
- package/dist_ts/classes.mcpcontrollerhost.js +19 -1
- package/dist_ts/classes.mcpvalidation.js +4 -1
- package/dist_ts/classes.mcpworkercaller.d.ts +6 -0
- package/dist_ts/classes.mcpworkercaller.js +26 -4
- package/dist_ts/classes.pushdelivery.d.ts +115 -0
- package/dist_ts/classes.pushdelivery.js +311 -0
- package/dist_ts/classes.pushhandover.d.ts +46 -0
- package/dist_ts/classes.pushhandover.js +131 -0
- package/dist_ts/classes.pushregistrations.d.ts +96 -0
- package/dist_ts/classes.pushregistrations.js +263 -0
- package/dist_ts/classes.pushsettings.d.ts +125 -0
- package/dist_ts/classes.pushsettings.js +377 -0
- package/dist_ts/classes.workercallers.d.ts +73 -2
- package/dist_ts/classes.workercallers.js +354 -43
- package/dist_ts/driver/classes.directreports.d.ts +5 -0
- package/dist_ts/driver/classes.directreports.js +3 -2
- package/dist_ts/fleet/classes.workerlaunches.d.ts +6 -4
- package/dist_ts/fleet/classes.workerlaunches.js +10 -9
- package/dist_ts/fleet/classes.workers.d.ts +12 -2
- package/dist_ts/fleet/classes.workers.js +82 -2
- package/dist_ts/functions.deviceapi.d.ts +23 -3
- package/dist_ts/functions.deviceapi.js +41 -3
- package/dist_ts/functions.inferencecli.js +2 -1
- package/dist_ts/functions.pushcli.d.ts +43 -0
- package/dist_ts/functions.pushcli.js +201 -0
- package/dist_ts/functions.pushcredentials.d.ts +53 -0
- package/dist_ts/functions.pushcredentials.js +111 -0
- package/dist_ts/functions.pushwire.d.ts +8 -0
- package/dist_ts/functions.pushwire.js +83 -0
- package/dist_ts/functions.remotecli.d.ts +2 -2
- package/dist_ts/functions.remotecli.js +4 -4
- package/dist_ts/functions.workercallervalidation.js +3 -2
- package/dist_ts/functions.workerprocessproof.d.ts +12 -0
- package/dist_ts/functions.workerprocessproof.js +32 -1
- package/dist_ts/interfaces.auth.d.ts +27 -3
- package/dist_ts/interfaces.auth.js +10 -1
- package/dist_ts/interfaces.lifecycle.d.ts +7 -1
- package/dist_ts/interfaces.push.d.ts +69 -0
- package/dist_ts/interfaces.push.js +25 -0
- package/dist_ts/plugins.d.ts +5 -2
- package/dist_ts/plugins.js +7 -3
- package/dist_ts_authswitch/authority-contract.d.ts +26 -0
- package/dist_ts_authswitch/authority-contract.js +1 -1
- package/dist_ts_authswitch/authority-overview.d.ts +8 -0
- package/dist_ts_authswitch/authority-overview.js +10 -4
- package/dist_ts_authswitch/authority-placement.d.ts +16 -9
- package/dist_ts_authswitch/authority-placement.js +10 -7
- package/dist_ts_authswitch/authority-priority.d.ts +20 -0
- package/dist_ts_authswitch/authority-priority.js +21 -0
- package/dist_ts_authswitch/classes.authoritybroker.d.ts +7 -0
- package/dist_ts_authswitch/classes.authoritybroker.js +26 -2
- package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
- package/dist_ts_authswitch/classes.authoritycli.js +43 -3
- package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
- package/dist_ts_authswitch/classes.authorityclient.js +12 -4
- package/dist_ts_authswitch/classes.authoritydaemon.js +7 -1
- package/dist_ts_authswitch/classes.authoritydatabase.d.ts +6 -0
- package/dist_ts_authswitch/classes.authoritydatabase.js +13 -2
- package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
- package/dist_ts_authswitch/classes.authoritymodels.js +17 -8
- package/dist_ts_interfaces/devices.d.ts +178 -2
- package/dist_ts_interfaces/devices.js +24 -2
- package/dist_ts_interfaces/index.d.ts +1 -0
- package/dist_ts_interfaces/index.js +2 -1
- package/dist_ts_interfaces/mcprequests.d.ts +3 -2
- package/dist_ts_interfaces/mcprequests.js +3 -1
- package/dist_ts_interfaces/push.d.ts +166 -0
- package/dist_ts_interfaces/push.js +24 -0
- package/dist_ts_interfaces/requests.accounts.d.ts +19 -0
- package/dist_ts_interfaces/requests.accounts.js +1 -1
- package/dist_ts_interfaces/requests.d.ts +2 -2
- package/dist_ts_interfaces/requests.js +1 -1
- package/dist_ts_interfaces/workercallers.d.ts +43 -3
- package/docs/authswitch.md +25 -0
- package/package.json +1 -1
- package/readme.md +93 -16
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/aglapi/interfaces.ts +8 -0
- package/ts/classes.accountsactions.ts +25 -0
- package/ts/classes.apnsclient.ts +389 -0
- package/ts/classes.authmodels.ts +21 -5
- package/ts/classes.authstore.ts +14 -1
- package/ts/classes.cli.ts +7 -0
- package/ts/classes.controller.ts +277 -10
- package/ts/classes.controllerdevices.ts +94 -12
- package/ts/classes.controllerpush.ts +351 -0
- package/ts/classes.fcmclient.ts +292 -0
- package/ts/classes.inbox.ts +13 -2
- package/ts/classes.inferencerouter.ts +61 -16
- package/ts/classes.inferenceservice.ts +1 -1
- package/ts/classes.mcpclient.ts +20 -5
- package/ts/classes.mcpcontrollerhost.ts +20 -0
- package/ts/classes.mcpvalidation.ts +2 -0
- package/ts/classes.mcpworkercaller.ts +24 -2
- package/ts/classes.pushdelivery.ts +378 -0
- package/ts/classes.pushhandover.ts +98 -0
- package/ts/classes.pushregistrations.ts +244 -0
- package/ts/classes.pushsettings.ts +428 -0
- package/ts/classes.workercallers.ts +329 -37
- package/ts/driver/classes.directreports.ts +7 -1
- package/ts/fleet/classes.workerlaunches.ts +9 -7
- package/ts/fleet/classes.workers.ts +65 -2
- package/ts/functions.deviceapi.ts +52 -2
- package/ts/functions.inferencecli.ts +1 -0
- package/ts/functions.pushcli.ts +212 -0
- package/ts/functions.pushcredentials.ts +129 -0
- package/ts/functions.pushwire.ts +106 -0
- package/ts/functions.remotecli.ts +3 -2
- package/ts/functions.workercallervalidation.ts +2 -1
- package/ts/functions.workerprocessproof.ts +34 -0
- package/ts/interfaces.auth.ts +27 -3
- package/ts/interfaces.lifecycle.ts +7 -1
- package/ts/interfaces.push.ts +78 -0
- package/ts/plugins.ts +6 -1
- package/ts_authswitch/authority-contract.ts +21 -0
- package/ts_authswitch/authority-overview.ts +19 -5
- package/ts_authswitch/authority-placement.ts +18 -10
- package/ts_authswitch/authority-priority.ts +25 -0
- package/ts_authswitch/classes.authoritybroker.ts +26 -1
- package/ts_authswitch/classes.authoritycli.ts +48 -2
- package/ts_authswitch/classes.authorityclient.ts +14 -4
- package/ts_authswitch/classes.authoritydaemon.ts +8 -1
- package/ts_authswitch/classes.authoritydatabase.ts +11 -1
- package/ts_authswitch/classes.authoritymodels.ts +17 -6
- package/ts_authswitch/readme.md +1 -1
- package/ts_interfaces/devices.schema.json +327 -0
- package/ts_interfaces/devices.ts +206 -1
- package/ts_interfaces/index.ts +1 -0
- package/ts_interfaces/mcprequests.ts +3 -0
- package/ts_interfaces/push.ts +162 -0
- package/ts_interfaces/requests.accounts.ts +17 -0
- package/ts_interfaces/requests.ts +2 -0
- package/ts_interfaces/workercallers.ts +34 -2
- package/ts_web/00_commitinfo_data.ts +1 -1
- package/ts_web/accounts.plugins.ts +4 -2
- package/ts_web/classes.accountsreadmodel.ts +36 -2
- package/ts_web/elements.accounts.ts +48 -0
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
import type { IDevicePushFailure, TDevicePushData, TDevicePushFailureReason, TDevicePushPlatform } from '../ts_interfaces/devices.js';
|
|
2
|
+
import { pushClockSkewText, pushTestAnswerWaitMs, type IPushFailureStatus } from '../ts_interfaces/push.js';
|
|
3
|
+
import { ApnsClient } from './classes.apnsclient.js';
|
|
4
|
+
import { FcmClient } from './classes.fcmclient.js';
|
|
5
|
+
import type { ControllerPushSettings } from './classes.pushsettings.js';
|
|
6
|
+
import type { IPushEndpoints, IPushSender, IPushSendTarget, TPushSendResult } from './interfaces.push.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The host's notification delivery (AGL-1639): what the Inbox's push trigger hands it goes to Apple or Google with the
|
|
10
|
+
* platform's sender, never holding the caller up. A send that failed for a reason that passes (rate limited, the service
|
|
11
|
+
* failed, unreachable) waits in a bounded queue of the device, in memory only: the newest notification per key, sent
|
|
12
|
+
* again after 1 s, doubling up to 5 min, and dropped once it is an hour old. A token the push service calls gone deletes
|
|
13
|
+
* the registration that still holds it; a refused credential stops its platform until the owner sets it again. Nothing
|
|
14
|
+
* is kept across a restart, and `stop` leaves no timer, request or connection behind.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** The timers the delivery runs on: Node's own, or a test's clock. */
|
|
18
|
+
export interface IPushDeliveryClock {
|
|
19
|
+
now(): number;
|
|
20
|
+
setTimeout(callbackArg: () => void, delayMsArg: number): unknown;
|
|
21
|
+
clearTimeout(handleArg: unknown): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const nodeClock: IPushDeliveryClock = {
|
|
25
|
+
now: () => Date.now(),
|
|
26
|
+
setTimeout: (callbackArg, delayMsArg) => setTimeout(callbackArg, delayMsArg),
|
|
27
|
+
clearTimeout: (handleArg) => clearTimeout(handleArg as NodeJS.Timeout),
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export const pushDeliveryTimings = Object.freeze({
|
|
31
|
+
/** The first wait after a failure that passes; it doubles with every failure after it. */
|
|
32
|
+
initialBackoffMs: 1000,
|
|
33
|
+
maximumBackoffMs: 5 * 60_000,
|
|
34
|
+
/** A notification older than this is dropped, and Apple and Google are told it expires then. */
|
|
35
|
+
maximumAgeMs: 60 * 60_000,
|
|
36
|
+
/** Past this many notifications for one device, the oldest is dropped. */
|
|
37
|
+
maximumQueuedPerDevice: 64,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/** A paired device's registration as the delivery sends to it: never leaves the host but to its push service. */
|
|
41
|
+
export interface IPushDeliveryTarget extends IPushSendTarget {
|
|
42
|
+
deviceId: string;
|
|
43
|
+
platform: TDevicePushPlatform;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** What one attempt came to: a send's outcome, or `unavailable` when the host holds no usable credential for the platform. */
|
|
47
|
+
export type TPushDeliveryOutcome = 'delivered' | 'unregistered' | 'unavailable' | TDevicePushFailureReason;
|
|
48
|
+
|
|
49
|
+
export interface IPushDeliveryAttempt {
|
|
50
|
+
outcome: TPushDeliveryOutcome;
|
|
51
|
+
/** The push service's code, when it named one. */
|
|
52
|
+
vendorReason?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** What `deliver` answers: the attempt, or `no_answer` when the push service did not answer within the wait. */
|
|
56
|
+
export interface IPushDeliveryAnswer {
|
|
57
|
+
outcome: TPushDeliveryOutcome | 'no_answer';
|
|
58
|
+
vendorReason?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface IControllerPushDeliveryOptions {
|
|
62
|
+
settings: ControllerPushSettings;
|
|
63
|
+
/** Deletes the device's registration if it still holds `tokenArg`: the push service called that token gone. */
|
|
64
|
+
unregistered(deviceIdArg: string, tokenArg: string): Promise<void>;
|
|
65
|
+
/** A fault no send result names (a deletion or a refusal that could not be stored, a sender that threw). */
|
|
66
|
+
fault(errorArg: unknown): void;
|
|
67
|
+
/** Where the senders connect; Apple's and Google's hosts when absent. For tests. */
|
|
68
|
+
endpoints?: IPushEndpoints;
|
|
69
|
+
/** For tests. */
|
|
70
|
+
clock?: IPushDeliveryClock;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface IQueuedPush {
|
|
74
|
+
target: IPushDeliveryTarget;
|
|
75
|
+
payload: TDevicePushData;
|
|
76
|
+
enqueuedAt: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
interface IDeviceQueue {
|
|
80
|
+
/** By key, oldest first: a notification with a key already queued replaces it and goes last. */
|
|
81
|
+
entries: Map<string, IQueuedPush>;
|
|
82
|
+
/** Failures since the last notification went out: the next wait. */
|
|
83
|
+
failures: number;
|
|
84
|
+
timer?: unknown;
|
|
85
|
+
running: boolean;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** An attempt as the queue reads it: also how long the push service asked the host to wait. */
|
|
89
|
+
interface IAttemptResult extends IPushDeliveryAttempt {
|
|
90
|
+
retryAfterMs?: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface IHeldSender {
|
|
94
|
+
generation: number;
|
|
95
|
+
sender: IPushSender;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** An attempt in flight for a device; `forget` marks it, so its outcome no longer writes the device's state. */
|
|
99
|
+
interface IAttemptTicket {
|
|
100
|
+
forgotten: boolean;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The key a queued notification is replaced by: an item's key, or the keys a `clear` names. */
|
|
104
|
+
const queueKey = (payloadArg: TDevicePushData): string => (payloadArg.type === 'clear' ? `clear ${payloadArg.keys}` : payloadArg.key);
|
|
105
|
+
|
|
106
|
+
const platformNames = { apns: 'APNs', fcm: 'FCM' } as const satisfies Record<TDevicePushPlatform, string>;
|
|
107
|
+
|
|
108
|
+
const retryable = (outcomeArg: TPushDeliveryOutcome): boolean => (
|
|
109
|
+
outcomeArg === 'rate_limited' || outcomeArg === 'service_failed' || outcomeArg === 'unreachable'
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
export class ControllerPushDelivery {
|
|
113
|
+
private readonly clock: IPushDeliveryClock;
|
|
114
|
+
private readonly queues = new Map<string, IDeviceQueue>();
|
|
115
|
+
private readonly senders = new Map<TDevicePushPlatform, IHeldSender>();
|
|
116
|
+
private readonly lastFailures = new Map<string, IDevicePushFailure>();
|
|
117
|
+
private readonly platformFailures = new Map<TDevicePushPlatform, IPushFailureStatus>();
|
|
118
|
+
private readonly attempts = new Map<string, Set<IAttemptTicket>>();
|
|
119
|
+
/** Drains, attempts and sender closes still running: `stop` waits for them. */
|
|
120
|
+
private readonly running = new Set<Promise<unknown>>();
|
|
121
|
+
private readonly abort = new AbortController();
|
|
122
|
+
private readonly unsubscribe: () => void;
|
|
123
|
+
private stopping?: Promise<void>;
|
|
124
|
+
|
|
125
|
+
constructor(private readonly options: IControllerPushDeliveryOptions) {
|
|
126
|
+
this.clock = options.clock ?? nodeClock;
|
|
127
|
+
// A credential set, removed or refused: the platform's sender goes, and the next send makes one for what is held.
|
|
128
|
+
this.unsubscribe = options.settings.onChange((platformArg) => this.dropSender(platformArg));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Whether the host can send on the platform now: it holds a credential Apple or Google did not refuse. */
|
|
132
|
+
public available(platformArg: TDevicePushPlatform): boolean {
|
|
133
|
+
return this.stopping === undefined && this.options.settings.ready(platformArg);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The last notification to the device that did not go out, while none went out after it. */
|
|
137
|
+
public lastFailure(deviceIdArg: string): IDevicePushFailure | undefined {
|
|
138
|
+
return this.lastFailures.get(deviceIdArg);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The platform's last failed send, with the push service's code (`agl push status`). */
|
|
142
|
+
public platformFailure(platformArg: TDevicePushPlatform): IPushFailureStatus | undefined {
|
|
143
|
+
return this.platformFailures.get(platformArg);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Queues a notification for the device and returns at once. Nothing is queued while the host cannot send on the
|
|
148
|
+
* device's platform; a notification with a key already queued replaces that one.
|
|
149
|
+
*/
|
|
150
|
+
public send(targetArg: IPushDeliveryTarget, payloadArg: TDevicePushData): void {
|
|
151
|
+
if (!this.available(targetArg.platform)) return;
|
|
152
|
+
let queue = this.queues.get(targetArg.deviceId);
|
|
153
|
+
if (!queue) {
|
|
154
|
+
queue = { entries: new Map(), failures: 0, running: false };
|
|
155
|
+
this.queues.set(targetArg.deviceId, queue);
|
|
156
|
+
}
|
|
157
|
+
const key = queueKey(payloadArg);
|
|
158
|
+
queue.entries.delete(key);
|
|
159
|
+
queue.entries.set(key, { target: { ...targetArg }, payload: payloadArg, enqueuedAt: this.clock.now() });
|
|
160
|
+
while (queue.entries.size > pushDeliveryTimings.maximumQueuedPerDevice) queue.entries.delete(queue.entries.keys().next().value!);
|
|
161
|
+
if (!queue.running && queue.timer === undefined) queueMicrotask(() => this.track(this.drain(targetArg.deviceId)));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Drops the device's queued notifications with these keys (items that left the Inbox before they went out). */
|
|
165
|
+
public withdraw(deviceIdArg: string, keysArg: readonly string[]): void {
|
|
166
|
+
const queue = this.queues.get(deviceIdArg);
|
|
167
|
+
if (!queue) return;
|
|
168
|
+
for (const key of keysArg) queue.entries.delete(key);
|
|
169
|
+
if (queue.entries.size === 0) this.dropQueue(deviceIdArg);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Drops everything queued for the device and its last failure: it was revoked or ended its registration. An attempt
|
|
174
|
+
* still in flight for it no longer records a failure for it.
|
|
175
|
+
*/
|
|
176
|
+
public forget(deviceIdArg: string): void {
|
|
177
|
+
this.dropQueue(deviceIdArg);
|
|
178
|
+
this.lastFailures.delete(deviceIdArg);
|
|
179
|
+
for (const ticket of this.attempts.get(deviceIdArg) ?? []) ticket.forgotten = true;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* One attempt now, outside the queue, answering what the push service said (`agl push test`), or `no_answer` once
|
|
184
|
+
* `waitMsArg` passed without an answer: the attempt goes on, and its outcome counts as any other's.
|
|
185
|
+
*/
|
|
186
|
+
public async deliver(targetArg: IPushDeliveryTarget, payloadArg: TDevicePushData, waitMsArg = pushTestAnswerWaitMs): Promise<IPushDeliveryAnswer> {
|
|
187
|
+
if (!this.available(targetArg.platform)) return { outcome: 'unavailable' };
|
|
188
|
+
const attempt = this.attempt(targetArg, payloadArg, this.clock.now() + pushDeliveryTimings.maximumAgeMs);
|
|
189
|
+
this.track(attempt);
|
|
190
|
+
let timer: unknown;
|
|
191
|
+
const waited = new Promise<IPushDeliveryAnswer>((resolve) => {
|
|
192
|
+
timer = this.clock.setTimeout(() => resolve({ outcome: 'no_answer' }), waitMsArg);
|
|
193
|
+
});
|
|
194
|
+
try {
|
|
195
|
+
const answer = await Promise.race([attempt, waited]);
|
|
196
|
+
return { outcome: answer.outcome, ...(answer.vendorReason === undefined ? {} : { vendorReason: answer.vendorReason }) };
|
|
197
|
+
} finally {
|
|
198
|
+
this.clock.clearTimeout(timer);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** How many notifications wait for the device, and whether a retry is armed for it. For tests. */
|
|
203
|
+
public queued(deviceIdArg: string): { count: number; retrying: boolean } {
|
|
204
|
+
const queue = this.queues.get(deviceIdArg);
|
|
205
|
+
return { count: queue?.entries.size ?? 0, retrying: queue?.timer !== undefined };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Whether nothing runs: no queue, timer, attempt or connection. For tests. */
|
|
209
|
+
public idle(): boolean {
|
|
210
|
+
return this.queues.size === 0 && this.running.size === 0 && this.senders.size === 0;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Stops for good: every timer cleared, every queue dropped, every request aborted and every connection closed before
|
|
215
|
+
* it resolves. Never rejects; a second call waits for the first.
|
|
216
|
+
*/
|
|
217
|
+
public stop(): Promise<void> {
|
|
218
|
+
this.stopping ??= (async () => {
|
|
219
|
+
this.unsubscribe();
|
|
220
|
+
for (const deviceId of [...this.queues.keys()]) this.dropQueue(deviceId);
|
|
221
|
+
this.abort.abort();
|
|
222
|
+
for (const platform of [...this.senders.keys()]) this.dropSender(platform);
|
|
223
|
+
while (this.running.size > 0) await Promise.allSettled([...this.running]);
|
|
224
|
+
})();
|
|
225
|
+
return this.stopping;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private track(promiseArg: Promise<unknown>): void {
|
|
229
|
+
const tracked = promiseArg.catch((errorArg: unknown) => { this.options.fault(errorArg); });
|
|
230
|
+
this.running.add(tracked);
|
|
231
|
+
void tracked.finally(() => { this.running.delete(tracked); });
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
private dropQueue(deviceIdArg: string): void {
|
|
235
|
+
const queue = this.queues.get(deviceIdArg);
|
|
236
|
+
if (!queue) return;
|
|
237
|
+
if (queue.timer !== undefined) this.clock.clearTimeout(queue.timer);
|
|
238
|
+
queue.timer = undefined;
|
|
239
|
+
queue.entries.clear();
|
|
240
|
+
if (!queue.running) this.queues.delete(deviceIdArg);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
private dropSender(platformArg: TDevicePushPlatform): void {
|
|
244
|
+
const held = this.senders.get(platformArg);
|
|
245
|
+
if (!held) return;
|
|
246
|
+
this.senders.delete(platformArg);
|
|
247
|
+
this.track(held.sender.close());
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** The platform's sender for the credential held now; none while the host holds no usable one. */
|
|
251
|
+
private sender(platformArg: TDevicePushPlatform): IHeldSender | undefined {
|
|
252
|
+
if (this.stopping !== undefined) return undefined;
|
|
253
|
+
const { settings, endpoints } = this.options;
|
|
254
|
+
const common = { ...(endpoints === undefined ? {} : { endpoints }), now: () => this.clock.now() };
|
|
255
|
+
const credential = platformArg === 'apns' ? settings.apnsCredential() : settings.fcmCredential();
|
|
256
|
+
if (!credential) return undefined;
|
|
257
|
+
const held = this.senders.get(platformArg);
|
|
258
|
+
if (held?.generation === credential.generation) return held;
|
|
259
|
+
if (held) this.dropSender(platformArg);
|
|
260
|
+
const created: IHeldSender = {
|
|
261
|
+
generation: credential.generation,
|
|
262
|
+
sender: 'keyId' in credential ? new ApnsClient({ credential, ...common }) : new FcmClient({ credential, ...common }),
|
|
263
|
+
};
|
|
264
|
+
this.senders.set(platformArg, created);
|
|
265
|
+
return created;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** One send, and what its outcome means for the registration, the device's state and the platform. */
|
|
269
|
+
private async attempt(targetArg: IPushDeliveryTarget, payloadArg: TDevicePushData, expiresAtArg: number): Promise<IAttemptResult> {
|
|
270
|
+
const ticket: IAttemptTicket = { forgotten: false };
|
|
271
|
+
const tickets = this.attempts.get(targetArg.deviceId) ?? new Set<IAttemptTicket>();
|
|
272
|
+
tickets.add(ticket);
|
|
273
|
+
this.attempts.set(targetArg.deviceId, tickets);
|
|
274
|
+
try {
|
|
275
|
+
return await this.attemptOnce(targetArg, payloadArg, expiresAtArg, ticket);
|
|
276
|
+
} finally {
|
|
277
|
+
tickets.delete(ticket);
|
|
278
|
+
if (tickets.size === 0 && this.attempts.get(targetArg.deviceId) === tickets) this.attempts.delete(targetArg.deviceId);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
private async attemptOnce(targetArg: IPushDeliveryTarget, payloadArg: TDevicePushData, expiresAtArg: number, ticketArg: IAttemptTicket): Promise<IAttemptResult> {
|
|
283
|
+
const held = this.sender(targetArg.platform);
|
|
284
|
+
if (!held) return { outcome: 'unavailable' };
|
|
285
|
+
let result: TPushSendResult;
|
|
286
|
+
try {
|
|
287
|
+
result = await held.sender.send(targetArg, payloadArg, expiresAtArg, this.abort.signal);
|
|
288
|
+
} catch (errorArg) {
|
|
289
|
+
this.options.fault(errorArg);
|
|
290
|
+
result = { outcome: 'service_failed' };
|
|
291
|
+
}
|
|
292
|
+
const attempt: IAttemptResult = {
|
|
293
|
+
outcome: result.outcome,
|
|
294
|
+
...(result.outcome !== 'delivered' && result.vendorReason !== undefined ? { vendorReason: result.vendorReason } : {}),
|
|
295
|
+
...('retryAfterMs' in result && result.retryAfterMs !== undefined ? { retryAfterMs: result.retryAfterMs } : {}),
|
|
296
|
+
};
|
|
297
|
+
if (this.stopping !== undefined) return attempt;
|
|
298
|
+
const at = this.clock.now();
|
|
299
|
+
if (result.outcome === 'delivered') {
|
|
300
|
+
this.lastFailures.delete(targetArg.deviceId);
|
|
301
|
+
return attempt;
|
|
302
|
+
}
|
|
303
|
+
if (result.outcome === 'unregistered') {
|
|
304
|
+
this.forget(targetArg.deviceId);
|
|
305
|
+
try {
|
|
306
|
+
await this.options.unregistered(targetArg.deviceId, targetArg.token);
|
|
307
|
+
} catch (errorArg) {
|
|
308
|
+
this.options.fault(errorArg);
|
|
309
|
+
}
|
|
310
|
+
return attempt;
|
|
311
|
+
}
|
|
312
|
+
// A device forgotten while the attempt ran (revoked, or its registration ended) keeps no failure.
|
|
313
|
+
if (!ticketArg.forgotten) this.lastFailures.set(targetArg.deviceId, { at, reason: result.outcome });
|
|
314
|
+
const clockSkewMs = 'clockSkewMs' in result ? result.clockSkewMs : undefined;
|
|
315
|
+
const previous = this.platformFailures.get(targetArg.platform);
|
|
316
|
+
this.platformFailures.set(targetArg.platform, { at, reason: result.outcome,
|
|
317
|
+
...(attempt.vendorReason === undefined ? {} : { vendorReason: attempt.vendorReason }),
|
|
318
|
+
...(clockSkewMs === undefined ? {} : { clockSkewMs }) });
|
|
319
|
+
// The host's clock, not the credential: named once when the refusals for it begin, and in `agl push status` throughout.
|
|
320
|
+
if (clockSkewMs !== undefined && previous?.clockSkewMs === undefined) {
|
|
321
|
+
this.options.fault(new Error(`${platformNames[targetArg.platform]} refused (${attempt.vendorReason ?? 'no code'}) while the push service's `
|
|
322
|
+
+ `clock and the host's were ${pushClockSkewText(clockSkewMs)}: the credential is kept and the send is tried again. `
|
|
323
|
+
+ 'Set the host\'s clock right (NTP).'));
|
|
324
|
+
}
|
|
325
|
+
if (result.outcome === 'credential_refused') {
|
|
326
|
+
// The platform stops: its queues go, and the settings keep the refusal until the owner sets the credential again.
|
|
327
|
+
for (const [deviceId, queue] of [...this.queues]) {
|
|
328
|
+
const first = queue.entries.values().next().value;
|
|
329
|
+
if (first?.target.platform === targetArg.platform) this.dropQueue(deviceId);
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
await this.options.settings.refuse(targetArg.platform, held.generation, attempt.vendorReason);
|
|
333
|
+
} catch (errorArg) {
|
|
334
|
+
this.options.fault(errorArg);
|
|
335
|
+
}
|
|
336
|
+
this.dropSender(targetArg.platform);
|
|
337
|
+
}
|
|
338
|
+
return attempt;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Sends the device's queue in order until it is empty, or a failure that passes arms the retry. */
|
|
342
|
+
private async drain(deviceIdArg: string): Promise<void> {
|
|
343
|
+
const queue = this.queues.get(deviceIdArg);
|
|
344
|
+
if (!queue || queue.running || queue.timer !== undefined) return;
|
|
345
|
+
queue.running = true;
|
|
346
|
+
try {
|
|
347
|
+
while (this.stopping === undefined && this.queues.get(deviceIdArg) === queue) {
|
|
348
|
+
const now = this.clock.now();
|
|
349
|
+
for (const [key, entry] of queue.entries) {
|
|
350
|
+
if (now - entry.enqueuedAt >= pushDeliveryTimings.maximumAgeMs) queue.entries.delete(key);
|
|
351
|
+
}
|
|
352
|
+
const next = queue.entries.entries().next();
|
|
353
|
+
if (next.done) break;
|
|
354
|
+
const [key, entry] = next.value;
|
|
355
|
+
const attempt = await this.attempt(entry.target, entry.payload, entry.enqueuedAt + pushDeliveryTimings.maximumAgeMs);
|
|
356
|
+
if (this.stopping !== undefined || this.queues.get(deviceIdArg) !== queue) break;
|
|
357
|
+
if (retryable(attempt.outcome)) {
|
|
358
|
+
queue.failures += 1;
|
|
359
|
+
const backoff = Math.min(pushDeliveryTimings.initialBackoffMs * 2 ** Math.min(queue.failures - 1, 30), pushDeliveryTimings.maximumBackoffMs);
|
|
360
|
+
// A service that asked for a longer wait (Retry-After) gets it; what is an hour old by then is dropped.
|
|
361
|
+
const delay = Math.max(backoff, attempt.retryAfterMs ?? 0);
|
|
362
|
+
queue.timer = this.clock.setTimeout(() => {
|
|
363
|
+
queue.timer = undefined;
|
|
364
|
+
this.track(this.drain(deviceIdArg));
|
|
365
|
+
}, delay);
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
// Gone (delivered, refused for good, the credential or the registration gone): a newer one under the key stays.
|
|
369
|
+
if (queue.entries.get(key) === entry) queue.entries.delete(key);
|
|
370
|
+
if (attempt.outcome === 'unavailable') queue.entries.clear();
|
|
371
|
+
else queue.failures = 0;
|
|
372
|
+
}
|
|
373
|
+
} finally {
|
|
374
|
+
queue.running = false;
|
|
375
|
+
if (queue.entries.size === 0 && queue.timer === undefined && this.queues.get(deviceIdArg) === queue) this.queues.delete(deviceIdArg);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The push trigger's clean-stop handover (AGL-1639): the Inbox items it announced that still waited when the controller
|
|
5
|
+
* stopped cleanly, and the pairs the handover it started from named that it had not met yet, by id and `since`, so the
|
|
6
|
+
* next start does not alert again for the same waits. One document per controller in `agl_controller_push_handover`,
|
|
7
|
+
* `{ id, announced }`, its top level fixed for good. `ControllerPush.stop` writes both in it, whole, once (an announced
|
|
8
|
+
* pair wins over a handed-over one with the same id); nothing is written while the controller runs. The next start reads
|
|
9
|
+
* it once and deletes it, so a controller killed later leaves none and its next start announces what waits once more
|
|
10
|
+
* under the same keys. An older controller has no model for the collection and never reads it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** One announced item: its Inbox id and the `since` it was announced with. */
|
|
14
|
+
export interface IPushHandoverEntry {
|
|
15
|
+
id: string;
|
|
16
|
+
since: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface IControllerPushHandoverDocument {
|
|
20
|
+
/** `controller:<port>`. */
|
|
21
|
+
id: string;
|
|
22
|
+
/** Newest `since` first. */
|
|
23
|
+
announced: IPushHandoverEntry[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* At most `entries` items are handed over (the Inbox lists at most 200), the newest by `since` when there are more; an
|
|
28
|
+
* item whose id is longer than `idBytes` UTF-8 bytes is left out and announced again. A document is read with up to
|
|
29
|
+
* `readEntries` entries, so one a later release wrote with more is still read and deleted.
|
|
30
|
+
*/
|
|
31
|
+
export const pushHandoverLimits = { entries: 200, idBytes: 1024, readEntries: 1000, documentBytes: 2 * 1024 * 1024 } as const;
|
|
32
|
+
|
|
33
|
+
const isPlainObject = (valueArg: unknown): valueArg is Record<string, unknown> => (
|
|
34
|
+
!!valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg)
|
|
35
|
+
&& (Object.getPrototypeOf(valueArg) === Object.prototype || Object.getPrototypeOf(valueArg) === null)
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
const assertDocument: (valueArg: unknown) => asserts valueArg is IControllerPushHandoverDocument = (valueArg) => {
|
|
39
|
+
const value = valueArg as Partial<IControllerPushHandoverDocument> | null;
|
|
40
|
+
let size = Number.POSITIVE_INFINITY;
|
|
41
|
+
try { size = Buffer.byteLength(JSON.stringify(value?.announced), 'utf8'); } catch { /* refused below */ }
|
|
42
|
+
if (!isPlainObject(value)
|
|
43
|
+
|| Object.keys(value).length !== 2
|
|
44
|
+
|| typeof value.id !== 'string' || !/^controller:[1-9][0-9]{0,4}$/u.test(value.id)
|
|
45
|
+
|| !Array.isArray(value.announced) || value.announced.length > pushHandoverLimits.readEntries
|
|
46
|
+
|| !value.announced.every(isPlainObject)
|
|
47
|
+
|| size > pushHandoverLimits.documentBytes) {
|
|
48
|
+
throw new Error('Invalid push handover record.');
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
@plugins.nosqldb.managed({ collectionName: 'agl_controller_push_handover' })
|
|
53
|
+
@plugins.nosqldb.exactPersistence({ assertDocument })
|
|
54
|
+
export class ControllerPushHandoverModel extends plugins.nosqldb.SmartDataDbDoc<ControllerPushHandoverModel, IControllerPushHandoverDocument> {
|
|
55
|
+
declare static exact: plugins.nosqldb.TExact<ControllerPushHandoverModel>;
|
|
56
|
+
@plugins.nosqldb.unI() public id!: string;
|
|
57
|
+
@plugins.nosqldb.svDb() public announced!: IPushHandoverEntry[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const isEntry = (valueArg: unknown): valueArg is IPushHandoverEntry => (
|
|
61
|
+
isPlainObject(valueArg) && typeof valueArg.id === 'string' && valueArg.id !== ''
|
|
62
|
+
&& Buffer.byteLength(valueArg.id, 'utf8') <= pushHandoverLimits.idBytes
|
|
63
|
+
&& typeof valueArg.since === 'number' && Number.isFinite(valueArg.since)
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
/** What a stop hands over of `announcedArg` (item id to `since`): at most 200, newest `since` first, then by id. */
|
|
67
|
+
export const pushHandoverEntries = (announcedArg: ReadonlyMap<string, number>): IPushHandoverEntry[] => (
|
|
68
|
+
[...announcedArg].map(([id, since]) => ({ id, since })).filter(isEntry)
|
|
69
|
+
.sort((leftArg, rightArg) => rightArg.since - leftArg.since || (leftArg.id < rightArg.id ? -1 : leftArg.id > rightArg.id ? 1 : 0))
|
|
70
|
+
.slice(0, pushHandoverLimits.entries)
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Reads the controller's handover and deletes it: what the last clean stop announced, item id to `since`, or none when
|
|
75
|
+
* no clean stop left one. Throws when the document does not read or could not be deleted; it is then not used.
|
|
76
|
+
*/
|
|
77
|
+
export const takePushHandover = async (controllerIdArg: string): Promise<ReadonlyMap<string, number> | undefined> => {
|
|
78
|
+
const current = await ControllerPushHandoverModel.exact.findStoredOne({ id: controllerIdArg });
|
|
79
|
+
if (!current) return undefined;
|
|
80
|
+
const { announced } = ControllerPushHandoverModel.exact.toPersisted(current);
|
|
81
|
+
const deleted = await ControllerPushHandoverModel.exact.delete({ current });
|
|
82
|
+
if (deleted.status !== 'deleted') throw new Error('The push handover changed while it was read and was not used.');
|
|
83
|
+
// An entry a later release wrote in another shape is not one of these, and is announced again.
|
|
84
|
+
return new Map(announced.filter(isEntry).map((entryArg) => [entryArg.id, entryArg.since]));
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** Writes the controller's handover whole: what `announcedArg` names (`pushHandoverEntries`), replacing any there. */
|
|
88
|
+
export const keepPushHandover = async (controllerIdArg: string, announcedArg: ReadonlyMap<string, number>): Promise<void> => {
|
|
89
|
+
const announced = pushHandoverEntries(announcedArg);
|
|
90
|
+
const current = await ControllerPushHandoverModel.exact.findStoredOne({ id: controllerIdArg });
|
|
91
|
+
if (!current) {
|
|
92
|
+
const inserted = await ControllerPushHandoverModel.exact.insert({ id: controllerIdArg, announced });
|
|
93
|
+
if (inserted.status !== 'inserted') throw new Error('The push handover changed concurrently and was not stored.');
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const result = await ControllerPushHandoverModel.exact.transition({ current, change: (modelArg) => { modelArg.announced = announced; } });
|
|
97
|
+
if (result.status !== 'transitioned') throw new Error('The push handover changed concurrently and was not stored.');
|
|
98
|
+
};
|