@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.
- package/README.md +1 -1
- package/dist/contribution.d.ts +51 -11
- package/dist/contribution.js +13 -9
- package/dist/http-query.d.ts +34 -0
- package/dist/http-query.js +75 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/indexer-backfill.d.ts +80 -0
- package/dist/indexer-backfill.js +123 -0
- package/dist/indexer-reconcile.d.ts +78 -0
- package/dist/indexer-reconcile.js +141 -0
- package/dist/indexer-write.d.ts +86 -0
- package/dist/indexer-write.js +174 -0
- package/dist/indexer.d.ts +2 -4
- package/dist/indexer.js +59 -374
- package/dist/ports.d.ts +2 -1
- package/dist/service.js +19 -16
- package/dist/testkit/conformance.js +31 -27
- package/dist/testkit/fakes.js +7 -1
- package/dist/testkit/memory-provider.js +111 -95
- package/dist/tools.js +36 -30
- package/package.json +11 -16
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ results through the composition tokens.
|
|
|
14
14
|
|---|---|---|
|
|
15
15
|
| `@jini-ai/search` | universal | The contract (`SearchProvider`, documents, keys, revisions, tombstones), host ports, the `SearchService`/`SearchIndexer` APIs, `createSearchProviderRegistry`, `validateSearchProvider`, and the tokens `SearchProviderRegistryToken`, `SearchServiceToken`, `SearchIndexerToken`, `SearchDocumentSourceToken` (many). |
|
|
16
16
|
| `@jini-ai/search/tools` | universal | Agent tools over a `SearchService`. |
|
|
17
|
-
| `@jini-ai/search/contribution` | node | `defineSearchProviderContribution({ filename })` for plugin-contributed providers,
|
|
17
|
+
| `@jini-ai/search/contribution` | node | `defineSearchProviderContribution({ filename, define })` for plugin-contributed providers: search owns the manifest parser, the restricted-content refusal and the manifest-id check; the host passes `define` (`spec => defineProviderContribution(spec, recovery)` from `@jini-ai/agent-plugins/lifecycle`), and offers the loaded result to that package's `contributeProviders`. |
|
|
18
18
|
| `@jini-ai/search/testkit` | universal | `runSearchProviderConformance`, the in-memory reference provider, and fakes (`createFakeHttpClient`, `createUnavailableHttpClient`, `createInMemorySearchState`, `createStaticAccessPort`, `createPredicateAccessPort`). Test-only. |
|
|
19
19
|
|
|
20
20
|
## Plugin providers
|
package/dist/contribution.d.ts
CHANGED
|
@@ -11,22 +11,33 @@
|
|
|
11
11
|
* and offers the results to its registry:
|
|
12
12
|
*
|
|
13
13
|
* ```ts
|
|
14
|
-
* const definition = defineSearchProviderContribution({
|
|
14
|
+
* const definition = defineSearchProviderContribution({
|
|
15
|
+
* filename: 'host-search-providers.json',
|
|
16
|
+
* define: spec => defineProviderContribution(spec, { onReadError }), // agent-plugins' loader, host-bound
|
|
17
|
+
* });
|
|
15
18
|
* const loaded = await loader.loadPluginContributions({ workspaceId, definition });
|
|
16
|
-
* const { accepted, refusals } = contributeProviders({ registry, loaded }); //
|
|
19
|
+
* const { accepted, refusals } = contributeProviders({ registry, loaded }); // agent-plugins' function
|
|
17
20
|
* ```
|
|
18
21
|
*
|
|
19
22
|
* Every fault (bad JSON, bad entry, duplicate id, bad export, restricted vendor, id mismatch) is a
|
|
20
23
|
* refusal string, never a throw: a broken plugin must not crash boot.
|
|
21
24
|
*/
|
|
22
|
-
import { defineProviderContribution, type LoadedProviderContribution, type PluginContributionDefinition, type PluginContributionParseResult, type ProviderContributionDescriptor } from '@jini-ai/agent-plugins/lifecycle';
|
|
23
25
|
import { type SearchProvider } from './contract.js';
|
|
24
|
-
export { contributeProviders } from '@jini-ai/agent-plugins/lifecycle';
|
|
25
26
|
export declare const SEARCH_PROVIDER_MANIFEST_SCHEMA_VERSION = 1;
|
|
26
|
-
|
|
27
|
+
/** One manifest entry: the provider id, its label and the plain-JS module that exports it. */
|
|
28
|
+
export interface SearchProviderDescriptor {
|
|
29
|
+
readonly id: string;
|
|
27
30
|
readonly label: string;
|
|
31
|
+
readonly module: string;
|
|
28
32
|
}
|
|
29
|
-
|
|
33
|
+
/** The parse result agent-plugins' loader expects: the entries, or why the manifest is refused. */
|
|
34
|
+
export type SearchManifestParseResult = {
|
|
35
|
+
readonly ok: true;
|
|
36
|
+
readonly descriptors: readonly SearchProviderDescriptor[];
|
|
37
|
+
} | {
|
|
38
|
+
readonly ok: false;
|
|
39
|
+
readonly reason: string;
|
|
40
|
+
};
|
|
30
41
|
/**
|
|
31
42
|
* Parse a search provider manifest. The id grammar is checked later, per entry, before its module
|
|
32
43
|
* is imported (so one bad id refuses one provider, not the whole manifest).
|
|
@@ -34,7 +45,7 @@ export type SearchProviderContributionDefinition = PluginContributionDefinition<
|
|
|
34
45
|
*/
|
|
35
46
|
export declare function parseSearchProviderManifest(required: {
|
|
36
47
|
readonly raw: string;
|
|
37
|
-
}, _optional?: Record<string, never>):
|
|
48
|
+
}, _optional?: Record<string, never>): SearchManifestParseResult;
|
|
38
49
|
/**
|
|
39
50
|
* The module's default export as a search provider, or why not.
|
|
40
51
|
*
|
|
@@ -48,14 +59,43 @@ export declare function parseSearchProviderManifest(required: {
|
|
|
48
59
|
export declare function validateContributedSearchProvider(required: {
|
|
49
60
|
readonly exported: unknown;
|
|
50
61
|
}, _optional?: Record<string, never>): SearchProvider | string;
|
|
62
|
+
/** What search hands the host's contribution machinery (agent-plugins' `defineProviderContribution`). */
|
|
63
|
+
export interface SearchContributionSpec {
|
|
64
|
+
readonly contract: string;
|
|
65
|
+
readonly filename: string;
|
|
66
|
+
readonly parse: typeof parseSearchProviderManifest;
|
|
67
|
+
readonly validate: typeof validateContributedSearchProvider;
|
|
68
|
+
}
|
|
69
|
+
/** What the wrapper touches of the definition the host builds: the loader's `load`, and nothing else. */
|
|
70
|
+
export type SearchContributionLoaded = {
|
|
71
|
+
readonly definition: {
|
|
72
|
+
readonly provider: {
|
|
73
|
+
readonly id: string;
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
} | string;
|
|
77
|
+
export interface SearchContributionBase {
|
|
78
|
+
load(input: {
|
|
79
|
+
readonly descriptor: {
|
|
80
|
+
readonly id: string;
|
|
81
|
+
};
|
|
82
|
+
readonly plugin: {
|
|
83
|
+
readonly pluginId: string;
|
|
84
|
+
};
|
|
85
|
+
}): SearchContributionLoaded | Promise<SearchContributionLoaded>;
|
|
86
|
+
}
|
|
51
87
|
/**
|
|
52
88
|
* Define the search provider contribution for a host-chosen manifest filename.
|
|
89
|
+
* Search keeps its parser, its restricted-content refusal and the manifest-id check; the host
|
|
90
|
+
* supplies only the loader: `define` is agent-plugins' `defineProviderContribution`, with the host's
|
|
91
|
+
* read/import recovery policy bound inside it.
|
|
53
92
|
* @param required.filename - The manifest file a plugin ships at its package root.
|
|
54
|
-
* @param
|
|
55
|
-
* @returns A definition for `loadPluginContributions`; its items go to `contributeProviders`.
|
|
93
|
+
* @param required.define - Builds the executable contribution from {@link SearchContributionSpec}.
|
|
94
|
+
* @returns A definition for `loadPluginContributions`; its items go to agent-plugins' `contributeProviders`.
|
|
56
95
|
* @complexity O(1); each load is one contained import per declared provider.
|
|
57
96
|
*/
|
|
58
|
-
export declare function defineSearchProviderContribution(required: {
|
|
97
|
+
export declare function defineSearchProviderContribution<Base extends SearchContributionBase>(required: {
|
|
59
98
|
readonly filename: string;
|
|
60
|
-
|
|
99
|
+
readonly define: (spec: SearchContributionSpec) => Base;
|
|
100
|
+
}, _optional?: Record<string, never>): Base;
|
|
61
101
|
//# sourceMappingURL=contribution.d.ts.map
|
package/dist/contribution.js
CHANGED
|
@@ -11,18 +11,19 @@
|
|
|
11
11
|
* and offers the results to its registry:
|
|
12
12
|
*
|
|
13
13
|
* ```ts
|
|
14
|
-
* const definition = defineSearchProviderContribution({
|
|
14
|
+
* const definition = defineSearchProviderContribution({
|
|
15
|
+
* filename: 'host-search-providers.json',
|
|
16
|
+
* define: spec => defineProviderContribution(spec, { onReadError }), // agent-plugins' loader, host-bound
|
|
17
|
+
* });
|
|
15
18
|
* const loaded = await loader.loadPluginContributions({ workspaceId, definition });
|
|
16
|
-
* const { accepted, refusals } = contributeProviders({ registry, loaded }); //
|
|
19
|
+
* const { accepted, refusals } = contributeProviders({ registry, loaded }); // agent-plugins' function
|
|
17
20
|
* ```
|
|
18
21
|
*
|
|
19
22
|
* Every fault (bad JSON, bad entry, duplicate id, bad export, restricted vendor, id mismatch) is a
|
|
20
23
|
* refusal string, never a throw: a broken plugin must not crash boot.
|
|
21
24
|
*/
|
|
22
|
-
import { defineProviderContribution, } from '@jini-ai/agent-plugins/lifecycle';
|
|
23
25
|
import { SEARCH_CONTRACT } from './contract.js';
|
|
24
26
|
import { validateSearchProvider } from './registry.js';
|
|
25
|
-
export { contributeProviders } from '@jini-ai/agent-plugins/lifecycle';
|
|
26
27
|
export const SEARCH_PROVIDER_MANIFEST_SCHEMA_VERSION = 1;
|
|
27
28
|
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
28
29
|
/** Relative, forward-looking `.mjs` path; on-disk containment is still enforced by the loader at import. */
|
|
@@ -95,16 +96,19 @@ export function validateContributedSearchProvider(required, _optional = {}) {
|
|
|
95
96
|
}
|
|
96
97
|
/**
|
|
97
98
|
* Define the search provider contribution for a host-chosen manifest filename.
|
|
99
|
+
* Search keeps its parser, its restricted-content refusal and the manifest-id check; the host
|
|
100
|
+
* supplies only the loader: `define` is agent-plugins' `defineProviderContribution`, with the host's
|
|
101
|
+
* read/import recovery policy bound inside it.
|
|
98
102
|
* @param required.filename - The manifest file a plugin ships at its package root.
|
|
99
|
-
* @param
|
|
100
|
-
* @returns A definition for `loadPluginContributions`; its items go to `contributeProviders`.
|
|
103
|
+
* @param required.define - Builds the executable contribution from {@link SearchContributionSpec}.
|
|
104
|
+
* @returns A definition for `loadPluginContributions`; its items go to agent-plugins' `contributeProviders`.
|
|
101
105
|
* @complexity O(1); each load is one contained import per declared provider.
|
|
102
106
|
*/
|
|
103
|
-
export function defineSearchProviderContribution(required,
|
|
104
|
-
const base =
|
|
107
|
+
export function defineSearchProviderContribution(required, _optional = {}) {
|
|
108
|
+
const base = required.define({
|
|
105
109
|
contract: SEARCH_CONTRACT, filename: required.filename,
|
|
106
110
|
parse: parseSearchProviderManifest, validate: validateContributedSearchProvider,
|
|
107
|
-
}
|
|
111
|
+
});
|
|
108
112
|
return {
|
|
109
113
|
...base,
|
|
110
114
|
load: async (input) => {
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { SearchQuery } from "./contract.js";
|
|
2
|
+
export type SearchQueryIssue = {
|
|
3
|
+
readonly code: "not-single";
|
|
4
|
+
readonly field: "q" | "collection" | "limit" | "cursor";
|
|
5
|
+
} | {
|
|
6
|
+
readonly code: "text-required";
|
|
7
|
+
} | {
|
|
8
|
+
readonly code: "text-too-long";
|
|
9
|
+
} | {
|
|
10
|
+
readonly code: "invalid-collections";
|
|
11
|
+
} | {
|
|
12
|
+
readonly code: "invalid-limit";
|
|
13
|
+
} | {
|
|
14
|
+
readonly code: "invalid-cursor";
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The request's query string as a service query, or the first reason it is malformed. Never reads
|
|
18
|
+
* audiences or any other field from the request.
|
|
19
|
+
* @complexity O(q + collections).
|
|
20
|
+
*/
|
|
21
|
+
export declare function parseSearchRequest(required: {
|
|
22
|
+
readonly query: Readonly<Record<string, unknown>>;
|
|
23
|
+
readonly limits: {
|
|
24
|
+
maxTextLength: number;
|
|
25
|
+
maxCollections: number;
|
|
26
|
+
maxLimit: number;
|
|
27
|
+
maxCursorLength: number;
|
|
28
|
+
};
|
|
29
|
+
}, _optional?: Record<string, never>): {
|
|
30
|
+
query: Omit<SearchQuery, "audiences">;
|
|
31
|
+
} | {
|
|
32
|
+
error: SearchQueryIssue;
|
|
33
|
+
};
|
|
34
|
+
//# sourceMappingURL=http-query.d.ts.map
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** The collection grammar of `@jini-ai/search` document keys. */
|
|
2
|
+
const COLLECTION = /^[a-z][a-z0-9_]{0,63}$/;
|
|
3
|
+
const LIMIT = /^\d{1,3}$/;
|
|
4
|
+
/** One query-string value as a string; a repeated parameter (an array) is malformed. */
|
|
5
|
+
function single({ value, name }, _optional = {}) {
|
|
6
|
+
if (value === undefined)
|
|
7
|
+
return undefined;
|
|
8
|
+
if (typeof value !== "string")
|
|
9
|
+
return { error: { code: "not-single", field: name } };
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
function readText({ raw, maxTextLength }, _optional = {}) {
|
|
13
|
+
const value = single({ value: raw, name: "q" });
|
|
14
|
+
if (typeof value === "object")
|
|
15
|
+
return value;
|
|
16
|
+
const text = (value ?? "").trim();
|
|
17
|
+
if (text.length === 0)
|
|
18
|
+
return { error: { code: "text-required" } };
|
|
19
|
+
if (text.length > maxTextLength)
|
|
20
|
+
return { error: { code: "text-too-long" } };
|
|
21
|
+
return text;
|
|
22
|
+
}
|
|
23
|
+
/** `collection=post` or `collection=post,page`. */
|
|
24
|
+
function readCollections({ raw, maxCollections }, _optional = {}) {
|
|
25
|
+
const value = single({ value: raw, name: "collection" });
|
|
26
|
+
if (typeof value !== "string")
|
|
27
|
+
return value;
|
|
28
|
+
const collections = value.split(",").map(part => part.trim());
|
|
29
|
+
if (collections.length > maxCollections || !collections.every(part => COLLECTION.test(part))) {
|
|
30
|
+
return { error: { code: "invalid-collections" } };
|
|
31
|
+
}
|
|
32
|
+
return collections;
|
|
33
|
+
}
|
|
34
|
+
function readLimit({ raw, maxLimit }, _optional = {}) {
|
|
35
|
+
const value = single({ value: raw, name: "limit" });
|
|
36
|
+
if (typeof value !== "string")
|
|
37
|
+
return value;
|
|
38
|
+
const limit = LIMIT.test(value) ? Number(value) : 0;
|
|
39
|
+
if (limit < 1 || limit > maxLimit)
|
|
40
|
+
return { error: { code: "invalid-limit" } };
|
|
41
|
+
return limit;
|
|
42
|
+
}
|
|
43
|
+
function readCursor({ raw, maxCursorLength }, _optional = {}) {
|
|
44
|
+
const value = single({ value: raw, name: "cursor" });
|
|
45
|
+
if (typeof value !== "string")
|
|
46
|
+
return value;
|
|
47
|
+
if (value.length === 0 || value.length > maxCursorLength)
|
|
48
|
+
return { error: { code: "invalid-cursor" } };
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
const isError = (value) => typeof value === "object" && value !== null && "error" in value;
|
|
52
|
+
/**
|
|
53
|
+
* The request's query string as a service query, or the first reason it is malformed. Never reads
|
|
54
|
+
* audiences or any other field from the request.
|
|
55
|
+
* @complexity O(q + collections).
|
|
56
|
+
*/
|
|
57
|
+
export function parseSearchRequest(required, _optional = {}) {
|
|
58
|
+
const { query, limits } = required;
|
|
59
|
+
const text = readText({ raw: query.q, maxTextLength: limits.maxTextLength });
|
|
60
|
+
const collections = readCollections({ raw: query.collection, maxCollections: limits.maxCollections });
|
|
61
|
+
const limit = readLimit({ raw: query.limit, maxLimit: limits.maxLimit });
|
|
62
|
+
const cursor = readCursor({ raw: query.cursor, maxCursorLength: limits.maxCursorLength });
|
|
63
|
+
const failed = [text, collections, limit, cursor].find(isError);
|
|
64
|
+
if (failed)
|
|
65
|
+
return { error: failed.error };
|
|
66
|
+
return {
|
|
67
|
+
query: {
|
|
68
|
+
text: text,
|
|
69
|
+
...(collections === undefined ? {} : { collections: collections }),
|
|
70
|
+
...(limit === undefined ? {} : { limit: limit }),
|
|
71
|
+
...(cursor === undefined ? {} : { cursor: cursor }),
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=http-query.js.map
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type SearchIndexer } from './api.js';
|
|
2
|
+
import { type SearchDocumentSource, type SearchIndexStatePort, type SearchTarget, type SearchTargetPort } from './ports.js';
|
|
3
|
+
import type { SearchIndexerRequired } from './indexer.js';
|
|
4
|
+
import { type createIndexerResolve, type createIndexerWriteToTarget } from './indexer-write.js';
|
|
5
|
+
type Watermark = Awaited<ReturnType<SearchIndexStatePort['getWatermark']>>;
|
|
6
|
+
/** Scan one source from its watermark, writing each page; the watermark moves after EVERY page. */
|
|
7
|
+
export declare function createIndexerScanSource({ state, scanPageSize }: {
|
|
8
|
+
state: SearchIndexStatePort;
|
|
9
|
+
scanPageSize: number;
|
|
10
|
+
}, dependencies: () => {
|
|
11
|
+
writeToTarget: ReturnType<typeof createIndexerWriteToTarget>;
|
|
12
|
+
}): (input: {
|
|
13
|
+
source: SearchDocumentSource;
|
|
14
|
+
target: SearchTarget;
|
|
15
|
+
siteId: string;
|
|
16
|
+
workspaceId: string;
|
|
17
|
+
cursor: string | undefined;
|
|
18
|
+
pages: number;
|
|
19
|
+
}) => Promise<{
|
|
20
|
+
done: boolean;
|
|
21
|
+
written: number;
|
|
22
|
+
pages: number;
|
|
23
|
+
}>;
|
|
24
|
+
/**
|
|
25
|
+
* Flip building→active once nothing is in flight. Partial `failed` rows do not block: they would
|
|
26
|
+
* block forever, and reconcile keeps retrying them against the new active target. If every write
|
|
27
|
+
* failed, keep the old generation serving queries until a retry succeeds. It is dropped only
|
|
28
|
+
* after the atomic flip.
|
|
29
|
+
*/
|
|
30
|
+
export declare function createIndexerPromote({ targets, state }: {
|
|
31
|
+
targets: SearchTargetPort;
|
|
32
|
+
state: SearchIndexStatePort;
|
|
33
|
+
}, dependencies: () => {
|
|
34
|
+
dropRetired: ReturnType<typeof createIndexerDropRetired>;
|
|
35
|
+
}): (siteId: string, workspaceId: string, target: SearchTarget) => Promise<boolean>;
|
|
36
|
+
/**
|
|
37
|
+
* Drop every retired (replaced) generation of a site. The bookkeeping rows are deleted either
|
|
38
|
+
* way, since a replaced target is never written or read again. The vendor index can be dropped
|
|
39
|
+
* only while its provider is registered and configured (nothing else can reach it), and the
|
|
40
|
+
* retired record is forgotten only once the drop is CONFIRMED (`ok`): a refusal, an indeterminate
|
|
41
|
+
* outcome, a missing credential or an unregistered provider leaves it for the next reconcile,
|
|
42
|
+
* instead of leaving the old content in the vendor index forever.
|
|
43
|
+
*/
|
|
44
|
+
export declare function createIndexerDropRetired({ targets, state }: {
|
|
45
|
+
targets: SearchTargetPort;
|
|
46
|
+
state: SearchIndexStatePort;
|
|
47
|
+
}, dependencies: () => {
|
|
48
|
+
resolve: ReturnType<typeof createIndexerResolve>;
|
|
49
|
+
}): (siteId: string, workspaceId: string) => Promise<void>;
|
|
50
|
+
export declare function createIndexerBackfillTarget({ sources }: {
|
|
51
|
+
sources: SearchIndexerRequired['sources'];
|
|
52
|
+
}, dependencies: () => {
|
|
53
|
+
scanSource: ReturnType<typeof createIndexerScanSource>;
|
|
54
|
+
}): (input: {
|
|
55
|
+
siteId: string;
|
|
56
|
+
workspaceId: string;
|
|
57
|
+
target: SearchTarget;
|
|
58
|
+
pageBudget: number;
|
|
59
|
+
marks: readonly Watermark[];
|
|
60
|
+
}) => Promise<{
|
|
61
|
+
done: boolean;
|
|
62
|
+
written: number;
|
|
63
|
+
}>;
|
|
64
|
+
export declare function createIndexerReadMarks({ sources, state }: {
|
|
65
|
+
sources: SearchIndexerRequired['sources'];
|
|
66
|
+
state: SearchIndexStatePort;
|
|
67
|
+
}): (target: SearchTarget) => Promise<Watermark[]>;
|
|
68
|
+
export declare function createIndexerBackfill({ targets }: {
|
|
69
|
+
targets: SearchTargetPort;
|
|
70
|
+
}, dependencies: () => {
|
|
71
|
+
resolve: ReturnType<typeof createIndexerResolve>;
|
|
72
|
+
promote: ReturnType<typeof createIndexerPromote>;
|
|
73
|
+
backfillTarget: ReturnType<typeof createIndexerBackfillTarget>;
|
|
74
|
+
readMarks: ReturnType<typeof createIndexerReadMarks>;
|
|
75
|
+
}): SearchIndexer['backfill'];
|
|
76
|
+
export declare function createIndexerStartRebuild({ targets }: {
|
|
77
|
+
targets: SearchTargetPort;
|
|
78
|
+
}): SearchIndexer['startRebuild'];
|
|
79
|
+
export {};
|
|
80
|
+
//# sourceMappingURL=indexer-backfill.d.ts.map
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import {} from './api.js';
|
|
2
|
+
import {} from './ports.js';
|
|
3
|
+
import { guarded } from './indexer-write.js';
|
|
4
|
+
/** Scan one source from its watermark, writing each page; the watermark moves after EVERY page. */
|
|
5
|
+
export function createIndexerScanSource({ state, scanPageSize }, dependencies) {
|
|
6
|
+
return async (input) => {
|
|
7
|
+
const { writeToTarget } = dependencies();
|
|
8
|
+
const { source, target } = input;
|
|
9
|
+
let { cursor, pages } = input;
|
|
10
|
+
let written = 0;
|
|
11
|
+
while (pages > 0) {
|
|
12
|
+
const page = await source.scan({ siteId: input.siteId, workspaceId: input.workspaceId, limit: scanPageSize }, cursor === undefined ? {} : { cursor });
|
|
13
|
+
pages -= 1;
|
|
14
|
+
written += (await writeToTarget({ target, workspaceId: input.workspaceId, records: page.records, retry: false })).written;
|
|
15
|
+
cursor = page.nextCursor;
|
|
16
|
+
const done = cursor === undefined;
|
|
17
|
+
// Persisted per page so a crash resumes here instead of rescanning the whole collection.
|
|
18
|
+
await state.putWatermark({ target, collection: source.collection, done, ...(cursor === undefined ? {} : { cursor }) });
|
|
19
|
+
if (done)
|
|
20
|
+
return { done: true, written, pages };
|
|
21
|
+
}
|
|
22
|
+
return { done: false, written, pages };
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Flip building→active once nothing is in flight. Partial `failed` rows do not block: they would
|
|
27
|
+
* block forever, and reconcile keeps retrying them against the new active target. If every write
|
|
28
|
+
* failed, keep the old generation serving queries until a retry succeeds. It is dropped only
|
|
29
|
+
* after the atomic flip.
|
|
30
|
+
*/
|
|
31
|
+
export function createIndexerPromote({ targets, state }, dependencies) {
|
|
32
|
+
return async (siteId, workspaceId, target) => {
|
|
33
|
+
const { dropRetired } = dependencies();
|
|
34
|
+
const counts = await state.counts({ target });
|
|
35
|
+
if (counts.pending + counts.unknown > 0)
|
|
36
|
+
return false;
|
|
37
|
+
if (counts.indexed === 0 && counts.failed > 0)
|
|
38
|
+
return false;
|
|
39
|
+
const flipped = await targets.promote({ siteId, expected: target });
|
|
40
|
+
if (flipped === false)
|
|
41
|
+
return false;
|
|
42
|
+
await dropRetired(siteId, workspaceId);
|
|
43
|
+
return true;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Drop every retired (replaced) generation of a site. The bookkeeping rows are deleted either
|
|
48
|
+
* way, since a replaced target is never written or read again. The vendor index can be dropped
|
|
49
|
+
* only while its provider is registered and configured (nothing else can reach it), and the
|
|
50
|
+
* retired record is forgotten only once the drop is CONFIRMED (`ok`): a refusal, an indeterminate
|
|
51
|
+
* outcome, a missing credential or an unregistered provider leaves it for the next reconcile,
|
|
52
|
+
* instead of leaving the old content in the vendor index forever.
|
|
53
|
+
*/
|
|
54
|
+
export function createIndexerDropRetired({ targets, state }, dependencies) {
|
|
55
|
+
return async (siteId, workspaceId) => {
|
|
56
|
+
const { resolve } = dependencies();
|
|
57
|
+
for (const retired of await targets.listRetired({ siteId })) {
|
|
58
|
+
await state.deleteTarget({ target: retired });
|
|
59
|
+
const resolved = await resolve(retired, workspaceId);
|
|
60
|
+
const dropped = resolved ? await guarded(() => resolved.provider.dropIndex(resolved.ctx)) : null;
|
|
61
|
+
if (dropped?.status === 'ok')
|
|
62
|
+
await targets.forgetRetired({ target: retired });
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export function createIndexerBackfillTarget({ sources }, dependencies) {
|
|
67
|
+
return async (input) => {
|
|
68
|
+
const { scanSource } = dependencies();
|
|
69
|
+
let written = 0;
|
|
70
|
+
let pages = input.pageBudget;
|
|
71
|
+
for (const [index, source] of sources.entries()) {
|
|
72
|
+
const mark = input.marks[index];
|
|
73
|
+
if (mark?.done)
|
|
74
|
+
continue;
|
|
75
|
+
const scanned = await scanSource({ source, target: input.target, siteId: input.siteId, workspaceId: input.workspaceId, cursor: mark?.cursor, pages });
|
|
76
|
+
written += scanned.written;
|
|
77
|
+
pages = scanned.pages;
|
|
78
|
+
if (!scanned.done)
|
|
79
|
+
return { done: false, written };
|
|
80
|
+
}
|
|
81
|
+
return { done: true, written };
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
export function createIndexerReadMarks({ sources, state }) {
|
|
85
|
+
return async (target) => {
|
|
86
|
+
const marks = [];
|
|
87
|
+
for (const source of sources)
|
|
88
|
+
marks.push(await state.getWatermark({ target, collection: source.collection }));
|
|
89
|
+
return marks;
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export function createIndexerBackfill({ targets }, dependencies) {
|
|
93
|
+
const operation = async ({ siteId, workspaceId }, { pageBudget = 10 } = {}) => {
|
|
94
|
+
const { resolve, promote, backfillTarget, readMarks } = dependencies();
|
|
95
|
+
const current = await targets.get({ siteId });
|
|
96
|
+
const target = current.building ?? current.active;
|
|
97
|
+
if (target === null)
|
|
98
|
+
return { done: true, written: 0, promoted: false };
|
|
99
|
+
const resolved = await resolve(target, workspaceId);
|
|
100
|
+
if (!resolved)
|
|
101
|
+
return { done: false, written: 0, promoted: false };
|
|
102
|
+
const marks = await readMarks(target);
|
|
103
|
+
// A fresh target (no source started yet) gets its index created before the very first page.
|
|
104
|
+
if (marks.every(mark => mark === null) && (await guarded(() => resolved.provider.ensureIndex(resolved.ctx))).status !== 'ok') {
|
|
105
|
+
return { done: false, written: 0, promoted: false };
|
|
106
|
+
}
|
|
107
|
+
const { done, written } = await backfillTarget({ siteId, workspaceId, target, pageBudget, marks });
|
|
108
|
+
// `target` is the building one whenever one exists; only a building target is ever promoted.
|
|
109
|
+
const promoted = done && current.building !== null ? await promote(siteId, workspaceId, target) : false;
|
|
110
|
+
return { done, written, promoted };
|
|
111
|
+
};
|
|
112
|
+
return operation;
|
|
113
|
+
}
|
|
114
|
+
export function createIndexerStartRebuild({ targets }) {
|
|
115
|
+
const operation = async ({ siteId, providerId }) => {
|
|
116
|
+
const current = await targets.get({ siteId });
|
|
117
|
+
const generation = Math.max(current.active?.generation ?? 0, current.building?.generation ?? 0) + 1;
|
|
118
|
+
await targets.setBuilding({ target: { siteId, providerId, generation } });
|
|
119
|
+
return targets.get({ siteId });
|
|
120
|
+
};
|
|
121
|
+
return operation;
|
|
122
|
+
}
|
|
123
|
+
//# sourceMappingURL=indexer-backfill.js.map
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { type SearchProvider } from './contract.js';
|
|
2
|
+
import { type SearchIndexer } from './api.js';
|
|
3
|
+
import { type SearchIndexStatePort, type SearchIndexStateRow, type SearchTarget } from './ports.js';
|
|
4
|
+
import type { SearchIndexerRequired } from './indexer.js';
|
|
5
|
+
import { type Resolved, type Settle, type createIndexerResolve, type createIndexerWriteToTarget, type createIndexerCurrentTargets } from './indexer-write.js';
|
|
6
|
+
import type { createIndexerDropRetired } from './indexer-backfill.js';
|
|
7
|
+
/** Compare-and-swap a settled row against the identity the caller observed (see `settle`). */
|
|
8
|
+
export declare function createIndexerSettleObserved({ state }: {
|
|
9
|
+
state: SearchIndexStatePort;
|
|
10
|
+
}): (row: SearchIndexStateRow, settled: SearchIndexStateRow) => Promise<boolean>;
|
|
11
|
+
export declare function createIndexerSettledRow({ now }: {
|
|
12
|
+
now: SearchIndexerRequired['now'];
|
|
13
|
+
}): (row: SearchIndexStateRow, settle: Settle) => SearchIndexStateRow;
|
|
14
|
+
/**
|
|
15
|
+
* Ask an async provider how an earlier `pending` write ended. 1 when it is now indexed. The settle
|
|
16
|
+
* only lands while the row still holds this revision AND this task: an event that wrote a newer
|
|
17
|
+
* revision while the task was awaited keeps its own pending task (and its retry) intact.
|
|
18
|
+
*/
|
|
19
|
+
export declare function createIndexerSettleTask(dependencies: () => {
|
|
20
|
+
settleObserved: ReturnType<typeof createIndexerSettleObserved>;
|
|
21
|
+
settledRow: ReturnType<typeof createIndexerSettledRow>;
|
|
22
|
+
}): (row: SearchIndexStateRow, resolved: Resolved, { taskId, awaitTask }: {
|
|
23
|
+
taskId: string;
|
|
24
|
+
awaitTask: NonNullable<SearchProvider["awaitTask"]>;
|
|
25
|
+
}) => Promise<number>;
|
|
26
|
+
/**
|
|
27
|
+
* Settle indeterminate rows by asking the provider what it holds. A row whose write landed is
|
|
28
|
+
* marked indexed; anything else is returned for a re-load and re-write (never blindly marked
|
|
29
|
+
* failed: an `unknown` outcome may well have happened).
|
|
30
|
+
*/
|
|
31
|
+
export declare function createIndexerCheckRevisions(dependencies: () => {
|
|
32
|
+
checkChunk: ReturnType<typeof createIndexerCheckChunk>;
|
|
33
|
+
}): (rows: readonly SearchIndexStateRow[], resolved: Resolved) => Promise<{
|
|
34
|
+
settled: number;
|
|
35
|
+
rewrite: SearchIndexStateRow[];
|
|
36
|
+
}>;
|
|
37
|
+
/** One `revisionOf` call's worth of {@link checkRevisions}; an indeterminate answer leaves the rows as they are. */
|
|
38
|
+
export declare function createIndexerCheckChunk(dependencies: () => {
|
|
39
|
+
settleObserved: ReturnType<typeof createIndexerSettleObserved>;
|
|
40
|
+
settledRow: ReturnType<typeof createIndexerSettledRow>;
|
|
41
|
+
}): (chunk: readonly SearchIndexStateRow[], resolved: Resolved) => Promise<{
|
|
42
|
+
settled: number;
|
|
43
|
+
rewrite: SearchIndexStateRow[];
|
|
44
|
+
}>;
|
|
45
|
+
/** `pending` rows with a task are awaited; `unknown` rows (and a `pending` row whose process died
|
|
46
|
+
* between marking and the call, so it has no task) are checked with `revisionOf`. */
|
|
47
|
+
export declare function createIndexerSettleInFlight(dependencies: () => {
|
|
48
|
+
settleTask: ReturnType<typeof createIndexerSettleTask>;
|
|
49
|
+
checkRevisions: ReturnType<typeof createIndexerCheckRevisions>;
|
|
50
|
+
}): (rows: readonly SearchIndexStateRow[], resolved: Resolved) => Promise<{
|
|
51
|
+
settled: number;
|
|
52
|
+
rewrite: SearchIndexStateRow[];
|
|
53
|
+
}>;
|
|
54
|
+
/** Re-load the row's document from its source and write the current truth again (a retry). */
|
|
55
|
+
export declare function createIndexerRewriteRow({ sources, now }: {
|
|
56
|
+
sources: SearchIndexerRequired['sources'];
|
|
57
|
+
now: SearchIndexerRequired['now'];
|
|
58
|
+
}, dependencies: () => {
|
|
59
|
+
settleObserved: ReturnType<typeof createIndexerSettleObserved>;
|
|
60
|
+
writeToTarget: ReturnType<typeof createIndexerWriteToTarget>;
|
|
61
|
+
settledRow: ReturnType<typeof createIndexerSettledRow>;
|
|
62
|
+
}): (row: SearchIndexStateRow, workspaceId: string) => Promise<number>;
|
|
63
|
+
export declare function createIndexerReconcileTarget({ state, maxAttempts }: {
|
|
64
|
+
state: SearchIndexStatePort;
|
|
65
|
+
maxAttempts: number;
|
|
66
|
+
}, dependencies: () => {
|
|
67
|
+
resolve: ReturnType<typeof createIndexerResolve>;
|
|
68
|
+
settleInFlight: ReturnType<typeof createIndexerSettleInFlight>;
|
|
69
|
+
rewriteRow: ReturnType<typeof createIndexerRewriteRow>;
|
|
70
|
+
}): (target: SearchTarget, workspaceId: string, limit: number) => Promise<number>;
|
|
71
|
+
export declare function createIndexerReconcile({ state }: {
|
|
72
|
+
state: SearchIndexStatePort;
|
|
73
|
+
}, dependencies: () => {
|
|
74
|
+
currentTargets: ReturnType<typeof createIndexerCurrentTargets>;
|
|
75
|
+
reconcileTarget: ReturnType<typeof createIndexerReconcileTarget>;
|
|
76
|
+
dropRetired: ReturnType<typeof createIndexerDropRetired>;
|
|
77
|
+
}): SearchIndexer['reconcile'];
|
|
78
|
+
//# sourceMappingURL=indexer-reconcile.d.ts.map
|