@jini-ai/search 0.7.2 → 0.7.3-next.2

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,141 @@
1
+ import { encodeSearchKey } from './contract.js';
2
+ import {} from './api.js';
3
+ import {} from './ports.js';
4
+ import { guarded, chunks } from './indexer-write.js';
5
+ const RECONCILE_STATUSES = ['pending', 'unknown', 'failed'];
6
+ /** Compare-and-swap a settled row against the identity the caller observed (see `settle`). */
7
+ export function createIndexerSettleObserved({ state }) {
8
+ return (row, settled) => state.settle({ row: settled, expected: { revision: row.revision, taskId: row.taskId ?? null } });
9
+ }
10
+ export function createIndexerSettledRow({ now }) {
11
+ return (row, settle) => ({
12
+ target: row.target, key: row.key, revision: row.revision, deleted: row.deleted, attempts: row.attempts,
13
+ status: settle.status, updatedAtMs: now(),
14
+ ...(settle.lastError === undefined ? {} : { lastError: settle.lastError }),
15
+ });
16
+ }
17
+ /**
18
+ * Ask an async provider how an earlier `pending` write ended. 1 when it is now indexed. The settle
19
+ * only lands while the row still holds this revision AND this task: an event that wrote a newer
20
+ * revision while the task was awaited keeps its own pending task (and its retry) intact.
21
+ */
22
+ export function createIndexerSettleTask(dependencies) {
23
+ return async (row, resolved, { taskId, awaitTask }) => {
24
+ const { settleObserved, settledRow } = dependencies();
25
+ const result = await guarded(() => awaitTask.call(resolved.provider, resolved.ctx, { taskId }));
26
+ if (result.status !== 'ok' || result.value === 'pending')
27
+ return 0;
28
+ const succeeded = result.value === 'succeeded';
29
+ const written = await settleObserved(row, settledRow(row, succeeded ? { status: 'indexed' } : { status: 'failed', lastError: 'task_failed' }));
30
+ return succeeded && written ? 1 : 0;
31
+ };
32
+ }
33
+ /**
34
+ * Settle indeterminate rows by asking the provider what it holds. A row whose write landed is
35
+ * marked indexed; anything else is returned for a re-load and re-write (never blindly marked
36
+ * failed: an `unknown` outcome may well have happened).
37
+ */
38
+ export function createIndexerCheckRevisions(dependencies) {
39
+ return async (rows, resolved) => {
40
+ const { checkChunk } = dependencies();
41
+ let settled = 0;
42
+ const rewrite = [];
43
+ for (const chunk of chunks(rows, Math.max(1, resolved.provider.capabilities.maxBatch))) {
44
+ const checked = await checkChunk(chunk, resolved);
45
+ settled += checked.settled;
46
+ rewrite.push(...checked.rewrite);
47
+ }
48
+ return { settled, rewrite };
49
+ };
50
+ }
51
+ /** One `revisionOf` call's worth of {@link checkRevisions}; an indeterminate answer leaves the rows as they are. */
52
+ export function createIndexerCheckChunk(dependencies) {
53
+ return async (chunk, resolved) => {
54
+ const { settleObserved, settledRow } = dependencies();
55
+ const result = await guarded(() => resolved.provider.revisionOf(resolved.ctx, { keys: chunk.map(row => row.key) }));
56
+ if (result.status !== 'ok')
57
+ return { settled: 0, rewrite: [] };
58
+ const held = new Map(result.value.map(entry => [encodeSearchKey({ key: entry.key }), entry]));
59
+ let settled = 0;
60
+ const rewrite = [];
61
+ for (const row of chunk) {
62
+ if (!hasLanded(held.get(encodeSearchKey({ key: row.key })), row)) {
63
+ rewrite.push(row);
64
+ continue;
65
+ }
66
+ if (await settleObserved(row, settledRow(row, { status: 'indexed' })))
67
+ settled += 1;
68
+ }
69
+ return { settled, rewrite };
70
+ };
71
+ }
72
+ /** `pending` rows with a task are awaited; `unknown` rows (and a `pending` row whose process died
73
+ * between marking and the call, so it has no task) are checked with `revisionOf`. */
74
+ export function createIndexerSettleInFlight(dependencies) {
75
+ return async (rows, resolved) => {
76
+ const { settleTask, checkRevisions } = dependencies();
77
+ const { awaitTask } = resolved.provider;
78
+ let settled = 0;
79
+ const check = [];
80
+ for (const row of rows) {
81
+ if (row.status === 'pending' && row.taskId !== undefined && awaitTask)
82
+ settled += await settleTask(row, resolved, { taskId: row.taskId, awaitTask });
83
+ else
84
+ check.push(row);
85
+ }
86
+ const checked = await checkRevisions(check, resolved);
87
+ return { settled: settled + checked.settled, rewrite: checked.rewrite };
88
+ };
89
+ }
90
+ /** Re-load the row's document from its source and write the current truth again (a retry). */
91
+ export function createIndexerRewriteRow({ sources, now }, dependencies) {
92
+ return async (row, workspaceId) => {
93
+ const { settleObserved, writeToTarget, settledRow } = dependencies();
94
+ const source = sources.find(candidate => candidate.collection === row.key.collection);
95
+ if (!source) {
96
+ await settleObserved(row, { ...settledRow(row, { status: 'failed', lastError: 'no_source' }), attempts: row.attempts + 1 });
97
+ return 0;
98
+ }
99
+ const record = await source.load({ siteId: row.target.siteId, workspaceId: row.key.workspaceId, documentId: row.key.documentId, occurredAtMs: now() });
100
+ return (await writeToTarget({ target: row.target, workspaceId, records: [record], retry: true })).indexed;
101
+ };
102
+ }
103
+ export function createIndexerReconcileTarget({ state, maxAttempts }, dependencies) {
104
+ return async (target, workspaceId, limit) => {
105
+ const { resolve, settleInFlight, rewriteRow } = dependencies();
106
+ // Exhausted failures are excluded before the limit, or the oldest of them would fill every sweep.
107
+ const rows = await state.listByStatus({ target, statuses: RECONCILE_STATUSES, limit }, { failedBelowAttempts: maxAttempts });
108
+ const retry = rows.filter(row => row.status === 'failed' && row.attempts < maxAttempts);
109
+ const inFlight = rows.filter(row => row.status !== 'failed');
110
+ const resolved = inFlight.length === 0 ? null : await resolve(target, workspaceId);
111
+ // Without a provider nothing in flight can be checked; those rows wait for configuration.
112
+ const inFlightResult = resolved ? await settleInFlight(inFlight, resolved) : { settled: 0, rewrite: [] };
113
+ let settled = inFlightResult.settled;
114
+ for (const row of [...inFlightResult.rewrite, ...retry])
115
+ settled += await rewriteRow(row, workspaceId);
116
+ return settled;
117
+ };
118
+ }
119
+ export function createIndexerReconcile({ state }, dependencies) {
120
+ const operation = async ({ siteId, workspaceId }, { limit = 50 } = {}) => {
121
+ const { currentTargets, reconcileTarget, dropRetired } = dependencies();
122
+ // Retries the index drop of every replaced generation not yet confirmed gone.
123
+ await dropRetired(siteId, workspaceId);
124
+ const list = await currentTargets(siteId);
125
+ let settled = 0;
126
+ for (const target of list)
127
+ settled += await reconcileTarget(target, workspaceId, limit);
128
+ let remaining = 0;
129
+ for (const target of list) {
130
+ const counts = await state.counts({ target });
131
+ remaining += counts.pending + counts.unknown + counts.failed;
132
+ }
133
+ return { settled, remaining };
134
+ };
135
+ return operation;
136
+ }
137
+ /** Whether the provider holds this row's write: its revision or a newer one, with the same deletion state. */
138
+ function hasLanded(entry, row) {
139
+ return entry !== undefined && entry.revision !== null && entry.revision >= row.revision && entry.deleted === row.deleted;
140
+ }
141
+ //# sourceMappingURL=indexer-reconcile.js.map
@@ -0,0 +1,86 @@
1
+ import { type ProviderResult } from '@jini-ai/core/provider-registry';
2
+ import { type SearchProvider, type SearchProviderContext, type SearchWriteResult } from './contract.js';
3
+ import { type SearchIndexStatePort, type SearchIndexStateRow, type SearchIndexStatus, type SearchSourceRecord, type SearchTarget, type SearchTargetPort } from './ports.js';
4
+ import type { SearchIndexerRequired } from './indexer.js';
5
+ /** The lastError recorded when a target's provider is not registered or has no context. */
6
+ export declare const SEARCH_NOT_CONFIGURED = "not_configured";
7
+ export interface Resolved {
8
+ readonly provider: SearchProvider;
9
+ readonly ctx: SearchProviderContext;
10
+ }
11
+ interface Plan {
12
+ readonly record: SearchSourceRecord;
13
+ readonly attempts: number;
14
+ readonly upsert: boolean;
15
+ }
16
+ export interface Settle {
17
+ readonly status: SearchIndexStatus;
18
+ readonly taskId?: string;
19
+ readonly lastError?: string;
20
+ }
21
+ interface WriteTally {
22
+ readonly written: number;
23
+ readonly indexed: number;
24
+ }
25
+ /** Run one provider call; a provider that throws despite the contract becomes an `unknown`. */
26
+ export declare function guarded<T>(call: () => Promise<ProviderResult<T>>): Promise<ProviderResult<T>>;
27
+ export declare function chunks<T>(items: readonly T[], size: number): T[][];
28
+ export declare function createIndexerResolve({ required, registry }: {
29
+ required: SearchIndexerRequired;
30
+ registry: SearchIndexerRequired['registry'];
31
+ }): (target: SearchTarget, workspaceId: string) => Promise<Resolved | null>;
32
+ export declare function createIndexerPlanRow({ now }: {
33
+ now: SearchIndexerRequired['now'];
34
+ }): (target: SearchTarget, plan: Plan, settle: Settle) => SearchIndexStateRow;
35
+ export declare function createIndexerPutPlan({ state }: {
36
+ state: SearchIndexStatePort;
37
+ }, dependencies: () => {
38
+ planRow: ReturnType<typeof createIndexerPlanRow>;
39
+ }): (target: SearchTarget, plan: Plan, settle: Settle) => Promise<boolean>;
40
+ /**
41
+ * Records worth writing, each with its attempt number. An event/backfill write is skipped when
42
+ * the row already holds an equal or newer revision (a delayed or duplicated event); a retry only
43
+ * skips an OLDER revision, because retrying the same revision is the point of a retry.
44
+ */
45
+ export declare function createIndexerFreshRecords({ state }: {
46
+ state: SearchIndexStatePort;
47
+ }): (target: SearchTarget, records: readonly SearchSourceRecord[], retry: boolean) => Promise<{
48
+ record: SearchSourceRecord;
49
+ attempts: number;
50
+ }[]>;
51
+ /**
52
+ * Map one write call's result onto its plans' rows; returns how many ended `indexed`. Each settle
53
+ * is a compare-and-swap on the `pending` mark this write made (its revision, no task): a newer
54
+ * revision written meanwhile owns the row and is never overwritten by this older completion.
55
+ */
56
+ export declare function createIndexerSettleCall({ state }: {
57
+ state: SearchIndexStatePort;
58
+ }, dependencies: () => {
59
+ planRow: ReturnType<typeof createIndexerPlanRow>;
60
+ }): (target: SearchTarget, plans: readonly Plan[], result: ProviderResult<SearchWriteResult>) => Promise<number>;
61
+ export declare function createIndexerWriteChunks(dependencies: () => {
62
+ settleCall: ReturnType<typeof createIndexerSettleCall>;
63
+ }): <T>(input: {
64
+ target: SearchTarget;
65
+ plans: readonly Plan[];
66
+ maxBatch: number;
67
+ payload: (plan: Plan) => T;
68
+ call: (items: T[]) => Promise<ProviderResult<SearchWriteResult>>;
69
+ }) => Promise<number>;
70
+ /** Write records to ONE target: mark pending, call the provider in batches, settle each row. */
71
+ export declare function createIndexerWriteToTarget(dependencies: () => {
72
+ resolve: ReturnType<typeof createIndexerResolve>;
73
+ putPlan: ReturnType<typeof createIndexerPutPlan>;
74
+ freshRecords: ReturnType<typeof createIndexerFreshRecords>;
75
+ writeChunks: ReturnType<typeof createIndexerWriteChunks>;
76
+ }): (input: {
77
+ target: SearchTarget;
78
+ workspaceId: string;
79
+ records: readonly SearchSourceRecord[];
80
+ retry: boolean;
81
+ }) => Promise<WriteTally>;
82
+ export declare function createIndexerCurrentTargets({ targets }: {
83
+ targets: SearchTargetPort;
84
+ }): (siteId: string) => Promise<SearchTarget[]>;
85
+ export {};
86
+ //# sourceMappingURL=indexer-write.d.ts.map
@@ -0,0 +1,174 @@
1
+ import { providerUnknown } from '@jini-ai/core/provider-registry';
2
+ import { encodeSearchKey } from './contract.js';
3
+ import {} from './ports.js';
4
+ /** The lastError recorded when a target's provider is not registered or has no context. */
5
+ export const SEARCH_NOT_CONFIGURED = 'not_configured';
6
+ const OUTCOME_STATUS = {
7
+ applied: 'indexed',
8
+ // The provider already holds an equal or newer revision: nothing is left to do for this key.
9
+ stale: 'indexed',
10
+ pending: 'pending',
11
+ rejected: 'failed',
12
+ };
13
+ /** Run one provider call; a provider that throws despite the contract becomes an `unknown`. */
14
+ export async function guarded(call) {
15
+ try {
16
+ return await call();
17
+ }
18
+ catch {
19
+ return providerUnknown({ code: 'unexpected_response', message: 'search provider threw' });
20
+ }
21
+ }
22
+ export function chunks(items, size) {
23
+ const out = [];
24
+ for (let i = 0; i < items.length; i += size)
25
+ out.push(items.slice(i, i + size));
26
+ return out;
27
+ }
28
+ function targetList(targets) {
29
+ return [targets.active, targets.building].filter((target) => target !== null);
30
+ }
31
+ /**
32
+ * Upsert only a document the target's provider may hold. Vendors are public-only, so a restricted
33
+ * document, a draft, a trashed or a not-yet-live record all become a REMOVAL there: a public→members
34
+ * change must delete the document from the vendor, not update it in place.
35
+ */
36
+ function shouldUpsert(record, provider) {
37
+ const { document } = record;
38
+ if (document === null)
39
+ return false;
40
+ return document.visibility.kind === 'public' || provider.capabilities.acceptsRestricted;
41
+ }
42
+ export function createIndexerResolve({ required, registry }) {
43
+ return async (target, workspaceId) => {
44
+ const provider = registry.get({ id: target.providerId })?.provider;
45
+ if (!provider)
46
+ return null;
47
+ const ctx = await required.contextFor({ target, workspaceId });
48
+ return ctx ? { provider, ctx } : null;
49
+ };
50
+ }
51
+ export function createIndexerPlanRow({ now }) {
52
+ return (target, plan, settle) => ({
53
+ target, key: plan.record.key, revision: plan.record.revision, deleted: !plan.upsert,
54
+ status: settle.status, attempts: plan.attempts, updatedAtMs: now(),
55
+ ...(settle.taskId === undefined ? {} : { taskId: settle.taskId }),
56
+ ...(settle.lastError === undefined ? {} : { lastError: settle.lastError }),
57
+ });
58
+ }
59
+ export function createIndexerPutPlan({ state }, dependencies) {
60
+ return (target, plan, settle) => {
61
+ const { planRow } = dependencies();
62
+ return state.put({ row: planRow(target, plan, settle) });
63
+ };
64
+ }
65
+ /**
66
+ * Records worth writing, each with its attempt number. An event/backfill write is skipped when
67
+ * the row already holds an equal or newer revision (a delayed or duplicated event); a retry only
68
+ * skips an OLDER revision, because retrying the same revision is the point of a retry.
69
+ */
70
+ export function createIndexerFreshRecords({ state }) {
71
+ return async (target, records, retry) => {
72
+ const fresh = [];
73
+ for (const record of records) {
74
+ const prior = await state.get({ target, key: record.key });
75
+ const skip = prior !== null && (retry ? prior.revision > record.revision : prior.revision >= record.revision);
76
+ if (skip)
77
+ continue;
78
+ const attempts = (prior !== null && prior.revision === record.revision ? prior.attempts : 0) + 1;
79
+ fresh.push({ record, attempts });
80
+ }
81
+ return fresh;
82
+ };
83
+ }
84
+ /**
85
+ * Map one write call's result onto its plans' rows; returns how many ended `indexed`. Each settle
86
+ * is a compare-and-swap on the `pending` mark this write made (its revision, no task): a newer
87
+ * revision written meanwhile owns the row and is never overwritten by this older completion.
88
+ */
89
+ export function createIndexerSettleCall({ state }, dependencies) {
90
+ return async (target, plans, result) => {
91
+ const { planRow } = dependencies();
92
+ let indexed = 0;
93
+ for (const plan of plans) {
94
+ const settle = settleOf(plan, result);
95
+ const written = await state.settle({ row: planRow(target, plan, settle), expected: { revision: plan.record.revision, taskId: null } });
96
+ if (written && settle.status === 'indexed')
97
+ indexed += 1;
98
+ }
99
+ return indexed;
100
+ };
101
+ }
102
+ export function createIndexerWriteChunks(dependencies) {
103
+ return async (input) => {
104
+ const { settleCall } = dependencies();
105
+ let indexed = 0;
106
+ for (const chunk of chunks(input.plans, input.maxBatch)) {
107
+ const result = await guarded(() => input.call(chunk.map(input.payload)));
108
+ indexed += await settleCall(input.target, chunk, result);
109
+ }
110
+ return indexed;
111
+ };
112
+ }
113
+ /** Write records to ONE target: mark pending, call the provider in batches, settle each row. */
114
+ export function createIndexerWriteToTarget(dependencies) {
115
+ return async (input) => {
116
+ const { resolve, putPlan, freshRecords, writeChunks } = dependencies();
117
+ const { target } = input;
118
+ const fresh = await freshRecords(target, input.records, input.retry);
119
+ if (fresh.length === 0)
120
+ return { written: 0, indexed: 0 };
121
+ const resolved = await resolve(target, input.workspaceId);
122
+ if (!resolved) {
123
+ // No provider call is possible; the row records why so `status` can show it.
124
+ const plans = [];
125
+ for (const item of fresh) {
126
+ const plan = { ...item, upsert: item.record.document !== null };
127
+ if (await putPlan(target, plan, { status: 'failed', lastError: SEARCH_NOT_CONFIGURED }))
128
+ plans.push(plan);
129
+ }
130
+ return { written: plans.length, indexed: 0 };
131
+ }
132
+ const { provider, ctx } = resolved;
133
+ const plans = [];
134
+ for (const item of fresh) {
135
+ const plan = { ...item, upsert: shouldUpsert(item.record, provider) };
136
+ if (await putPlan(target, plan, { status: 'pending' }))
137
+ plans.push(plan);
138
+ }
139
+ const maxBatch = Math.max(1, provider.capabilities.maxBatch);
140
+ const upserted = await writeChunks({
141
+ target, maxBatch, plans: plans.filter(plan => plan.upsert),
142
+ payload: plan => plan.record.document,
143
+ call: documents => provider.upsert(ctx, { documents }),
144
+ });
145
+ const removed = await writeChunks({
146
+ target, maxBatch, plans: plans.filter(plan => !plan.upsert),
147
+ payload: (plan) => ({ key: plan.record.key, revision: plan.record.revision }),
148
+ call: tombstones => provider.remove(ctx, { tombstones }),
149
+ });
150
+ return { written: plans.length, indexed: upserted + removed };
151
+ };
152
+ }
153
+ export function createIndexerCurrentTargets({ targets }) {
154
+ return async (siteId) => targetList(await targets.get({ siteId }));
155
+ }
156
+ /** One plan's row outcome from its write call's result. */
157
+ function settleOf(plan, result) {
158
+ if (result.status === 'rejected')
159
+ return { status: 'failed', lastError: result.error.message };
160
+ // Indeterminate: the write may have happened. Reconcile asks the provider, never marks it failed.
161
+ if (result.status === 'unknown')
162
+ return { status: 'unknown', lastError: result.error.code };
163
+ const encoded = encodeSearchKey({ key: plan.record.key });
164
+ const outcome = result.value.outcomes.find(candidate => encodeSearchKey({ key: candidate.key }) === encoded);
165
+ if (!outcome)
166
+ return { status: 'unknown', lastError: 'missing_outcome' };
167
+ const status = OUTCOME_STATUS[outcome.status];
168
+ if (status === 'pending')
169
+ return result.value.taskId === undefined ? { status } : { status, taskId: result.value.taskId };
170
+ if (status === 'failed')
171
+ return { status, lastError: outcome.message ?? 'rejected' };
172
+ return { status };
173
+ }
174
+ //# sourceMappingURL=indexer-write.js.map
package/dist/indexer.d.ts CHANGED
@@ -13,8 +13,8 @@
13
13
  */
14
14
  import { type ProviderRegistry } from '@jini-ai/core/provider-registry';
15
15
  import { type SearchProvider, type SearchProviderContext } from './contract.js';
16
- import type { SearchIndexer } from './api.js';
17
- import type { SearchDocumentSource, SearchIndexStatePort, SearchTarget, SearchTargetPort } from './ports.js';
16
+ import { type SearchIndexer } from './api.js';
17
+ import { type SearchDocumentSource, type SearchIndexStatePort, type SearchTarget, type SearchTargetPort } from './ports.js';
18
18
  export interface SearchIndexerRequired {
19
19
  readonly sources: readonly SearchDocumentSource[];
20
20
  readonly registry: ProviderRegistry<SearchProvider>;
@@ -35,8 +35,6 @@ export interface SearchIndexerOptional {
35
35
  /** Records requested per `scan` page during backfill. */
36
36
  readonly scanPageSize?: number;
37
37
  }
38
- /** The lastError recorded when a target's provider is not registered or has no context. */
39
- export declare const SEARCH_NOT_CONFIGURED = "not_configured";
40
38
  /**
41
39
  * Build the single-writer indexer.
42
40
  * @param required - Sources, provider registry and the host's target/state/site/context ports.