@ovok/core 0.4.49 → 0.4.50

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 (75) hide show
  1. package/dist/client/observation/fhir-systems.d.ts +12 -0
  2. package/dist/client/observation/fhir-systems.js +13 -1
  3. package/dist/client/observation/observation-groups.d.ts +4 -3
  4. package/dist/client/observation/observation-groups.js +8 -4
  5. package/dist/client/observation/series.d.ts +21 -3
  6. package/dist/client/observation/series.js +14 -4
  7. package/dist/client/observation/services/ecg-observation-fragments.js +1 -0
  8. package/dist/client/offline/offline-measurement-queue.d.ts +3 -1
  9. package/dist/client/offline/offline-measurement-queue.js +2 -1
  10. package/dist/conformance/capability-requirements.js +1 -1
  11. package/dist/next/config/ovok-config.d.ts +18 -0
  12. package/dist/next/config/settings.js +10 -1
  13. package/dist/next/errors/ovok-errors.d.ts +7 -0
  14. package/dist/next/errors/ovok-errors.js +9 -1
  15. package/dist/next/http/transmit.js +4 -2
  16. package/dist/next/index.d.ts +15 -1
  17. package/dist/next/index.js +18 -1
  18. package/dist/next/logging/ovok-logger.d.ts +26 -0
  19. package/dist/next/logging/ovok-logger.js +10 -0
  20. package/dist/next/outbox/entry-observation.d.ts +3 -0
  21. package/dist/next/outbox/entry-observation.js +6 -0
  22. package/dist/next/outbox/failure-policy.d.ts +45 -0
  23. package/dist/next/outbox/failure-policy.js +92 -0
  24. package/dist/next/outbox/group-links.d.ts +19 -0
  25. package/dist/next/outbox/group-links.js +65 -0
  26. package/dist/next/outbox/indexed-db-outbox-store.d.ts +38 -0
  27. package/dist/next/outbox/indexed-db-outbox-store.js +90 -0
  28. package/dist/next/outbox/item-settler.d.ts +37 -0
  29. package/dist/next/outbox/item-settler.js +49 -0
  30. package/dist/next/outbox/legacy-queue-import.d.ts +7 -0
  31. package/dist/next/outbox/legacy-queue-import.js +50 -0
  32. package/dist/next/outbox/memory-outbox-store.d.ts +22 -0
  33. package/dist/next/outbox/memory-outbox-store.js +40 -0
  34. package/dist/next/outbox/outbox-items.d.ts +17 -0
  35. package/dist/next/outbox/outbox-items.js +89 -0
  36. package/dist/next/outbox/outbox-queries.d.ts +4 -0
  37. package/dist/next/outbox/outbox-queries.js +9 -0
  38. package/dist/next/outbox/outbox-resource.d.ts +73 -0
  39. package/dist/next/outbox/outbox-resource.js +170 -0
  40. package/dist/next/outbox/outbox-runner.d.ts +56 -0
  41. package/dist/next/outbox/outbox-runner.js +179 -0
  42. package/dist/next/outbox/outbox-snapshot.d.ts +3 -0
  43. package/dist/next/outbox/outbox-snapshot.js +40 -0
  44. package/dist/next/outbox/outbox-store.d.ts +21 -0
  45. package/dist/next/outbox/outbox-store.js +2 -0
  46. package/dist/next/outbox/outbox-triggers.d.ts +30 -0
  47. package/dist/next/outbox/outbox-triggers.js +38 -0
  48. package/dist/next/outbox/outbox-types.d.ts +138 -0
  49. package/dist/next/outbox/outbox-types.js +2 -0
  50. package/dist/next/outbox/outcome-handlers.d.ts +30 -0
  51. package/dist/next/outbox/outcome-handlers.js +50 -0
  52. package/dist/next/outbox/pending-saves.d.ts +6 -0
  53. package/dist/next/outbox/pending-saves.js +18 -0
  54. package/dist/next/outbox/request-budget.d.ts +10 -0
  55. package/dist/next/outbox/request-budget.js +22 -0
  56. package/dist/next/outbox/request-planner.d.ts +5 -0
  57. package/dist/next/outbox/request-planner.js +39 -0
  58. package/dist/next/outbox/runner-state.d.ts +34 -0
  59. package/dist/next/outbox/runner-state.js +61 -0
  60. package/dist/next/outbox/store-contract.d.ts +19 -0
  61. package/dist/next/outbox/store-contract.js +108 -0
  62. package/dist/next/outbox/wakeup.d.ts +11 -0
  63. package/dist/next/outbox/wakeup.js +34 -0
  64. package/dist/next/ovok.d.ts +3 -0
  65. package/dist/next/ovok.js +13 -2
  66. package/dist/next/react/index.d.ts +11 -1
  67. package/dist/next/react/index.js +15 -1
  68. package/dist/next/resources/measurements/measurement-sender.d.ts +27 -0
  69. package/dist/next/resources/measurements/measurement-sender.js +66 -0
  70. package/dist/next/resources/measurements/measurements-resource.d.ts +36 -25
  71. package/dist/next/resources/measurements/measurements-resource.js +62 -65
  72. package/dist/next/resources/measurements/offline-measurement-queue-types.d.ts +12 -14
  73. package/dist/next/resources/measurements/offline-measurement-queue.d.ts +4 -23
  74. package/dist/next/resources/measurements/offline-measurement-queue.js +18 -143
  75. package/package.json +1 -1
