@ovok/core 0.4.49 → 0.4.51

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.
Files changed (79) hide show
  1. package/dist/client/cms/locale.d.ts +3 -3
  2. package/dist/client/cms/locale.js +14 -2
  3. package/dist/client/observation/fhir-systems.d.ts +12 -0
  4. package/dist/client/observation/fhir-systems.js +13 -1
  5. package/dist/client/observation/observation-groups.d.ts +4 -3
  6. package/dist/client/observation/observation-groups.js +8 -4
  7. package/dist/client/observation/series.d.ts +23 -3
  8. package/dist/client/observation/series.js +22 -4
  9. package/dist/client/observation/services/ecg-observation-fragments.js +1 -0
  10. package/dist/client/observation/types/generate-observation-body/GenerateObservationBodyParams.d.ts +2 -0
  11. package/dist/client/offline/offline-measurement-queue.d.ts +3 -1
  12. package/dist/client/offline/offline-measurement-queue.js +2 -1
  13. package/dist/conformance/capability-requirements.js +1 -1
  14. package/dist/next/config/ovok-config.d.ts +18 -0
  15. package/dist/next/config/settings.js +10 -1
  16. package/dist/next/errors/ovok-errors.d.ts +7 -0
  17. package/dist/next/errors/ovok-errors.js +9 -1
  18. package/dist/next/http/transmit.js +4 -2
  19. package/dist/next/index.d.ts +15 -1
  20. package/dist/next/index.js +18 -1
  21. package/dist/next/logging/ovok-logger.d.ts +26 -0
  22. package/dist/next/logging/ovok-logger.js +10 -0
  23. package/dist/next/outbox/entry-observation.d.ts +3 -0
  24. package/dist/next/outbox/entry-observation.js +6 -0
  25. package/dist/next/outbox/failure-policy.d.ts +45 -0
  26. package/dist/next/outbox/failure-policy.js +92 -0
  27. package/dist/next/outbox/group-links.d.ts +19 -0
  28. package/dist/next/outbox/group-links.js +65 -0
  29. package/dist/next/outbox/indexed-db-outbox-store.d.ts +38 -0
  30. package/dist/next/outbox/indexed-db-outbox-store.js +90 -0
  31. package/dist/next/outbox/item-settler.d.ts +37 -0
  32. package/dist/next/outbox/item-settler.js +49 -0
  33. package/dist/next/outbox/legacy-queue-import.d.ts +7 -0
  34. package/dist/next/outbox/legacy-queue-import.js +50 -0
  35. package/dist/next/outbox/memory-outbox-store.d.ts +22 -0
  36. package/dist/next/outbox/memory-outbox-store.js +40 -0
  37. package/dist/next/outbox/outbox-items.d.ts +17 -0
  38. package/dist/next/outbox/outbox-items.js +89 -0
  39. package/dist/next/outbox/outbox-queries.d.ts +4 -0
  40. package/dist/next/outbox/outbox-queries.js +9 -0
  41. package/dist/next/outbox/outbox-resource.d.ts +73 -0
  42. package/dist/next/outbox/outbox-resource.js +170 -0
  43. package/dist/next/outbox/outbox-runner.d.ts +56 -0
  44. package/dist/next/outbox/outbox-runner.js +179 -0
  45. package/dist/next/outbox/outbox-snapshot.d.ts +3 -0
  46. package/dist/next/outbox/outbox-snapshot.js +40 -0
  47. package/dist/next/outbox/outbox-store.d.ts +21 -0
  48. package/dist/next/outbox/outbox-store.js +2 -0
  49. package/dist/next/outbox/outbox-triggers.d.ts +30 -0
  50. package/dist/next/outbox/outbox-triggers.js +38 -0
  51. package/dist/next/outbox/outbox-types.d.ts +138 -0
  52. package/dist/next/outbox/outbox-types.js +2 -0
  53. package/dist/next/outbox/outcome-handlers.d.ts +30 -0
  54. package/dist/next/outbox/outcome-handlers.js +50 -0
  55. package/dist/next/outbox/pending-saves.d.ts +6 -0
  56. package/dist/next/outbox/pending-saves.js +18 -0
  57. package/dist/next/outbox/request-budget.d.ts +10 -0
  58. package/dist/next/outbox/request-budget.js +22 -0
  59. package/dist/next/outbox/request-planner.d.ts +5 -0
  60. package/dist/next/outbox/request-planner.js +39 -0
  61. package/dist/next/outbox/runner-state.d.ts +34 -0
  62. package/dist/next/outbox/runner-state.js +61 -0
  63. package/dist/next/outbox/store-contract.d.ts +19 -0
  64. package/dist/next/outbox/store-contract.js +108 -0
  65. package/dist/next/outbox/wakeup.d.ts +11 -0
  66. package/dist/next/outbox/wakeup.js +34 -0
  67. package/dist/next/ovok.d.ts +3 -0
  68. package/dist/next/ovok.js +13 -2
  69. package/dist/next/react/index.d.ts +11 -1
  70. package/dist/next/react/index.js +15 -1
  71. package/dist/next/resources/measurements/measurement-sender.d.ts +27 -0
  72. package/dist/next/resources/measurements/measurement-sender.js +66 -0
  73. package/dist/next/resources/measurements/measurements-resource.d.ts +36 -25
  74. package/dist/next/resources/measurements/measurements-resource.js +62 -65
  75. package/dist/next/resources/measurements/observation-builder.js +6 -3
  76. package/dist/next/resources/measurements/offline-measurement-queue-types.d.ts +12 -14
  77. package/dist/next/resources/measurements/offline-measurement-queue.d.ts +4 -23
  78. package/dist/next/resources/measurements/offline-measurement-queue.js +18 -143
  79. package/package.json +1 -1
