@capybara-hq/kernel 0.1.0-rc.131 → 0.1.0-rc.133
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/bootstrap.json +5 -5
- package/dist/admin/admin.module.js +3 -0
- package/dist/admin/admin.schemas.d.ts +4 -0
- package/dist/admin/health.service.d.ts +2 -2
- package/dist/admin/health.service.js +6 -2
- package/dist/admin/setup.service.js +6 -1
- package/dist/agents/agents.controller.js +3 -2
- package/dist/agents/agents.service.d.ts +2 -0
- package/dist/agents/agents.service.js +7 -0
- package/dist/catalog/catalog.service.d.ts +2 -0
- package/dist/catalog/catalog.service.js +28 -5
- package/dist/catalog/marketplace-fetch.d.ts +2 -0
- package/dist/catalog/marketplace-fetch.js +15 -0
- package/dist/catalog/marketplaces.service.d.ts +4 -4
- package/dist/catalog/marketplaces.service.js +3 -2
- package/dist/catalog/owned-items.d.ts +2 -0
- package/dist/catalog/owned-items.js +30 -31
- package/dist/catalog/ownership.js +40 -38
- package/dist/catalog/plugin-import.d.ts +6 -5
- package/dist/catalog/plugin-import.js +69 -16
- package/dist/catalog/plugin-upgrade.d.ts +8 -0
- package/dist/catalog/plugin-upgrade.js +95 -7
- package/dist/catalog/publisher-policy.d.ts +9 -0
- package/dist/catalog/publisher-policy.js +12 -0
- package/dist/catalog/unshare.js +66 -58
- package/dist/client/client-access.service.js +5 -3
- package/dist/config/schema.d.ts +1 -0
- package/dist/config/schema.js +9 -1
- package/dist/conversations/conversations.controller.js +4 -14
- package/dist/conversations/conversations.service.d.ts +14 -0
- package/dist/conversations/conversations.service.js +20 -2
- package/dist/ctx/create-ctx.d.ts +14 -4
- package/dist/ctx/create-ctx.js +131 -59
- package/dist/ctx/queue.js +7 -4
- package/dist/db/extension-db.d.ts +30 -0
- package/dist/db/extension-db.js +91 -0
- package/dist/db/extension-rls-predicate.d.ts +1 -0
- package/dist/db/extension-rls-predicate.js +8 -0
- package/dist/db/extension-schema-transfer.d.ts +6 -0
- package/dist/db/extension-schema-transfer.js +141 -0
- package/dist/db/kernel-schema.d.ts +50 -4
- package/dist/db/migrator.d.ts +6 -0
- package/dist/db/migrator.js +35 -7
- package/dist/db/pool.d.ts +6 -2
- package/dist/db/pool.js +37 -2
- package/dist/db/sql-statements.d.ts +3 -0
- package/dist/db/sql-statements.js +15 -5
- package/dist/device-access/device-access.module.js +12 -2
- package/dist/device-access/device-access.service.d.ts +30 -2
- package/dist/device-access/device-access.service.js +38 -4
- package/dist/device-access/host-gate.d.ts +45 -0
- package/dist/device-access/host-gate.js +92 -0
- package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
- package/dist/device-access/host-service-stop-sweep.js +112 -0
- package/dist/device-access/host-service-stop.d.ts +78 -0
- package/dist/device-access/host-service-stop.js +144 -0
- package/dist/device-access/host-services.d.ts +211 -0
- package/dist/device-access/host-services.js +803 -0
- package/dist/device-access/person-handles.d.ts +10 -0
- package/dist/device-access/person-handles.js +25 -0
- package/dist/device-access/service-events.d.ts +199 -0
- package/dist/device-access/service-events.js +704 -0
- package/dist/device-access/token.d.ts +5 -0
- package/dist/device-access/token.js +5 -0
- package/dist/devices/devices.service.js +3 -0
- package/dist/dial-in/access.d.ts +5 -5
- package/dist/dial-in/access.js +19 -12
- package/dist/dial-in/gateway.js +6 -2
- package/dist/dial-in/machines.d.ts +9 -2
- package/dist/dial-in/machines.js +27 -4
- package/dist/erasure/device-cleanup.js +12 -0
- package/dist/erasure/org-catalog.js +2 -2
- package/dist/erasure/org-rules.js +9 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/extensions/admin-ops.d.ts +3 -1
- package/dist/extensions/admin-ops.js +19 -9
- package/dist/extensions/deployed-snapshots.d.ts +4 -1
- package/dist/extensions/deployed-snapshots.js +7 -2
- package/dist/extensions/extensions.module.js +3 -0
- package/dist/extensions/host.d.ts +11 -3
- package/dist/extensions/host.js +40 -8
- package/dist/extensions/instance.d.ts +6 -0
- package/dist/extensions/instance.js +7 -1
- package/dist/extensions/ledger.d.ts +1 -1
- package/dist/extensions/lifecycle-hooks.js +3 -3
- package/dist/extensions/migrate-lock.d.ts +4 -1
- package/dist/extensions/migrate-lock.js +19 -2
- package/dist/extensions/org-config.js +6 -1
- package/dist/extensions/permission-set.d.ts +7 -0
- package/dist/extensions/permission-set.js +10 -0
- package/dist/extensions/permission-view.d.ts +1 -1
- package/dist/extensions/permission-view.js +10 -1
- package/dist/git/tickets.js +32 -27
- package/dist/http/app.js +5 -3
- package/dist/identity/accounts.d.ts +6 -1
- package/dist/identity/accounts.js +11 -2
- package/dist/identity/api-tokens.js +7 -6
- package/dist/identity/settings.d.ts +9 -1
- package/dist/identity/settings.js +16 -1
- package/dist/inbox/org-notices.js +3 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/infra/database/scoped-dialect.d.ts +3 -2
- package/dist/infra/database/scoped-dialect.js +260 -72
- package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
- package/dist/infra/database/startup-activation-transaction.js +3 -2
- package/dist/infra/outbox/registry.d.ts +28 -14
- package/dist/infra/outbox/registry.js +30 -15
- package/dist/infra/queue/queue-names.d.ts +1 -1
- package/dist/infra/queue/queue-names.js +1 -0
- package/dist/infra/queue/run-job.d.ts +4 -1
- package/dist/infra/queue/run-job.js +10 -2
- package/dist/kernel.js +4 -0
- package/dist/kernel.module.js +3 -0
- package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
- package/dist/lifecycle/kernel-lifecycle.js +26 -21
- package/dist/orgs/offboarding.js +18 -9
- package/dist/orgs/settings.service.js +3 -0
- package/dist/packages/npm-publish-keys.json +27 -0
- package/dist/packages/official-publisher.d.ts +19 -0
- package/dist/packages/official-publisher.js +152 -0
- package/dist/packages/provenance.d.ts +7 -0
- package/dist/packages/provenance.js +22 -19
- package/dist/packages/sigstore-trusted-root.json +126 -0
- package/dist/platform/ops/admin.ops.js +2 -1
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/roles/worker-role.d.ts +6 -3
- package/dist/roles/worker-role.js +12 -4
- package/dist/roles/worker.module.js +7 -6
- package/dist/runtime/maintenance.d.ts +5 -4
- package/dist/runtime/maintenance.js +16 -13
- package/dist/sandbox/device-reports.d.ts +4 -4
- package/dist/sandbox/device-reports.js +40 -30
- package/dist/sandbox/device-services.d.ts +2 -1
- package/dist/sandbox/device-services.js +5 -1
- package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
- package/dist/sandbox/permission-ceiling-writes.js +21 -0
- package/dist/sandbox/permission-config-publication.js +5 -1
- package/dist/themes/theme-state.js +24 -13
- package/dist/tools/call-scope.d.ts +6 -0
- package/dist/tools/call-scope.js +22 -0
- package/dist/tools/registry.js +20 -2
- package/dist/ui/views.js +36 -8
- package/package.json +9 -4
- package/src/migrations/0219_event_org_constraint_check.sql +29 -0
- package/src/migrations/0220_require_event_org.sql +18 -0
- package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
- package/src/migrations/0222_device_host_services.sql +27 -0
- package/src/migrations/0223_device_service_events.sql +54 -0
- package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
- package/dist/conversations/event-org-backfill.d.ts +0 -111
- package/dist/conversations/event-org-backfill.js +0 -264
- package/dist/conversations/event-org-backfill.module.d.ts +0 -3
- package/dist/conversations/event-org-backfill.module.js +0 -18
|
@@ -0,0 +1,704 @@
|
|
|
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 { DEVICE_SERVICE_EVENT_MAX_BODY, DEVICE_SERVICE_ID_RE, } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { OnWorkerEvent, Processor, WorkerHost } from "@nestjs/bullmq";
|
|
12
|
+
import { Inject, Injectable, Module } from "@nestjs/common";
|
|
13
|
+
import { sql } from "kysely";
|
|
14
|
+
import { isExtensionEnabled } from "../extensions/enabled.js";
|
|
15
|
+
import { ExtensionsModule } from "../extensions/extensions.module.js";
|
|
16
|
+
import { ExtensionHost } from "../extensions/host.js";
|
|
17
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
18
|
+
import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
|
|
19
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
20
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
21
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
22
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
23
|
+
import { QueueModule } from "../infra/queue/queue.module.js";
|
|
24
|
+
import { runJob } from "../infra/queue/run-job.js";
|
|
25
|
+
import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
|
|
26
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
27
|
+
import { SERVICE_EVENTS_BACKEND } from "./token.js";
|
|
28
|
+
/** The queue of device service event deliveries (one consumer, {@link ServiceEventProcessor}). */
|
|
29
|
+
export const SERVICE_EVENTS_QUEUE = "cap-device-service-events";
|
|
30
|
+
/** The job name of a delivery (registered in `infra/outbox/registry.ts`). */
|
|
31
|
+
export const SERVICE_EVENTS_JOB = "device-service-events";
|
|
32
|
+
/** The sweep of delivered events (scheduler key and lock; no `:`). */
|
|
33
|
+
export const SERVICE_EVENTS_SWEEP_JOB = "device-service-events-sweep";
|
|
34
|
+
/** Delivered events are kept this long, then deleted by the sweep. */
|
|
35
|
+
export const SERVICE_EVENTS_RETAIN_DAYS = 7;
|
|
36
|
+
/** One handler call's time limit. */
|
|
37
|
+
export const SERVICE_EVENT_HANDLER_TIMEOUT_MS = 30_000;
|
|
38
|
+
/** Concurrent deliveries per worker replica (a job whose service is busy ends at once). */
|
|
39
|
+
const DELIVERY_CONCURRENCY = 4;
|
|
40
|
+
/** The lifetime of a delivery lock without renewal (renewed while held). */
|
|
41
|
+
const DELIVERY_LOCK_TTL_MS = 30_000;
|
|
42
|
+
/** Undelivered events read per round of a delivery. */
|
|
43
|
+
const DELIVERY_BATCH = 100;
|
|
44
|
+
/** Delivered events deleted per statement of the sweep. */
|
|
45
|
+
const SWEEP_BATCH = 5_000;
|
|
46
|
+
/** Stalled services owed again per sweep (the next sweep takes the rest). */
|
|
47
|
+
const STALL_BATCH = 1_000;
|
|
48
|
+
/**
|
|
49
|
+
* How old a service's first undelivered event may get before the sweep owes its delivery again:
|
|
50
|
+
* past the delivery job's retries (about 17 minutes) only for an event whose retries ran out, but
|
|
51
|
+
* a job that is still retrying is owed under another id and simply takes the lock in turn.
|
|
52
|
+
*/
|
|
53
|
+
export const SERVICE_EVENTS_STALL_MS = 5 * 60_000;
|
|
54
|
+
/**
|
|
55
|
+
* The deterministic job id of the delivery owed by the event `seq` (no `:`; device ids, extension
|
|
56
|
+
* names and service names carry none). One id per event, not per service: a job of the service
|
|
57
|
+
* that is already running would swallow an add of its own id, and the event stored after its last
|
|
58
|
+
* read would wait for the next one. Deliveries of one service take its lock in turn.
|
|
59
|
+
*/
|
|
60
|
+
export const serviceEventsJobId = (d, seq) => `dse-${d.deviceId}-${d.extension}-${d.service}-${seq}`;
|
|
61
|
+
/** The delivery lock of one service (no `:`; `LockService` adds its prefix). */
|
|
62
|
+
const deliveryLockKey = (d) => `service-events-${d.deviceId}-${d.extension}-${d.service}`;
|
|
63
|
+
const errMsg = (e) => (e instanceof Error ? e.message : String(e));
|
|
64
|
+
/**
|
|
65
|
+
* Device service events (local agents spec, Part 1): a host service on a personal machine emits
|
|
66
|
+
* events; its provider reports each one ({@link record}, `ctx.devices.serviceEvent`) and the
|
|
67
|
+
* kernel delivers it to the extension's `ctx.deviceAccess.onServiceEvent` handler, at least once,
|
|
68
|
+
* in `seq` order per (device, extension, service).
|
|
69
|
+
*
|
|
70
|
+
* - **Store** ({@link record}, any role: the provider's dial-in handler runs on the gateway): the
|
|
71
|
+
* device must be bound to the reporting provider and the service must be a host service the
|
|
72
|
+
* kernel placed there (`device_host_services`) or one it already delivered events of there (a
|
|
73
|
+
* delivery cursor, `device_service_event_cursors`: the events a stopped service sent before its
|
|
74
|
+
* stop still arrive); the row is inserted (a seq stored before is a no-op) with an outbox job
|
|
75
|
+
* owed in the same transaction, so the provider acks the machine only once both are committed.
|
|
76
|
+
* - **Deliver** ({@link deliver}, worker role): under the service's lock, the undelivered rows in
|
|
77
|
+
* `seq` order go to the handler of the extension's instance loaded here, each marked delivered
|
|
78
|
+
* once it resolved. The first failure fails the job (BullMQ retries it) and the events after it
|
|
79
|
+
* wait. An extension not enabled in the org, or loaded without a handler for the service, drops
|
|
80
|
+
* the event with a log line; an extension not loaded on this replica fails the job (another
|
|
81
|
+
* replica or a later attempt has it).
|
|
82
|
+
* - **Sweep** ({@link ServiceEventSweepJob}): delivered rows older than
|
|
83
|
+
* {@link SERVICE_EVENTS_RETAIN_DAYS} days are deleted.
|
|
84
|
+
*/
|
|
85
|
+
let ServiceEvents = class ServiceEvents {
|
|
86
|
+
kdb;
|
|
87
|
+
txHost;
|
|
88
|
+
outbox;
|
|
89
|
+
locks;
|
|
90
|
+
host;
|
|
91
|
+
log;
|
|
92
|
+
constructor(kdb, txHost, outbox, locks,
|
|
93
|
+
/** The extension's instance loaded on this replica, and its handlers. */
|
|
94
|
+
host, log) {
|
|
95
|
+
this.kdb = kdb;
|
|
96
|
+
this.txHost = txHost;
|
|
97
|
+
this.outbox = outbox;
|
|
98
|
+
this.locks = locks;
|
|
99
|
+
this.host = host;
|
|
100
|
+
this.log = log;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Stores one event `provider` reported and owes its delivery. Throws a `TypeError` for a
|
|
104
|
+
* malformed event (seqs start at 1); `not-served` when the device is not bound to `provider`;
|
|
105
|
+
* `dropped` (logged) when the service is not a host service the kernel placed on the device and
|
|
106
|
+
* none of its events was ever delivered there (an event of a service stopped since, still in
|
|
107
|
+
* flight or resent on a reconnect, is stored: the device numbered it, and dropping it would hold
|
|
108
|
+
* the service's next start behind the hole).
|
|
109
|
+
*/
|
|
110
|
+
async record(provider, e) {
|
|
111
|
+
if (typeof e?.deviceId !== "string" || e.deviceId === "")
|
|
112
|
+
throw new TypeError("serviceEvent deviceId must be a device id");
|
|
113
|
+
if (typeof e.service !== "string" || !DEVICE_SERVICE_ID_RE.test(e.service))
|
|
114
|
+
throw new TypeError("serviceEvent service must be the service id <extension>.<service>");
|
|
115
|
+
if (!Number.isSafeInteger(e.seq) || e.seq < 1)
|
|
116
|
+
throw new TypeError("serviceEvent seq must be a positive safe integer (seqs start at 1)");
|
|
117
|
+
if (!(e.body instanceof Uint8Array))
|
|
118
|
+
throw new TypeError("serviceEvent body must be a Uint8Array");
|
|
119
|
+
if (e.body.byteLength > DEVICE_SERVICE_EVENT_MAX_BODY)
|
|
120
|
+
throw new TypeError(`serviceEvent body of ${e.body.byteLength} bytes exceeds ${DEVICE_SERVICE_EVENT_MAX_BODY} bytes`);
|
|
121
|
+
// copied now: what is stored is what was checked
|
|
122
|
+
const body = Buffer.from(e.body);
|
|
123
|
+
const dot = e.service.indexOf(".");
|
|
124
|
+
const extension = e.service.slice(0, dot);
|
|
125
|
+
const service = e.service.slice(dot + 1);
|
|
126
|
+
// org-filter: the device's org is what this lookup finds (the provider's report names only
|
|
127
|
+
// the device); the reporting provider must serve it
|
|
128
|
+
const device = await asPlatform("resolve a reported device's org", () => this.kdb.db
|
|
129
|
+
.selectFrom("devices")
|
|
130
|
+
.select(["org_id", "provider"])
|
|
131
|
+
.where("id", "=", e.deviceId)
|
|
132
|
+
.executeTakeFirst());
|
|
133
|
+
if (!device || device.provider !== provider)
|
|
134
|
+
return "not-served";
|
|
135
|
+
const data = {
|
|
136
|
+
orgId: device.org_id,
|
|
137
|
+
deviceId: e.deviceId,
|
|
138
|
+
extension,
|
|
139
|
+
service,
|
|
140
|
+
};
|
|
141
|
+
const stored = await withOrgScope(device.org_id, () => this.store(data, e.seq, body));
|
|
142
|
+
if (!stored) {
|
|
143
|
+
this.log.warn("device service event dropped: no host service of the kind runs there", {
|
|
144
|
+
deviceId: e.deviceId,
|
|
145
|
+
extension,
|
|
146
|
+
service,
|
|
147
|
+
seq: e.seq,
|
|
148
|
+
});
|
|
149
|
+
return "dropped";
|
|
150
|
+
}
|
|
151
|
+
return "stored";
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* The insert and its owed delivery, in one transaction; false when the service is neither placed
|
|
155
|
+
* on the device nor known there by a delivery cursor (it never ran there as a host service).
|
|
156
|
+
*/
|
|
157
|
+
async store(d, seq, body) {
|
|
158
|
+
const placed = await this.kdb.db
|
|
159
|
+
.selectFrom("device_host_services")
|
|
160
|
+
.select("service")
|
|
161
|
+
.where("org_id", "=", d.orgId)
|
|
162
|
+
.where("device_id", "=", d.deviceId)
|
|
163
|
+
.where("extension", "=", d.extension)
|
|
164
|
+
.where("service", "=", d.service)
|
|
165
|
+
.executeTakeFirst();
|
|
166
|
+
const cursor = await this.kdb.db
|
|
167
|
+
.selectFrom("device_service_event_cursors")
|
|
168
|
+
.select("delivered_seq")
|
|
169
|
+
.where("org_id", "=", d.orgId)
|
|
170
|
+
.where("device_id", "=", d.deviceId)
|
|
171
|
+
.where("extension", "=", d.extension)
|
|
172
|
+
.where("service", "=", d.service)
|
|
173
|
+
.executeTakeFirst();
|
|
174
|
+
// a stopped service's events (its placement is gone) are kept once it delivered there
|
|
175
|
+
if (!placed && !cursor)
|
|
176
|
+
return false;
|
|
177
|
+
const inserted = await this.kdb.db
|
|
178
|
+
.insertInto("device_service_events")
|
|
179
|
+
.values({
|
|
180
|
+
org_id: d.orgId,
|
|
181
|
+
device_id: d.deviceId,
|
|
182
|
+
extension: d.extension,
|
|
183
|
+
service: d.service,
|
|
184
|
+
seq,
|
|
185
|
+
body,
|
|
186
|
+
})
|
|
187
|
+
.onConflict((oc) => oc.columns(["device_id", "extension", "service", "seq"]).doNothing())
|
|
188
|
+
.executeTakeFirst();
|
|
189
|
+
const isNew = Number(inserted.numInsertedOrUpdatedRows ?? 0) > 0;
|
|
190
|
+
if (isNew && cursor && seq <= Number(cursor.delivered_seq))
|
|
191
|
+
// a new event behind the cursor (late after a gap was skipped, or a device directory
|
|
192
|
+
// restored from an older copy) is marked delivered without a handler call
|
|
193
|
+
this.log.warn("device service event seq at or below the delivered cursor; not delivered", {
|
|
194
|
+
deviceId: d.deviceId,
|
|
195
|
+
extension: d.extension,
|
|
196
|
+
service: d.service,
|
|
197
|
+
seq,
|
|
198
|
+
cursor: Number(cursor.delivered_seq),
|
|
199
|
+
});
|
|
200
|
+
if (!isNew) {
|
|
201
|
+
// a resend is the same event; another body under a stored seq breaks the seq contract
|
|
202
|
+
const kept = await this.kdb.db
|
|
203
|
+
.selectFrom("device_service_events")
|
|
204
|
+
.select("body")
|
|
205
|
+
.where("org_id", "=", d.orgId)
|
|
206
|
+
.where("device_id", "=", d.deviceId)
|
|
207
|
+
.where("extension", "=", d.extension)
|
|
208
|
+
.where("service", "=", d.service)
|
|
209
|
+
.where("seq", "=", String(seq))
|
|
210
|
+
.executeTakeFirst();
|
|
211
|
+
if (kept && !kept.body.equals(body))
|
|
212
|
+
this.log.warn("device service event seq stored before with another body; the first is kept", {
|
|
213
|
+
deviceId: d.deviceId,
|
|
214
|
+
extension: d.extension,
|
|
215
|
+
service: d.service,
|
|
216
|
+
seq,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
// owed again for a seq stored before: a delivery whose retries ran out resumes with it
|
|
220
|
+
await this.outbox.add({
|
|
221
|
+
queue: SERVICE_EVENTS_QUEUE,
|
|
222
|
+
name: SERVICE_EVENTS_JOB,
|
|
223
|
+
jobId: serviceEventsJobId(d, seq),
|
|
224
|
+
data: d,
|
|
225
|
+
orgId: d.orgId,
|
|
226
|
+
});
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* One delivery job (the consumer {@link ServiceEventProcessor} calls it, in the job's org
|
|
231
|
+
* scope). Order per service: the seqs right after the service's cursor (the last seq delivered,
|
|
232
|
+
* `device_service_event_cursors`, 0 before the first: seqs start at 1) go out in turn. A gap (a
|
|
233
|
+
* seq not stored yet: the device resends what it was not acked for) holds the delivery, at most
|
|
234
|
+
* {@link SERVICE_EVENTS_STALL_MS} after the event behind it was stored; then the missing seqs are
|
|
235
|
+
* skipped with a warning (the sweep owes the held delivery again). A seq at or below the cursor
|
|
236
|
+
* is a duplicate: marked delivered without a call.
|
|
237
|
+
*
|
|
238
|
+
* The service's lock is only tried, never waited for: a busy lock ends the job at once (no
|
|
239
|
+
* worker slot waits). The holder reads until nothing is deliverable, and after releasing the
|
|
240
|
+
* lock checks once more and owes a `-tail` job when an event stored meanwhile became deliverable.
|
|
241
|
+
*/
|
|
242
|
+
async deliver(d, stop) {
|
|
243
|
+
const lock = await this.locks.acquire(deliveryLockKey(d), {
|
|
244
|
+
ttlMs: DELIVERY_LOCK_TTL_MS,
|
|
245
|
+
waitMs: 0,
|
|
246
|
+
signal: stop,
|
|
247
|
+
});
|
|
248
|
+
// the holder delivers this job's event too, or owes the tail that does
|
|
249
|
+
if (!lock)
|
|
250
|
+
return;
|
|
251
|
+
try {
|
|
252
|
+
const signal = AbortSignal.any([stop, lock.lost]);
|
|
253
|
+
let cursor = await this.cursorOf(d);
|
|
254
|
+
for (;;) {
|
|
255
|
+
signal.throwIfAborted();
|
|
256
|
+
const rows = await this.undelivered(d, DELIVERY_BATCH);
|
|
257
|
+
if (rows.length === 0)
|
|
258
|
+
break;
|
|
259
|
+
let held = false;
|
|
260
|
+
for (const row of rows) {
|
|
261
|
+
signal.throwIfAborted();
|
|
262
|
+
const seq = Number(row.seq);
|
|
263
|
+
if (seq <= cursor) {
|
|
264
|
+
// the same event stored again under its seq after the cursor passed it
|
|
265
|
+
await this.markDelivered(d, seq);
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
if (seq > cursor + 1) {
|
|
269
|
+
if (!gapExpired(row.created_at)) {
|
|
270
|
+
this.log.info("device service events wait for a missing seq", {
|
|
271
|
+
deviceId: d.deviceId,
|
|
272
|
+
extension: d.extension,
|
|
273
|
+
service: d.service,
|
|
274
|
+
missing: cursor + 1,
|
|
275
|
+
next: seq,
|
|
276
|
+
});
|
|
277
|
+
held = true;
|
|
278
|
+
break;
|
|
279
|
+
}
|
|
280
|
+
this.log.warn(`device service events skipped missing seqs ${cursor + 1}..${seq - 1}`, {
|
|
281
|
+
deviceId: d.deviceId,
|
|
282
|
+
extension: d.extension,
|
|
283
|
+
service: d.service,
|
|
284
|
+
from: cursor + 1,
|
|
285
|
+
to: seq - 1,
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
await this.deliverOne(d, seq, row.body, signal);
|
|
289
|
+
cursor = seq;
|
|
290
|
+
}
|
|
291
|
+
if (held)
|
|
292
|
+
break;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
finally {
|
|
296
|
+
await lock.release();
|
|
297
|
+
}
|
|
298
|
+
await this.oweTailIfDeliverable(d);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* After the lock is released: when the service's first undelivered event can go now (an event
|
|
302
|
+
* stored while the holder was past its last read, whose own job found the lock busy), owes one
|
|
303
|
+
* tail delivery for it.
|
|
304
|
+
*/
|
|
305
|
+
async oweTailIfDeliverable(d) {
|
|
306
|
+
const [first] = await this.undelivered(d, 1);
|
|
307
|
+
if (!first)
|
|
308
|
+
return;
|
|
309
|
+
const seq = Number(first.seq);
|
|
310
|
+
const cursor = await this.cursorOf(d);
|
|
311
|
+
if (seq > cursor + 1 && !gapExpired(first.created_at))
|
|
312
|
+
return;
|
|
313
|
+
await this.oweTail(d, seq);
|
|
314
|
+
}
|
|
315
|
+
async oweTail(d, seq) {
|
|
316
|
+
await this.outbox.add({
|
|
317
|
+
queue: SERVICE_EVENTS_QUEUE,
|
|
318
|
+
name: SERVICE_EVENTS_JOB,
|
|
319
|
+
jobId: `${serviceEventsJobId(d, seq)}-tail`,
|
|
320
|
+
data: d,
|
|
321
|
+
orgId: d.orgId,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
/** The service's undelivered events in seq order (at most `limit`). */
|
|
325
|
+
undelivered(d, limit) {
|
|
326
|
+
return this.kdb.db
|
|
327
|
+
.selectFrom("device_service_events")
|
|
328
|
+
.select(["seq", "body", "created_at"])
|
|
329
|
+
.where("org_id", "=", d.orgId)
|
|
330
|
+
.where("device_id", "=", d.deviceId)
|
|
331
|
+
.where("extension", "=", d.extension)
|
|
332
|
+
.where("service", "=", d.service)
|
|
333
|
+
.where("delivered_at", "is", null)
|
|
334
|
+
.orderBy("seq")
|
|
335
|
+
.limit(limit)
|
|
336
|
+
.execute();
|
|
337
|
+
}
|
|
338
|
+
/** The last seq delivered for the service (0 before the first). */
|
|
339
|
+
async cursorOf(d) {
|
|
340
|
+
const row = await this.kdb.db
|
|
341
|
+
.selectFrom("device_service_event_cursors")
|
|
342
|
+
.select("delivered_seq")
|
|
343
|
+
.where("org_id", "=", d.orgId)
|
|
344
|
+
.where("device_id", "=", d.deviceId)
|
|
345
|
+
.where("extension", "=", d.extension)
|
|
346
|
+
.where("service", "=", d.service)
|
|
347
|
+
.executeTakeFirst();
|
|
348
|
+
return row ? Number(row.delivered_seq) : 0;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Owes the delivery again of every service whose first undelivered event is older than
|
|
352
|
+
* {@link SERVICE_EVENTS_STALL_MS} (its job ran out of retries, or a gap holds it), under a fresh
|
|
353
|
+
* id per stall window; logs a stall once (`stalled_at`). Returns the services owed again.
|
|
354
|
+
*/
|
|
355
|
+
async resumeStalled(signal) {
|
|
356
|
+
// org-filter: deployment-wide scan for stalled deliveries, in every org; each one is owed
|
|
357
|
+
// again in its own org's scope
|
|
358
|
+
const stalled = await asPlatform("find stalled device service event deliveries", () => this.kdb.db
|
|
359
|
+
.selectFrom("device_service_events")
|
|
360
|
+
.distinctOn(["org_id", "device_id", "extension", "service"])
|
|
361
|
+
.select(["org_id", "device_id", "extension", "service", "seq", "stalled_at"])
|
|
362
|
+
.where("delivered_at", "is", null)
|
|
363
|
+
.where("created_at", "<", sql `now() - make_interval(secs => ${SERVICE_EVENTS_STALL_MS / 1000})`)
|
|
364
|
+
.orderBy("org_id")
|
|
365
|
+
.orderBy("device_id")
|
|
366
|
+
.orderBy("extension")
|
|
367
|
+
.orderBy("service")
|
|
368
|
+
.orderBy("seq")
|
|
369
|
+
.limit(STALL_BATCH)
|
|
370
|
+
.execute());
|
|
371
|
+
const windowId = Math.floor(Date.now() / SERVICE_EVENTS_STALL_MS);
|
|
372
|
+
for (const r of stalled) {
|
|
373
|
+
signal?.throwIfAborted();
|
|
374
|
+
const d = {
|
|
375
|
+
orgId: r.org_id,
|
|
376
|
+
deviceId: r.device_id,
|
|
377
|
+
extension: r.extension,
|
|
378
|
+
service: r.service,
|
|
379
|
+
};
|
|
380
|
+
const seq = Number(r.seq);
|
|
381
|
+
const first = await withOrgScope(d.orgId, () => this.oweAgain(d, seq, windowId));
|
|
382
|
+
if (first)
|
|
383
|
+
this.log.warn("device service event delivery stalled; owed again", {
|
|
384
|
+
deviceId: d.deviceId,
|
|
385
|
+
extension: d.extension,
|
|
386
|
+
service: d.service,
|
|
387
|
+
seq,
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
return stalled.length;
|
|
391
|
+
}
|
|
392
|
+
/** The stalled delivery owed again; true when the stall of `seq` was not noted before. */
|
|
393
|
+
async oweAgain(d, seq, windowId) {
|
|
394
|
+
const noted = await this.kdb.db
|
|
395
|
+
.updateTable("device_service_events")
|
|
396
|
+
.set({ stalled_at: sql `now()` })
|
|
397
|
+
.where("org_id", "=", d.orgId)
|
|
398
|
+
.where("device_id", "=", d.deviceId)
|
|
399
|
+
.where("extension", "=", d.extension)
|
|
400
|
+
.where("service", "=", d.service)
|
|
401
|
+
.where("seq", "=", String(seq))
|
|
402
|
+
.where("stalled_at", "is", null)
|
|
403
|
+
.executeTakeFirst();
|
|
404
|
+
await this.outbox.add({
|
|
405
|
+
queue: SERVICE_EVENTS_QUEUE,
|
|
406
|
+
name: SERVICE_EVENTS_JOB,
|
|
407
|
+
jobId: `${serviceEventsJobId(d, seq)}-stall${windowId}`,
|
|
408
|
+
data: d,
|
|
409
|
+
orgId: d.orgId,
|
|
410
|
+
});
|
|
411
|
+
return Number(noted.numUpdatedRows) > 0;
|
|
412
|
+
}
|
|
413
|
+
/** One event: to the handler, or dropped with a log line; then marked delivered. */
|
|
414
|
+
async deliverOne(d, seq, body, signal) {
|
|
415
|
+
const fields = { deviceId: d.deviceId, extension: d.extension, service: d.service, seq };
|
|
416
|
+
if (!(await isExtensionEnabled(this.kdb.db, d.orgId, d.extension))) {
|
|
417
|
+
this.log.info("device service event dropped: the extension is not enabled in the org", {
|
|
418
|
+
...fields,
|
|
419
|
+
orgId: d.orgId,
|
|
420
|
+
});
|
|
421
|
+
return this.markDelivered(d, seq);
|
|
422
|
+
}
|
|
423
|
+
const instance = this.host.current(d.extension);
|
|
424
|
+
// another replica or a later attempt may have it loaded
|
|
425
|
+
if (!instance)
|
|
426
|
+
throw new Error(`extension ${d.extension} is not loaded on this replica`);
|
|
427
|
+
const handler = instance.serviceEventHandlers.get(d.service);
|
|
428
|
+
if (!handler) {
|
|
429
|
+
this.log.warn("device service event dropped: the extension registered no handler", fields);
|
|
430
|
+
return this.markDelivered(d, seq);
|
|
431
|
+
}
|
|
432
|
+
const accountId = await this.ownerOf(d);
|
|
433
|
+
if (accountId === undefined) {
|
|
434
|
+
this.log.info("device service event dropped: the device is gone", fields);
|
|
435
|
+
return this.markDelivered(d, seq);
|
|
436
|
+
}
|
|
437
|
+
const event = {
|
|
438
|
+
orgId: d.orgId,
|
|
439
|
+
deviceId: d.deviceId,
|
|
440
|
+
accountId,
|
|
441
|
+
body: new Uint8Array(body),
|
|
442
|
+
seq,
|
|
443
|
+
};
|
|
444
|
+
await instance.inflight.run(signal, (s) => callWithin(() => handler(event), s));
|
|
445
|
+
await this.markDelivered(d, seq);
|
|
446
|
+
}
|
|
447
|
+
/** The device's owner (the person the host service runs for); undefined when it is gone. */
|
|
448
|
+
async ownerOf(d) {
|
|
449
|
+
const row = await this.kdb.db
|
|
450
|
+
.selectFrom("devices")
|
|
451
|
+
.select("owner_account_id")
|
|
452
|
+
.where("org_id", "=", d.orgId)
|
|
453
|
+
.where("id", "=", d.deviceId)
|
|
454
|
+
.executeTakeFirst();
|
|
455
|
+
return row?.owner_account_id;
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Marks the event delivered and moves the service's cursor to it, in one transaction.
|
|
459
|
+
*
|
|
460
|
+
* Lock order: `devices` (`FOR KEY SHARE`), then `device_service_events`, then
|
|
461
|
+
* `device_service_event_cursors`, matching `DELETE FROM devices` (cascade order from migration
|
|
462
|
+
* 0223) and `AccountDeviceCleanup.batch`. Taking `FOR KEY SHARE` on `devices` first prevents a
|
|
463
|
+
* deadlock when inserting a new cursor row (whose foreign key check locks `devices`), and
|
|
464
|
+
* updating `device_service_events` before `device_service_event_cursors` prevents a deadlock
|
|
465
|
+
* against the cascade order when updating an existing cursor.
|
|
466
|
+
*/
|
|
467
|
+
async markDelivered(d, seq) {
|
|
468
|
+
const device = await this.kdb.db
|
|
469
|
+
.selectFrom("devices")
|
|
470
|
+
.select("id")
|
|
471
|
+
.where("org_id", "=", d.orgId)
|
|
472
|
+
.where("id", "=", d.deviceId)
|
|
473
|
+
.forKeyShare()
|
|
474
|
+
.executeTakeFirst();
|
|
475
|
+
if (!device)
|
|
476
|
+
return;
|
|
477
|
+
await this.kdb.db
|
|
478
|
+
.updateTable("device_service_events")
|
|
479
|
+
.set({ delivered_at: sql `now()` })
|
|
480
|
+
.where("org_id", "=", d.orgId)
|
|
481
|
+
.where("device_id", "=", d.deviceId)
|
|
482
|
+
.where("extension", "=", d.extension)
|
|
483
|
+
.where("service", "=", d.service)
|
|
484
|
+
.where("seq", "=", String(seq))
|
|
485
|
+
.where("delivered_at", "is", null)
|
|
486
|
+
.execute();
|
|
487
|
+
await this.kdb.db
|
|
488
|
+
.insertInto("device_service_event_cursors")
|
|
489
|
+
.values({
|
|
490
|
+
org_id: d.orgId,
|
|
491
|
+
device_id: d.deviceId,
|
|
492
|
+
extension: d.extension,
|
|
493
|
+
service: d.service,
|
|
494
|
+
delivered_seq: seq,
|
|
495
|
+
})
|
|
496
|
+
.onConflict((oc) => oc.columns(["device_id", "extension", "service"]).doUpdateSet({
|
|
497
|
+
delivered_seq: sql `GREATEST(device_service_event_cursors.delivered_seq, excluded.delivered_seq)`,
|
|
498
|
+
updated_at: sql `now()`,
|
|
499
|
+
}))
|
|
500
|
+
.execute();
|
|
501
|
+
}
|
|
502
|
+
/** A job failed (the worker's `failed` event): a retry warns, the last attempt logs an error. */
|
|
503
|
+
onFailed(j, err) {
|
|
504
|
+
if (!j)
|
|
505
|
+
return;
|
|
506
|
+
const fields = {
|
|
507
|
+
jobId: j.id,
|
|
508
|
+
deviceId: j.data.deviceId,
|
|
509
|
+
extension: j.data.extension,
|
|
510
|
+
service: j.data.service,
|
|
511
|
+
attempt: j.attemptsMade,
|
|
512
|
+
error: errMsg(err),
|
|
513
|
+
};
|
|
514
|
+
if (j.attemptsMade >= (j.opts.attempts ?? 1))
|
|
515
|
+
this.log.error("device service event delivery failed on its last attempt; the sweep owes it again", fields);
|
|
516
|
+
else
|
|
517
|
+
this.log.warn("device service event delivery failed; retrying", fields);
|
|
518
|
+
}
|
|
519
|
+
};
|
|
520
|
+
__decorate([
|
|
521
|
+
Transactional()
|
|
522
|
+
], ServiceEvents.prototype, "store", null);
|
|
523
|
+
__decorate([
|
|
524
|
+
Transactional()
|
|
525
|
+
], ServiceEvents.prototype, "oweTail", null);
|
|
526
|
+
__decorate([
|
|
527
|
+
Transactional()
|
|
528
|
+
], ServiceEvents.prototype, "oweAgain", null);
|
|
529
|
+
__decorate([
|
|
530
|
+
Transactional()
|
|
531
|
+
], ServiceEvents.prototype, "markDelivered", null);
|
|
532
|
+
ServiceEvents = __decorate([
|
|
533
|
+
Injectable(),
|
|
534
|
+
__param(0, Inject(KernelDb)),
|
|
535
|
+
__param(1, Inject(TransactionHost)),
|
|
536
|
+
__param(2, Inject(OutboxService)),
|
|
537
|
+
__param(3, Inject(LockService)),
|
|
538
|
+
__param(4, Inject(ExtensionHost)),
|
|
539
|
+
__param(5, Inject(KERNEL_LOGGER))
|
|
540
|
+
], ServiceEvents);
|
|
541
|
+
export { ServiceEvents };
|
|
542
|
+
/** Whether a gap held before the event stored at `createdAt` has been waited out. */
|
|
543
|
+
const gapExpired = (createdAt) => Date.now() - new Date(createdAt).getTime() >= SERVICE_EVENTS_STALL_MS;
|
|
544
|
+
/** Runs `fn`, rejecting after {@link SERVICE_EVENT_HANDLER_TIMEOUT_MS} or when `signal` aborts. */
|
|
545
|
+
async function callWithin(fn, signal) {
|
|
546
|
+
const limit = AbortSignal.any([signal, AbortSignal.timeout(SERVICE_EVENT_HANDLER_TIMEOUT_MS)]);
|
|
547
|
+
limit.throwIfAborted();
|
|
548
|
+
let onAbort = () => { };
|
|
549
|
+
const aborted = new Promise((_, reject) => {
|
|
550
|
+
onAbort = () => reject(limit.reason);
|
|
551
|
+
limit.addEventListener("abort", onAbort, { once: true });
|
|
552
|
+
});
|
|
553
|
+
aborted.catch(() => { });
|
|
554
|
+
try {
|
|
555
|
+
await Promise.race([Promise.resolve().then(fn), aborted]);
|
|
556
|
+
}
|
|
557
|
+
finally {
|
|
558
|
+
limit.removeEventListener("abort", onAbort);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* The consumer of {@link SERVICE_EVENTS_QUEUE}: {@link ServiceEvents.deliver}. Worker role only
|
|
563
|
+
* (`DeviceServiceEventWorkersModule`); built with `autorun: false`, started by the worker role
|
|
564
|
+
* after the extensions loaded (their handlers are registered at setup).
|
|
565
|
+
*/
|
|
566
|
+
let ServiceEventProcessor = class ServiceEventProcessor extends WorkerHost {
|
|
567
|
+
events;
|
|
568
|
+
log;
|
|
569
|
+
stopping = new AbortController();
|
|
570
|
+
constructor(events, log) {
|
|
571
|
+
super();
|
|
572
|
+
this.events = events;
|
|
573
|
+
this.log = log;
|
|
574
|
+
}
|
|
575
|
+
async process(job) {
|
|
576
|
+
// the queue's only job; anything else (a malformed add) is never run without its org
|
|
577
|
+
const d = job.data;
|
|
578
|
+
if (job.name !== SERVICE_EVENTS_JOB ||
|
|
579
|
+
[d?.orgId, d?.deviceId, d?.extension, d?.service].some((v) => typeof v !== "string" || !v)) {
|
|
580
|
+
this.log.error("device service event job ignored: not a delivery", {
|
|
581
|
+
jobId: job.id,
|
|
582
|
+
name: job.name,
|
|
583
|
+
});
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
return runJob(SERVICE_EVENTS_QUEUE, job, () => this.events.deliver(job.data, this.stopping.signal));
|
|
587
|
+
}
|
|
588
|
+
/** Starts consuming (worker role, after the extensions loaded). */
|
|
589
|
+
start() {
|
|
590
|
+
void this.worker.run().catch((err) => this.error(err));
|
|
591
|
+
}
|
|
592
|
+
/** Aborts the handler calls in flight (retried) and closes the worker. */
|
|
593
|
+
async close() {
|
|
594
|
+
this.stopping.abort(new Error("replica stopping"));
|
|
595
|
+
await this.worker.close();
|
|
596
|
+
}
|
|
597
|
+
failed(job, err) {
|
|
598
|
+
this.events.onFailed(job, err);
|
|
599
|
+
}
|
|
600
|
+
error(err) {
|
|
601
|
+
this.log.error("device service event worker error", { err });
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
__decorate([
|
|
605
|
+
OnWorkerEvent("failed")
|
|
606
|
+
], ServiceEventProcessor.prototype, "failed", null);
|
|
607
|
+
__decorate([
|
|
608
|
+
OnWorkerEvent("error")
|
|
609
|
+
], ServiceEventProcessor.prototype, "error", null);
|
|
610
|
+
ServiceEventProcessor = __decorate([
|
|
611
|
+
Injectable(),
|
|
612
|
+
Processor(SERVICE_EVENTS_QUEUE, { autorun: false, concurrency: DELIVERY_CONCURRENCY }),
|
|
613
|
+
__param(0, Inject(ServiceEvents)),
|
|
614
|
+
__param(1, Inject(KERNEL_LOGGER))
|
|
615
|
+
], ServiceEventProcessor);
|
|
616
|
+
export { ServiceEventProcessor };
|
|
617
|
+
/**
|
|
618
|
+
* The device service event sweep, every 5 minutes (a `@LockedCron`, once per tick across
|
|
619
|
+
* replicas, under `WorkerModule`): owes again the deliveries that stalled
|
|
620
|
+
* ({@link ServiceEvents.resumeStalled}: a job whose retries ran out leaves its events undelivered
|
|
621
|
+
* until something owes a delivery of the service again), then deletes delivered events older
|
|
622
|
+
* than {@link SERVICE_EVENTS_RETAIN_DAYS} days, in batches.
|
|
623
|
+
*/
|
|
624
|
+
let ServiceEventSweepJob = class ServiceEventSweepJob {
|
|
625
|
+
kdb;
|
|
626
|
+
events;
|
|
627
|
+
lockService;
|
|
628
|
+
log;
|
|
629
|
+
constructor(kdb, events, lockService, log) {
|
|
630
|
+
this.kdb = kdb;
|
|
631
|
+
this.events = events;
|
|
632
|
+
this.lockService = lockService;
|
|
633
|
+
this.log = log;
|
|
634
|
+
}
|
|
635
|
+
async sweep(signal) {
|
|
636
|
+
const r = await this.runOnce(signal);
|
|
637
|
+
if (r.deleted > 0)
|
|
638
|
+
this.log.info("delivered device service events deleted", { count: r.deleted });
|
|
639
|
+
}
|
|
640
|
+
/** One sweep (the test seam): the stalled services owed again and the rows deleted. */
|
|
641
|
+
async runOnce(signal) {
|
|
642
|
+
const resumed = await this.events.resumeStalled(signal);
|
|
643
|
+
return { resumed, deleted: await this.deleteDelivered(signal) };
|
|
644
|
+
}
|
|
645
|
+
async deleteDelivered(signal) {
|
|
646
|
+
let total = 0;
|
|
647
|
+
for (;;) {
|
|
648
|
+
signal?.throwIfAborted();
|
|
649
|
+
const n = await asPlatform("sweep delivered device service events", async () => {
|
|
650
|
+
// org-filter: deployment-wide sweep of delivered events past their retention, in every org
|
|
651
|
+
const r = await sql `
|
|
652
|
+
DELETE FROM capybara.device_service_events
|
|
653
|
+
WHERE ctid IN (
|
|
654
|
+
SELECT ctid FROM capybara.device_service_events
|
|
655
|
+
WHERE delivered_at IS NOT NULL
|
|
656
|
+
AND delivered_at < now() - make_interval(days => ${SERVICE_EVENTS_RETAIN_DAYS})
|
|
657
|
+
LIMIT ${SWEEP_BATCH}
|
|
658
|
+
)`.execute(this.kdb.db);
|
|
659
|
+
return Number(r.numAffectedRows ?? 0);
|
|
660
|
+
});
|
|
661
|
+
total += n;
|
|
662
|
+
if (n < SWEEP_BATCH)
|
|
663
|
+
return total;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
};
|
|
667
|
+
__decorate([
|
|
668
|
+
LockedCron("*/5 * * * *", { name: SERVICE_EVENTS_SWEEP_JOB })
|
|
669
|
+
], ServiceEventSweepJob.prototype, "sweep", null);
|
|
670
|
+
ServiceEventSweepJob = __decorate([
|
|
671
|
+
Injectable(),
|
|
672
|
+
__param(0, Inject(KernelDb)),
|
|
673
|
+
__param(1, Inject(ServiceEvents)),
|
|
674
|
+
__param(2, Inject(LockService)),
|
|
675
|
+
__param(3, Inject(KERNEL_LOGGER))
|
|
676
|
+
], ServiceEventSweepJob);
|
|
677
|
+
export { ServiceEventSweepJob };
|
|
678
|
+
const SERVICE_EVENTS_QUEUE_MODULE = QueueModule.registerQueue(SERVICE_EVENTS_QUEUE);
|
|
679
|
+
/**
|
|
680
|
+
* Device service events on every role: storing them (`ctx.devices.serviceEvent`, found by the
|
|
681
|
+
* extension host at the time of use through {@link SERVICE_EVENTS_BACKEND}) and the queue the
|
|
682
|
+
* outbox adds their deliveries to.
|
|
683
|
+
*/
|
|
684
|
+
let DeviceServiceEventsModule = class DeviceServiceEventsModule {
|
|
685
|
+
};
|
|
686
|
+
DeviceServiceEventsModule = __decorate([
|
|
687
|
+
Module({
|
|
688
|
+
imports: [ExtensionsModule, SERVICE_EVENTS_QUEUE_MODULE],
|
|
689
|
+
providers: [ServiceEvents, { provide: SERVICE_EVENTS_BACKEND, useExisting: ServiceEvents }],
|
|
690
|
+
exports: [ServiceEvents, SERVICE_EVENTS_BACKEND, SERVICE_EVENTS_QUEUE_MODULE],
|
|
691
|
+
})
|
|
692
|
+
], DeviceServiceEventsModule);
|
|
693
|
+
export { DeviceServiceEventsModule };
|
|
694
|
+
/** The deliveries' consumer and the sweep; imported only by the worker role (`WorkerModule`). */
|
|
695
|
+
let DeviceServiceEventWorkersModule = class DeviceServiceEventWorkersModule {
|
|
696
|
+
};
|
|
697
|
+
DeviceServiceEventWorkersModule = __decorate([
|
|
698
|
+
Module({
|
|
699
|
+
imports: [DeviceServiceEventsModule],
|
|
700
|
+
providers: [ServiceEventProcessor, ServiceEventSweepJob],
|
|
701
|
+
exports: [ServiceEventProcessor],
|
|
702
|
+
})
|
|
703
|
+
], DeviceServiceEventWorkersModule);
|
|
704
|
+
export { DeviceServiceEventWorkersModule };
|