@@ -1,7 +1,8 @@
1
1
  import * as React from "react";
2
+ import type { OvokQueryState } from "./query-hooks";
2
3
  import type { Session } from "../auth/session";
4
+ import type { OutboxSnapshot } from "../outbox/outbox-types";
3
5
  import type { Ovok } from "../ovok";
4
- import type { OvokQueryState } from "./query-hooks";
5
6
  import { useOvok } from "./context";
6
7
  /**
7
8
  * Props for `OvokProvider`.
@@ -33,6 +34,15 @@ export declare const useSession: () => OvokQueryState<Session | null>;
33
34
  * @category React
34
35
  */
35
36
  export declare const useProfile: () => OvokQueryState<Session["profile"] | null>;
37
+ /**
38
+ * Returns what the outbox holds and is doing, or undefined before the first snapshot, and updates as it changes.
39
+ *
40
+ * @example
41
+ * const outbox = useOutbox();
42
+ *
43
+ * @category React
44
+ */
45
+ export declare const useOutbox: () => OutboxSnapshot | undefined;
36
46
  export { useOvokMutation, useOvokQuery, useResource, useSearch, useSubscription } from "./query-hooks";
37
47
  export { useOvok };
38
48
  export type { OvokMutationState, OvokQueryOptions, OvokQueryState } from "./query-hooks";
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  };
35
35
  })();
36
36
  Object.defineProperty(exports, "__esModule", { value: true });
37
- exports.useOvok = exports.useSubscription = exports.useSearch = exports.useResource = exports.useOvokQuery = exports.useOvokMutation = exports.useProfile = exports.useSession = exports.OvokProvider = void 0;
37
+ exports.useOvok = exports.useSubscription = exports.useSearch = exports.useResource = exports.useOvokQuery = exports.useOvokMutation = exports.useOutbox = exports.useProfile = exports.useSession = exports.OvokProvider = void 0;
38
38
  const React = __importStar(require("react"));
39
39
  const context_1 = require("./context");
40
40
  Object.defineProperty(exports, "useOvok", { enumerable: true, get: function () { return context_1.useOvok; } });
@@ -78,6 +78,20 @@ const useProfile = () => {
78
78
  };
79
79
  };
80
80
  exports.useProfile = useProfile;
81
+ /**
82
+ * Returns what the outbox holds and is doing, or undefined before the first snapshot, and updates as it changes.
83
+ *
84
+ * @example
85
+ * const outbox = useOutbox();
86
+ *
87
+ * @category React
88
+ */
89
+ const useOutbox = () => {
90
+ const client = (0, context_1.useOvok)();
91
+ const subscribe = React.useCallback((listener) => client.outbox.subscribe(listener), [client]);
92
+ return (0, query_hooks_1.useSubscription)(subscribe);
93
+ };
94
+ exports.useOutbox = useOutbox;
81
95
  var query_hooks_2 = require("./query-hooks");
82
96
  Object.defineProperty(exports, "useOvokMutation", { enumerable: true, get: function () { return query_hooks_2.useOvokMutation; } });
83
97
  Object.defineProperty(exports, "useOvokQuery", { enumerable: true, get: function () { return query_hooks_2.useOvokQuery; } });
