@tallyui/database 3.18.0 → 3.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,122 @@
1
+ import type { RxCollection, RxDatabase, RxJsonSchema } from 'rxdb';
2
+
3
+ import { REQUEST_METRICS_MAX_BUCKETS, type RequestMetrics, type RequestMetricsBucket } from './request-metrics';
4
+
5
+ // WCPOS v2's MetricsPersistenceBridge (`apps/main/app/(app)/_layout.tsx`) keeps the whole bucket array under one RxDB
6
+ // state key. Here each hour is its own row, so a write touches only the hours that changed.
7
+
8
+ /** The request metrics of this device. The host adds the collection as `request_metrics`, as with `sync_cadence`. */
9
+ export const REQUEST_METRICS_COLLECTION = 'request_metrics';
10
+ /** v2 METRICS_PERSIST_INTERVAL_MS. */
11
+ export const REQUEST_METRICS_PERSIST_INTERVAL_MS = 300_000;
12
+
13
+ export interface RequestMetricsDoc extends RequestMetricsBucket {
14
+ /** String(hourStartMs): the primary key. */
15
+ hour: string;
16
+ }
17
+
18
+ const COUNT = { type: 'integer', minimum: 0 } as const;
19
+ const AMOUNT = { type: 'number', minimum: 0 } as const;
20
+
21
+ // Local only: never replicated, never made with connectorCollection().
22
+ export const requestMetricsSchema: RxJsonSchema<RequestMetricsDoc> = {
23
+ version: 0, primaryKey: 'hour', type: 'object', additionalProperties: false,
24
+ properties: {
25
+ hour: { type: 'string', maxLength: 16 },
26
+ hourStartMs: COUNT, requests: COUNT, bytes: AMOUNT, durationTotalMs: AMOUNT, durationCount: COUNT, errors: COUNT,
27
+ loadLast: { type: 'number' }, loadMax: { type: 'number' },
28
+ },
29
+ required: ['hour', 'hourStartMs', 'requests', 'bytes', 'durationTotalMs', 'durationCount', 'errors'],
30
+ };
31
+
32
+ export function requestMetricsCollection(): { readonly schema: RxJsonSchema<RequestMetricsDoc> } {
33
+ return { schema: requestMetricsSchema } as const;
34
+ }
35
+ export type RequestMetricsCollection = RxCollection<RequestMetricsDoc>;
36
+
37
+ export async function addRequestMetricsCollection(db: RxDatabase): Promise<RequestMetricsCollection> {
38
+ const added = await db.addCollections({ [REQUEST_METRICS_COLLECTION]: requestMetricsCollection() });
39
+ return added[REQUEST_METRICS_COLLECTION] as RequestMetricsCollection;
40
+ }
41
+
42
+ export interface RequestMetricsPersistence {
43
+ /** Resolves once the stored rows have been hydrated into the counter. */
44
+ readonly ready: Promise<void>;
45
+ /** Write the changed hours now, and delete rows beyond the newest REQUEST_METRICS_MAX_BUCKETS. */
46
+ flush(): Promise<void>;
47
+ /** Stop the timer, then flush once. Idempotent; later flushes are no-ops. */
48
+ stop(): Promise<void>;
49
+ }
50
+
51
+ const FIELDS = [
52
+ 'hourStartMs', 'requests', 'bytes', 'durationTotalMs', 'durationCount', 'errors', 'loadLast', 'loadMax',
53
+ ] as const;
54
+
55
+ /** The bucket fields of a row or bucket, with an optional load reading only when it is defined (RxDB rejects undefined). */
56
+ function toBucket(source: Readonly<RequestMetricsBucket>): RequestMetricsBucket {
57
+ const bucket = {} as Record<string, number>;
58
+ for (const key of FIELDS) if (source[key] !== undefined) bucket[key] = source[key];
59
+ return bucket as unknown as RequestMetricsBucket;
60
+ }
61
+
62
+ const sameBucket = (a: RequestMetricsBucket, b: RequestMetricsBucket): boolean => FIELDS.every((key) => a[key] === b[key]);
63
+
64
+ export function persistRequestMetrics(
65
+ metrics: RequestMetrics, collection: RequestMetricsCollection, options: { everyMs?: number } = {},
66
+ ): RequestMetricsPersistence {
67
+ /** What this persistence last wrote (or read) per hour, so a flush writes only the hours that differ. */
68
+ const written = new Map<number, RequestMetricsBucket>();
69
+
70
+ const ready = (async () => {
71
+ const rows = (await collection.find().exec()).map((doc) => toBucket(doc.toJSON()));
72
+ for (const row of rows) written.set(row.hourStartMs, row);
73
+ metrics.hydrate(rows);
74
+ })();
75
+ // A rejected read surfaces through `ready` and every flush; this only keeps it from being reported as unhandled.
76
+ ready.catch(() => undefined);
77
+
78
+ const write = async (): Promise<void> => {
79
+ await ready;
80
+ const buckets = metrics.buckets();
81
+ const changed = buckets.filter((bucket) => {
82
+ const last = written.get(bucket.hourStartMs);
83
+ return !last || !sameBucket(last, bucket);
84
+ });
85
+ if (changed.length > 0) {
86
+ const docs = changed.map((bucket) => ({ hour: String(bucket.hourStartMs), ...toBucket(bucket) }));
87
+ const result = await collection.bulkUpsert(docs);
88
+ for (const doc of result.success) written.set(doc.hourStartMs, toBucket(doc.toJSON()));
89
+ if (result.error.length > 0) throw new Error(`request metrics: ${result.error.length} hour(s) not written`);
90
+ }
91
+ // The counter keeps the newest REQUEST_METRICS_MAX_BUCKETS by count; a stored row older than its oldest is gone.
92
+ if (buckets.length < REQUEST_METRICS_MAX_BUCKETS) return;
93
+ const oldest = buckets[0].hourStartMs;
94
+ await collection.find({ selector: { hourStartMs: { $lt: oldest } } }).remove();
95
+ for (const hour of written.keys()) if (hour < oldest) written.delete(hour);
96
+ };
97
+
98
+ // Flushes run one at a time: each waits for the one before it, whether that succeeded or not.
99
+ let tail: Promise<void> = Promise.resolve();
100
+ const enqueue = (): Promise<void> => {
101
+ const run = tail.then(write);
102
+ tail = run.catch(() => undefined);
103
+ return run;
104
+ };
105
+
106
+ let stopping: Promise<void> | undefined;
107
+ // A failed timed flush is retried by the next tick; the caller of flush() or stop() sees its own failure.
108
+ const timer = setInterval(() => void enqueue().catch(() => undefined),
109
+ options.everyMs ?? REQUEST_METRICS_PERSIST_INTERVAL_MS);
110
+
111
+ return {
112
+ ready,
113
+ flush: () => (stopping ? Promise.resolve() : enqueue()),
114
+ stop() {
115
+ stopping ??= (() => {
116
+ clearInterval(timer);
117
+ return enqueue();
118
+ })();
119
+ return stopping;
120
+ },
121
+ };
122
+ }
@@ -0,0 +1,180 @@
1
+ import { BehaviorSubject, type Observable } from 'rxjs';
2
+
3
+ // WCPOS v2's hourly request metrics (`apps/main/lib/metrics.ts`) and the part of its engine fetcher that feeds them
4
+ // (`apps/main/lib/engine-fetcher.ts`). One instance per store session: a host makes a new one on a store switch, so
5
+ // v2's epoch and reset are not needed.
6
+
7
+ export const REQUEST_METRICS_HOUR_MS = 3_600_000;
8
+ /** Hourly buckets kept: the newest 48 that exist, by count not age (an idle hour makes no bucket). v2 metrics.ts:4. */
9
+ export const REQUEST_METRICS_MAX_BUCKETS = 48;
10
+
11
+ export interface RequestMetricsBucket {
12
+ hourStartMs: number;
13
+ requests: number;
14
+ bytes: number;
15
+ durationTotalMs: number;
16
+ durationCount: number;
17
+ errors: number;
18
+ loadLast?: number;
19
+ loadMax?: number;
20
+ }
21
+
22
+ /**
23
+ * One completed request attempt.
24
+ *
25
+ * `errors` counts failed request ATTEMPTS, not records: one queued record can contribute several and then leave the
26
+ * queue acknowledged, so reconciling it against the sync backlog is a category error. `failed` is the settled
27
+ * verdict, not the raw HTTP status, and a request we cancelled is not a failure.
28
+ */
29
+ export interface RequestAttempt { atMs: number; durationMs: number; bytes: number; failed: boolean }
30
+
31
+ export interface RequestMetrics {
32
+ record(attempt: RequestAttempt): void;
33
+ /** Ignored unless finite. Lands in the bucket of `atMs` (default now()). */
34
+ recordServerLoad(load1: number, atMs?: number): void;
35
+ /** Sorted by hour, ascending; copies. */
36
+ buckets(): RequestMetricsBucket[];
37
+ /** Emits buckets() now and after every change. */
38
+ readonly buckets$: Observable<RequestMetricsBucket[]>;
39
+ /** Folds persisted buckets into the live ones (v2 hydrateMetricsBuckets); invalid entries skipped. */
40
+ hydrate(persisted: unknown): void;
41
+ }
42
+
43
+ const REQUIRED_NUMBERS = ['hourStartMs', 'requests', 'bytes', 'durationTotalMs', 'durationCount', 'errors'] as const;
44
+ const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
45
+
46
+ export function isRequestMetricsBucket(value: unknown): value is RequestMetricsBucket {
47
+ if (!value || typeof value !== 'object') return false;
48
+ const bucket = value as Record<string, unknown>;
49
+ if (!REQUIRED_NUMBERS.every((key) => isFiniteNumber(bucket[key]))) return false;
50
+ return (bucket.loadLast === undefined || isFiniteNumber(bucket.loadLast))
51
+ && (bucket.loadMax === undefined || isFiniteNumber(bucket.loadMax));
52
+ }
53
+
54
+ export function createRequestMetrics(options: { now?: () => number } = {}): RequestMetrics {
55
+ const now = options.now ?? Date.now;
56
+ const map = new Map<number, RequestMetricsBucket>();
57
+
58
+ const buckets = (): RequestMetricsBucket[] =>
59
+ [...map.values()].sort((a, b) => a.hourStartMs - b.hourStartMs).map((bucket) => ({ ...bucket }));
60
+ const subject = new BehaviorSubject<RequestMetricsBucket[]>([]);
61
+
62
+ const getOrCreateBucket = (atMs: number): RequestMetricsBucket => {
63
+ const start = Math.floor(atMs / REQUEST_METRICS_HOUR_MS) * REQUEST_METRICS_HOUR_MS;
64
+ let bucket = map.get(start);
65
+ if (!bucket) {
66
+ bucket = { hourStartMs: start, requests: 0, bytes: 0, durationTotalMs: 0, durationCount: 0, errors: 0 };
67
+ map.set(start, bucket);
68
+ }
69
+ return bucket;
70
+ };
71
+
72
+ // Prune, then publish: every change ends here.
73
+ const commit = (): void => {
74
+ const hours = [...map.keys()].sort((a, b) => a - b);
75
+ for (const start of hours.slice(0, -REQUEST_METRICS_MAX_BUCKETS)) map.delete(start);
76
+ subject.next(buckets());
77
+ };
78
+
79
+ return {
80
+ record({ atMs, durationMs, bytes, failed }) {
81
+ const bucket = getOrCreateBucket(atMs);
82
+ bucket.requests += 1;
83
+ // Guard against a malformed byte count leaking in from any caller: a single NaN or negative value would
84
+ // otherwise corrupt this bucket's running total.
85
+ if (Number.isFinite(bytes) && bytes >= 0) bucket.bytes += bytes;
86
+ bucket.durationTotalMs += Math.max(0, durationMs); // A clock that stepped back must not make the hour unwritable.
87
+ bucket.durationCount += 1;
88
+ if (failed) bucket.errors += 1;
89
+ commit();
90
+ },
91
+ recordServerLoad(load1, atMs) {
92
+ if (!Number.isFinite(load1)) return;
93
+ const bucket = getOrCreateBucket(atMs ?? now());
94
+ bucket.loadLast = load1;
95
+ bucket.loadMax = Math.max(bucket.loadMax ?? load1, load1);
96
+ commit();
97
+ },
98
+ buckets,
99
+ buckets$: subject.asObservable(),
100
+ hydrate(persisted) {
101
+ if (!Array.isArray(persisted)) return;
102
+ let changed = false;
103
+ for (const bucket of persisted) {
104
+ if (!isRequestMetricsBucket(bucket)) continue;
105
+ changed = true;
106
+ const existing = map.get(bucket.hourStartMs);
107
+ if (!existing) {
108
+ map.set(bucket.hourStartMs, { ...bucket });
109
+ continue;
110
+ }
111
+ // The sync engine can open the current hour's bucket with startup requests before this (async) hydrate
112
+ // resolves. Fold the persisted counts into the live bucket rather than skipping it, so earlier-in-the-hour
113
+ // totals from a previous session survive the restart instead of being dropped.
114
+ existing.requests += bucket.requests;
115
+ existing.bytes += bucket.bytes;
116
+ existing.durationTotalMs += bucket.durationTotalMs;
117
+ existing.durationCount += bucket.durationCount;
118
+ existing.errors += bucket.errors;
119
+ if (bucket.loadMax !== undefined) existing.loadMax = Math.max(existing.loadMax ?? bucket.loadMax, bucket.loadMax);
120
+ // Keep the live reading when the session has already recorded one (it is the most recent); otherwise fall
121
+ // back to the persisted last reading.
122
+ if (existing.loadLast === undefined && bucket.loadLast !== undefined) existing.loadLast = bucket.loadLast;
123
+ }
124
+ if (changed) commit();
125
+ },
126
+ };
127
+ }
128
+
129
+ export interface MeteredFetchOptions {
130
+ /** Default: !response.ok && response.status !== 304. */
131
+ isFailure?: (response: Response) => boolean;
132
+ /** Read this header as a server-load reading (WCPOS: 'X-Server-Load'). Default: not read. */
133
+ serverLoadHeader?: string;
134
+ now?: () => number;
135
+ }
136
+
137
+ // A 304 is a conditional poll answered from cache: a healthy request, not an amber hour.
138
+ const defaultIsFailure = (response: Response): boolean => !response.ok && response.status !== 304;
139
+
140
+ /** The header's value is a JSON array of load averages; its first entry is the reading. Anything else is ignored. */
141
+ function parseServerLoad(raw: string | null): number | undefined {
142
+ if (raw === null) return undefined;
143
+ try {
144
+ const parsed: unknown = JSON.parse(raw);
145
+ return Array.isArray(parsed) && isFiniteNumber(parsed[0]) ? parsed[0] : undefined;
146
+ } catch {
147
+ // Malformed server diagnostics must not affect the request.
148
+ return undefined;
149
+ }
150
+ }
151
+
152
+ /** Wraps `fetch` so each request lands in `metrics`. The response is returned as is, unread. */
153
+ export function meteredFetch(
154
+ fetch: typeof globalThis.fetch, metrics: RequestMetrics, options: MeteredFetchOptions = {},
155
+ ): typeof globalThis.fetch {
156
+ const now = options.now ?? Date.now;
157
+ const isFailure = options.isFailure ?? defaultIsFailure;
158
+ return async (input, init) => {
159
+ const start = now();
160
+ let response: Response;
161
+ try {
162
+ response = await fetch(input, init);
163
+ } catch (error) {
164
+ // An abort is OUR cancellation (a superseded request, a scope switch): it counts as a request that happened and
165
+ // never as a fault, or the hour turns amber with nothing in the log to explain it.
166
+ const aborted = (error as { name?: unknown } | null)?.name === 'AbortError' || init?.signal?.aborted === true;
167
+ metrics.record({ atMs: start, durationMs: now() - start, bytes: 0, failed: !aborted });
168
+ throw error;
169
+ }
170
+ const contentLength = Number(response.headers.get('content-length'));
171
+ // A malformed or negative content-length (a broken server or proxy) must not poison the hourly byte totals.
172
+ const bytes = Number.isFinite(contentLength) && contentLength >= 0 ? contentLength : 0;
173
+ metrics.record({ atMs: start, durationMs: now() - start, bytes, failed: isFailure(response) });
174
+ if (options.serverLoadHeader !== undefined) {
175
+ const load = parseServerLoad(response.headers.get(options.serverLoadHeader));
176
+ if (load !== undefined) metrics.recordServerLoad(load, start);
177
+ }
178
+ return response;
179
+ };
180
+ }
@@ -0,0 +1,93 @@
1
+ import { BehaviorSubject, type Observable } from 'rxjs';
2
+
3
+ import type { ConnectivityTracker } from './connectivity';
4
+ import type { SyncCadence } from './sync-cadence';
5
+
6
+ /** What a tick asks to check again. RxDB's replication state (and TallyReplicationState) fits as is. */
7
+ export interface SyncCadenceTarget { reSync(): void; isPaused?(): boolean }
8
+
9
+ export interface StartSyncCadenceOptions {
10
+ targets: readonly SyncCadenceTarget[];
11
+ /** Usually syncCadence$(collection). No timer runs until its first value. */
12
+ cadence$: Observable<SyncCadence>;
13
+ connectivity?: ConnectivityTracker;
14
+ /** Injectable for tests; default Math.random. */
15
+ random?: () => number;
16
+ /** Injectable for tests; default Date.now. Only used for nextDueAtMs$. */
17
+ now?: () => number;
18
+ }
19
+
20
+ export interface SyncCadenceRunner {
21
+ /** When the next tick is due (the `now()` clock), or undefined before the first cadence value and after stop. */
22
+ readonly nextDueAtMs$: Observable<number | undefined>;
23
+ /** Tick now ("Check now"), then re-arm from now. A no-op after stop. */
24
+ tickNow(): void;
25
+ /** Clears the timer, unsubscribes from cadence$, and emits undefined then completes nextDueAtMs$. Idempotent. */
26
+ stop(): void;
27
+ }
28
+
29
+ /** v2's ±20 % jitter (sync-engine change-signal/tick-cadence.ts). Exported for tests and for a "next check in" line. */
30
+ export function jitteredIntervalMs(intervalMs: number, random: () => number): number {
31
+ return Math.round(intervalMs * (0.8 + 0.4 * random()));
32
+ }
33
+
34
+ /**
35
+ * Opt-in polling beside startReplication: on each jittered tick, `reSync()` on every target that is not paused. A new
36
+ * cadence value re-arms the timer from now, as v2's reconfigure does. A tick is skipped while connectivity's
37
+ * update-required latch is set, never for offline or degraded: the replication's own backoff and holds decide those.
38
+ */
39
+ export function startSyncCadence({
40
+ targets, cadence$, connectivity, random = Math.random, now = Date.now,
41
+ }: StartSyncCadenceOptions): SyncCadenceRunner {
42
+ const nextDueAtMs$ = new BehaviorSubject<number | undefined>(undefined);
43
+ let current: SyncCadence | undefined;
44
+ let timer: ReturnType<typeof setTimeout> | undefined;
45
+ let stopped = false;
46
+
47
+ const tick = () => {
48
+ if (connectivity?.current().updateRequired) return;
49
+ for (const target of targets) {
50
+ // One throwing target never stops the others or the timer.
51
+ try {
52
+ if (target.isPaused?.() !== true) target.reSync();
53
+ } catch { /* swallowed */ }
54
+ }
55
+ };
56
+ const arm = () => {
57
+ if (timer !== undefined) clearTimeout(timer);
58
+ timer = undefined;
59
+ if (stopped || !current) return;
60
+ const delay = jitteredIntervalMs(current.checkIntervalMs, random);
61
+ timer = setTimeout(() => {
62
+ timer = undefined;
63
+ tick();
64
+ arm();
65
+ }, delay);
66
+ nextDueAtMs$.next(now() + delay);
67
+ };
68
+
69
+ const subscription = cadence$.subscribe((cadence) => {
70
+ if (stopped) return;
71
+ if (current && current.checkIntervalMs === cadence.checkIntervalMs && current.pullBatchSize === cadence.pullBatchSize) return;
72
+ current = cadence;
73
+ arm();
74
+ });
75
+
76
+ return {
77
+ nextDueAtMs$: nextDueAtMs$.asObservable(),
78
+ tickNow: () => {
79
+ if (stopped) return;
80
+ tick();
81
+ arm();
82
+ },
83
+ stop: () => {
84
+ if (stopped) return;
85
+ stopped = true;
86
+ if (timer !== undefined) clearTimeout(timer);
87
+ timer = undefined;
88
+ subscription.unsubscribe();
89
+ nextDueAtMs$.next(undefined);
90
+ nextDueAtMs$.complete();
91
+ },
92
+ };
93
+ }
@@ -0,0 +1,91 @@
1
+ import type { RxCollection, RxDatabase, RxJsonSchema } from 'rxdb';
2
+ import { distinctUntilChanged, map, type Observable } from 'rxjs';
3
+
4
+ import {
5
+ clampSyncCadence, DEFAULT_SYNC_CADENCE_PRESET, isSyncCadencePreset, SYNC_CADENCE_LIMITS, SYNC_CADENCE_PRESETS,
6
+ syncCadencePresetFor, type SyncCadence, type SyncCadenceChoice, type SyncCadencePreset,
7
+ } from './sync-cadence';
8
+
9
+ /** The chosen sync cadence of this device. The host adds the collection as `sync_cadence`, as with `printer_profiles`. */
10
+ export const SYNC_CADENCE_COLLECTION = 'sync_cadence';
11
+ /** One document per database: a TallyUI database belongs to one store session. */
12
+ export const SYNC_CADENCE_DOC_ID = 'default';
13
+
14
+ export interface SyncCadenceDoc {
15
+ id: string;
16
+ /** A named preset is stored by name; its numbers always come from SYNC_CADENCE_PRESETS. */
17
+ preset: SyncCadenceChoice;
18
+ /** Only when preset is 'custom'. */
19
+ checkIntervalMs?: number;
20
+ pullBatchSize?: number;
21
+ /** ISO 8601 instant of the last set. */
22
+ updatedAt: string;
23
+ }
24
+
25
+ // Local only: never replicated, never made with connectorCollection().
26
+ export const syncCadenceSchema: RxJsonSchema<SyncCadenceDoc> = {
27
+ version: 0, primaryKey: 'id', type: 'object', additionalProperties: false,
28
+ properties: {
29
+ id: { type: 'string', maxLength: 64 },
30
+ preset: { type: 'string', enum: ['eco', 'balanced', 'realtime', 'custom'] },
31
+ checkIntervalMs: {
32
+ type: 'integer', minimum: SYNC_CADENCE_LIMITS.checkIntervalMs.min, maximum: SYNC_CADENCE_LIMITS.checkIntervalMs.max,
33
+ },
34
+ pullBatchSize: {
35
+ type: 'integer', minimum: SYNC_CADENCE_LIMITS.pullBatchSize.min, maximum: SYNC_CADENCE_LIMITS.pullBatchSize.max,
36
+ },
37
+ updatedAt: { type: 'string' },
38
+ },
39
+ required: ['id', 'preset', 'updatedAt'],
40
+ };
41
+
42
+ export function syncCadenceCollection(): { readonly schema: RxJsonSchema<SyncCadenceDoc> } {
43
+ return { schema: syncCadenceSchema } as const;
44
+ }
45
+ export type SyncCadenceCollection = RxCollection<SyncCadenceDoc>;
46
+
47
+ export async function addSyncCadenceCollection(db: RxDatabase): Promise<SyncCadenceCollection> {
48
+ const added = await db.addCollections({ [SYNC_CADENCE_COLLECTION]: syncCadenceCollection() });
49
+ return added[SYNC_CADENCE_COLLECTION] as SyncCadenceCollection;
50
+ }
51
+
52
+ export interface SyncCadenceProfile extends SyncCadence { preset: SyncCadenceChoice }
53
+
54
+ function resolve(doc: Pick<SyncCadenceDoc, 'preset' | 'checkIntervalMs' | 'pullBatchSize'> | null): SyncCadenceProfile {
55
+ if (!doc) return { preset: DEFAULT_SYNC_CADENCE_PRESET, ...SYNC_CADENCE_PRESETS[DEFAULT_SYNC_CADENCE_PRESET] };
56
+ if (isSyncCadencePreset(doc.preset)) return { preset: doc.preset, ...SYNC_CADENCE_PRESETS[doc.preset] };
57
+ const { checkIntervalMs, pullBatchSize } = doc;
58
+ return { preset: 'custom', ...clampSyncCadence({ checkIntervalMs, pullBatchSize }) };
59
+ }
60
+
61
+ export async function readSyncCadence(collection: SyncCadenceCollection): Promise<SyncCadenceProfile> {
62
+ return resolve(await collection.findOne(SYNC_CADENCE_DOC_ID).exec());
63
+ }
64
+
65
+ export function syncCadence$(collection: SyncCadenceCollection): Observable<SyncCadenceProfile> {
66
+ return collection.findOne(SYNC_CADENCE_DOC_ID).$.pipe(
67
+ map(resolve),
68
+ distinctUntilChanged((a, b) =>
69
+ a.preset === b.preset && a.checkIntervalMs === b.checkIntervalMs && a.pullBatchSize === b.pullBatchSize),
70
+ );
71
+ }
72
+
73
+ export async function setSyncCadence(
74
+ collection: SyncCadenceCollection, value: SyncCadencePreset | SyncCadence, options?: { now?: () => number },
75
+ ): Promise<SyncCadenceProfile> {
76
+ if (typeof value === 'string' && !isSyncCadencePreset(value)) {
77
+ throw new TypeError(`unknown sync cadence preset: ${String(value)}`);
78
+ }
79
+ const updatedAt = new Date((options?.now ?? Date.now)()).toISOString();
80
+ const clamped = typeof value === 'string' ? undefined : clampSyncCadence(value);
81
+ const preset = clamped ? syncCadencePresetFor(clamped) : (value as SyncCadencePreset);
82
+ const doc: SyncCadenceDoc = { id: SYNC_CADENCE_DOC_ID, preset, ...(preset === 'custom' ? clamped : {}), updatedAt };
83
+ await collection.upsert(doc);
84
+ return resolve(doc);
85
+ }
86
+
87
+ export function resetSyncCadence(
88
+ collection: SyncCadenceCollection, options?: { now?: () => number },
89
+ ): Promise<SyncCadenceProfile> {
90
+ return setSyncCadence(collection, DEFAULT_SYNC_CADENCE_PRESET, options);
91
+ }
@@ -0,0 +1,79 @@
1
+ // Ported from WCPOS v2 apps/main/components/health/performance-logic.ts (monorepo 85ecbd43f).
2
+
3
+ /** How often the till checks the store for changes, and how many records each check's page may carry. */
4
+ export interface SyncCadence { checkIntervalMs: number; pullBatchSize: number }
5
+
6
+ /**
7
+ * The presets, macros over the two dials.
8
+ *
9
+ * Two independent budget lines: `checkIntervalMs` prices how often we ask, `pullBatchSize` how heavy each request
10
+ * is. Page weight is what hurts shared hosting, and the check interval only multiplies it, so each tier moves both
11
+ * lines, and no preset ships the 100-record maximum: that stays reachable only through Custom.
12
+ *
13
+ * Eco 5 min · 25 — 12 checks/hour, lightest page
14
+ * Balanced 60 s · 50 — 60 checks/hour
15
+ * Realtime 10 s · 75 — 360 checks/hour, fast but not max-weight pages
16
+ *
17
+ * The numbers are in one table so they are easy to re-tune.
18
+ */
19
+ export const SYNC_CADENCE_PRESETS = {
20
+ eco: { checkIntervalMs: 300_000, pullBatchSize: 25 },
21
+ balanced: { checkIntervalMs: 60_000, pullBatchSize: 50 },
22
+ realtime: { checkIntervalMs: 10_000, pullBatchSize: 75 },
23
+ } as const;
24
+
25
+ export type SyncCadencePreset = keyof typeof SYNC_CADENCE_PRESETS;
26
+ export type SyncCadenceChoice = SyncCadencePreset | 'custom';
27
+
28
+ /** The shipped default: what a fresh till gets, and what "Reset" restores. */
29
+ export const DEFAULT_SYNC_CADENCE_PRESET: SyncCadencePreset = 'balanced';
30
+
31
+ /** v2 cadence-controller.ts reconfigure's clamp bounds. */
32
+ export const SYNC_CADENCE_LIMITS = {
33
+ checkIntervalMs: { min: 5000, max: 300000 },
34
+ pullBatchSize: { min: 10, max: 100 },
35
+ } as const;
36
+
37
+ export function isSyncCadencePreset(value: unknown): value is SyncCadencePreset {
38
+ return typeof value === 'string' && Object.prototype.hasOwnProperty.call(SYNC_CADENCE_PRESETS, value);
39
+ }
40
+
41
+ function clampField(name: keyof SyncCadence, value: number | undefined): number {
42
+ const raw = value ?? SYNC_CADENCE_PRESETS[DEFAULT_SYNC_CADENCE_PRESET][name];
43
+ if (!Number.isFinite(raw)) throw new TypeError(`${name} must be a finite number`);
44
+ const { min, max } = SYNC_CADENCE_LIMITS[name];
45
+ return Math.min(max, Math.max(min, Math.trunc(raw)));
46
+ }
47
+
48
+ /**
49
+ * Math.trunc, then clamp to SYNC_CADENCE_LIMITS. A missing field takes Balanced's number. Throws TypeError on a
50
+ * non-finite number, as v2's reconfigure does.
51
+ */
52
+ export function clampSyncCadence(value: Partial<SyncCadence>): SyncCadence {
53
+ return {
54
+ checkIntervalMs: clampField('checkIntervalMs', value.checkIntervalMs),
55
+ pullBatchSize: clampField('pullBatchSize', value.pullBatchSize),
56
+ };
57
+ }
58
+
59
+ /** v2's presetFor: an exact match on both numbers gives the preset's name, anything else gives 'custom'. */
60
+ export function syncCadencePresetFor(value: SyncCadence): SyncCadenceChoice {
61
+ for (const name of Object.keys(SYNC_CADENCE_PRESETS) as SyncCadencePreset[]) {
62
+ const preset = SYNC_CADENCE_PRESETS[name];
63
+ if (preset.checkIntervalMs === value.checkIntervalMs && preset.pullBatchSize === value.pullBatchSize) return name;
64
+ }
65
+ return 'custom';
66
+ }
67
+
68
+ /** Both budget lines in the preset's own numbers, derived so copy can never drift from the table. */
69
+ export function syncCadencePresetBudget(name: SyncCadencePreset): { intervalSeconds: number; records: number } {
70
+ return {
71
+ intervalSeconds: Math.round(SYNC_CADENCE_PRESETS[name].checkIntervalMs / 1000),
72
+ records: SYNC_CADENCE_PRESETS[name].pullBatchSize,
73
+ };
74
+ }
75
+
76
+ /** Checks per hour at this interval, rounded to a whole number. */
77
+ export function requestsPerHour(checkIntervalMs: number): number {
78
+ return Math.round(3_600_000 / checkIntervalMs);
79
+ }