agl 43.7.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 +17 -0
- package/dist_serve/bundle.js +786 -786
- 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.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 +30 -3
- package/dist_ts/classes.controller.js +250 -9
- 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.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.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 +9 -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 +3 -1
- package/dist_ts/plugins.js +4 -2
- 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/workercallers.d.ts +43 -3
- package/package.json +1 -1
- package/readme.md +64 -11
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/aglapi/interfaces.ts +8 -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 +273 -7
- 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.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.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 +26 -3
- package/ts/interfaces.lifecycle.ts +7 -1
- package/ts/interfaces.push.ts +78 -0
- package/ts/plugins.ts +3 -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/workercallers.ts +34 -2
- package/ts_web/00_commitinfo_data.ts +1 -1
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
maximumDevices,
|
|
9
9
|
maximumPendingDevicePairings,
|
|
10
10
|
type IReq_DevicePair,
|
|
11
|
+
type TDevicePushPlatform,
|
|
11
12
|
type TDeviceRefusalCode,
|
|
12
13
|
} from '../ts_interfaces/devices.js';
|
|
13
14
|
import type {
|
|
@@ -25,6 +26,18 @@ import {
|
|
|
25
26
|
importDevicePublicKey,
|
|
26
27
|
verifyDeviceSignature,
|
|
27
28
|
} from './functions.deviceproof.js';
|
|
29
|
+
import {
|
|
30
|
+
countPushRegistrations,
|
|
31
|
+
deletePushRegistration,
|
|
32
|
+
deletePushRegistrationHolding,
|
|
33
|
+
readPushRegistration,
|
|
34
|
+
readPushTargets,
|
|
35
|
+
sweepPushRegistrations,
|
|
36
|
+
writePushRegistration,
|
|
37
|
+
type IControllerPushTarget,
|
|
38
|
+
type TControllerPushRegistrationRequest,
|
|
39
|
+
type TControllerPushRegistrationState,
|
|
40
|
+
} from './classes.pushregistrations.js';
|
|
28
41
|
|
|
29
42
|
/** One paired device of a controller. Revoking it deletes the record; its history is the audit log's. */
|
|
30
43
|
export interface IControllerDeviceDocument {
|
|
@@ -93,9 +106,9 @@ export class ControllerDeviceModel extends plugins.nosqldb.SmartDataDbDoc<Contro
|
|
|
93
106
|
}
|
|
94
107
|
|
|
95
108
|
/**
|
|
96
|
-
* Deletes every device of a controller whose public origin moves: each signed the old
|
|
97
|
-
* authenticate at the new one. Answers how many it deleted. `optionsArg.session` runs it inside
|
|
98
|
-
* transaction (`moveRuntimeConfig` deletes the devices with the configuration change, or not at all).
|
|
109
|
+
* Deletes every device of a controller whose public origin moves, with its push registration: each signed the old
|
|
110
|
+
* origin and could never authenticate at the new one. Answers how many it deleted. `optionsArg.session` runs it inside
|
|
111
|
+
* the caller's transaction (`moveRuntimeConfig` deletes the devices with the configuration change, or not at all).
|
|
99
112
|
*/
|
|
100
113
|
export const deleteControllerDevices = async (
|
|
101
114
|
controllerIdArg: string,
|
|
@@ -103,8 +116,9 @@ export const deleteControllerDevices = async (
|
|
|
103
116
|
): Promise<number> => {
|
|
104
117
|
let deleted = 0;
|
|
105
118
|
for (const current of await ControllerDeviceModel.exact.findStored({ filter: { controllerId: controllerIdArg }, ...optionsArg })) {
|
|
106
|
-
const result = await ControllerDeviceModel.exact.delete({ current }, optionsArg);
|
|
107
119
|
const { id } = ControllerDeviceModel.exact.toPersisted(current);
|
|
120
|
+
await deletePushRegistration(id, optionsArg);
|
|
121
|
+
const result = await ControllerDeviceModel.exact.delete({ current }, optionsArg);
|
|
108
122
|
if (result.status !== 'deleted' && await ControllerDeviceModel.exact.findStoredOne({ id }, optionsArg)) {
|
|
109
123
|
throw new Error('A paired device could not be removed.');
|
|
110
124
|
}
|
|
@@ -171,13 +185,19 @@ export class ControllerDevices {
|
|
|
171
185
|
|
|
172
186
|
private constructor(private readonly options: IControllerDevicesOptions) {}
|
|
173
187
|
|
|
174
|
-
/**
|
|
188
|
+
/**
|
|
189
|
+
* Reads the devices of the controller, and deletes every push registration whose device is gone (paired with no
|
|
190
|
+
* controller of the store).
|
|
191
|
+
*/
|
|
175
192
|
public static async open(optionsArg: IControllerDevicesOptions): Promise<ControllerDevices> {
|
|
176
193
|
const devices = new ControllerDevices(optionsArg);
|
|
177
194
|
for (const stored of await ControllerDeviceModel.exact.findStored({ filter: { controllerId: optionsArg.controllerId } })) {
|
|
178
195
|
const record = ControllerDeviceModel.exact.toPersisted(stored);
|
|
179
196
|
devices.records.set(record.id, record);
|
|
180
197
|
}
|
|
198
|
+
await sweepPushRegistrations(async (deviceIdArg) => (
|
|
199
|
+
devices.records.has(deviceIdArg) || await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg }) !== null
|
|
200
|
+
));
|
|
181
201
|
return devices;
|
|
182
202
|
}
|
|
183
203
|
|
|
@@ -444,18 +464,30 @@ export class ControllerDevices {
|
|
|
444
464
|
}
|
|
445
465
|
|
|
446
466
|
/**
|
|
447
|
-
* Revokes a device: its record
|
|
448
|
-
* connections, which the caller closes, or `revoked: false` for
|
|
467
|
+
* Revokes a device: its record and its push registration are deleted in one transaction, and every connection
|
|
468
|
+
* authenticated as it loses that at once. Answers the connections, which the caller closes, or `revoked: false` for
|
|
469
|
+
* a device that is gone already.
|
|
449
470
|
*/
|
|
450
471
|
public revoke(deviceIdArg: string): Promise<{ revoked: boolean; peers: IControllerDevicePeer[] }> {
|
|
451
472
|
return this.mutate(async () => {
|
|
452
473
|
if (!this.records.has(deviceIdArg)) return { revoked: false, peers: [] };
|
|
453
|
-
const
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
474
|
+
const session = ControllerDeviceModel.collection.smartdataDb.createSession();
|
|
475
|
+
try {
|
|
476
|
+
await session.withTransaction(async (transactionArg) => {
|
|
477
|
+
await deletePushRegistration(deviceIdArg, { session: transactionArg });
|
|
478
|
+
const current = await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg }, { session: transactionArg });
|
|
479
|
+
if (current === null) return;
|
|
480
|
+
const result = await ControllerDeviceModel.exact.delete({ current }, { session: transactionArg });
|
|
481
|
+
if (result.status !== 'deleted') throw new Error('The device record changed concurrently and was not revoked.');
|
|
482
|
+
});
|
|
483
|
+
} catch (errorArg) {
|
|
484
|
+
if (plugins.nosqldb.SmartdataSession.getCommitOutcome(errorArg) === 'not_committed') throw errorArg;
|
|
485
|
+
// The commit may have landed: the device is revoked only if the store holds neither of them any more.
|
|
486
|
+
if (await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg }) !== null || await readPushRegistration(deviceIdArg)) {
|
|
487
|
+
throw new Error('The device revocation has an ambiguous outcome.', { cause: errorArg });
|
|
458
488
|
}
|
|
489
|
+
} finally {
|
|
490
|
+
await session.close();
|
|
459
491
|
}
|
|
460
492
|
this.records.delete(deviceIdArg);
|
|
461
493
|
const peers = [...this.live.get(deviceIdArg) ?? []];
|
|
@@ -466,6 +498,56 @@ export class ControllerDevices {
|
|
|
466
498
|
});
|
|
467
499
|
}
|
|
468
500
|
|
|
501
|
+
/** The push registration of a paired device, without its token; none while it holds none. */
|
|
502
|
+
public async pushRegistration(deviceIdArg: string): Promise<TControllerPushRegistrationState | undefined> {
|
|
503
|
+
if (!this.records.has(deviceIdArg)) return undefined;
|
|
504
|
+
return readPushRegistration(deviceIdArg);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Registers a paired device for notifications, replacing its registration: it runs in the order of the device
|
|
509
|
+
* writes, after a revocation that came first, so a revoked device is never registered.
|
|
510
|
+
*/
|
|
511
|
+
public registerPush(deviceIdArg: string, requestArg: TControllerPushRegistrationRequest): Promise<TControllerPushRegistrationState> {
|
|
512
|
+
if (this.closed) return Promise.reject(deviceRefusal('controller_unavailable', 'The controller is stopping.'));
|
|
513
|
+
return this.mutate(async () => {
|
|
514
|
+
if (!this.records.has(deviceIdArg)) throw deviceRefusal('device_unknown', 'No such device is paired with this controller.');
|
|
515
|
+
return writePushRegistration(deviceIdArg, requestArg, this.now());
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* The registrations of the paired devices, with their tokens and the devices' names, or of the one device
|
|
521
|
+
* `deviceIdArg` names: what the delivery sends to.
|
|
522
|
+
*/
|
|
523
|
+
public async pushTargets(deviceIdArg?: string): Promise<Array<IControllerPushTarget & { name: string }>> {
|
|
524
|
+
const ids = deviceIdArg === undefined ? [...this.records.keys()] : this.records.has(deviceIdArg) ? [deviceIdArg] : [];
|
|
525
|
+
return (await readPushTargets(ids)).map((targetArg) => ({ ...targetArg, name: this.records.get(targetArg.deviceId)?.name ?? '' }));
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Deletes a paired device's registration if it still holds `tokenArg`, in the order of the device's writes: its push
|
|
530
|
+
* service called that token gone. Answers whether it deleted one.
|
|
531
|
+
*/
|
|
532
|
+
public deletePushHolding(deviceIdArg: string, tokenArg: string): Promise<boolean> {
|
|
533
|
+
if (this.closed) return Promise.resolve(false);
|
|
534
|
+
return this.mutate(async () => this.records.has(deviceIdArg) && deletePushRegistrationHolding(deviceIdArg, tokenArg));
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** How many paired devices hold a registration, per platform. */
|
|
538
|
+
public pushRegistrationCounts(): Promise<Record<TDevicePushPlatform, number>> {
|
|
539
|
+
return countPushRegistrations(new Set(this.records.keys()));
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/** Ends a paired device's registration; answers whether it held one. */
|
|
543
|
+
public unregisterPush(deviceIdArg: string): Promise<boolean> {
|
|
544
|
+
if (this.closed) return Promise.reject(deviceRefusal('controller_unavailable', 'The controller is stopping.'));
|
|
545
|
+
return this.mutate(async () => {
|
|
546
|
+
if (!this.records.has(deviceIdArg)) throw deviceRefusal('device_unknown', 'No such device is paired with this controller.');
|
|
547
|
+
return deletePushRegistration(deviceIdArg);
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
|
|
469
551
|
/** Voids every pairing code and refuses everything from now on; waits for the writes already taken. */
|
|
470
552
|
public async close(): Promise<void> {
|
|
471
553
|
this.closed = true;
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
import {
|
|
2
|
+
devicePushReportSentence,
|
|
3
|
+
devicePushSentences,
|
|
4
|
+
devicePushSummarySentence,
|
|
5
|
+
type IDevicePushInboxData,
|
|
6
|
+
type IDevicePushReportData,
|
|
7
|
+
type TDevicePushData,
|
|
8
|
+
type TDevicePushPlatform,
|
|
9
|
+
} from '../ts_interfaces/devices.js';
|
|
10
|
+
import type { IDirectReport } from '../ts_interfaces/directreports.js';
|
|
11
|
+
import {
|
|
12
|
+
controllerInboxLimits,
|
|
13
|
+
type IControllerInboxSnapshot,
|
|
14
|
+
type TControllerInboxDelta,
|
|
15
|
+
type TControllerInboxItem,
|
|
16
|
+
type TControllerInboxWhere,
|
|
17
|
+
} from '../ts_interfaces/index.js';
|
|
18
|
+
import { apnsRequest } from './classes.apnsclient.js';
|
|
19
|
+
import { fcmMessage } from './classes.fcmclient.js';
|
|
20
|
+
import { inboxTitle } from './classes.inbox.js';
|
|
21
|
+
import type { IPushDeliveryTarget } from './classes.pushdelivery.js';
|
|
22
|
+
import { pushKeySubjects, pushNotificationKey, type IControllerPushTarget } from './classes.pushregistrations.js';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The Inbox's push trigger (AGL-1639): it turns the deltas the Inbox publishes, and the direct reports' new results,
|
|
26
|
+
* into notifications for the registrations of this controller's paired devices, and hands them to the delivery, which
|
|
27
|
+
* returns at once. It never reads the Inbox's sources: an item that came is one the Inbox published, by id, and an item
|
|
28
|
+
* that left is one it removed. What it knows of the Inbox is the ids it saw in this process; only a clean stop hands
|
|
29
|
+
* over what it announced, and what the handover it started from named that it has not met yet
|
|
30
|
+
* (`IControllerPushHandover`): the next start does not announce again an item that still waits with the same id and
|
|
31
|
+
* `since`. Every other item that waits after a start goes out once more under its key, replacing what a device shows:
|
|
32
|
+
* after a kill, a failed handover, or an item stamped anew.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** More new items than this in one pass are announced by one summary instead of one notification each. */
|
|
36
|
+
export const pushSummaryThreshold = 4;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A `clear`'s keys, space-separated, stay within this many bytes, so the payload stays under Apple's 4096 bytes and
|
|
40
|
+
* FCM's 4096 bytes of data (about 80 keys of 43 characters).
|
|
41
|
+
*/
|
|
42
|
+
export const pushClearKeysMaximumBytes = 3584;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Where a clean stop leaves what the trigger hands over, item id to `since`, for the next start (`takePushHandover` and
|
|
46
|
+
* `keepPushHandover` in `ts/classes.pushhandover.ts`). `take` answers what the last clean stop left and removes it, none
|
|
47
|
+
* when no clean stop left any; `keep` replaces it.
|
|
48
|
+
*/
|
|
49
|
+
export interface IControllerPushHandover {
|
|
50
|
+
take(): Promise<ReadonlyMap<string, number> | undefined>;
|
|
51
|
+
keep(announcedArg: ReadonlyMap<string, number>): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What the trigger asks of the delivery (`ControllerPushDelivery`). */
|
|
55
|
+
export interface IControllerPushDelivery {
|
|
56
|
+
available(platformArg: TDevicePushPlatform): boolean;
|
|
57
|
+
send(targetArg: IPushDeliveryTarget, payloadArg: TDevicePushData): void;
|
|
58
|
+
withdraw(deviceIdArg: string, keysArg: readonly string[]): void;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface IControllerPushOptions {
|
|
62
|
+
/** The registrations of this controller's paired devices, never another controller's (`ControllerDevices.pushTargets`). */
|
|
63
|
+
targets(): Promise<readonly IControllerPushTarget[]>;
|
|
64
|
+
delivery: IControllerPushDelivery;
|
|
65
|
+
/** Whether notifications carry previews (`ControllerPushSettings.previews`). */
|
|
66
|
+
previews(): boolean;
|
|
67
|
+
/** Read once as the trigger starts, before any change is sent, and written once by `stop`. */
|
|
68
|
+
handover: IControllerPushHandover;
|
|
69
|
+
/** A failure no caller sees: a registration read that failed, a handover that was not there or not kept, a fault of the trigger. */
|
|
70
|
+
fault(errorArg: unknown): void;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** What one Inbox pass changed, as the trigger sends it. */
|
|
74
|
+
interface IInboxChange {
|
|
75
|
+
added: TControllerInboxItem[];
|
|
76
|
+
removed: string[];
|
|
77
|
+
/** The Inbox's count after the pass: the badge. */
|
|
78
|
+
total: number;
|
|
79
|
+
previews: boolean;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Where an item lives, as a previewed notification's title: the session, the driver or the ticket. */
|
|
83
|
+
const pushPlace = (whereArg: TControllerInboxWhere): string => {
|
|
84
|
+
switch (whereArg.kind) {
|
|
85
|
+
case 'conversation':
|
|
86
|
+
case 'native':
|
|
87
|
+
return whereArg.name;
|
|
88
|
+
case 'child':
|
|
89
|
+
return `${whereArg.childName} in ${whereArg.name}`;
|
|
90
|
+
case 'driver':
|
|
91
|
+
return 'Driver';
|
|
92
|
+
case 'ticket':
|
|
93
|
+
return `${whereArg.ticketKey} · ${whereArg.ticketTitle}`;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** Whether a payload fits both push services' limits, as their senders build the request. */
|
|
98
|
+
const pushPayloadFits = (payloadArg: TDevicePushData): boolean => (
|
|
99
|
+
apnsRequest('com.modelprofile.harness', payloadArg, 0) !== undefined && fcmMessage('token', payloadArg, 0, 0) !== undefined
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
/** At most `charactersArg` characters of one line, its end marked when it was cut. */
|
|
103
|
+
const cut = (textArg: string, charactersArg: number): string => {
|
|
104
|
+
const characters = [...textArg];
|
|
105
|
+
return characters.length <= charactersArg ? textArg : `${characters.slice(0, Math.max(0, charactersArg - 1)).join('').trimEnd()}…`;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A previewed notification within the push services' limits: its title and body cut shorter until it fits (Apple
|
|
110
|
+
* repeats both in `aps`), or, for an item whose id alone leaves no room, `plainArg`.
|
|
111
|
+
*/
|
|
112
|
+
const fitted = <TPayload extends IDevicePushInboxData | IDevicePushReportData>(
|
|
113
|
+
plainArg: TPayload,
|
|
114
|
+
previewArg: (charactersArg: number) => TPayload,
|
|
115
|
+
): TPayload => {
|
|
116
|
+
for (let characters: number = controllerInboxLimits.titleChars; characters > 0; characters = Math.floor(characters / 2)) {
|
|
117
|
+
const payload = previewArg(characters);
|
|
118
|
+
if (pushPayloadFits(payload)) return payload;
|
|
119
|
+
}
|
|
120
|
+
return plainArg;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/** The device a registration names, as the delivery sends to it: its token never leaves the host but to its push service. */
|
|
124
|
+
const deliveryTarget = (targetArg: IControllerPushTarget): IPushDeliveryTarget => ({
|
|
125
|
+
deviceId: targetArg.deviceId,
|
|
126
|
+
platform: targetArg.platform,
|
|
127
|
+
...(targetArg.environment === undefined ? {} : { environment: targetArg.environment }),
|
|
128
|
+
token: targetArg.token,
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const messageOf = (errorArg: unknown): string => (errorArg instanceof Error ? errorArg.message : String(errorArg));
|
|
132
|
+
|
|
133
|
+
/** Space-separated keys in groups of at most `pushClearKeysMaximumBytes`. */
|
|
134
|
+
export const pushClearChunks = (keysArg: readonly string[]): string[] => {
|
|
135
|
+
const chunks: string[] = [];
|
|
136
|
+
let current = '';
|
|
137
|
+
for (const key of keysArg) {
|
|
138
|
+
const next = current === '' ? key : `${current} ${key}`;
|
|
139
|
+
if (current !== '' && Buffer.byteLength(next, 'utf8') > pushClearKeysMaximumBytes) {
|
|
140
|
+
chunks.push(current);
|
|
141
|
+
current = key;
|
|
142
|
+
} else {
|
|
143
|
+
current = next;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (current !== '') chunks.push(current);
|
|
147
|
+
return chunks;
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
export class ControllerPush {
|
|
151
|
+
/** The ids of the items the Inbox published last, as this trigger saw them. */
|
|
152
|
+
private known = new Set<string>();
|
|
153
|
+
private epoch?: string;
|
|
154
|
+
/**
|
|
155
|
+
* The items handed to the delivery for at least one registration, alone or under a summary, that still wait: id to the
|
|
156
|
+
* `since` they were announced with. What `stop` hands over.
|
|
157
|
+
*/
|
|
158
|
+
private readonly announced = new Map<string, number>();
|
|
159
|
+
/**
|
|
160
|
+
* What the handover this process started from named that it has not met yet: handed over again by `stop`, so a
|
|
161
|
+
* clean stop before every item came back loses none. A pair goes once its id comes, with the same `since` or not.
|
|
162
|
+
*/
|
|
163
|
+
private handedOver = new Map<string, number>();
|
|
164
|
+
/** Changes are sent one after the other, in the order the Inbox published them, after the handover was read. */
|
|
165
|
+
private tail: Promise<void>;
|
|
166
|
+
private stopped = false;
|
|
167
|
+
private stopping?: Promise<void>;
|
|
168
|
+
|
|
169
|
+
constructor(private readonly options: IControllerPushOptions) {
|
|
170
|
+
this.tail = this.receiveHandover();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Whether a notification could go out now: a registration of this controller's devices on a platform the host holds
|
|
175
|
+
* a usable credential for. While none could, the Inbox runs as it runs without push: it passes only for a connected
|
|
176
|
+
* browser or device.
|
|
177
|
+
*/
|
|
178
|
+
public async receives(): Promise<boolean> {
|
|
179
|
+
if (this.stopped) return false;
|
|
180
|
+
const { delivery } = this.options;
|
|
181
|
+
if (!delivery.available('apns') && !delivery.available('fcm')) return false;
|
|
182
|
+
try {
|
|
183
|
+
return (await this.options.targets()).some((targetArg) => delivery.available(targetArg.platform));
|
|
184
|
+
} catch (errorArg) {
|
|
185
|
+
this.options.fault(errorArg);
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* One delta as the Inbox published it, while the Inbox publishes it: an item that came is a notification (more than
|
|
192
|
+
* `pushSummaryThreshold` in one pass, one summary), an item that left a `clear` and the withdrawal of its notification
|
|
193
|
+
* still queued, a changed item nothing. `currentArg` answers what the Inbox published, read only for a `reset` or
|
|
194
|
+
* another epoch. Returns at once; it never throws into the Inbox's pass.
|
|
195
|
+
*/
|
|
196
|
+
public inboxChanged(deltaArg: TControllerInboxDelta, currentArg: () => IControllerInboxSnapshot | undefined): void {
|
|
197
|
+
if (this.stopped) return;
|
|
198
|
+
try {
|
|
199
|
+
const change = this.change(deltaArg, currentArg);
|
|
200
|
+
if (!change || (change.added.length === 0 && change.removed.length === 0)) return;
|
|
201
|
+
this.tail = this.tail.then(async () => {
|
|
202
|
+
// In the order the Inbox published: an item that left is no longer announced, and one the last clean stop had
|
|
203
|
+
// announced that waits as it did then is not announced again.
|
|
204
|
+
for (const id of change.removed) this.announced.delete(id);
|
|
205
|
+
const added = change.added.filter((itemArg) => !this.metAgain(itemArg));
|
|
206
|
+
if (this.stopped || (added.length === 0 && change.removed.length === 0)) return;
|
|
207
|
+
const targets = await this.availableTargets();
|
|
208
|
+
if (this.stopped || targets.length === 0) return;
|
|
209
|
+
this.sendInboxChange({ ...change, added }, targets);
|
|
210
|
+
for (const item of added) this.announced.set(item.id, item.since);
|
|
211
|
+
}).catch((errorArg: unknown) => { this.options.fault(errorArg); });
|
|
212
|
+
} catch (errorArg) {
|
|
213
|
+
this.options.fault(errorArg);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** A direct report's new `result:` line: a notification for the devices that asked for results, with no badge. */
|
|
218
|
+
public reportResult(reportArg: IDirectReport): void {
|
|
219
|
+
if (this.stopped || reportArg.latestResult === undefined) return;
|
|
220
|
+
const { name } = reportArg;
|
|
221
|
+
const text = reportArg.latestResult.text;
|
|
222
|
+
const previews = this.options.previews();
|
|
223
|
+
this.enqueue(async (targetsArg) => {
|
|
224
|
+
for (const target of targetsArg) {
|
|
225
|
+
if (!target.reports) continue;
|
|
226
|
+
const key = pushNotificationKey(target.salt, pushKeySubjects.report(name));
|
|
227
|
+
const plain: IDevicePushReportData = { type: 'report', key, body: devicePushReportSentence };
|
|
228
|
+
this.options.delivery.send(deliveryTarget(target), previews
|
|
229
|
+
? fitted(plain, (charactersArg) => ({ ...plain, title: cut(inboxTitle(name), charactersArg), body: cut(inboxTitle(text), charactersArg) }))
|
|
230
|
+
: plain);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Sends nothing more, waits for the change being sent, and hands over, once, what was announced and still waits and
|
|
237
|
+
* what the handover this process started from named that it has not met yet (an announced pair wins). Never rejects: a
|
|
238
|
+
* handover that was not kept is a fault, and the next start announces what waits once more.
|
|
239
|
+
*/
|
|
240
|
+
public stop(): Promise<void> {
|
|
241
|
+
this.stopped = true;
|
|
242
|
+
this.stopping ??= (async () => {
|
|
243
|
+
await this.tail;
|
|
244
|
+
try {
|
|
245
|
+
await this.options.handover.keep(new Map([...this.handedOver, ...this.announced]));
|
|
246
|
+
} catch (errorArg) {
|
|
247
|
+
this.options.fault(new Error(`The push handover was not kept, so the next start announces what still waits once more: ${messageOf(errorArg)}`));
|
|
248
|
+
}
|
|
249
|
+
})();
|
|
250
|
+
return this.stopping;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Reads what the last clean stop handed over; without it every item that waits is announced, as after a kill. A missing
|
|
255
|
+
* handover is recorded only while a notification could go out (`receives`): on a host that cannot send it changes
|
|
256
|
+
* nothing. One that does not read is always recorded.
|
|
257
|
+
*/
|
|
258
|
+
private async receiveHandover(): Promise<void> {
|
|
259
|
+
try {
|
|
260
|
+
const handover = await this.options.handover.take();
|
|
261
|
+
if (handover === undefined) {
|
|
262
|
+
if (await this.receives()) {
|
|
263
|
+
this.options.fault(new Error('No push handover from a clean stop: the items that still wait are announced once more.'));
|
|
264
|
+
}
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
this.handedOver = new Map(handover);
|
|
268
|
+
} catch (errorArg) {
|
|
269
|
+
this.options.fault(new Error(`The push handover could not be read, so the items that still wait are announced once more: ${messageOf(errorArg)}`));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Whether the handover named the item with the same id and `since`: it is then not announced again, and is announced
|
|
275
|
+
* in this process. An item stamped anew (another `since`) is announced as a new one; either way the pair has been met
|
|
276
|
+
* and is no longer handed over.
|
|
277
|
+
*/
|
|
278
|
+
private metAgain(itemArg: TControllerInboxItem): boolean {
|
|
279
|
+
const since = this.handedOver.get(itemArg.id);
|
|
280
|
+
if (since === undefined) return false;
|
|
281
|
+
this.handedOver.delete(itemArg.id);
|
|
282
|
+
if (since !== itemArg.since) return false;
|
|
283
|
+
this.announced.set(itemArg.id, itemArg.since);
|
|
284
|
+
return true;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** The registrations of this controller's devices on a platform the host can send on now. */
|
|
288
|
+
private async availableTargets(): Promise<readonly IControllerPushTarget[]> {
|
|
289
|
+
return (await this.options.targets()).filter((targetArg) => this.options.delivery.available(targetArg.platform));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** The items that came and left with the delta, against the ids this trigger saw last. */
|
|
293
|
+
private change(deltaArg: TControllerInboxDelta, currentArg: () => IControllerInboxSnapshot | undefined): IInboxChange | undefined {
|
|
294
|
+
const previews = this.options.previews();
|
|
295
|
+
if ('reset' in deltaArg || deltaArg.epoch !== this.epoch) {
|
|
296
|
+
const snapshot = currentArg();
|
|
297
|
+
if (!snapshot) return undefined;
|
|
298
|
+
const ids = new Set(snapshot.items.map((itemArg) => itemArg.id));
|
|
299
|
+
const added = snapshot.items.filter((itemArg) => !this.known.has(itemArg.id));
|
|
300
|
+
const removed = [...this.known].filter((idArg) => !ids.has(idArg));
|
|
301
|
+
this.known = ids;
|
|
302
|
+
this.epoch = snapshot.epoch;
|
|
303
|
+
return { added, removed, total: snapshot.total, previews };
|
|
304
|
+
}
|
|
305
|
+
const added = deltaArg.upserts.filter((itemArg) => !this.known.has(itemArg.id));
|
|
306
|
+
const removed = deltaArg.removed.filter((idArg) => this.known.has(idArg));
|
|
307
|
+
for (const item of added) this.known.add(item.id);
|
|
308
|
+
for (const id of removed) this.known.delete(id);
|
|
309
|
+
return { added, removed, total: deltaArg.total, previews };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Reads the registrations once for the work, after the work queued before it; a failure is reported, never thrown. */
|
|
313
|
+
private enqueue(workArg: (targetsArg: readonly IControllerPushTarget[]) => Promise<void>): void {
|
|
314
|
+
this.tail = this.tail.then(async () => {
|
|
315
|
+
if (this.stopped) return;
|
|
316
|
+
const targets = await this.availableTargets();
|
|
317
|
+
if (this.stopped || targets.length === 0) return;
|
|
318
|
+
await workArg(targets);
|
|
319
|
+
}).catch((errorArg: unknown) => { this.options.fault(errorArg); });
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
private sendInboxChange(changeArg: IInboxChange, targetsArg: readonly IControllerPushTarget[]): void {
|
|
323
|
+
const { delivery } = this.options;
|
|
324
|
+
const badge = String(changeArg.total);
|
|
325
|
+
for (const registration of targetsArg) {
|
|
326
|
+
const target = deliveryTarget(registration);
|
|
327
|
+
const summaryKey = pushNotificationKey(registration.salt, pushKeySubjects.summary);
|
|
328
|
+
if (changeArg.removed.length > 0) {
|
|
329
|
+
const keys = changeArg.removed.map((idArg) => pushNotificationKey(registration.salt, idArg));
|
|
330
|
+
// Nothing waits any more: the summary, which says new items wait, goes too.
|
|
331
|
+
if (changeArg.total === 0) keys.push(summaryKey);
|
|
332
|
+
delivery.withdraw(target.deviceId, keys);
|
|
333
|
+
for (const chunk of pushClearChunks(keys)) delivery.send(target, { type: 'clear', keys: chunk, badge });
|
|
334
|
+
}
|
|
335
|
+
if (changeArg.added.length > pushSummaryThreshold) {
|
|
336
|
+
delivery.send(target, { type: 'summary', key: summaryKey, count: String(changeArg.added.length), badge, body: devicePushSummarySentence });
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
for (const item of changeArg.added) {
|
|
340
|
+
const plain: IDevicePushInboxData = {
|
|
341
|
+
type: 'inbox', key: pushNotificationKey(registration.salt, item.id), kind: item.kind, badge, body: devicePushSentences[item.kind],
|
|
342
|
+
};
|
|
343
|
+
delivery.send(target, changeArg.previews
|
|
344
|
+
? fitted(plain, (charactersArg) => ({
|
|
345
|
+
...plain, title: cut(inboxTitle(pushPlace(item.where)), charactersArg), body: cut(item.title, charactersArg), itemId: item.id,
|
|
346
|
+
}))
|
|
347
|
+
: plain);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|