@@ -0,0 +1,27 @@
1
+ import type { RequestOptions } from "../../http/transmit";
2
+ import type { FhirResource } from "../fhir-resource";
3
+ import type { Bundle, BundleEntry } from "@medplum/fhirtypes";
4
+ /** Who a send is for and how: the account that must still be signed in, the caller's options, a request counter. */
5
+ export type SendContext = {
6
+ owner: string | null;
7
+ options?: RequestOptions;
8
+ onRequest?: () => void;
9
+ };
10
+ /** Sends observation bundles to the server for the account that owns them. */
11
+ export declare class MeasurementSender {
12
+ private readonly fhir;
13
+ private readonly currentOwnerKey;
14
+ constructor(fhir: FhirResource, currentOwnerKey: () => Promise<string | null>);
15
+ /** One reading is a transaction, several are batches, main observations first. */
16
+ sendGroups(groups: BundleEntry[][], context: SendContext): Promise<Bundle>;
17
+ /** Readings packed into as few requests as fit, one request after another. */
18
+ sendPacked(groups: BundleEntry[][], context: SendContext): Promise<Bundle>;
19
+ /**
20
+ * A reading split over several requests stops once another account signs in, so none of it lands elsewhere. A
21
+ * transaction refused because its main observation matched several saved copies is sent again as batches.
22
+ */
23
+ send(bundle: Bundle, context: SendContext): Promise<Bundle>;
24
+ private sendReadings;
25
+ private guarded;
26
+ private requireOwner;
27
+ }
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MeasurementSender = void 0;
4
+ const observation_bundle_utils_1 = require("../../../client/observation/observation-bundle-utils");
5
+ const observation_groups_1 = require("../../../client/observation/observation-groups");
6
+ const ovok_errors_1 = require("../../errors/ovok-errors");
7
+ const save_error_1 = require("./save-error");
8
+ const PRECONDITION_FAILED = 412;
9
+ /** Sends observation bundles to the server for the account that owns them. */
10
+ class MeasurementSender {
11
+ constructor(fhir, currentOwnerKey) {
12
+ this.fhir = fhir;
13
+ this.currentOwnerKey = currentOwnerKey;
14
+ }
15
+ /** One reading is a transaction, several are batches, main observations first. */
16
+ sendGroups(groups, context) {
17
+ return groups.length === 1
18
+ ? this.send({ resourceType: "Bundle", type: "transaction", entry: groups[0] }, context)
19
+ : this.sendReadings(groups, context);
20
+ }
21
+ /** Readings packed into as few requests as fit, one request after another. */
22
+ async sendPacked(groups, context) {
23
+ const responses = [];
24
+ for (const request of (0, observation_groups_1.packObservationGroups)(groups)) {
25
+ responses.push(await this.sendGroups(request, context));
26
+ }
27
+ return { resourceType: "Bundle", type: "batch-response", entry: responses.flatMap((response) => { var _a; return (_a = response.entry) !== null && _a !== void 0 ? _a : []; }) };
28
+ }
29
+ /**
30
+ * A reading split over several requests stops once another account signs in, so none of it lands elsewhere. A
31
+ * transaction refused because its main observation matched several saved copies is sent again as batches.
32
+ */
33
+ async send(bundle, context) {
34
+ var _a;
35
+ try {
36
+ return await this.guarded((execute) => (0, observation_bundle_utils_1.executeObservationBundle)(bundle, execute), context);
37
+ }
38
+ catch (error) {
39
+ if (bundle.type === "transaction" && error instanceof ovok_errors_1.OvokError && error.status === PRECONDITION_FAILED) {
40
+ return this.sendReadings([(_a = bundle.entry) !== null && _a !== void 0 ? _a : []], context);
41
+ }
42
+ throw error;
43
+ }
44
+ }
45
+ sendReadings(groups, context) {
46
+ return this.guarded((execute) => (0, observation_groups_1.executeReadingsBatch)(groups, execute), context);
47
+ }
48
+ async guarded(run, { owner, options, onRequest }) {
49
+ try {
50
+ return await run(async (request) => {
51
+ await this.requireOwner(owner);
52
+ onRequest === null || onRequest === void 0 ? void 0 : onRequest();
53
+ return this.fhir.batch(request, options);
54
+ });
55
+ }
56
+ catch (error) {
57
+ throw (0, save_error_1.isBundle)(error) ? (0, save_error_1.saveErrorFrom)(error) : error;
58
+ }
59
+ }
60
+ async requireOwner(owner) {
61
+ if (owner !== (await this.currentOwnerKey())) {
62
+ throw new ovok_errors_1.OvokConflictError((0, ovok_errors_1.detailsFor)("The signed-in account changed during the save; the rest was not sent."));
63
+ }
64
+ }
65
+ }
66
+ exports.MeasurementSender = MeasurementSender;
@@ -1,11 +1,12 @@
1
1
  import type { OfflineMeasurementQueueApi } from "./offline-measurement-queue";
2
2
  import type { GetLatestObservationsByCodeParams } from "../../../client/observation/types/GetLatestObservationsByCodeParams";
3
- import type { OvokStorage } from "../../storage/ovok-storage";
3
+ import type { OutboxSettings } from "../../outbox/outbox-resource";
4
4
  import type { Bundle, Observation } from "@medplum/fhirtypes";
5
5
  import { observationCodesForTypes } from "../../../client/observation/methods/observationsToMeasurements";
