agl 43.7.0 → 43.9.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 +33 -0
- package/dist_serve/bundle.js +871 -858
- package/dist_serve/bundle.js.map +2 -2
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/aglapi/aglapisurface.document.js +824 -6
- package/dist_ts/aglapi/interfaces.d.ts +43 -0
- package/dist_ts/aglapi/interfaces.js +11 -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 +20 -8
- package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
- package/dist_ts/classes.mcpcontrollerhost.js +21 -2
- package/dist_ts/classes.mcptools.d.ts +1 -1
- package/dist_ts/classes.mcptools.js +2 -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.ticketstore.d.ts +3 -3
- package/dist_ts/classes.ticketstore.js +23 -4
- 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 +43 -3
- package/dist_ts/functions.mcptickettools.d.ts +60 -0
- package/dist_ts/functions.mcptickettools.js +4 -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.ticketcli.d.ts +4 -2
- package/dist_ts/functions.ticketcli.js +70 -4
- package/dist_ts/functions.ticketlisting.d.ts +38 -0
- package/dist_ts/functions.ticketlisting.js +211 -0
- package/dist_ts/functions.ticketvalidation.d.ts +62 -0
- package/dist_ts/functions.ticketvalidation.js +41 -3
- 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/requests.tickets.d.ts +31 -3
- package/dist_ts_interfaces/requests.tickets.js +2 -2
- package/dist_ts_interfaces/tickets.d.ts +174 -2
- package/dist_ts_interfaces/tickets.js +20 -2
- package/dist_ts_interfaces/workercallers.d.ts +43 -3
- package/package.json +2 -2
- package/readme.md +95 -14
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/aglapi/aglapisurface.document.ts +823 -5
- package/ts/aglapi/interfaces.ts +10 -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 +22 -7
- package/ts/classes.mcpcontrollerhost.ts +22 -1
- package/ts/classes.mcptools.ts +1 -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.ticketstore.ts +21 -3
- 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 +54 -2
- package/ts/functions.mcptickettools.ts +3 -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.ticketcli.ts +70 -5
- package/ts/functions.ticketlisting.ts +214 -0
- package/ts/functions.ticketvalidation.ts +41 -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/requests.tickets.ts +32 -2
- package/ts_interfaces/tickets.ts +136 -3
- package/ts_interfaces/workercallers.ts +34 -2
- package/ts_web/00_commitinfo_data.ts +1 -1
- package/ts_web/elements.inbox.ts +50 -9
package/ts/classes.inbox.ts
CHANGED
|
@@ -24,7 +24,10 @@ export interface IInboxSources {
|
|
|
24
24
|
* the part of them a failed partial read could not renew. A read that fails keeps the source's previous items.
|
|
25
25
|
*/
|
|
26
26
|
read(sourceArg: TInboxSource, previousArg: readonly TControllerInboxItem[], signalArg: AbortSignal): Promise<TControllerInboxItem[]>;
|
|
27
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Whether a browser or a device receives controller events, or a notification could go out (a registered device on
|
|
29
|
+
* a platform the host can send on); without either the Inbox only marks its sources stale.
|
|
30
|
+
*/
|
|
28
31
|
hasViewers(): Promise<boolean>;
|
|
29
32
|
publish(deltaArg: TControllerInboxDelta): void;
|
|
30
33
|
reportError(messageArg: string, errorArg: unknown): void;
|
|
@@ -72,7 +75,7 @@ export const boundInboxItem = (itemArg: TControllerInboxItem): TControllerInboxI
|
|
|
72
75
|
* deltas. Nothing is stored: every item is read from the component that owns it, so an answer anywhere removes it.
|
|
73
76
|
*
|
|
74
77
|
* Events mark the sources they concern stale; a pass reads only the stale ones, coalesced, and only while a browser
|
|
75
|
-
* or a device is connected. `list()` reads every stale source first.
|
|
78
|
+
* or a device is connected or a notification could go out. `list()` reads every stale source first.
|
|
76
79
|
*/
|
|
77
80
|
export class ControllerInbox {
|
|
78
81
|
private readonly abort = new AbortController();
|
|
@@ -99,6 +102,14 @@ export class ControllerInbox {
|
|
|
99
102
|
public async list(): Promise<IControllerInboxSnapshot> {
|
|
100
103
|
this.abort.signal.throwIfAborted();
|
|
101
104
|
await this.enqueuePass();
|
|
105
|
+
return this.current();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* What the last pass published, reading nothing: for a consumer of the published deltas that met a `reset` (the push
|
|
110
|
+
* trigger), never a second computation of the Inbox.
|
|
111
|
+
*/
|
|
112
|
+
public current(): IControllerInboxSnapshot {
|
|
102
113
|
return { epoch: this.published.epoch, revision: this.published.revision, items: this.published.values(), total: this.total, limited: this.limited };
|
|
103
114
|
}
|
|
104
115
|
|
package/ts/classes.mcpclient.ts
CHANGED
|
@@ -6,12 +6,14 @@ import type { TWorkerCallerEnrollment, IWorkerCallerEnrollmentResponse } from '.
|
|
|
6
6
|
import type { IControllerMcpWireCaller } from '../ts_interfaces/mcprequests.js';
|
|
7
7
|
import type { TFleetOperation, TFleetRequest, TFleetResult, IFleetOperation } from '../ts_interfaces/fleet.js';
|
|
8
8
|
import { assertFleetOperation, assertFleetWireRequest } from './fleet/functions.validation.js';
|
|
9
|
-
import { readTicketRevisionConflict, ticketErrorMessages, type TTicketClientErrorCode, type TTicketOperation, type TTicketRequest, type TTicketResponse } from '../ts_interfaces/tickets.js';
|
|
9
|
+
import { readTicketRevisionConflict, ticketErrorMessages, ticketPageErrorMessages, type TTicketClientErrorCode, type TTicketOperation, type TTicketRequest, type TTicketResponse } from '../ts_interfaces/tickets.js';
|
|
10
10
|
import { assertMcpTicketRequest, assertTicketResponse } from './functions.ticketvalidation.js';
|
|
11
11
|
import { assertSessionFeedWireRequest, assertSessionFeedWireResponse } from './functions.sessionfeedvalidation.js';
|
|
12
12
|
import { assertFleetDeployResponse, assertFleetDeployWireRequest } from './fleet/functions.deployvalidation.js';
|
|
13
|
+
import { assertPushResponse, assertPushWireRequest, isControllerMcpPushMethod, redactPushRequest } from './functions.pushwire.js';
|
|
13
14
|
import { fleetDeployRefreshClientMarginMs, fleetDeployRefreshWaitMs, type IFleetDeployOperations, type TFleetDeployOperation } from '../ts_interfaces/deployments.js';
|
|
14
15
|
import type { IReq_ControllerMcpSessionFeedAcknowledge, IReq_ControllerMcpSessionFeedList } from '../ts_interfaces/sessionfeed.js';
|
|
16
|
+
import type { IPushOperations, TControllerMcpPushMethod, TPushOperation } from '../ts_interfaces/push.js';
|
|
15
17
|
import { isProxyCapacityAnswer, type IProxyCapacityAnswer, type IProxyCapacityRequest } from '../ts_interfaces/proxycapacity.js';
|
|
16
18
|
import {
|
|
17
19
|
controllerMcpNativeDeliveries,
|
|
@@ -358,6 +360,10 @@ const assertResponsePayload = (
|
|
|
358
360
|
assertFleetDeployResponse(methodArg, valueArg);
|
|
359
361
|
return;
|
|
360
362
|
}
|
|
363
|
+
if (isControllerMcpPushMethod(methodArg)) {
|
|
364
|
+
assertPushResponse(methodArg, valueArg);
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
361
367
|
if (methodArg.startsWith('agl.mcp.ticket.')) {
|
|
362
368
|
assertTicketResponse(methodArg, valueArg);
|
|
363
369
|
return;
|
|
@@ -790,6 +796,14 @@ export class ControllerMcpClient {
|
|
|
790
796
|
operation === 'refresh' ? Math.max(this.requestTimeoutMs, deployRefreshRequestTimeoutMs) : undefined,
|
|
791
797
|
) as Promise<IFleetDeployOperations[TOperation]['response']>;
|
|
792
798
|
}
|
|
799
|
+
/** The host's push settings as the local owner reads and changes them (`agl push`, AGL-1639). */
|
|
800
|
+
public async push<TOperation extends TPushOperation>(operation: TOperation,
|
|
801
|
+
request: IPushOperations[TOperation]['request'] & { ownerToken: string }, signal?: AbortSignal,
|
|
802
|
+
): Promise<IPushOperations[TOperation]['response']> {
|
|
803
|
+
const method = `agl.mcp.push.${operation}` as const;
|
|
804
|
+
const wireRequest = assertPushWireRequest(method, request);
|
|
805
|
+
return this.dispatchAfterHandshake(method as TControllerMcpPushMethod, wireRequest as never, signal, operation !== 'status') as Promise<IPushOperations[TOperation]['response']>;
|
|
806
|
+
}
|
|
793
807
|
public async fleetStatus(id: string, ownerToken: string, signal?: AbortSignal, ticketKey?: string): Promise<IFleetOperation> {
|
|
794
808
|
return this.dispatchAfterHandshake('agl.mcp.fleet.status', { id, ownerToken, ...(ticketKey ? { ticketKey } : {}) }, signal, false);
|
|
795
809
|
}
|
|
@@ -972,11 +986,12 @@ export class ControllerMcpClient {
|
|
|
972
986
|
|| decoded.method !== methodArg
|
|
973
987
|
|| !plugins.util.isDeepStrictEqual(
|
|
974
988
|
decoded.request,
|
|
975
|
-
(methodArg
|
|
976
|
-
|| methodArg.startsWith('agl.mcp.
|
|
977
|
-
|
|
978
|
-
...(
|
|
979
|
-
|
|
989
|
+
isControllerMcpPushMethod(methodArg) ? redactPushRequest(requestArg as Record<string, unknown>)
|
|
990
|
+
: (methodArg.startsWith('agl.mcp.configuration.') || methodArg.startsWith('agl.mcp.ticket.') || methodArg.startsWith('agl.mcp.fleet.')
|
|
991
|
+
|| methodArg.startsWith('agl.mcp.deploy.'))
|
|
992
|
+
? { ...requestArg, ...(Object.hasOwn(requestArg, 'ownerToken') ? { ownerToken: '[redacted]' } : {}),
|
|
993
|
+
...(methodArg === 'agl.mcp.configuration.master.save' ? { masterJson: '[redacted]' } : {}) }
|
|
994
|
+
: requestArg,
|
|
980
995
|
)
|
|
981
996
|
|| !controllerMcpValueIsRecord(decoded.response)
|
|
982
997
|
|| !controllerMcpValueIsRecord(decoded.correlation)
|
|
@@ -1007,7 +1022,7 @@ export class ControllerMcpClient {
|
|
|
1007
1022
|
const conflict = readTicketRevisionConflict(decoded.error.data);
|
|
1008
1023
|
if (serverCode === 'ticket_revision_conflict' && !conflict) throw new Error('Invalid conflict metadata.');
|
|
1009
1024
|
currentRevision = conflict?.currentRevision;
|
|
1010
|
-
if (typeof serverCode === 'string' && Object.hasOwn(ticketErrorMessages, serverCode)) code = serverCode.toUpperCase() as TTicketClientErrorCode;
|
|
1025
|
+
if (typeof serverCode === 'string' && (Object.hasOwn(ticketErrorMessages, serverCode) || Object.hasOwn(ticketPageErrorMessages, serverCode))) code = serverCode.toUpperCase() as TTicketClientErrorCode;
|
|
1011
1026
|
if (serverCode === 'controller_unavailable') code = 'CONTROLLER_UNAVAILABLE';
|
|
1012
1027
|
if (serverCode === 'authentication_failed') code = 'AUTHENTICATION_FAILED';
|
|
1013
1028
|
if (serverCode === 'response_limit') code = 'RESPONSE_LIMIT';
|
|
@@ -31,8 +31,10 @@ import type { IFleetOperation } from '../ts_interfaces/fleet.js';
|
|
|
31
31
|
import { controllerMcpTicketMethods, type TControllerMcpTicketTypedRequest } from '../ts_interfaces/requests.tickets.js';
|
|
32
32
|
import type { IReq_ControllerMcpSessionFeedAcknowledge, IReq_ControllerMcpSessionFeedList } from '../ts_interfaces/sessionfeed.js';
|
|
33
33
|
import { controllerMcpDeployMethods, type TControllerMcpDeployMethod, type TControllerMcpDeployTypedRequest } from '../ts_interfaces/deployments.js';
|
|
34
|
+
import { controllerMcpPushMethods, pushErrorCodes, type TControllerMcpPushMethod, type TControllerMcpPushTypedRequest } from '../ts_interfaces/push.js';
|
|
35
|
+
import { redactPushRequest } from './functions.pushwire.js';
|
|
34
36
|
import { deployErrorCodes } from './fleet/classes.deploymonitor.js';
|
|
35
|
-
import { readTicketRevisionConflict, ticketErrorMessages, type TTicketOperation, type TTicketRequest, type TTicketResponse } from '../ts_interfaces/tickets.js';
|
|
37
|
+
import { readTicketRevisionConflict, ticketErrorMessages, ticketPageErrorMessages, type TTicketOperation, type TTicketRequest, type TTicketResponse } from '../ts_interfaces/tickets.js';
|
|
36
38
|
import { ticketOperation } from './functions.ticketvalidation.js';
|
|
37
39
|
import { controllerFailureJournal } from './classes.failurejournal.js';
|
|
38
40
|
import { configurationErrorCodes } from './configuration/classes.configurationerror.js';
|
|
@@ -94,6 +96,8 @@ export interface IControllerMcpPrivateApi {
|
|
|
94
96
|
fleet?: (method: string, request: Record<string, unknown>, signal: AbortSignal) => Promise<IFleetOperation>;
|
|
95
97
|
/** Deploy status, history, a probe now and release state for the local owner (`agl deploy`, `agl release status`). */
|
|
96
98
|
deploy?: (method: TControllerMcpDeployMethod, request: Record<string, unknown>, signal: AbortSignal) => Promise<unknown>;
|
|
99
|
+
/** The host's push settings for the local owner (`agl push`, AGL-1639); each call verifies the owner capability. */
|
|
100
|
+
push?: (method: TControllerMcpPushMethod, request: Record<string, unknown>, signal: AbortSignal) => Promise<unknown>;
|
|
97
101
|
/** A pool's room for new work in AGL's inference proxy, asked of the proxy (AGL-1097); open to every caller. */
|
|
98
102
|
proxyCapacity?: (request: IReq_ControllerMcpProxyCapacity['request'], signal: AbortSignal)
|
|
99
103
|
=> Promise<IReq_ControllerMcpProxyCapacity['response']>;
|
|
@@ -246,6 +250,11 @@ class ControllerMcpBoundedTypedRouter extends plugins.typedrequest.TypedRouter {
|
|
|
246
250
|
// and refuses anything else, an installed older one included. TypedRequest 9 answers `null` where TypedRequest 8
|
|
247
251
|
// returned the `{}` the client sent (an error, a handler that returns nothing), so the host restores it here.
|
|
248
252
|
if (response.response === null) (response as plugins.typedrequestInterfaces.ITypedRequest).response = {};
|
|
253
|
+
if (typeof response.method === 'string' && response.method.startsWith('agl.mcp.push.')
|
|
254
|
+
&& response.request && typeof response.request === 'object') {
|
|
255
|
+
// The owner capability and the push keys never travel back in the echo, including on rejected operations.
|
|
256
|
+
(response as plugins.typedrequestInterfaces.ITypedRequest).request = redactPushRequest(response.request as Record<string, unknown>);
|
|
257
|
+
}
|
|
249
258
|
if (typeof response.method === 'string' && (response.method.startsWith('agl.mcp.configuration.')
|
|
250
259
|
|| response.method.startsWith('agl.mcp.ticket.') || response.method.startsWith('agl.mcp.fleet.') || response.method.startsWith('agl.mcp.deploy.'))) {
|
|
251
260
|
// TypedRequest normally echoes the request. The owner capability must not travel back in
|
|
@@ -304,12 +313,17 @@ const safeTypedResponseError = (
|
|
|
304
313
|
if (methodArg.startsWith('agl.mcp.deploy.') && (deployErrorCodes as readonly unknown[]).includes(code)) {
|
|
305
314
|
return new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 1024), { code });
|
|
306
315
|
}
|
|
316
|
+
// A push refusal's sentence names the field and the rule, never the input (`PushError`).
|
|
317
|
+
if (methodArg.startsWith('agl.mcp.push.') && (pushErrorCodes as readonly unknown[]).includes(code)) {
|
|
318
|
+
return new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 1024), { code });
|
|
319
|
+
}
|
|
307
320
|
if (methodArg.startsWith('agl.mcp.fleet.worker.') && (fleetWorkerErrorCodes as readonly unknown[]).includes(code)) {
|
|
308
321
|
return new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 1024), { code });
|
|
309
322
|
}
|
|
310
323
|
if (typeof code === 'string' && /^[a-z0-9_]{1,64}$/.test(code)) {
|
|
311
324
|
const messages: Record<string, string> = {
|
|
312
325
|
...ticketErrorMessages,
|
|
326
|
+
...ticketPageErrorMessages,
|
|
313
327
|
controller_unavailable: 'The controller is not ready to accept this operation.',
|
|
314
328
|
operation_limit: 'The controller is busy. Try again after current operations settle.',
|
|
315
329
|
rate_limited: 'The authenticated operation rate limit was reached.',
|
|
@@ -696,6 +710,13 @@ export class ControllerMcpHost {
|
|
|
696
710
|
return this.options.api.deploy(method, request as unknown as Record<string, unknown>, tools?.abortSignal ?? new AbortController().signal) as never;
|
|
697
711
|
})));
|
|
698
712
|
}
|
|
713
|
+
for (const method of controllerMcpPushMethods) {
|
|
714
|
+
routerArg.addTypedHandler(new plugins.typedrequest.TypedHandler<TControllerMcpPushTypedRequest>(method,
|
|
715
|
+
async (request, tools) => run(method, async () => {
|
|
716
|
+
if (!this.options.api.push) throw new Error('Push API is unavailable.');
|
|
717
|
+
return this.options.api.push(method, request as unknown as Record<string, unknown>, tools?.abortSignal ?? new AbortController().signal) as never;
|
|
718
|
+
})));
|
|
719
|
+
}
|
|
699
720
|
routerArg.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_ControllerMcpProxyCapacity>(
|
|
700
721
|
'agl.mcp.proxy.capacity', async (requestArg, toolsArg) => run('agl.mcp.proxy.capacity', async () => {
|
|
701
722
|
if (!this.options.api.proxyCapacity) throw new Error('Proxy capacity API is unavailable.');
|
package/ts/classes.mcptools.ts
CHANGED
|
@@ -28,6 +28,7 @@ import { assertMcpTicketRequest } from './functions.ticketvalidation.js';
|
|
|
28
28
|
import { assertFleetWireRequest } from './fleet/functions.validation.js';
|
|
29
29
|
import { assertSessionFeedWireRequest } from './functions.sessionfeedvalidation.js';
|
|
30
30
|
import { assertFleetDeployWireRequest } from './fleet/functions.deployvalidation.js';
|
|
31
|
+
import { assertPushWireRequest } from './functions.pushwire.js';
|
|
31
32
|
import { isProxyCapacityRequest } from '../ts_interfaces/proxycapacity.js';
|
|
32
33
|
|
|
33
34
|
const maximumIdBytes = 1024;
|
|
@@ -145,6 +146,7 @@ const assertMethodRequest = (
|
|
|
145
146
|
return assertSessionFeedWireRequest(methodArg, requestArg);
|
|
146
147
|
}
|
|
147
148
|
if (methodArg.startsWith('agl.mcp.deploy.')) return assertFleetDeployWireRequest(methodArg, requestArg);
|
|
149
|
+
if (methodArg.startsWith('agl.mcp.push.')) return assertPushWireRequest(methodArg, requestArg);
|
|
148
150
|
if (methodArg === 'agl.mcp.proxy.capacity') {
|
|
149
151
|
if (!isProxyCapacityRequest(requestArg)) throw new Error('Invalid private controller request.');
|
|
150
152
|
return requestArg;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ControllerMcpClient } from './classes.mcpclient.js';
|
|
1
|
+
import { ControllerMcpClient, ControllerMcpClientError } from './classes.mcpclient.js';
|
|
2
2
|
import {
|
|
3
3
|
workerCallerLaunchIdEnvironmentVariable, workerCallerLaunchGenerationEnvironmentVariable,
|
|
4
4
|
type IWorkerCallerReadiness,
|
|
@@ -25,7 +25,13 @@ export class McpWorkerCaller {
|
|
|
25
25
|
if (this.closed) throw new Error('Worker caller enrollment is closed.');
|
|
26
26
|
return this.client.withCaller(response?.credential, undefined, operationArg);
|
|
27
27
|
}
|
|
28
|
-
if (nativeThreadIdArg === undefined)
|
|
28
|
+
if (nativeThreadIdArg === undefined) {
|
|
29
|
+
// Without a launch the controller identifies the bridge by the Claude job its parent runs (AGL-1888). A credential
|
|
30
|
+
// it answers with is the caller, never the one this process inherited; without one the call runs as before.
|
|
31
|
+
const credential = await this.enrollProcess();
|
|
32
|
+
if (this.closed) throw new Error('Worker caller enrollment is closed.');
|
|
33
|
+
return credential === undefined ? operationArg() : this.client.withCaller(credential, undefined, operationArg);
|
|
34
|
+
}
|
|
29
35
|
const response = await this.client.enrollWorker({ nativeThreadId: nativeThreadIdArg, bridgePid: process.pid });
|
|
30
36
|
if (this.closed) throw new Error('Worker caller enrollment is closed.');
|
|
31
37
|
return this.client.withCaller(response.credential, nativeThreadIdArg, operationArg);
|
|
@@ -44,4 +50,20 @@ export class McpWorkerCaller {
|
|
|
44
50
|
public close(): void {
|
|
45
51
|
this.closed = true;
|
|
46
52
|
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The credential the controller answers a process enrollment with, if any. A controller that rejects the request
|
|
56
|
+
* (one older than process enrollment answers HTTP 400, read as `PROTOCOL_MISMATCH`) or fails it (`REQUEST_FAILED`)
|
|
57
|
+
* leaves the bridge as it was; every other failure is the call's own, as it would be without the enrollment.
|
|
58
|
+
*/
|
|
59
|
+
private async enrollProcess(): Promise<string | undefined> {
|
|
60
|
+
try {
|
|
61
|
+
return (await this.client.enrollWorker({ bridgePid: process.pid })).credential;
|
|
62
|
+
} catch (errorArg) {
|
|
63
|
+
if (errorArg instanceof ControllerMcpClientError && (errorArg.code === 'PROTOCOL_MISMATCH' || errorArg.code === 'REQUEST_FAILED')) {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
throw errorArg;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
47
69
|
}
|
|
@@ -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
|
+
}
|