Repository navigation
Expand file tree
/
Copy pathknowledge-record-sync-queue.ts
More file actions
250 lines (228 loc) · 11.9 KB
/
Copy pathknowledge-record-sync-queue.ts
File metadata and controls
250 lines (228 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
import type { IQueueService, QueuePublishOptions } from '@objectstack/spec/contracts';
/**
* The queue the record sync runs through (ADR-0161 K1): the save of an
* indexed record publishes one message here per source over its object, and
* the plugin's worker, subscribed in `kernel:ready`, syncs the document.
*/
export const KNOWLEDGE_RECORD_SYNC_QUEUE = 'knowledge-record-sync';
/**
* Why a record sync was asked for: a record change (`event`, from either
* trigger — the realtime subscription or the after-write hooks), or a search
* that found the record's document stale (`freshness`).
*/
export type KnowledgeRecordSyncReason = 'event' | 'freshness';
/**
* One record-sync message: identifiers only. ⛔ Never a field value:
* `sys_job_queue` is an object an administrator can list, and a record body
* there would be a copy of the row outside its permissions. The worker
* re-reads the row, so it needs nothing else.
*/
export interface KnowledgeRecordSyncMessage {
/** The source's index key (the registry's key, never its face). */
source: string;
/** The object the record belongs to. */
object: string;
/** The record's id. */
recordId: string;
reason: KnowledgeRecordSyncReason;
}
/**
* The retry budget of a queued record sync: a failed attempt is thrown to the
* queue, which runs it again after an exponential backoff (`backoffMs`,
* doubled each attempt, capped at `maxBackoffMs`); after `maxAttempts` the
* message is a dead letter (`IQueueService.listFailed`).
*/
export interface KnowledgeRecordSyncRetry {
maxAttempts: number;
backoffMs: number;
maxBackoffMs: number;
}
/**
* The default budget: eight attempts, 5 s doubling to a 2 min cap. The seven
* waits between them sum to 395 s, so a provider outage of six and a half
* minutes is ridden out before a message becomes a dead letter; the reconcile
* repairs what a dead letter names.
*/
export const RECORD_SYNC_RETRY_DEFAULTS: Readonly<KnowledgeRecordSyncRetry> = Object.freeze({
maxAttempts: 8,
backoffMs: 5_000,
maxBackoffMs: 120_000,
});
/** `retry` with every member it leaves out taken from {@link RECORD_SYNC_RETRY_DEFAULTS}. */
export function resolveRecordSyncRetry(retry: Partial<KnowledgeRecordSyncRetry> | undefined): KnowledgeRecordSyncRetry {
const positive = (value: unknown, fallback: number): number =>
typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : fallback;
return {
maxAttempts: positive(retry?.maxAttempts, RECORD_SYNC_RETRY_DEFAULTS.maxAttempts),
backoffMs: positive(retry?.backoffMs, RECORD_SYNC_RETRY_DEFAULTS.backoffMs),
maxBackoffMs: positive(retry?.maxBackoffMs, RECORD_SYNC_RETRY_DEFAULTS.maxBackoffMs),
};
}
/**
* The publish options of one message: the retry budget, and the source and
* record in the message metadata, so a dead letter names them. No
* `idempotencyKey`, deliberately: the database queue suppresses a publish
* while a message with the same key is `pending` or `running`, and for its
* idempotency window after it completed. Keyed by document, a save made while
* a sync of the same record runs — the sync has already read the row — would
* be lost, and a completed sync would block every later save of that record
* for the window. So every save publishes its own message, and each worker
* run re-reads the row as it is then.
*/
export function recordSyncPublishOptions(
message: KnowledgeRecordSyncMessage,
retry: KnowledgeRecordSyncRetry,
): QueuePublishOptions {
return {
maxAttempts: retry.maxAttempts,
backoff: { type: 'exponential', delayMs: retry.backoffMs, maxDelayMs: retry.maxBackoffMs },
metadata: { source: message.source, object: message.object, recordId: message.recordId, reason: message.reason },
};
}
/** `data` as a {@link KnowledgeRecordSyncMessage}, or `undefined` when it is not one. */
export function readRecordSyncMessage(data: unknown): KnowledgeRecordSyncMessage | undefined {
if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;
const { source, object, recordId, reason } = data as Record<string, unknown>;
const text = (value: unknown): value is string => typeof value === 'string' && value !== '';
if (!text(source) || !text(object) || !text(recordId)) return undefined;
if (reason !== 'event' && reason !== 'freshness') return undefined;
return { source, object, recordId, reason };
}
/**
* The `queue` service the record sync can run through, else `undefined`:
* none registered, one that cannot publish and subscribe, the kernel's
* built-in fallback (it labels itself `degraded`: synchronous in-process
* delivery, no durability, no retry — the reading of `resolveDurableQueue`
* in `@objectstack/plugin-email`), or one with no dead-letter surface
* (`listFailed`). The last is this sync's own condition: a sync that fails
* every attempt must stay somewhere an operator can list, and an in-memory
* queue (`MemoryQueueAdapter`) retries nothing and keeps nothing, so a failed
* sync there would be lost without a line in any log. The platform's
* database queue (`DbQueueAdapter`) has one.
*/
export function resolveRecordSyncQueue(getService: (name: string) => unknown): IQueueService | undefined {
let queue: unknown;
try {
queue = getService('queue');
} catch {
return undefined;
}
const candidate = queue as (Partial<IQueueService> & { __serviceInfo?: { status?: unknown } }) | undefined;
if (!candidate || typeof candidate.publish !== 'function' || typeof candidate.subscribe !== 'function') return undefined;
if (candidate.__serviceInfo?.status === 'degraded') return undefined;
if (typeof candidate.listFailed !== 'function') return undefined;
return candidate as IQueueService;
}
/**
* What one worker run of a message did. Every outcome but a throw completes
* the message: the ones below are not retried, because a retry cannot change
* them.
*
* - `synced` — the document was written from the row, or deleted because no
* row matches the source's `where` (a `whole` document over the embedder's
* budget is removed and reported at `error`, as on every path);
* - `source-gone` — no source has the message's index key any more;
* - `not-synced` — the source no longer indexes the message's object on
* record change (`refresh.onRecordChange: false`, or another object), or
* no data engine is bound to re-read the row;
* - `malformed` — the message is not a record-sync message;
* - `covered` — a complete build of the source that finished on this node
* (`done`, with its purge run) began at least
* {@link RECORD_SYNC_COVER_MARGIN_MS} after the message was published, so
* its walk wrote the record's document or its purge deleted it: nothing is
* read, embedded or written. A build that purged nothing covers nothing.
*/
export type KnowledgeRecordSyncOutcome = 'synced' | 'source-gone' | 'not-synced' | 'malformed' | 'covered';
/**
* The most record-sync messages the worker takes in one call where the queue
* consumes in batches (`IQueueService.subscribeBatch`): the reindex page size
* (`REINDEX_PAGE_SIZE`), so a batch is one re-read, one split, one `upsert`
* the embedder splits into its provider's requests, and one `delete` — about
* what one page of a rebuild costs. The adapter renews the lease of every
* claimed message while the batch runs; a batch that settles in seconds also
* leaves a crashed worker's messages to come back one lease (30 s by
* default) later, not after a long batch.
*/
export const RECORD_SYNC_BATCH_SIZE = 100;
/**
* The smallest estimated backlog of one source, in waiting record-sync
* messages, for which the worker schedules one reconcile of that source (the
* complete build, trigger `reconcile`) beside its syncs. The estimate is the
* queue's waiting count (`IQueueService.getQueueSize`) times the source's
* share of the batch in hand. Measured (#38413, a local model: SQLite, a
* 50,000-row source, an embedder at 200 ms per request + 0.5 ms per input),
* the batch worker drains 214 changed records per second, so 5,000 messages
* are about 23 s of draining; a smaller backlog is gone about as soon as a
* walk could start.
*/
export const RECORD_SYNC_BACKLOG_THRESHOLD = 5_000;
/**
* The share of a source's rows (its `where`, counted) that its estimated
* backlog must also reach ({@link RECORD_SYNC_BACKLOG_THRESHOLD}), so a small
* write to a large source is drained, not walked. In the same local model a
* reconcile walk reads 50,000 unchanged rows in 1.4 s (no embedding), and
* draining costs 2.1 ms per message for an unchanged record and 4.7 ms for a
* changed one; at 5 % of the rows the walk's own reading is about a quarter
* of the drain it runs beside, or less. Measured on a 50,000-message backlog
* of a 50,000-row source: 217 s against 233 s draining alone with every
* record changed, 91 s against 106 s with none changed.
*/
export const RECORD_SYNC_BACKLOG_ROW_SHARE = 0.05;
/**
* After a backlog reconcile of a source ended `done`, the next one for that
* source waits at least this long: a source under sustained writes is
* drained between walks, not walked back to back.
*/
export const RECORD_SYNC_BACKLOG_REWALK_MS = 10 * 60_000;
/**
* After a backlog reconcile of a source did not end `done` (failed, lease
* lost, timed out, purge not run), the next one waits this long, doubling
* per failure up to {@link RECORD_SYNC_BACKLOG_RETRY_MAX_MS}.
*/
export const RECORD_SYNC_BACKLOG_RETRY_MS = 5 * 60_000;
/** The ceiling of {@link RECORD_SYNC_BACKLOG_RETRY_MS}'s doubling. */
export const RECORD_SYNC_BACKLOG_RETRY_MAX_MS = 60 * 60_000;
/** How long the worker keeps a source's counted rows ({@link RECORD_SYNC_BACKLOG_ROW_SHARE}) before it counts again. */
export const RECORD_SYNC_SOURCE_ROWS_TTL_MS = 10 * 60_000;
/** How often the worker reads the queue's backlog at most: one count per interval, not one per batch. */
export const RECORD_SYNC_BACKLOG_READ_INTERVAL_MS = 30_000;
/**
* How much earlier than a build's start a message must have been published
* for that build to cover it (`covered`). A message inside the margin is
* synced as usual; that normal sync is the margin's only cost. It guards two
* things:
*
* - clock skew: the publish time is stamped by the publishing node's queue
* and the build's start by the building node's clock;
* - a sync still in flight: a sync that re-read the record before a later
* write, and whose store write lands after the build's walk wrote the
* record (or after its listing, for a record created and then deleted),
* leaves the older document in the index. The later write's message must
* then be synced, not covered, and it is whenever the build began within
* the margin of that write.
*
* The margin is the queue adapter's default message lease
* (`DbQueueAdapterOptions.leaseMs`, 30 s), which a batch is sized to settle
* well inside (`QueueBatchSubscribeOptions.maxBatch`). What stays uncovered:
* a sync in flight for longer than the margin (a live handler keeps renewing
* its lease, so the lease does not bound it; a slow embedding provider is the
* way there), plus skew beyond what the sync's own time leaves of the margin.
* Such a stale document stays until the next build that purges, which is
* where ADR-0161 K1 puts an index's correctness.
*/
export const RECORD_SYNC_COVER_MARGIN_MS = 30_000;
/** One message handed to `KnowledgeService.processRecordSyncBatch`: its payload, and when the queue says it was published (epoch ms). */
export interface KnowledgeRecordSyncBatchItem {
data: unknown;
publishedAt?: number;
}
/**
* What `KnowledgeService.processRecordSyncBatch` answers for one message, in
* the batch's order: an outcome that completes it, or the error that fails
* it (the queue retries it, and keeps it as a dead letter once its attempts
* are spent).
*/
export type KnowledgeRecordSyncBatchResult =
| { ok: true; outcome: KnowledgeRecordSyncOutcome }
| { ok: false; error: unknown };