6
6
  import { HttpClient } from "../../http/http-client";
7
7
  import { RequestOptions } from "../../http/transmit";
8
8
  import { QueryParams } from "../../http/url";
9
+ import { OutboxResource } from "../../outbox/outbox-resource";
9
10
  import { FhirResource } from "../fhir-resource";
10
11
  import { BuildObservationsParams } from "./observation-builder";
11
12
  import { SessionSource } from "./signed-in-account";
@@ -21,7 +22,7 @@ export type SaveObservationsOptions = RequestOptions & {
21
22
  replace?: boolean;
22
23
  };
23
24
  /**
24
- * Either the saved bundle, or the queue id of a reading kept for a later retry.
25
+ * Either the saved bundle, or the outbox id of a reading kept for a later retry.
25
26
  *
26
27
  * @category measurements
27
28
  */
@@ -31,15 +32,17 @@ export type SaveObservationsResult = {
31
32
  /** The server's response bundle. */
32
33
  response: Bundle;
33
34
  } | {
34
- /** The reading is stored offline and will be retried. */
35
+ /** The reading is in the outbox and will be sent when it can be. */
35
36
  status: "queued";
36
- /** Id of the queued reading, as used in a flush result. */
37
+ /** Id of the queued reading's last item, as `ovok.outbox.items` lists it. */
37
38
  queueId: string;
38
39
  };
