@capybara-hq/kernel 0.1.0-rc.60 → 0.1.0-rc.61
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/dist/admin/admin.module.js +3 -0
- package/dist/admin/extensions.controller.d.ts +32 -1
- package/dist/admin/extensions.controller.js +72 -3
- package/dist/admin/health.service.d.ts +2 -2
- package/dist/admin/health.service.js +6 -2
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +6 -0
- package/dist/config/schema.js +12 -0
- package/dist/conversations/event-log.d.ts +12 -3
- package/dist/conversations/event-log.js +17 -5
- package/dist/ctx/secrets.d.ts +10 -5
- package/dist/ctx/secrets.js +16 -5
- package/dist/db/kernel-schema.d.ts +34 -2
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +7 -0
- package/dist/extensions/config-hash.d.ts +2 -0
- package/dist/extensions/config-hash.js +1 -1
- package/dist/extensions/guide-places.d.ts +5 -1
- package/dist/extensions/guide-places.js +9 -2
- package/dist/extensions/permission-view.d.ts +6 -4
- package/dist/extensions/permission-view.js +6 -3
- package/dist/extensions/plugin-guides.d.ts +20 -0
- package/dist/extensions/plugin-guides.js +49 -1
- package/dist/extensions/registry.js +1 -0
- package/dist/http/api.module.js +7 -0
- package/dist/http/meta.controller.d.ts +7 -1
- package/dist/http/meta.controller.js +14 -3
- package/dist/identity/accounts.js +5 -0
- package/dist/identity/sessions.d.ts +7 -0
- package/dist/identity/sessions.js +26 -4
- package/dist/inbox/platform-inbox.service.d.ts +21 -11
- package/dist/inbox/platform-inbox.service.js +27 -12
- package/dist/inbox/platform-notices.d.ts +15 -1
- package/dist/inbox/platform-notices.js +20 -0
- package/dist/infra/config/kernel-config.service.js +2 -0
- package/dist/infra/outbox/registry.d.ts +36 -0
- package/dist/infra/outbox/registry.js +30 -0
- package/dist/infra/queue/queue-names.d.ts +1 -1
- package/dist/infra/queue/queue-names.js +1 -0
- package/dist/orgs/offboarding.js +3 -0
- package/dist/overrides.d.ts +4 -0
- package/dist/overrides.js +2 -0
- package/dist/platform/exclusions.js +15 -0
- package/dist/platform/ops/extensions-admin.ops.d.ts +5 -1
- package/dist/platform/ops/extensions-admin.ops.js +97 -2
- package/dist/platform/ops/inbox.ops.d.ts +1 -1
- package/dist/platform/ops/inbox.ops.js +17 -7
- package/dist/platform/ops/platform.ops.d.ts +4 -2
- package/dist/platform/ops/platform.ops.js +55 -3
- package/dist/platform/platform-ops.module.js +2 -0
- package/dist/platform/route-schemas.js +3 -0
- package/dist/push/delivery.d.ts +88 -0
- package/dist/push/delivery.js +269 -0
- package/dist/push/fanout.d.ts +29 -0
- package/dist/push/fanout.js +95 -0
- package/dist/push/jobs.d.ts +43 -0
- package/dist/push/jobs.js +19 -0
- package/dist/push/preferences.service.d.ts +18 -0
- package/dist/push/preferences.service.js +82 -0
- package/dist/push/provider-host.d.ts +34 -0
- package/dist/push/provider-host.js +94 -0
- package/dist/push/push-owed.d.ts +33 -0
- package/dist/push/push-owed.js +93 -0
- package/dist/push/push-processor.d.ts +40 -0
- package/dist/push/push-processor.js +114 -0
- package/dist/push/push.controller.d.ts +28 -0
- package/dist/push/push.controller.js +92 -0
- package/dist/push/push.module.d.ts +6 -0
- package/dist/push/push.module.js +29 -0
- package/dist/push/push.schemas.d.ts +88 -0
- package/dist/push/push.schemas.js +53 -0
- package/dist/push/recipients.d.ts +29 -0
- package/dist/push/recipients.js +263 -0
- package/dist/push/registration-cleanup.d.ts +9 -0
- package/dist/push/registration-cleanup.js +16 -0
- package/dist/push/registrations.service.d.ts +55 -0
- package/dist/push/registrations.service.js +254 -0
- package/dist/push/stale.job.d.ts +25 -0
- package/dist/push/stale.job.js +76 -0
- package/dist/push/texts.d.ts +31 -0
- package/dist/push/texts.js +46 -0
- package/dist/push/token-store.d.ts +31 -0
- package/dist/push/token-store.js +52 -0
- package/dist/push/triggers.d.ts +19 -0
- package/dist/push/triggers.js +30 -0
- package/dist/roles/worker-role.d.ts +7 -4
- package/dist/roles/worker-role.js +12 -5
- package/dist/roles/worker.module.d.ts +1 -1
- package/dist/roles/worker.module.js +4 -1
- package/dist/schedules/run-tracker.d.ts +10 -2
- package/dist/schedules/run-tracker.js +18 -4
- package/dist/setup/setup-checks.schemas.d.ts +29 -0
- package/dist/setup/setup-checks.schemas.js +32 -0
- package/dist/setup/setup-checks.service.d.ts +36 -3
- package/dist/setup/setup-checks.service.js +137 -29
- package/package.json +4 -4
- package/src/migrations/0172_push.sql +40 -0
- package/src/migrations/0173_push_auth_notice.sql +10 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { ReplicaStatusStore } from "../extensions/sources.js";
|
|
2
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
3
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
4
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
5
|
+
import type { KernelLogger } from "../log.js";
|
|
6
|
+
import type { PushDeliverData } from "./jobs.js";
|
|
7
|
+
import { PushProviderHost } from "./provider-host.js";
|
|
8
|
+
import { PushTokenStore } from "./token-store.js";
|
|
9
|
+
/**
|
|
10
|
+
* Test seam (`KernelSeams`): one send's time limit in ms, asked at every send; default
|
|
11
|
+
* `PUSH_LIMITS.sendTimeoutMs`.
|
|
12
|
+
*/
|
|
13
|
+
export declare const PUSH_SEND_TIMEOUT_MS: unique symbol;
|
|
14
|
+
/** How one delivery job ended without a retry. */
|
|
15
|
+
export type PushDeliveryOutcome = "delivered" | "dropped" | "unregistered" | "auth" | "invalid";
|
|
16
|
+
/**
|
|
17
|
+
* A delivery that failed in a way a later attempt may fix (the queue retries it with the
|
|
18
|
+
* registry's backoff). Its message names ids, the plugin and the failure kind, never the token or
|
|
19
|
+
* a text the provider returned (which could echo it).
|
|
20
|
+
*/
|
|
21
|
+
export declare class PushRetryableError extends Error {
|
|
22
|
+
constructor(message: string);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* One `push-deliver` job (mobile app spec §9.4, plan task C6): sends one message to one
|
|
26
|
+
* registration through the push provider the registration names.
|
|
27
|
+
*
|
|
28
|
+
* - A message failing `validatePushMessage` -> `invalid`, no send, an error log with the ids only
|
|
29
|
+
* (a retry would carry the same message).
|
|
30
|
+
* - The registration is read when the job runs: gone (removed, its session revoked, pruned) ->
|
|
31
|
+
* `dropped`, no send. Reassigned to another account since the job was rendered (the same token
|
|
32
|
+
* posted by someone else keeps the row id) -> `dropped`, no send, the registration kept.
|
|
33
|
+
* - Its provider not loaded on this replica: when a live replica reports it loaded (a rolling
|
|
34
|
+
* deploy, a reload in progress) the job is retried; otherwise the provider is disabled or
|
|
35
|
+
* uninstalled -> `dropped`, no send, the registration kept. A provider whose deployment config
|
|
36
|
+
* no longer covers the registration's app id -> `dropped` the same way (review focus 5).
|
|
37
|
+
* - The token is opened from the row only for the call; job data never carries it.
|
|
38
|
+
* - The call is aborted after {@link PUSH_SEND_TIMEOUT_MS} (default `PUSH_LIMITS.sendTimeoutMs`)
|
|
39
|
+
* and retried. A replica that stops lets its calls in flight finish (each is bounded by that
|
|
40
|
+
* limit): aborting one the provider may already have accepted would only resend it.
|
|
41
|
+
* - `delivered` -> done; `unregistered` -> the registration is deleted, only while it still holds
|
|
42
|
+
* the token that was sent and was not posted again since it was read (a re-post refreshes
|
|
43
|
+
* `last_seen_at`, so the app's fresh registration survives a stale dead report); `auth`
|
|
44
|
+
* -> done, with the platform notice `push_auth_failed` for the plugin (one open per plugin);
|
|
45
|
+
* `rate_limited`, `transient`, a thrown non-`PushError`, a timeout and an answer failing
|
|
46
|
+
* `checkPushResults` -> {@link PushRetryableError} (5 attempts, 10 s doubling: registry). A
|
|
47
|
+
* provider's `retryAfterMs` is not used: the registry's backoff already waits longer than a
|
|
48
|
+
* typical hint.
|
|
49
|
+
*
|
|
50
|
+
* Duplicate adds are one job: the id is deterministic and a finished job is kept a day, so the
|
|
51
|
+
* outbox fast path and the relay adding it again (or the event owed again) is swallowed. A crash or
|
|
52
|
+
* a timeout after the provider accepted the message can still resend it (at least once, not
|
|
53
|
+
* exactly once); a per-event collapse id lets the device replace the duplicate.
|
|
54
|
+
*/
|
|
55
|
+
export declare class PushDelivery {
|
|
56
|
+
private readonly kdb;
|
|
57
|
+
readonly txHost: TransactionHost;
|
|
58
|
+
private readonly host;
|
|
59
|
+
private readonly tokens;
|
|
60
|
+
private readonly config;
|
|
61
|
+
/** This process's replica id (its own `extension_replica_status` rows). */
|
|
62
|
+
private readonly replica;
|
|
63
|
+
private readonly log;
|
|
64
|
+
private readonly timeoutMs;
|
|
65
|
+
constructor(kdb: KernelDb, txHost: TransactionHost, host: Pick<PushProviderHost, "provider" | "covers">, tokens: Pick<PushTokenStore, "open">, config: Pick<KernelConfigService, "get">,
|
|
66
|
+
/** This process's replica id (its own `extension_replica_status` rows). */
|
|
67
|
+
replica: Pick<ReplicaStatusStore, "replicaId">, log: KernelLogger, timeoutMs?: () => number);
|
|
68
|
+
/** Delivers one job (see the class). */
|
|
69
|
+
deliver(data: PushDeliverData): Promise<PushDeliveryOutcome>;
|
|
70
|
+
/**
|
|
71
|
+
* One provider call for one registration, bounded by the time limit; returns its one valid
|
|
72
|
+
* result or throws (an `auth` `PushError` becomes an `auth` result).
|
|
73
|
+
*/
|
|
74
|
+
private send;
|
|
75
|
+
/**
|
|
76
|
+
* Deletes the registration while it still holds the token that was reported dead and was not
|
|
77
|
+
* posted again after `seen` (its `last_seen_at` as read before the send, exact text).
|
|
78
|
+
*/
|
|
79
|
+
private forget;
|
|
80
|
+
/** The platform notice `push_auth_failed` for `plugin`, unless one is open. */
|
|
81
|
+
private recordAuthFailure;
|
|
82
|
+
/**
|
|
83
|
+
* Whether another live replica (heartbeat within the stale window) reports `plugin` loaded: then
|
|
84
|
+
* this replica merely lags (a rolling deploy) and a later attempt may land where it is loaded.
|
|
85
|
+
* This replica's own row is not counted: the registry already answered for it.
|
|
86
|
+
*/
|
|
87
|
+
private loadedElsewhere;
|
|
88
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { checkPushResults, PUSH_LIMITS, PushError, validatePushMessage, } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { Inject, Injectable, Optional } from "@nestjs/common";
|
|
12
|
+
import { sql } from "kysely";
|
|
13
|
+
import { STALE_RECONCILE_PERIODS } from "../extensions/lifecycle-topics.js";
|
|
14
|
+
import { ReplicaStatusStore } from "../extensions/sources.js";
|
|
15
|
+
import { addPushAuthNotice } from "../inbox/platform-notices.js";
|
|
16
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
17
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
18
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
19
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
20
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
21
|
+
import { PushProviderHost } from "./provider-host.js";
|
|
22
|
+
import { PushTokenStore } from "./token-store.js";
|
|
23
|
+
/**
|
|
24
|
+
* Test seam (`KernelSeams`): one send's time limit in ms, asked at every send; default
|
|
25
|
+
* `PUSH_LIMITS.sendTimeoutMs`.
|
|
26
|
+
*/
|
|
27
|
+
export const PUSH_SEND_TIMEOUT_MS = Symbol("PUSH_SEND_TIMEOUT_MS");
|
|
28
|
+
/**
|
|
29
|
+
* A delivery that failed in a way a later attempt may fix (the queue retries it with the
|
|
30
|
+
* registry's backoff). Its message names ids, the plugin and the failure kind, never the token or
|
|
31
|
+
* a text the provider returned (which could echo it).
|
|
32
|
+
*/
|
|
33
|
+
export class PushRetryableError extends Error {
|
|
34
|
+
constructor(message) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.name = "PushRetryableError";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* One `push-deliver` job (mobile app spec §9.4, plan task C6): sends one message to one
|
|
41
|
+
* registration through the push provider the registration names.
|
|
42
|
+
*
|
|
43
|
+
* - A message failing `validatePushMessage` -> `invalid`, no send, an error log with the ids only
|
|
44
|
+
* (a retry would carry the same message).
|
|
45
|
+
* - The registration is read when the job runs: gone (removed, its session revoked, pruned) ->
|
|
46
|
+
* `dropped`, no send. Reassigned to another account since the job was rendered (the same token
|
|
47
|
+
* posted by someone else keeps the row id) -> `dropped`, no send, the registration kept.
|
|
48
|
+
* - Its provider not loaded on this replica: when a live replica reports it loaded (a rolling
|
|
49
|
+
* deploy, a reload in progress) the job is retried; otherwise the provider is disabled or
|
|
50
|
+
* uninstalled -> `dropped`, no send, the registration kept. A provider whose deployment config
|
|
51
|
+
* no longer covers the registration's app id -> `dropped` the same way (review focus 5).
|
|
52
|
+
* - The token is opened from the row only for the call; job data never carries it.
|
|
53
|
+
* - The call is aborted after {@link PUSH_SEND_TIMEOUT_MS} (default `PUSH_LIMITS.sendTimeoutMs`)
|
|
54
|
+
* and retried. A replica that stops lets its calls in flight finish (each is bounded by that
|
|
55
|
+
* limit): aborting one the provider may already have accepted would only resend it.
|
|
56
|
+
* - `delivered` -> done; `unregistered` -> the registration is deleted, only while it still holds
|
|
57
|
+
* the token that was sent and was not posted again since it was read (a re-post refreshes
|
|
58
|
+
* `last_seen_at`, so the app's fresh registration survives a stale dead report); `auth`
|
|
59
|
+
* -> done, with the platform notice `push_auth_failed` for the plugin (one open per plugin);
|
|
60
|
+
* `rate_limited`, `transient`, a thrown non-`PushError`, a timeout and an answer failing
|
|
61
|
+
* `checkPushResults` -> {@link PushRetryableError} (5 attempts, 10 s doubling: registry). A
|
|
62
|
+
* provider's `retryAfterMs` is not used: the registry's backoff already waits longer than a
|
|
63
|
+
* typical hint.
|
|
64
|
+
*
|
|
65
|
+
* Duplicate adds are one job: the id is deterministic and a finished job is kept a day, so the
|
|
66
|
+
* outbox fast path and the relay adding it again (or the event owed again) is swallowed. A crash or
|
|
67
|
+
* a timeout after the provider accepted the message can still resend it (at least once, not
|
|
68
|
+
* exactly once); a per-event collapse id lets the device replace the duplicate.
|
|
69
|
+
*/
|
|
70
|
+
let PushDelivery = class PushDelivery {
|
|
71
|
+
kdb;
|
|
72
|
+
txHost;
|
|
73
|
+
host;
|
|
74
|
+
tokens;
|
|
75
|
+
config;
|
|
76
|
+
replica;
|
|
77
|
+
log;
|
|
78
|
+
timeoutMs;
|
|
79
|
+
constructor(kdb, txHost, host, tokens, config,
|
|
80
|
+
/** This process's replica id (its own `extension_replica_status` rows). */
|
|
81
|
+
replica, log, timeoutMs = () => PUSH_LIMITS.sendTimeoutMs) {
|
|
82
|
+
this.kdb = kdb;
|
|
83
|
+
this.txHost = txHost;
|
|
84
|
+
this.host = host;
|
|
85
|
+
this.tokens = tokens;
|
|
86
|
+
this.config = config;
|
|
87
|
+
this.replica = replica;
|
|
88
|
+
this.log = log;
|
|
89
|
+
this.timeoutMs = timeoutMs;
|
|
90
|
+
}
|
|
91
|
+
/** Delivers one job (see the class). */
|
|
92
|
+
async deliver(data) {
|
|
93
|
+
const fields = { eventId: data.eventId, registrationId: data.registrationId };
|
|
94
|
+
if (!messageValid(data.message)) {
|
|
95
|
+
// a retry would carry the same message: the job ends without a send
|
|
96
|
+
this.log.error("push delivery dropped: the message is invalid", fields);
|
|
97
|
+
return "invalid";
|
|
98
|
+
}
|
|
99
|
+
const row = await this.kdb.db
|
|
100
|
+
.selectFrom("push_registrations")
|
|
101
|
+
.select(["id", "account_id", "platform", "app_id", "provider", "token_hash"])
|
|
102
|
+
.select(["master_key_id", "token_ciphertext"])
|
|
103
|
+
// exact (microseconds): a JS Date would cut it to milliseconds
|
|
104
|
+
.select(sql `last_seen_at::text`.as("seen"))
|
|
105
|
+
.where("id", "=", data.registrationId)
|
|
106
|
+
.executeTakeFirst();
|
|
107
|
+
if (row === undefined) {
|
|
108
|
+
this.log.debug("push delivery dropped: the registration is gone", fields);
|
|
109
|
+
return "dropped";
|
|
110
|
+
}
|
|
111
|
+
if (row.account_id !== data.accountId) {
|
|
112
|
+
// the token moved to another account (the phone changed hands): the message was rendered
|
|
113
|
+
// for the previous one and must not reach the new one (review focus 3)
|
|
114
|
+
this.log.info("push delivery dropped: the registration now belongs to another account", fields);
|
|
115
|
+
return "dropped";
|
|
116
|
+
}
|
|
117
|
+
const plugin = row.provider;
|
|
118
|
+
const provider = this.host.provider(plugin);
|
|
119
|
+
if (provider === null) {
|
|
120
|
+
if (await this.loadedElsewhere(plugin)) {
|
|
121
|
+
throw new PushRetryableError(`push provider ${plugin} is not loaded on this replica`);
|
|
122
|
+
}
|
|
123
|
+
this.log.info("push delivery dropped: its provider is not enabled", { ...fields, plugin });
|
|
124
|
+
return "dropped";
|
|
125
|
+
}
|
|
126
|
+
if (!this.host.covers(plugin, row.app_id)) {
|
|
127
|
+
this.log.info("push delivery dropped: its provider no longer covers the app", {
|
|
128
|
+
...fields,
|
|
129
|
+
plugin,
|
|
130
|
+
appId: row.app_id,
|
|
131
|
+
});
|
|
132
|
+
return "dropped";
|
|
133
|
+
}
|
|
134
|
+
const target = {
|
|
135
|
+
id: row.id,
|
|
136
|
+
platform: row.platform,
|
|
137
|
+
appId: row.app_id,
|
|
138
|
+
token: this.tokens.open(row),
|
|
139
|
+
};
|
|
140
|
+
const result = await this.send(plugin, provider, target, data.message);
|
|
141
|
+
switch (result.status) {
|
|
142
|
+
case "delivered":
|
|
143
|
+
return "delivered";
|
|
144
|
+
case "unregistered":
|
|
145
|
+
await this.forget(row.id, row.token_hash, row.seen);
|
|
146
|
+
this.log.info("push registration deleted: the provider reports its token dead", {
|
|
147
|
+
...fields,
|
|
148
|
+
plugin,
|
|
149
|
+
});
|
|
150
|
+
return "unregistered";
|
|
151
|
+
case "failed":
|
|
152
|
+
if (result.kind === "auth") {
|
|
153
|
+
await this.recordAuthFailure(plugin);
|
|
154
|
+
this.log.warn("push delivery refused: the provider's credentials were rejected", {
|
|
155
|
+
...fields,
|
|
156
|
+
plugin,
|
|
157
|
+
});
|
|
158
|
+
return "auth";
|
|
159
|
+
}
|
|
160
|
+
throw new PushRetryableError(`push provider ${plugin} answered ${result.kind}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* One provider call for one registration, bounded by the time limit; returns its one valid
|
|
165
|
+
* result or throws (an `auth` `PushError` becomes an `auth` result).
|
|
166
|
+
*/
|
|
167
|
+
async send(plugin, provider, target, message) {
|
|
168
|
+
const limit = this.timeoutMs();
|
|
169
|
+
const ac = new AbortController();
|
|
170
|
+
let timer;
|
|
171
|
+
let results;
|
|
172
|
+
try {
|
|
173
|
+
results = await Promise.race([
|
|
174
|
+
Promise.resolve().then(() => provider.send({ registrations: [target], message, signal: ac.signal })),
|
|
175
|
+
new Promise((_, reject) => {
|
|
176
|
+
timer = setTimeout(() => ac.abort(new PushRetryableError(`push send timed out after ${limit} ms`)), limit);
|
|
177
|
+
if (ac.signal.aborted)
|
|
178
|
+
reject(ac.signal.reason);
|
|
179
|
+
else
|
|
180
|
+
ac.signal.addEventListener("abort", () => reject(ac.signal.reason), { once: true });
|
|
181
|
+
}),
|
|
182
|
+
]);
|
|
183
|
+
}
|
|
184
|
+
catch (err) {
|
|
185
|
+
if (err instanceof PushRetryableError)
|
|
186
|
+
throw err;
|
|
187
|
+
if (ac.signal.aborted)
|
|
188
|
+
throw ac.signal.reason;
|
|
189
|
+
if (err instanceof PushError) {
|
|
190
|
+
if (err.kind === "auth") {
|
|
191
|
+
return { registrationId: target.id, status: "failed", kind: "auth", message: "" };
|
|
192
|
+
}
|
|
193
|
+
throw new PushRetryableError(`push provider ${plugin} threw ${err.kind}`);
|
|
194
|
+
}
|
|
195
|
+
// the error's text is not kept: a provider's message could echo the token
|
|
196
|
+
throw new PushRetryableError(`push provider ${plugin} threw an error`);
|
|
197
|
+
}
|
|
198
|
+
finally {
|
|
199
|
+
clearTimeout(timer);
|
|
200
|
+
}
|
|
201
|
+
const problem = checkPushResults([target], results);
|
|
202
|
+
if (problem !== null) {
|
|
203
|
+
throw new PushRetryableError(`push provider ${plugin} answered invalidly: ${problem}`);
|
|
204
|
+
}
|
|
205
|
+
return results[0];
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Deletes the registration while it still holds the token that was reported dead and was not
|
|
209
|
+
* posted again after `seen` (its `last_seen_at` as read before the send, exact text).
|
|
210
|
+
*/
|
|
211
|
+
async forget(id, tokenHash, seen) {
|
|
212
|
+
await this.kdb.db
|
|
213
|
+
.deleteFrom("push_registrations")
|
|
214
|
+
.where("id", "=", id)
|
|
215
|
+
.where("token_hash", "=", tokenHash)
|
|
216
|
+
.where("last_seen_at", "<=", sql `${seen}::timestamptz`)
|
|
217
|
+
.execute();
|
|
218
|
+
}
|
|
219
|
+
/** The platform notice `push_auth_failed` for `plugin`, unless one is open. */
|
|
220
|
+
async recordAuthFailure(plugin) {
|
|
221
|
+
await addPushAuthNotice(this.kdb.db, plugin);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Whether another live replica (heartbeat within the stale window) reports `plugin` loaded: then
|
|
225
|
+
* this replica merely lags (a rolling deploy) and a later attempt may land where it is loaded.
|
|
226
|
+
* This replica's own row is not counted: the registry already answered for it.
|
|
227
|
+
*/
|
|
228
|
+
async loadedElsewhere(plugin) {
|
|
229
|
+
const staleSeconds = STALE_RECONCILE_PERIODS * this.config.get().extensionHost.reconcileIntervalSeconds;
|
|
230
|
+
const rows = await this.kdb.db
|
|
231
|
+
.selectFrom("extension_replica_status")
|
|
232
|
+
.select("plugin")
|
|
233
|
+
.where("plugin", "=", plugin)
|
|
234
|
+
.where("replica_id", "<>", this.replica.replicaId)
|
|
235
|
+
.where("state", "=", "loaded")
|
|
236
|
+
.where("heartbeat_at", ">", sql `now() - make_interval(secs => ${staleSeconds})`)
|
|
237
|
+
.limit(1)
|
|
238
|
+
.execute();
|
|
239
|
+
return rows.length > 0;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
__decorate([
|
|
243
|
+
Transactional()
|
|
244
|
+
], PushDelivery.prototype, "forget", null);
|
|
245
|
+
__decorate([
|
|
246
|
+
Transactional()
|
|
247
|
+
], PushDelivery.prototype, "recordAuthFailure", null);
|
|
248
|
+
PushDelivery = __decorate([
|
|
249
|
+
Injectable(),
|
|
250
|
+
__param(0, Inject(KernelDb)),
|
|
251
|
+
__param(1, Inject(TransactionHost)),
|
|
252
|
+
__param(2, Inject(PushProviderHost)),
|
|
253
|
+
__param(3, Inject(PushTokenStore)),
|
|
254
|
+
__param(4, Inject(KernelConfigService)),
|
|
255
|
+
__param(5, Inject(ReplicaStatusStore)),
|
|
256
|
+
__param(6, Inject(KERNEL_LOGGER)),
|
|
257
|
+
__param(7, Optional()),
|
|
258
|
+
__param(7, Inject(PUSH_SEND_TIMEOUT_MS))
|
|
259
|
+
], PushDelivery);
|
|
260
|
+
export { PushDelivery };
|
|
261
|
+
/** Whether `m` passes `validatePushMessage` (a malformed shape, e.g. a missing field, does not). */
|
|
262
|
+
function messageValid(m) {
|
|
263
|
+
try {
|
|
264
|
+
return validatePushMessage(m) === null;
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
2
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
3
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
4
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
5
|
+
import type { KernelLogger } from "../log.js";
|
|
6
|
+
import { type PushFanoutData } from "./jobs.js";
|
|
7
|
+
import { PushPreferencesService } from "./preferences.service.js";
|
|
8
|
+
import { PushRegistrationsService } from "./registrations.service.js";
|
|
9
|
+
/**
|
|
10
|
+
* One `push-fanout` job (mobile app spec §9.4, plan task C7): resolves the event's recipients when
|
|
11
|
+
* it runs (`resolveRecipients`: membership, account status, org liveness, a pending approval or
|
|
12
|
+
* question), keeps those with the event's category on, and owes one `push-deliver` per
|
|
13
|
+
* registration of theirs, rendered in the registration's locale, under
|
|
14
|
+
* `push-<eventId>-<registrationId>`. A repeat owes nothing new: a pending row of the same id is
|
|
15
|
+
* skipped and BullMQ swallows an id it already holds (finished jobs are kept a day). Without
|
|
16
|
+
* `http.publicUrl` there is no origin for the app to match a profile with, so nothing is owed.
|
|
17
|
+
*/
|
|
18
|
+
export declare class PushFanout {
|
|
19
|
+
private readonly kdb;
|
|
20
|
+
readonly txHost: TransactionHost;
|
|
21
|
+
private readonly outbox;
|
|
22
|
+
private readonly registrations;
|
|
23
|
+
private readonly preferences;
|
|
24
|
+
private readonly config;
|
|
25
|
+
private readonly log;
|
|
26
|
+
constructor(kdb: KernelDb, txHost: TransactionHost, outbox: Pick<OutboxService, "addMany">, registrations: Pick<PushRegistrationsService, "forAccounts">, preferences: Pick<PushPreferencesService, "enabledFor">, config: Pick<KernelConfigService, "get">, log: KernelLogger);
|
|
27
|
+
/** Owes the deliveries of one event; returns how many outbox rows it wrote. */
|
|
28
|
+
run(data: PushFanoutData): Promise<number>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
12
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
13
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
14
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
15
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
16
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
17
|
+
import { PUSH_DELIVER_JOB, PUSH_QUEUE, pushDeliverJobId, } from "./jobs.js";
|
|
18
|
+
import { PushPreferencesService } from "./preferences.service.js";
|
|
19
|
+
import { resolveRecipients } from "./recipients.js";
|
|
20
|
+
import { PushRegistrationsService } from "./registrations.service.js";
|
|
21
|
+
import { renderPushMessage } from "./texts.js";
|
|
22
|
+
/**
|
|
23
|
+
* One `push-fanout` job (mobile app spec §9.4, plan task C7): resolves the event's recipients when
|
|
24
|
+
* it runs (`resolveRecipients`: membership, account status, org liveness, a pending approval or
|
|
25
|
+
* question), keeps those with the event's category on, and owes one `push-deliver` per
|
|
26
|
+
* registration of theirs, rendered in the registration's locale, under
|
|
27
|
+
* `push-<eventId>-<registrationId>`. A repeat owes nothing new: a pending row of the same id is
|
|
28
|
+
* skipped and BullMQ swallows an id it already holds (finished jobs are kept a day). Without
|
|
29
|
+
* `http.publicUrl` there is no origin for the app to match a profile with, so nothing is owed.
|
|
30
|
+
*/
|
|
31
|
+
let PushFanout = class PushFanout {
|
|
32
|
+
kdb;
|
|
33
|
+
txHost;
|
|
34
|
+
outbox;
|
|
35
|
+
registrations;
|
|
36
|
+
preferences;
|
|
37
|
+
config;
|
|
38
|
+
log;
|
|
39
|
+
constructor(kdb, txHost, outbox, registrations, preferences, config, log) {
|
|
40
|
+
this.kdb = kdb;
|
|
41
|
+
this.txHost = txHost;
|
|
42
|
+
this.outbox = outbox;
|
|
43
|
+
this.registrations = registrations;
|
|
44
|
+
this.preferences = preferences;
|
|
45
|
+
this.config = config;
|
|
46
|
+
this.log = log;
|
|
47
|
+
}
|
|
48
|
+
/** Owes the deliveries of one event; returns how many outbox rows it wrote. */
|
|
49
|
+
async run(data) {
|
|
50
|
+
const cfg = this.config.get();
|
|
51
|
+
const publicUrl = cfg.http.publicUrl;
|
|
52
|
+
if (publicUrl === undefined) {
|
|
53
|
+
this.log.warn("push fanout skipped: http.publicUrl is not set", { eventId: data.eventId });
|
|
54
|
+
return 0;
|
|
55
|
+
}
|
|
56
|
+
const origin = new URL(publicUrl).origin;
|
|
57
|
+
const resolved = await resolveRecipients(this.kdb.db, data.source);
|
|
58
|
+
if (resolved === null)
|
|
59
|
+
return 0;
|
|
60
|
+
const enabled = await this.preferences.enabledFor(resolved.accountIds, resolved.category);
|
|
61
|
+
if (enabled.size === 0)
|
|
62
|
+
return 0;
|
|
63
|
+
const regs = await this.registrations.forAccounts([...enabled]);
|
|
64
|
+
const push = { ...resolved, eventId: data.eventId };
|
|
65
|
+
const jobs = regs.map((reg) => ({
|
|
66
|
+
queue: PUSH_QUEUE,
|
|
67
|
+
name: PUSH_DELIVER_JOB,
|
|
68
|
+
jobId: pushDeliverJobId(data.eventId, reg.id),
|
|
69
|
+
data: {
|
|
70
|
+
eventId: data.eventId,
|
|
71
|
+
registrationId: reg.id,
|
|
72
|
+
accountId: reg.account_id,
|
|
73
|
+
message: renderPushMessage(push, reg.locale, cfg.push.previews, origin),
|
|
74
|
+
},
|
|
75
|
+
orgId: resolved.orgId,
|
|
76
|
+
}));
|
|
77
|
+
if (jobs.length === 0)
|
|
78
|
+
return 0;
|
|
79
|
+
return this.outbox.addMany(jobs);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
__decorate([
|
|
83
|
+
Transactional()
|
|
84
|
+
], PushFanout.prototype, "run", null);
|
|
85
|
+
PushFanout = __decorate([
|
|
86
|
+
Injectable(),
|
|
87
|
+
__param(0, Inject(KernelDb)),
|
|
88
|
+
__param(1, Inject(TransactionHost)),
|
|
89
|
+
__param(2, Inject(OutboxService)),
|
|
90
|
+
__param(3, Inject(PushRegistrationsService)),
|
|
91
|
+
__param(4, Inject(PushPreferencesService)),
|
|
92
|
+
__param(5, Inject(KernelConfigService)),
|
|
93
|
+
__param(6, Inject(KERNEL_LOGGER))
|
|
94
|
+
], PushFanout);
|
|
95
|
+
export { PushFanout };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { PushMessage } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
/**
|
|
3
|
+
* The push queue's names, job ids and job data (mobile app spec §9.4). Ids are deterministic and
|
|
4
|
+
* carry no `:` (kernel ids are UUIDs, seq is a number), so the outbox fast path and the relay
|
|
5
|
+
* adding the same job twice, or an event owed again, is one job.
|
|
6
|
+
*/
|
|
7
|
+
/** Queue of push fanouts and deliveries (no `:` in the name). */
|
|
8
|
+
export declare const PUSH_QUEUE = "cap-push-deliver";
|
|
9
|
+
/** Resolves an event's recipients and owes one {@link PUSH_DELIVER_JOB} per registration. */
|
|
10
|
+
export declare const PUSH_FANOUT_JOB = "push-fanout";
|
|
11
|
+
/** Sends one message to one registration through the provider it names. */
|
|
12
|
+
export declare const PUSH_DELIVER_JOB = "push-deliver";
|
|
13
|
+
/** The event id of a conversation event (`conv-<conversationId>-<seq>`). */
|
|
14
|
+
export declare const conversationEventId: (conversationId: string, seq: number) => string;
|
|
15
|
+
/** The event id of a scheduled task run's settle (`sched-<taskRunId>`). */
|
|
16
|
+
export declare const scheduleRunEventId: (taskRunId: string) => string;
|
|
17
|
+
/** One fanout per event: `push-fanout-<eventId>`. */
|
|
18
|
+
export declare const pushFanoutJobId: (eventId: string) => string;
|
|
19
|
+
/** One delivery per event and registration: `push-<eventId>-<registrationId>`. */
|
|
20
|
+
export declare const pushDeliverJobId: (eventId: string, registrationId: string) => string;
|
|
21
|
+
/** Data of a {@link PUSH_FANOUT_JOB}: the event, by id only (read when the job runs). */
|
|
22
|
+
export type PushFanoutData = {
|
|
23
|
+
eventId: string;
|
|
24
|
+
source: {
|
|
25
|
+
kind: "conversation";
|
|
26
|
+
conversationId: string;
|
|
27
|
+
seq: number;
|
|
28
|
+
} | {
|
|
29
|
+
kind: "schedule";
|
|
30
|
+
taskRunId: string;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Data of a {@link PUSH_DELIVER_JOB}: the registration by id, the account it was rendered for and
|
|
35
|
+
* the rendered message. Never the token: it is opened from the registration row when the job runs.
|
|
36
|
+
* A registration whose token moved to another account since (review focus 3) is not sent to.
|
|
37
|
+
*/
|
|
38
|
+
export type PushDeliverData = {
|
|
39
|
+
eventId: string;
|
|
40
|
+
registrationId: string;
|
|
41
|
+
accountId: string;
|
|
42
|
+
message: PushMessage;
|
|
43
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The push queue's names, job ids and job data (mobile app spec §9.4). Ids are deterministic and
|
|
3
|
+
* carry no `:` (kernel ids are UUIDs, seq is a number), so the outbox fast path and the relay
|
|
4
|
+
* adding the same job twice, or an event owed again, is one job.
|
|
5
|
+
*/
|
|
6
|
+
/** Queue of push fanouts and deliveries (no `:` in the name). */
|
|
7
|
+
export const PUSH_QUEUE = "cap-push-deliver";
|
|
8
|
+
/** Resolves an event's recipients and owes one {@link PUSH_DELIVER_JOB} per registration. */
|
|
9
|
+
export const PUSH_FANOUT_JOB = "push-fanout";
|
|
10
|
+
/** Sends one message to one registration through the provider it names. */
|
|
11
|
+
export const PUSH_DELIVER_JOB = "push-deliver";
|
|
12
|
+
/** The event id of a conversation event (`conv-<conversationId>-<seq>`). */
|
|
13
|
+
export const conversationEventId = (conversationId, seq) => `conv-${conversationId}-${seq}`;
|
|
14
|
+
/** The event id of a scheduled task run's settle (`sched-<taskRunId>`). */
|
|
15
|
+
export const scheduleRunEventId = (taskRunId) => `sched-${taskRunId}`;
|
|
16
|
+
/** One fanout per event: `push-fanout-<eventId>`. */
|
|
17
|
+
export const pushFanoutJobId = (eventId) => `push-fanout-${eventId}`;
|
|
18
|
+
/** One delivery per event and registration: `push-<eventId>-<registrationId>`. */
|
|
19
|
+
export const pushDeliverJobId = (eventId, registrationId) => `push-${eventId}-${registrationId}`;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
2
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
3
|
+
import { type PushCategory, type PushPreferences, type PushPreferencesPatch } from "./push.schemas.js";
|
|
4
|
+
/**
|
|
5
|
+
* A person's push category switches (mobile app spec §9.4): one row per category switched, an
|
|
6
|
+
* absent row is on. They belong to the account and apply in every org.
|
|
7
|
+
*/
|
|
8
|
+
export declare class PushPreferencesService {
|
|
9
|
+
private readonly db;
|
|
10
|
+
readonly txHost: TransactionHost;
|
|
11
|
+
constructor(db: KernelDb, txHost: TransactionHost);
|
|
12
|
+
/** The four switches of `accountId`. */
|
|
13
|
+
get(accountId: string): Promise<PushPreferences>;
|
|
14
|
+
/** Sets the switches given (the others keep their value) and answers all four. */
|
|
15
|
+
set(accountId: string, patch: PushPreferencesPatch): Promise<PushPreferences>;
|
|
16
|
+
/** The accounts among `accountIds` that have `category` on. */
|
|
17
|
+
enabledFor(accountIds: readonly string[], category: PushCategory): Promise<Set<string>>;
|
|
18
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import { sql } from "kysely";
|
|
12
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
13
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
14
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
15
|
+
import { PUSH_CATEGORIES, } from "./push.schemas.js";
|
|
16
|
+
/**
|
|
17
|
+
* A person's push category switches (mobile app spec §9.4): one row per category switched, an
|
|
18
|
+
* absent row is on. They belong to the account and apply in every org.
|
|
19
|
+
*/
|
|
20
|
+
let PushPreferencesService = class PushPreferencesService {
|
|
21
|
+
db;
|
|
22
|
+
txHost;
|
|
23
|
+
constructor(db, txHost) {
|
|
24
|
+
this.db = db;
|
|
25
|
+
this.txHost = txHost;
|
|
26
|
+
}
|
|
27
|
+
/** The four switches of `accountId`. */
|
|
28
|
+
async get(accountId) {
|
|
29
|
+
const rows = await this.db
|
|
30
|
+
.selectFrom("push_preferences")
|
|
31
|
+
.select(["category", "enabled"])
|
|
32
|
+
.where("account_id", "=", accountId)
|
|
33
|
+
.execute();
|
|
34
|
+
const out = { waiting: true, replies: true, tasks: true, schedules: true };
|
|
35
|
+
for (const r of rows)
|
|
36
|
+
out[r.category] = r.enabled;
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/** Sets the switches given (the others keep their value) and answers all four. */
|
|
40
|
+
async set(accountId, patch) {
|
|
41
|
+
const values = PUSH_CATEGORIES.flatMap((category) => {
|
|
42
|
+
const enabled = patch[category];
|
|
43
|
+
return enabled === undefined ? [] : [{ account_id: accountId, category, enabled }];
|
|
44
|
+
});
|
|
45
|
+
if (values.length > 0) {
|
|
46
|
+
await this.db
|
|
47
|
+
.insertInto("push_preferences")
|
|
48
|
+
.values(values)
|
|
49
|
+
.onConflict((oc) => oc.columns(["account_id", "category"]).doUpdateSet((eb) => ({
|
|
50
|
+
enabled: eb.ref("excluded.enabled"),
|
|
51
|
+
updated_at: sql `now()`,
|
|
52
|
+
})))
|
|
53
|
+
.execute();
|
|
54
|
+
}
|
|
55
|
+
return this.get(accountId);
|
|
56
|
+
}
|
|
57
|
+
/** The accounts among `accountIds` that have `category` on. */
|
|
58
|
+
async enabledFor(accountIds, category) {
|
|
59
|
+
const out = new Set(accountIds);
|
|
60
|
+
if (out.size === 0)
|
|
61
|
+
return out;
|
|
62
|
+
const off = await this.db
|
|
63
|
+
.selectFrom("push_preferences")
|
|
64
|
+
.select("account_id")
|
|
65
|
+
.where("account_id", "in", [...out])
|
|
66
|
+
.where("category", "=", category)
|
|
67
|
+
.where("enabled", "=", false)
|
|
68
|
+
.execute();
|
|
69
|
+
for (const r of off)
|
|
70
|
+
out.delete(r.account_id);
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
__decorate([
|
|
75
|
+
Transactional()
|
|
76
|
+
], PushPreferencesService.prototype, "set", null);
|
|
77
|
+
PushPreferencesService = __decorate([
|
|
78
|
+
Injectable(),
|
|
79
|
+
__param(0, Inject(KernelDb)),
|
|
80
|
+
__param(1, Inject(TransactionHost))
|
|
81
|
+
], PushPreferencesService);
|
|
82
|
+
export { PushPreferencesService };
|