@@ -0,0 +1,73 @@
1
+ import type { OutboxTransport } from "./outbox-runner";
2
+ import type { OutboxStore } from "./outbox-store";
3
+ import type { OutboxConnectivity, OutboxLifecycle } from "./outbox-triggers";
4
+ import type { OutboxDeleteTarget, OutboxFlushResult, OutboxItemSummary, OutboxSentItem, OutboxSnapshot } from "./outbox-types";
5
+ import type { RequestOptions } from "../http/transmit";
6
+ import type { OvokLogger } from "../logging/ovok-logger";
7
+ import type { OvokStorage } from "../storage/ovok-storage";
8
+ import type { Observation } from "@medplum/fhirtypes";
9
+ import { FlushReport } from "./item-settler";
10
+ import { OutboxDraft } from "./outbox-items";
11
+ /** What the outbox needs from the client around it. */
12
+ export type OutboxSettings = {
13
+ store?: OutboxStore;
14
+ transport: OutboxTransport;
15
+ ownerKey: () => Promise<string | null>;
16
+ signedInProfile: () => Promise<string>;
17
+ onSessionChange: (listener: () => void) => () => void;
18
+ connectivity: OutboxConnectivity;
19
+ lifecycle: OutboxLifecycle;
20
+ requestBudget: number;
21
+ logger: OvokLogger;
22
+ legacyQueue?: {
23
+ storage: OvokStorage;
24
+ key: string;
25
+ };
26
+ now?: () => number;
27
+ };
28
+ /**
29
+ * Measurements waiting to be sent, kept on the device until the server accepts them. Saves go in here first, so a
30
+ * reading is never lost to a dropped connection, and it is sent newest first, within the rate limit, whenever the
31
+ * connection returns.
32
+ *
33
+ * @category outbox
34
+ */
35
+ export declare class OutboxResource {
36
+ private readonly settings;
37
+ private readonly store;
38
+ private readonly runner;
39
+ private readonly ready;
40
+ private readonly listeners;
41
+ private readonly log;
42
+ private readonly now;
43
+ private notifications;
44
+ constructor(settings: OutboxSettings);
45
+ /** What the signed-in account has waiting and what the outbox is doing now. */
46
+ snapshot(): Promise<OutboxSnapshot>;
47
+ /** The signed-in account's items in any state, newest first, without their entries. */
48
+ items(): Promise<OutboxItemSummary[]>;
49
+ /** The last 50 items the server accepted, newest first. */
50
+ recentlySent(): OutboxSentItem[];
51
+ /** Calls `listener` with the snapshot now and after every change; returns a function that stops listening. */
52
+ subscribe(listener: (snapshot: OutboxSnapshot) => void): () => void;
53
+ /** Sends what is due now and resolves when nothing more can go. */
54
+ flush(options?: RequestOptions): Promise<OutboxFlushResult>;
55
+ /** Puts refused items back to pending, the given ones or all of them, and returns how many. */
56
+ resend(ids?: string[]): Promise<number>;
57
+ /** Deletes an item that has not been sent; a reading discarded here is not saved. */
58
+ discard(id: string): Promise<void>;
59
+ /** The observations of the pending items, for showing readings that are not saved yet. */
60
+ pendingObservations(): Promise<Observation[]>;
61
+ /** Queues the deletion of the observations with an identifier, for readings that were saved before. */
62
+ enqueueDelete(target: OutboxDeleteTarget): Promise<void>;
63
+ /** @internal Stores items for sending; a newer version of a series or segment replaces the stored one. */
64
+ enqueue(ownerKey: string, drafts: OutboxDraft[]): Promise<void>;
65
+ /** @internal Sends what is due now and reports what happened to each item. */
66
+ flushReport(options?: RequestOptions): Promise<FlushReport>;
67
+ private storeDraft;
68
+ private resendOne;
69
+ private storedSummaries;
70
+ private importOldQueue;
71
+ private wakeAfterReady;
72
+ private notify;
73
+ }
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OutboxResource = void 0;
4
+ const ovok_errors_1 = require("../errors/ovok-errors");
5
+ const ovok_logger_1 = require("../logging/ovok-logger");
6
+ const entry_observation_1 = require("./entry-observation");
7
+ const legacy_queue_import_1 = require("./legacy-queue-import");
8
+ const memory_outbox_store_1 = require("./memory-outbox-store");
9
+ const outbox_items_1 = require("./outbox-items");
10
+ const outbox_queries_1 = require("./outbox-queries");
11
+ const outbox_runner_1 = require("./outbox-runner");
12
+ const outbox_snapshot_1 = require("./outbox-snapshot");
13
+ const pending_saves_1 = require("./pending-saves");
14
+ const request_budget_1 = require("./request-budget");
15
+ const STARTUP_DELAY_MS = 1000;
16
+ const ENQUEUE_DELAY_MS = 1000;
17
+ /**
18
+ * Measurements waiting to be sent, kept on the device until the server accepts them. Saves go in here first, so a
19
+ * reading is never lost to a dropped connection, and it is sent newest first, within the rate limit, whenever the
20
+ * connection returns.
21
+ *
22
+ * @category outbox
23
+ */
24
+ class OutboxResource {
25
+ constructor(settings) {
26
+ var _a, _b;
27
+ this.settings = settings;
28
+ this.listeners = new Set();
29
+ this.notifications = 0;
30
+ this.store = (_a = settings.store) !== null && _a !== void 0 ? _a : new memory_outbox_store_1.MemoryOutboxStore();
31
+ this.now = (_b = settings.now) !== null && _b !== void 0 ? _b : Date.now;
32
+ this.log = (0, ovok_logger_1.scopedLogger)(settings.logger, "outbox");
33
+ this.runner = new outbox_runner_1.OutboxRunner({
34
+ store: this.store,
35
+ transport: settings.transport,
36
+ ownerKey: settings.ownerKey,
37
+ budget: new request_budget_1.RequestBudget(settings.requestBudget),
38
+ logger: this.log,
39
+ now: this.now,
40
+ changed: () => this.notify(),
41
+ });
42
+ this.ready = this.importOldQueue();
43
+ this.wakeAfterReady(STARTUP_DELAY_MS);
44
+ [settings.connectivity, settings.lifecycle].forEach((trigger) => trigger.subscribe(() => this.wakeAfterReady(0)));
45
+ settings.onSessionChange(() => {
46
+ this.wakeAfterReady(0);
47
+ this.notify();
48
+ });
49
+ }
50
+ /** What the signed-in account has waiting and what the outbox is doing now. */
51
+ async snapshot() {
52
+ return (0, outbox_snapshot_1.buildSnapshot)(await this.storedSummaries(), this.runner.view());
53
+ }
54
+ /** The signed-in account's items in any state, newest first, without their entries. */
55
+ async items() {
56
+ return (await this.storedSummaries()).sort(outbox_queries_1.newestFirst);
57
+ }
58
+ /** The last 50 items the server accepted, newest first. */
59
+ recentlySent() {
60
+ return this.runner.recentlySent();
61
+ }
62
+ /** Calls `listener` with the snapshot now and after every change; returns a function that stops listening. */
63
+ subscribe(listener) {
64
+ this.listeners.add(listener);
65
+ this.notify();
66
+ return () => {
67
+ this.listeners.delete(listener);
68
+ };
69
+ }
70
+ /** Sends what is due now and resolves when nothing more can go. */
71
+ async flush(options) {
72
+ const report = await this.flushReport(options);
73
+ const { pending } = await this.snapshot();
74
+ return { sent: report.sent, rejected: report.rejected, pending };
75
+ }
76
+ /** Puts refused items back to pending, the given ones or all of them, and returns how many. */
77
+ async resend(ids) {
78
+ const refused = (await this.storedSummaries()).filter(({ id, state }) => state === "rejected" && (ids === undefined || ids.includes(id)));
79
+ for (const { id } of refused) {
80
+ await this.resendOne(id);
81
+ }
82
+ this.wakeAfterReady(0);
83
+ return refused.length;
84
+ }
85
+ /** Deletes an item that has not been sent; a reading discarded here is not saved. */
86
+ async discard(id) {
87
+ await this.ready;
88
+ this.runner.supersede(id);
89
+ await this.store.remove(id);
90
+ this.notify();
91
+ }
92
+ /** The observations of the pending items, for showing readings that are not saved yet. */
93
+ async pendingObservations() {
94
+ const pending = (await this.items()).filter(({ state, kind }) => state === "pending" && kind !== "delete");
95
+ const items = await Promise.all(pending.map(({ id }) => this.store.get(id)));
96
+ return items.flatMap((item) => { var _a; return (_a = item === null || item === void 0 ? void 0 : item.entries.flatMap((entry) => { var _a; return (_a = (0, entry_observation_1.observationOf)(entry)) !== null && _a !== void 0 ? _a : []; })) !== null && _a !== void 0 ? _a : []; });
97
+ }
98
+ /** Queues the deletion of the observations with an identifier, for readings that were saved before. */
99
+ async enqueueDelete(target) {
100
+ const ownerKey = await this.settings.ownerKey();
101
+ if (ownerKey === null) {
102
+ throw new ovok_errors_1.OvokValidationError((0, ovok_errors_1.detailsFor)("No user is signed in; the outbox keeps items per account."));
103
+ }
104
+ const subject = target.patientId ? `Patient/${target.patientId}` : await this.settings.signedInProfile();
105
+ await (0, pending_saves_1.cancelPendingSaves)(this.store, ownerKey, target, (id) => this.runner.supersede(id));
106
+ await this.enqueue(ownerKey, [(0, outbox_items_1.deleteDraft)(target, subject, ownerKey, this.now())]);
107
+ }
108
+ /** @internal Stores items for sending; a newer version of a series or segment replaces the stored one. */
109
+ async enqueue(ownerKey, drafts) {
110
+ await this.ready;
111
+ for (const draft of drafts) {
112
+ await this.storeDraft(ownerKey, draft);
113
+ }
114
+ this.runner.wake(ENQUEUE_DELAY_MS);
115
+ this.notify();
116
+ }
117
+ /** @internal Sends what is due now and reports what happened to each item. */
118
+ async flushReport(options) {
119
+ await this.ready;
120
+ return this.runner.flush(options);
121
+ }
122
+ async storeDraft(ownerKey, draft) {
123
+ var _a;
124
+ const existing = await this.store.get(draft.id);
125
+ const keepsProgress = (existing === null || existing === void 0 ? void 0 : existing.state) === "pending" && (draft.kind === "measurement" || draft.kind === "delete");
126
+ if (keepsProgress) {
127
+ return;
128
+ }
129
+ this.runner.supersede(draft.id);
130
+ await this.store.put({
131
+ ...draft,
132
+ ownerKey,
133
+ state: "pending",
134
+ attempts: 0,
135
+ nextAttemptAt: 0,
136
+ createdAt: (_a = existing === null || existing === void 0 ? void 0 : existing.createdAt) !== null && _a !== void 0 ? _a : this.now(),
137
+ });
138
+ }
139
+ async resendOne(id) {
140
+ const item = await this.store.get(id);
141
+ if (item) {
142
+ const { lastFailure: _failure, ...rest } = item;
143
+ await this.store.put({ ...rest, state: "pending", attempts: 0, nextAttemptAt: 0 });
144
+ }
145
+ }
146
+ async storedSummaries() {
147
+ await this.ready;
148
+ const ownerKey = await this.settings.ownerKey();
149
+ return ownerKey === null ? [] : this.store.summaries(ownerKey);
150
+ }
151
+ importOldQueue() {
152
+ const { legacyQueue } = this.settings;
153
+ return (legacyQueue ? (0, legacy_queue_import_1.importLegacyQueue)(legacyQueue.storage, legacyQueue.key, this.store, this.now()) : Promise.resolve()).catch((error) => this.log.error("outbox.import-failed", { error: error.name }));
154
+ }
155
+ wakeAfterReady(delayMs) {
156
+ void this.ready.then(() => this.runner.wake(delayMs));
157
+ }
158
+ notify() {
159
+ const notification = ++this.notifications;
160
+ if (this.listeners.size === 0) {
161
+ return;
162
+ }
163
+ this.snapshot().then((snapshot) => {
164
+ if (notification === this.notifications) {
165
+ this.listeners.forEach((listener) => listener(snapshot));
166
+ }
167
+ }, (error) => this.log.error("outbox.snapshot-failed", { error: error.name }));
168
+ }
169
+ }
170
+ exports.OutboxResource = OutboxResource;
@@ -0,0 +1,56 @@
1
+ import type { OutboxStore } from "./outbox-store";
2
+ import type { OutboxSentItem } from "./outbox-types";
3
+ import type { RequestOptions } from "../http/transmit";
4
+ import type { ScopedLogger } from "../logging/ovok-logger";
5
+ import type { Bundle, BundleEntry } from "@medplum/fhirtypes";
6
+ import { FlushReport } from "./item-settler";
7
+ import { RequestBudget } from "./request-budget";
8
+ import { RunnerView } from "./runner-state";
9
+ /** Sends the entries of one or more items; one item is a transaction, several are batches. */
10
+ export type OutboxTransport = (groups: BundleEntry[][], context: {
11
+ ownerKey: string;
12
+ options?: RequestOptions;
13
+ countRequest: () => void;
14
+ }) => Promise<Bundle>;
15
+ export type RunnerDeps = {
16
+ store: OutboxStore;
17
+ transport: OutboxTransport;
18
+ ownerKey: () => Promise<string | null>;
19
+ budget: RequestBudget;
20
+ logger: ScopedLogger;
21
+ now: () => number;
22
+ changed: () => void;
23
+ };
24
+ /** Sends what is due: one exclusive loop, newest first, one request at a time, within the request budget. */
25
+ export declare class OutboxRunner {
26
+ private readonly deps;
27
+ private active;
28
+ private draining;
29
+ private again;
30
+ private lastOwnerKey;
31
+ private readonly state;
32
+ private readonly wakeup;
33
+ private readonly links;
34
+ private readonly settler;
35
+ private readonly handlers;
36
+ constructor(deps: RunnerDeps);
37
+ view(): RunnerView;
38
+ recentlySent(): OutboxSentItem[];
39
+ /** Runs a flush after `delayMs`, unless one is already due sooner. */
40
+ wake(delayMs: number): void;
41
+ /** A stored item was replaced or deleted: whatever is planned or sending for it is stale. */
42
+ supersede(id: string): void;
43
+ /** Sends what is due now and resolves when nothing more can go. A flush already running takes one more pass. */
44
+ flush(options?: RequestOptions): Promise<FlushReport>;
45
+ private flushInBackground;
46
+ private run;
47
+ private drain;
48
+ private round;
49
+ private sendRequests;
50
+ private sendRequest;
51
+ private attempt;
52
+ private entriesToSend;
53
+ private sendEach;
54
+ private finish;
55
+ private nextWakeMs;
56
+ }
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OutboxRunner = void 0;
4
+ const failure_policy_1 = require("./failure-policy");
5
+ const group_links_1 = require("./group-links");
6
+ const item_settler_1 = require("./item-settler");
7
+ const outcome_handlers_1 = require("./outcome-handlers");
8
+ const request_planner_1 = require("./request-planner");
9
+ const runner_state_1 = require("./runner-state");
10
+ const wakeup_1 = require("./wakeup");
11
+ const ROUND_LIMIT = 50;
12
+ const PENDING_TICK_MS = 15000;
13
+ const OFFLINE_PROBE_MS = 30000;
14
+ const MIN_WAKE_MS = 1000;
15
+ /** Sends what is due: one exclusive loop, newest first, one request at a time, within the request budget. */
16
+ class OutboxRunner {
17
+ constructor(deps) {
18
+ this.deps = deps;
19
+ this.active = null;
20
+ this.draining = false;
21
+ this.again = false;
22
+ this.lastOwnerKey = null;
23
+ this.state = new runner_state_1.RunnerState(deps.now);
24
+ this.links = new group_links_1.GroupLinks(deps.store);
25
+ this.settler = new item_settler_1.ItemSettler(deps.store, this.links, this.state, deps.now);
26
+ this.wakeup = new wakeup_1.Wakeup(deps.now, () => this.flushInBackground());
27
+ this.handlers = (0, outcome_handlers_1.outcomeHandlers)({
28
+ settler: this.settler,
29
+ state: this.state,
30
+ logger: deps.logger,
31
+ now: deps.now,
32
+ sendEach: (items, report, request) => this.sendEach(items, report, request),
33
+ });
34
+ }
35
+ view() {
36
+ return this.state.view();
37
+ }
38
+ recentlySent() {
39
+ return this.state.recentlySent();
40
+ }
41
+ /** Runs a flush after `delayMs`, unless one is already due sooner. */
42
+ wake(delayMs) {
43
+ this.wakeup.at(delayMs);
44
+ }
45
+ /** A stored item was replaced or deleted: whatever is planned or sending for it is stale. */
46
+ supersede(id) {
47
+ this.state.supersede(id);
48
+ }
49
+ /** Sends what is due now and resolves when nothing more can go. A flush already running takes one more pass. */
50
+ flush(options) {
51
+ if (this.active === null) {
52
+ this.active = this.run(options).finally(() => {
53
+ this.active = null;
54
+ });
55
+ return this.active;
56
+ }
57
+ if (this.draining) {
58
+ this.again = true;
59
+ return this.active;
60
+ }
61
+ return this.active.then(() => this.flush(options));
62
+ }
63
+ flushInBackground() {
64
+ this.flush().catch((error) => this.deps.logger.error("outbox.failed", { error: error.name }));
65
+ }
66
+ async run(options) {
67
+ const report = (0, item_settler_1.emptyReport)();
68
+ this.draining = true;
69
+ try {
70
+ do {
71
+ this.again = false;
72
+ await this.drain(report, options);
73
+ } while (this.again);
74
+ }
75
+ finally {
76
+ this.draining = false;
77
+ await this.finish(report);
78
+ }
79
+ return report;
80
+ }
81
+ async drain(report, options) {
82
+ const ownerKey = await this.deps.ownerKey();
83
+ this.lastOwnerKey = ownerKey;
84
+ if (ownerKey === null) {
85
+ return;
86
+ }
87
+ while (await this.round({ ownerKey, options }, report)) {
88
+ continue;
89
+ }
90
+ }
91
+ async round(request, report) {
92
+ if (this.state.isPaused()) {
93
+ return false;
94
+ }
95
+ const { store, now } = this.deps;
96
+ const due = await store.due(request.ownerKey, now(), ROUND_LIMIT);
97
+ const inRecordings = due.some(({ group }) => group !== undefined);
98
+ const ready = (0, request_planner_1.readyItems)(due, inRecordings ? await store.summaries(request.ownerKey) : []);
99
+ ready.forEach(({ id }) => this.state.claimed.add(id));
100
+ try {
101
+ return await this.sendRequests((0, request_planner_1.planRequests)(ready), report, request);
102
+ }
103
+ finally {
104
+ ready.forEach(({ id }) => this.state.claimed.delete(id));
105
+ }
106
+ }
107
+ async sendRequests(requests, report, request) {
108
+ for (const items of requests) {
109
+ if (!(await this.sendRequest(items, report, request))) {
110
+ return false;
111
+ }
112
+ }
113
+ return requests.length > 0;
114
+ }
115
+ async sendRequest(planned, report, request) {
116
+ const items = planned.filter(({ id }) => !this.state.wasSuperseded(id));
117
+ if (items.length === 0) {
118
+ return true;
119
+ }
120
+ const budgetWaitMs = this.deps.budget.waitMs(this.deps.now());
121
+ if (budgetWaitMs > 0) {
122
+ this.wake(budgetWaitMs);
123
+ return false;
124
+ }
125
+ if ((await this.deps.ownerKey()) !== request.ownerKey) {
126
+ return false;
127
+ }
128
+ const outcome = await this.attempt(items, report, request);
129
+ const handle = this.handlers[outcome.type];
130
+ const proceed = await handle(outcome, items, report, request);
131
+ this.deps.changed();
132
+ return proceed;
133
+ }
134
+ async attempt(items, report, request) {
135
+ var _a;
136
+ const { transport, budget, now } = this.deps;
137
+ items.forEach(({ id }) => this.state.sending.add(id));
138
+ report.attempted += items.length;
139
+ try {
140
+ const groups = await Promise.all(items.map((item) => this.entriesToSend(item)));
141
+ const response = await transport(groups, {
142
+ ownerKey: request.ownerKey,
143
+ options: request.options,
144
+ countRequest: () => budget.record(now()),
145
+ });
146
+ return { type: "sent", response };
147
+ }
148
+ catch (error) {
149
+ return (0, failure_policy_1.classify)(error, { items, signal: (_a = request.options) === null || _a === void 0 ? void 0 : _a.signal });
150
+ }
151
+ finally {
152
+ items.forEach(({ id }) => this.state.sending.delete(id));
153
+ }
154
+ }
155
+ entriesToSend(item) {
156
+ return item.group === undefined ? item.entries : this.links.entriesToSend(item);
157
+ }
158
+ sendEach(items, report, request) {
159
+ return this.sendRequests(items.map((item) => [item]), report, request);
160
+ }
161
+ async finish(report) {
162
+ const pending = this.lastOwnerKey === null ? 0 : await this.deps.store.count(this.lastOwnerKey, "pending");
163
+ if (report.sent + report.rejected > 0) {
164
+ this.deps.logger.info("outbox.flushed", { sent: report.sent, rejected: report.rejected, pending });
165
+ }
166
+ this.deps.changed();
167
+ if (pending > 0) {
168
+ this.wake(this.nextWakeMs());
169
+ }
170
+ }
171
+ nextWakeMs() {
172
+ const pausedUntil = this.state.pausedUntilTime();
173
+ if (pausedUntil !== null) {
174
+ return Math.max(MIN_WAKE_MS, pausedUntil - this.deps.now());
175
+ }
176
+ return this.state.offline ? OFFLINE_PROBE_MS : PENDING_TICK_MS;
177
+ }
178
+ }
179
+ exports.OutboxRunner = OutboxRunner;
@@ -0,0 +1,3 @@
1
+ import type { OutboxItemSummary, OutboxSnapshot } from "./outbox-types";
2
+ import type { RunnerView } from "./runner-state";
3
+ export declare const buildSnapshot: (stored: OutboxItemSummary[], state: RunnerView) => OutboxSnapshot;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSnapshot = void 0;
4
+ const KINDS = ["measurement", "series", "segment", "delete"];
5
+ const countByKind = (items) => Object.fromEntries(KINDS.map((kind) => [kind, items.filter((item) => item.kind === kind).length]));
6
+ const progressOf = (id, items) => {
7
+ var _a;
8
+ const segments = items.filter(({ kind }) => kind === "segment");
9
+ const closing = items.find(({ kind }) => kind !== "segment");
10
+ const lastSeq = segments.reduce((last, { seq }) => Math.max(last, seq !== null && seq !== void 0 ? seq : 0), -1);
11
+ const total = (_a = closing === null || closing === void 0 ? void 0 : closing.seq) !== null && _a !== void 0 ? _a : lastSeq + 1;
12
+ return { id, segmentsSent: total - segments.length, segmentsTotal: total };
13
+ };
14
+ /** Each recording that still has an item stored: its segments are counted from the group item's `seq`. */
15
+ const groupProgress = (items) => {
16
+ const byGroup = new Map();
17
+ items.forEach((item) => {
18
+ var _a;
19
+ if (item.group !== undefined) {
20
+ byGroup.set(item.group, [...((_a = byGroup.get(item.group)) !== null && _a !== void 0 ? _a : []), item]);
21
+ }
22
+ });
23
+ return [...byGroup].map(([id, members]) => progressOf(id, members));
24
+ };
25
+ const oldest = (items) => items.length === 0 ? null : items.reduce((first, { createdAt }) => Math.min(first, createdAt), Infinity);
26
+ const buildSnapshot = (stored, state) => {
27
+ const pending = stored.filter((item) => item.state === "pending");
28
+ return {
29
+ pending: pending.length,
30
+ sending: state.sending,
31
+ rejected: stored.length - pending.length,
32
+ offline: state.offline,
33
+ pausedUntil: state.pausedUntil,
34
+ oldestPendingAt: oldest(pending),
35
+ lastError: state.lastError,
36
+ byKind: countByKind(pending),
37
+ groups: groupProgress(stored),
38
+ };
39
+ };
40
+ exports.buildSnapshot = buildSnapshot;
@@ -0,0 +1,21 @@
1
+ import type { OutboxItem, OutboxItemSummary, OutboxState } from "./outbox-types";
2
+ /**
3
+ * Where the outbox keeps its items so they survive a restart. An adapter must keep every method atomic, so a crash
4
+ * leaves an item either stored or not. Run `outboxStoreContract` against it.
5
+ *
6
+ * @category outbox
7
+ */
8
+ export interface OutboxStore {
9
+ /** Stores an item, replacing the one with the same id. */
10
+ put(item: OutboxItem): Promise<void>;
11
+ /** Returns an item, or `null` when there is none. */
12
+ get(id: string): Promise<OutboxItem | null>;
13
+ /** Deletes an item; deleting an unknown id is not an error. */
14
+ remove(id: string): Promise<void>;
15
+ /** The owner's pending items whose `nextAttemptAt` is not after `now`, newest `recordedAt` first, at most `limit`. */
16
+ due(ownerKey: string, now: number, limit: number): Promise<OutboxItem[]>;
17
+ /** Every item of the owner, in any state, without its entries. */
18
+ summaries(ownerKey: string): Promise<OutboxItemSummary[]>;
19
+ /** How many of the owner's items are in `state`. */
20
+ count(ownerKey: string, state: OutboxState): Promise<number>;
21
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Tells the outbox when the device regains its network connection, so it sends at once.
3
+ *
4
+ * @category outbox
5
+ */
6
+ export type OutboxConnectivity = {
7
+ /** Calls `onOnline` each time the connection returns; returns a function that stops listening. */
8
+ subscribe(onOnline: () => void): () => void;
9
+ };
10
+ /**
11
+ * Tells the outbox when the app comes to the foreground, so it sends at once.
12
+ *
13
+ * @category outbox
14
+ */
15
+ export type OutboxLifecycle = {
16
+ /** Calls `onForeground` each time the app comes to the foreground; returns a function that stops listening. */
17
+ subscribe(onForeground: () => void): () => void;
18
+ };
19
+ /**
20
+ * The browser's `online` event; nothing to listen to outside a browser.
21
+ *
22
+ * @category outbox
23
+ */
24
+ export declare const browserConnectivity: OutboxConnectivity;
25
+ /**
26
+ * The browser tab becoming visible; nothing to listen to outside a browser.
27
+ *
28
+ * @category outbox
29
+ */
30
+ export declare const browserLifecycle: OutboxLifecycle;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.browserLifecycle = exports.browserConnectivity = void 0;
4
+ const noListening = () => () => undefined;
5
+ const canListen = (target) => typeof (target === null || target === void 0 ? void 0 : target.addEventListener) === "function";
6
+ /**
7
+ * The browser's `online` event; nothing to listen to outside a browser.
8
+ *
9
+ * @category outbox
10
+ */
11
+ exports.browserConnectivity = {
12
+ subscribe: (onOnline) => {
13
+ if (!canListen(globalThis.window)) {
14
+ return noListening();
15
+ }
16
+ window.addEventListener("online", onOnline);
17
+ return () => window.removeEventListener("online", onOnline);
18
+ },
19
+ };
20
+ /**
21
+ * The browser tab becoming visible; nothing to listen to outside a browser.
22
+ *
23
+ * @category outbox
24
+ */
25
+ exports.browserLifecycle = {
26
+ subscribe: (onForeground) => {
27
+ if (!canListen(globalThis.document)) {
28
+ return noListening();
29
+ }
30
+ const onVisibilityChange = () => {
31
+ if (document.visibilityState === "visible") {
32
+ onForeground();
33
+ }
34
+ };
35
+ document.addEventListener("visibilitychange", onVisibilityChange);
36
+ return () => document.removeEventListener("visibilitychange", onVisibilityChange);
37
+ },
38
+ };