39
- type MeasurementStorage = {
40
- storage: OvokStorage;
41
- queueKey: string;
40
+ /** What the measurements need beyond the clients they share: the machine client and the outbox's settings. */
41
+ export type MeasurementSettings = {
42
42
  machineClientId: string | null;
43
+ outbox: Pick<OutboxSettings, "store" | "legacyQueue" | "connectivity" | "lifecycle" | "requestBudget" | "logger"> & {
44
+ onSessionChange: OutboxSettings["onSessionChange"];
45
+ };
43
46
  };
44
47
  /**
45
48
  * Which patient and codes to read the latest observations for.
@@ -76,7 +79,8 @@ export type LastnQuery = QueryParams & {
76
79
  */
77
80
  export type MeasurementCodeTypes = Parameters<typeof observationCodesForTypes>[0];
78
81
  /**
79
- * Builds, saves and reads measurements as FHIR Observations, with an offline queue.
82
+ * Builds, saves and reads measurements as FHIR Observations. Saves go through the outbox, so a reading survives a
83
+ * dropped connection.
80
84
  *
81
85
  * @category measurements
82
86
  */
@@ -84,25 +88,37 @@ export declare class MeasurementsResource {
84
88
  private readonly http;
85
89
  private readonly fhir;
86
90
  private readonly account;
87
- private readonly offlineMeasurementQueue;
91
+ private readonly sender;
88
92
  private readonly machineClientId;
89
93
  private readonly session;
90
- /** The offline queue of measurements waiting to be sent. */
94
+ /** Measurements waiting to be sent. */
95
+ readonly outbox: OutboxResource;
96
+ /**
97
+ * The old queue's controls; the outbox holds the queue now.
98
+ *
99
+ * @deprecated Use `ovok.outbox`.
100
+ */
91
101
  readonly offlineQueue: OfflineMeasurementQueueApi;
92
- constructor(http: HttpClient, fhir: FhirResource, session: SessionSource | null, storageOptions: MeasurementStorage);
102
+ constructor(http: HttpClient, fhir: FhirResource, session: SessionSource | null, settings: MeasurementSettings);
93
103
  /**
94
- * Builds Observations from a measurement and saves them; queued offline when they cannot be sent.
104
+ * Builds Observations from a measurement and saves them; kept in the outbox when they cannot be sent.
95
105
  *
96
106
  * @example
97
107
  * const result = await ovok.measurements.save({ measurement, device });
98
108
  */
99
109
  save(params: BuildObservationsParams, options?: SaveObservationsOptions): Promise<SaveObservationsResult>;
100
- /** One reading, main observation first, created conditionally so a retry cannot duplicate it. */
110
+ /**
111
+ * One reading, main observation first, created conditionally so a retry cannot duplicate it. A series is written
112
+ * over by its identifier, and a recording of several segments goes up one segment at a time. It throws the server's
113
+ * error when the server refuses the reading, which then waits in the outbox as rejected.
114
+ */
101
115
  saveObservations(observations: Observation[], options?: SaveObservationsOptions): Promise<SaveObservationsResult>;
102
116
  /**
103
- * Many readings, each main observation first, in as few requests as fit. A request holding one reading is a
104
- * transaction, atomic when the project enables FHIR transactions. A request holding several is two batches, main
105
- * observations first: if it fails, some readings may be saved and others not, and saving them again is safe.
117
+ * Many readings, each main observation first, in as few requests as fit. They go through the outbox: readings the
118
+ * server accepts are in the response, the rest wait in the outbox and are sent when they can be, and a reading the
119
+ * server refuses throws its error and waits there as rejected. A request holding one reading is a transaction,
120
+ * atomic when the project enables FHIR transactions. A request holding several is two batches, main observations
121
+ * first: if it fails, some readings may be saved and others not, and saving them again is safe.
106
122
  */
107
123
  saveObservationGroups(groups: Observation[][], options?: SaveObservationsOptions): Promise<Bundle>;
108
124
  /** Builds the Observations for a measurement without saving them. */
@@ -116,14 +132,9 @@ export declare class MeasurementsResource {
116
132
  /** The comma-joined codes the types are saved under, as `latest` and FHIR `code` searches take them. */
117
133
  codesFor(types: MeasurementCodeTypes): string;
118
134
  private latestPatientId;
119
- /**
120
- * A reading split over several requests stops once another account signs in, so none of it lands elsewhere. A
121
- * transaction refused because its main observation matched several saved copies is sent again as batches.
122
- */
123
- private send;
124
- private sendReadings;
125
- private guarded;
135
+ private entriesFor;
136
+ private saveDirectly;
137
+ /** Stores the items, then sends what is due; a refusal of one of these items is thrown, nobody else's. */
138
+ private sendThroughOutbox;
126
139
  private currentOwnerKey;
127
- private requireOwner;
128
140
  }
129
- export {};
@@ -3,37 +3,41 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MeasurementsResource = void 0;
4
4
  const observationsToMeasurements_1 = require("../../../client/observation/methods/observationsToMeasurements");
5
5
  const observation_bundle_utils_1 = require("../../../client/observation/observation-bundle-utils");
6
- const observation_groups_1 = require("../../../client/observation/observation-groups");
7
6
  const offline_measurement_queue_1 = require("../../../client/offline/offline-measurement-queue");
8
7
  const query_string_1 = require("../../../client/query-string");
9
- const ovok_errors_1 = require("../../errors/ovok-errors");
10
8
  const url_1 = require("../../http/url");
9
+ const outbox_items_1 = require("../../outbox/outbox-items");
10
+ const outbox_resource_1 = require("../../outbox/outbox-resource");
11
+ const measurement_sender_1 = require("./measurement-sender");
11
12
  const observation_builder_1 = require("./observation-builder");
12
13
  const offline_measurement_queue_2 = require("./offline-measurement-queue");
13
- const save_error_1 = require("./save-error");
14
14
  const signed_in_account_1 = require("./signed-in-account");
15
15
  const LATEST_OBSERVATIONS_PATH = "fhir/Observation/$lastn";
16
16
  const LATEST_PER_CODE = 1;
17
- const PRECONDITION_FAILED = 412;
18
17
  /**
19
- * Builds, saves and reads measurements as FHIR Observations, with an offline queue.
18
+ * Builds, saves and reads measurements as FHIR Observations. Saves go through the outbox, so a reading survives a
19
+ * dropped connection.
20
20
  *
21
21
  * @category measurements
22
22
  */
23
23
  class MeasurementsResource {
24
- constructor(http, fhir, session, storageOptions) {
24
+ constructor(http, fhir, session, settings) {
25
25
  this.http = http;
26
26
  this.fhir = fhir;
27
27
  this.session = session;
28
- this.machineClientId = storageOptions.machineClientId;
28
+ this.machineClientId = settings.machineClientId;
29
29
  this.account = new signed_in_account_1.SignedInAccount(session);
30
- this.offlineMeasurementQueue = new offline_measurement_queue_2.OfflineMeasurementQueue(storageOptions.storage, storageOptions.queueKey, () => this.currentOwnerKey(), (bundle, ownerKey, requestOptions) => this.send(bundle, requestOptions, ownerKey));
31
- this.offlineQueue = {
32
- flush: (options, requestOptions) => this.offlineMeasurementQueue.flush(options, requestOptions),
33
- };
30
+ this.sender = new measurement_sender_1.MeasurementSender(fhir, () => this.currentOwnerKey());
31
+ this.outbox = new outbox_resource_1.OutboxResource({
32
+ ...settings.outbox,
33
+ transport: (groups, { ownerKey, options, countRequest }) => this.sender.sendGroups(groups, { owner: ownerKey, options, onRequest: countRequest }),
34
+ ownerKey: () => this.currentOwnerKey(),
35
+ signedInProfile: () => this.account.profileReference(),
36
+ });
37
+ this.offlineQueue = (0, offline_measurement_queue_2.offlineQueueFor)(this.outbox);
34
38
  }
35
39
  /**
36
- * Builds Observations from a measurement and saves them; queued offline when they cannot be sent.
40
+ * Builds Observations from a measurement and saves them; kept in the outbox when they cannot be sent.
37
41
  *
38
42
  * @example
39
43
  * const result = await ovok.measurements.save({ measurement, device });
@@ -41,39 +45,48 @@ class MeasurementsResource {
41
45
  async save(params, options) {
42
46
  return this.saveObservations(await this.build(params), options);
43
47
  }
44
- /** One reading, main observation first, created conditionally so a retry cannot duplicate it. */
48
+ /**
49
+ * One reading, main observation first, created conditionally so a retry cannot duplicate it. A series is written
50
+ * over by its identifier, and a recording of several segments goes up one segment at a time. It throws the server's
51
+ * error when the server refuses the reading, which then waits in the outbox as rejected.
52
+ */
45
53
  async saveObservations(observations, options = {}) {
46
54
  const { identifierSystems, replace, ...requestOptions } = options;
47
- const entry = (0, observation_bundle_utils_1.linkObservationMembers)(observations).map((observation) => (0, offline_measurement_queue_1.entryForObservation)(observation, { identifierSystems, replace }));
48
55
  const ownerKey = await this.currentOwnerKey();
49
- if (entry.length === 0 || ownerKey === null) {
50
- const response = await this.send({ resourceType: "Bundle", type: "transaction", entry }, requestOptions, ownerKey);
51
- return { status: "saved", response };
56
+ if (observations.length === 0 || ownerKey === null) {
57
+ return this.saveDirectly(observations, { identifierSystems, replace }, requestOptions, ownerKey);
52
58
  }
53
- const queued = await this.offlineMeasurementQueue.enqueueAndFlush(entry, ownerKey, requestOptions);
54
- const response = queued.flush.responses[queued.id];
55
- return response
59
+ const drafts = (0, outbox_items_1.draftsFor)(observations, { identifierSystems, replace }, ownerKey, Date.now());
60
+ const report = await this.sendThroughOutbox(ownerKey, drafts, requestOptions);
61
+ const response = report.responses.get(drafts[drafts.length - 1].id);
62
+ return drafts.every(({ id }) => report.responses.has(id)) && response
56
63
  ? { status: "saved", response }
57
- : { status: "queued", queueId: queued.id };
64
+ : { status: "queued", queueId: drafts[drafts.length - 1].id };
58
65
  }
59
66
  /**
60
- * Many readings, each main observation first, in as few requests as fit. A request holding one reading is a
61
- * transaction, atomic when the project enables FHIR transactions. A request holding several is two batches, main
62
- * observations first: if it fails, some readings may be saved and others not, and saving them again is safe.
67
+ * Many readings, each main observation first, in as few requests as fit. They go through the outbox: readings the
68
+ * server accepts are in the response, the rest wait in the outbox and are sent when they can be, and a reading the
69
+ * server refuses throws its error and waits there as rejected. A request holding one reading is a transaction,
70
+ * atomic when the project enables FHIR transactions. A request holding several is two batches, main observations
71
+ * first: if it fails, some readings may be saved and others not, and saving them again is safe.
63
72
  */
64
73
  async saveObservationGroups(groups, options = {}) {
65
74
  const { identifierSystems, replace, ...requestOptions } = options;
66
- const entryGroups = groups
67
- .filter((group) => group.length > 0)
68
- .map((group) => (0, observation_bundle_utils_1.linkObservationMembers)(group).map((observation) => (0, offline_measurement_queue_1.entryForObservation)(observation, { identifierSystems, replace })));
69
- const owner = await this.currentOwnerKey();
70
- const responses = [];
71
- for (const request of (0, observation_groups_1.packObservationGroups)(entryGroups)) {
72
- responses.push(request.length === 1
73
- ? await this.send({ resourceType: "Bundle", type: "transaction", entry: request.flat() }, requestOptions, owner)
74
- : await this.sendReadings(request, requestOptions, owner));
75
+ const entryOptions = { identifierSystems, replace };
76
+ const readings = groups.filter((group) => group.length > 0);
77
+ const ownerKey = await this.currentOwnerKey();
78
+ if (ownerKey === null) {
79
+ const entryGroups = readings.map((group) => this.entriesFor(group, entryOptions));
80
+ return this.sender.sendPacked(entryGroups, { owner: ownerKey, options: requestOptions });
75
81
  }
76
- return { resourceType: "Bundle", type: "batch-response", entry: responses.flatMap((response) => { var _a; return (_a = response.entry) !== null && _a !== void 0 ? _a : []; }) };
82
+ const drafts = readings.flatMap((group) => (0, outbox_items_1.draftsFor)(group, entryOptions, ownerKey, Date.now()));
83
+ const report = await this.sendThroughOutbox(ownerKey, drafts, requestOptions);
84
+ const responses = new Set(drafts.flatMap(({ id }) => { var _a; return (_a = report.responses.get(id)) !== null && _a !== void 0 ? _a : []; }));
85
+ return {
86
+ resourceType: "Bundle",
87
+ type: "batch-response",
88
+ entry: [...responses].flatMap((response) => { var _a; return (_a = response.entry) !== null && _a !== void 0 ? _a : []; }),
89
+ };
77
90
  }
78
91
  /** Builds the Observations for a measurement without saving them. */
79
92
  async build(params) {
@@ -108,35 +121,24 @@ class MeasurementsResource {
108
121
  }
109
122
  return params.patientId;
110
123
  }
111
- /**
112
- * A reading split over several requests stops once another account signs in, so none of it lands elsewhere. A
113
- * transaction refused because its main observation matched several saved copies is sent again as batches.
114
- */
115
- async send(bundle, options, owner) {
116
- var _a;
117
- try {
118
- return await this.guarded((execute) => (0, observation_bundle_utils_1.executeObservationBundle)(bundle, execute), options, owner);
119
- }
120
- catch (error) {
121
- if (bundle.type === "transaction" && error instanceof ovok_errors_1.OvokError && error.status === PRECONDITION_FAILED) {
122
- return this.sendReadings([(_a = bundle.entry) !== null && _a !== void 0 ? _a : []], options, owner);
123
- }
124
- throw error;
125
- }
124
+ entriesFor(observations, options) {
125
+ return (0, observation_bundle_utils_1.linkObservationMembers)(observations).map((observation) => (0, offline_measurement_queue_1.entryForObservation)(observation, options));
126
126
  }
127
- sendReadings(groups, options, owner) {
128
- return this.guarded((execute) => (0, observation_groups_1.executeReadingsBatch)(groups, execute), options, owner);
127
+ saveDirectly(observations, entryOptions, requestOptions, owner) {
128
+ const entry = this.entriesFor(observations, entryOptions);
129
+ return this.sender
130
+ .send({ resourceType: "Bundle", type: "transaction", entry }, { owner, options: requestOptions })
131
+ .then((response) => ({ status: "saved", response }));
129
132
  }
130
- async guarded(run, options, owner) {
131
- try {
132
- return await run(async (request) => {
133
- await this.requireOwner(owner);
134
- return this.fhir.batch(request, options);
135
- });
136
- }
137
- catch (error) {
138
- throw (0, save_error_1.isBundle)(error) ? (0, save_error_1.saveErrorFrom)(error) : error;
133
+ /** Stores the items, then sends what is due; a refusal of one of these items is thrown, nobody else's. */
134
+ async sendThroughOutbox(ownerKey, drafts, options) {
135
+ await this.outbox.enqueue(ownerKey, drafts);
136
+ const report = await this.outbox.flushReport(options);
137
+ const refusal = drafts.map(({ id }) => report.errors.get(id)).find((error) => error !== undefined);
138
+ if (refusal !== undefined) {
139
+ throw refusal;
139
140
  }
141
+ return report;
140
142
  }
141
143
  async currentOwnerKey() {
142
144
  const accountKey = await this.account.key();
@@ -145,11 +147,6 @@ class MeasurementsResource {
145
147
  }
146
148
  return this.session === null && this.machineClientId ? `machine:${this.machineClientId}` : null;
147
149
  }
148
- async requireOwner(owner) {
149
- if (owner !== (await this.currentOwnerKey())) {
150
- throw new ovok_errors_1.OvokConflictError((0, ovok_errors_1.detailsFor)("The signed-in account changed during the save; the rest was not sent."));
151
- }
152
- }
153
150
  }
154
151
  exports.MeasurementsResource = MeasurementsResource;
155
152
  const idOf = (reference) => reference.slice(reference.indexOf("/") + 1);
@@ -1,32 +1,29 @@
1
1
  import type { RequestOptions } from "../../http/transmit";
2
+ import type { OutboxFailure } from "../../outbox/outbox-types";
2
3
  import type { Bundle } from "@medplum/fhirtypes";
3
4
  /**
4
5
  * Options for retrying queued measurements.
5
6
  *
7
+ * @deprecated Use `ovok.outbox`.
6
8
  * @category measurements
7
9
  */
8
10
  export type OfflineMeasurementFlushOptions = {
9
- /** Also retry measurements that ran out of retries. */
11
+ /** Also retry measurements the server refused. */
10
12
  includeExhausted?: boolean;
11
- /** Give exhausted measurements a fresh set of retries before flushing. */
13
+ /** Give refused measurements a fresh set of retries before flushing. */
12
14
  resetExhausted?: boolean;
13
15
  };
14
16
  /**
15
17
  * A summary of why the last attempt to send a measurement failed.
16
18
  *
19
+ * @deprecated Use `OutboxFailure`.
17
20
  * @category measurements
18
21
  */
19
- export type OfflineMeasurementFailure = {
20
- /** Error name. */
21
- name: string;
22
- /** Error code, when it has one. */
23
- code?: string;
24
- /** HTTP status, when the failure was a response. */
25
- status?: number;
26
- };
22
+ export type OfflineMeasurementFailure = OutboxFailure;
27
23
  /**
28
24
  * The outcome of a flush, with counts and per-measurement responses.
29
25
  *
26
+ * @deprecated Use `OutboxFlushResult`.
30
27
  * @category measurements
31
28
  */
32
29
  export type OfflineMeasurementFlushResult = {
@@ -34,9 +31,9 @@ export type OfflineMeasurementFlushResult = {
34
31
  attempted: number;
35
32
  /** Measurements sent and removed from the queue. */
36
33
  saved: number;
37
- /** Measurements still waiting to be retried. */
34
+ /** Measurements still waiting to be sent. */
38
35
  queued: number;
39
- /** Measurements that ran out of retries and are held back. */
36
+ /** Measurements the server refused, which wait for `ovok.outbox.resend`. */
40
37
  exhausted: number;
41
38
  /** The server response for each saved measurement, by queue id. */
42
39
  responses: Record<string, Bundle>;
@@ -44,11 +41,12 @@ export type OfflineMeasurementFlushResult = {
44
41
  failures: Record<string, OfflineMeasurementFailure>;
45
42
  };
46
43
  /**
47
- * Controls for the offline measurement queue.
44
+ * Controls for the offline measurement queue, which the outbox now holds.
48
45
  *
46
+ * @deprecated Use `ovok.outbox`.
49
47
  * @category measurements
50
48
  */
51
49
  export type OfflineMeasurementQueueApi = {
52
- /** Sends queued measurements that are due and the signed-in account owns. */
50
+ /** Sends the outbox's measurements that are due; with either option, the refused ones go back to pending first. */
53
51
  flush: (options?: OfflineMeasurementFlushOptions, requestOptions?: RequestOptions) => Promise<OfflineMeasurementFlushResult>;
54
52
  };
@@ -1,25 +1,6 @@
1
- import type { OfflineMeasurementFlushOptions, OfflineMeasurementFlushResult } from "./offline-measurement-queue-types";
2
- import type { RequestOptions } from "../../http/transmit";
3
- import type { OvokStorage } from "../../storage/ovok-storage";
4
- import type { Bundle, BundleEntry, Observation } from "@medplum/fhirtypes";
1
+ import type { OfflineMeasurementQueueApi } from "./offline-measurement-queue-types";
2
+ import type { OutboxResource } from "../../outbox/outbox-resource";
5
3
  export type { OfflineMeasurementFailure, OfflineMeasurementFlushOptions, OfflineMeasurementFlushResult, OfflineMeasurementQueueApi, } from "./offline-measurement-queue-types";
6
- type MeasurementTransport = (bundle: Bundle, ownerKey: string, requestOptions?: RequestOptions) => Promise<Bundle>;
7
- type OwnerKey = () => Promise<string | null>;
8
4
  export declare const offlineMeasurementStorageKey: (tenantCode: string, baseUrl: string) => string;
9
- export declare class OfflineMeasurementQueue {
10
- private readonly storage;
11
- private readonly storageKey;
12
- private readonly getOwnerKey;
13
- private readonly transport;
14
- private operation;
15
- constructor(storage: OvokStorage, storageKey: string, getOwnerKey: OwnerKey, transport: MeasurementTransport);
16
- enqueueAndFlush: (entries: BundleEntry<Observation>[], ownerKey: string, requestOptions?: RequestOptions) => Promise<{
17
- id: string;
18
- flush: OfflineMeasurementFlushResult;
19
- }>;
20
- flush: (options?: OfflineMeasurementFlushOptions, requestOptions?: RequestOptions) => Promise<OfflineMeasurementFlushResult>;
21
- private runExclusive;
22
- private readQueue;
23
- private writeQueue;
24
- private flushQueue;
25
- }
5
+ /** The old queue's `flush`, answered by the outbox. */
6
+ export declare const offlineQueueFor: (outbox: OutboxResource) => OfflineMeasurementQueueApi;