@onlyflows/servicenow-mcp 2.3.0-dev.2 → 2.3.0-dev.3
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/CHANGELOG.md +212 -26
- package/README.md +108 -12
- package/dist/client.d.ts +5 -13
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +11 -26
- package/dist/client.js.map +1 -1
- package/dist/code-search-snippet.d.ts +25 -0
- package/dist/code-search-snippet.d.ts.map +1 -0
- package/dist/code-search-snippet.js +67 -0
- package/dist/code-search-snippet.js.map +1 -0
- package/dist/code-search-targets.d.ts +66 -0
- package/dist/code-search-targets.d.ts.map +1 -0
- package/dist/code-search-targets.js +82 -0
- package/dist/code-search-targets.js.map +1 -0
- package/dist/field-policy.d.ts.map +1 -1
- package/dist/field-policy.js +17 -5
- package/dist/field-policy.js.map +1 -1
- package/dist/http-observability.js +1 -0
- package/dist/http-observability.js.map +1 -1
- package/dist/metadata-cache.d.ts +2 -2
- package/dist/metadata-cache.d.ts.map +1 -1
- package/dist/metadata-cache.js +3 -2
- package/dist/metadata-cache.js.map +1 -1
- package/dist/policy-card.js +1 -1
- package/dist/policy-card.js.map +1 -1
- package/dist/response-too-large.d.ts +23 -0
- package/dist/response-too-large.d.ts.map +1 -0
- package/dist/response-too-large.js +42 -0
- package/dist/response-too-large.js.map +1 -0
- package/dist/risky-grants.d.ts.map +1 -1
- package/dist/risky-grants.js +1 -0
- package/dist/risky-grants.js.map +1 -1
- package/dist/setup.d.ts.map +1 -1
- package/dist/setup.js +22 -7
- package/dist/setup.js.map +1 -1
- package/dist/table-policy.d.ts +42 -2
- package/dist/table-policy.d.ts.map +1 -1
- package/dist/table-policy.js +90 -6
- package/dist/table-policy.js.map +1 -1
- package/dist/tool-error.d.ts +40 -4
- package/dist/tool-error.d.ts.map +1 -1
- package/dist/tool-error.js +81 -4
- package/dist/tool-error.js.map +1 -1
- package/dist/tool-table-access.d.ts +9 -2
- package/dist/tool-table-access.d.ts.map +1 -1
- package/dist/tool-table-access.js +93 -30
- package/dist/tool-table-access.js.map +1 -1
- package/dist/tools/batch.d.ts.map +1 -1
- package/dist/tools/batch.js +21 -5
- package/dist/tools/batch.js.map +1 -1
- package/dist/tools/catalog.d.ts.map +1 -1
- package/dist/tools/catalog.js +2 -1
- package/dist/tools/catalog.js.map +1 -1
- package/dist/tools/codesearch.d.ts +2 -2
- package/dist/tools/codesearch.d.ts.map +1 -1
- package/dist/tools/codesearch.js +535 -86
- package/dist/tools/codesearch.js.map +1 -1
- package/dist/tools/flow-view-contracts.d.ts +2 -2
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +13 -2
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/query-module.d.ts.map +1 -1
- package/dist/tools/query-module.js +25 -4
- package/dist/tools/query-module.js.map +1 -1
- package/dist/tools/result-envelope.d.ts +2 -2
- package/dist/tools/result-envelope.d.ts.map +1 -1
- package/dist/tools/result-envelope.js +20 -2
- package/dist/tools/result-envelope.js.map +1 -1
- package/dist/unknown-filter-fields.d.ts +52 -0
- package/dist/unknown-filter-fields.d.ts.map +1 -0
- package/dist/unknown-filter-fields.js +87 -0
- package/dist/unknown-filter-fields.js.map +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/CLIENT-SETUP.md +15 -4
- package/docs/PRODUCTION-SECURITY.md +10 -6
- package/docs/V2-MIGRATION.md +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/tools/codesearch.js
CHANGED
|
@@ -3,12 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.schema = exports.definition = void 0;
|
|
4
4
|
exports.handler = handler;
|
|
5
5
|
const zod_1 = require("zod");
|
|
6
|
+
const client_js_1 = require("../client.js");
|
|
6
7
|
const field_policy_js_1 = require("../field-policy.js");
|
|
7
8
|
const utils_js_1 = require("../utils.js");
|
|
8
9
|
const tool_error_js_1 = require("../tool-error.js");
|
|
10
|
+
const code_search_targets_js_1 = require("../code-search-targets.js");
|
|
11
|
+
const code_search_snippet_js_1 = require("../code-search-snippet.js");
|
|
12
|
+
const table_policy_js_1 = require("../table-policy.js");
|
|
9
13
|
exports.definition = {
|
|
10
14
|
name: "sn_codesearch",
|
|
11
|
-
description: "Search across ServiceNow code artifacts — business rules, script includes, UI scripts, client scripts,
|
|
15
|
+
description: "Search across ServiceNow code artifacts — business rules, script includes, UI scripts, client scripts, scripted REST operations, ES modules and ATF step scripts. Returns matches with a snippet around the first hit; with no table, tables take turns so each is on page 1.",
|
|
12
16
|
annotations: {
|
|
13
17
|
title: "Search code artifacts",
|
|
14
18
|
readOnlyHint: true,
|
|
@@ -19,101 +23,546 @@ exports.definition = {
|
|
|
19
23
|
};
|
|
20
24
|
exports.schema = zod_1.z.object({
|
|
21
25
|
search_term: zod_1.z.string().describe("Text to search for in script fields"),
|
|
22
|
-
table: zod_1.z.string().optional().describe("Search
|
|
23
|
-
field: zod_1.z.string().optional().describe("Specific field to search (default: script)"),
|
|
26
|
+
table: zod_1.z.string().optional().describe("Search one table only (default: all code tables you may read). Options: sys_script, sys_script_include, sys_ui_script, sys_script_client, sys_ws_operation, sys_module, sys_atf_step"),
|
|
27
|
+
field: zod_1.z.string().optional().describe("Specific field to search (default: the table's script field)"),
|
|
24
28
|
limit: zod_1.z.number().int().min(1).max(1000).optional().default(20).describe("Max total results (default 20, max 1000)"),
|
|
25
|
-
offset: zod_1.z.number().int().min(0).max(10000).optional().default(0).describe("
|
|
29
|
+
offset: zod_1.z.number().int().min(0).max(10000).optional().default(0).describe("Offset into the combined results (default 0)"),
|
|
26
30
|
});
|
|
27
|
-
|
|
31
|
+
/**
|
|
32
|
+
* A single-table search of at most this many rows (the page and its sentinel)
|
|
33
|
+
* reads each script in the same request that finds it. A bigger page, or a
|
|
34
|
+
* search across tables, first finds the rows without their scripts and then
|
|
35
|
+
* reads the scripts of the rows it returns. Bodies run to kilobytes, so reading
|
|
36
|
+
* a window of them from every table was what passed the response cap.
|
|
37
|
+
*/
|
|
38
|
+
const INLINE_MAX_ROWS = 50;
|
|
39
|
+
/** Records read in one request by id. A batch that is still too large is halved. */
|
|
40
|
+
const BATCH_ROWS = 50;
|
|
41
|
+
/** Requests by id in flight; the client's per-origin limiter is 4 as well. */
|
|
42
|
+
const BATCH_CONCURRENCY = 4;
|
|
43
|
+
/**
|
|
44
|
+
* What one search may spend on reading scripts by id, whatever the scripts'
|
|
45
|
+
* sizes: requests (a retry after a too-large answer counts), and bytes pulled,
|
|
46
|
+
* with an answer that passed the cap counted at the cap.
|
|
47
|
+
*/
|
|
48
|
+
/** A first batch of more rows than this is read alone before the others start. */
|
|
49
|
+
const PROBE_ROWS = 4;
|
|
50
|
+
const BODY_MAX_REQUESTS = 12;
|
|
51
|
+
const BODY_MAX_BYTES = 8 * 1024 * 1024;
|
|
52
|
+
/** The client's cap on one response, which a failed attempt may have pulled in full. */
|
|
53
|
+
const RESPONSE_CAP_BYTES = 1024 * 1024;
|
|
54
|
+
/** A snippet's length (the window plus its two markers), and room for an ATF row's longer name. */
|
|
55
|
+
const SNIPPET_ROOM = 206;
|
|
56
|
+
const ATF_NAME_ROOM = 40;
|
|
57
|
+
const SYS_ID = /^[0-9a-f]{32}$/u;
|
|
58
|
+
const TOO_LARGE_NOTE = "script too large to preview";
|
|
59
|
+
const UNNAMED = "unnamed";
|
|
60
|
+
async function handler(args, client, _config, context) {
|
|
61
|
+
const signal = context?.signal;
|
|
62
|
+
const term = (0, utils_js_1.escapeQueryValue)(args.search_term);
|
|
63
|
+
const { selection, skipped } = selectTargets(args);
|
|
64
|
+
const single = selection.length === 1;
|
|
65
|
+
const warnings = [];
|
|
66
|
+
if (skipped.length > 0)
|
|
67
|
+
warnings.push(skippedWarning(skipped));
|
|
68
|
+
// A search of one table reads exactly the page asked for (the instance
|
|
69
|
+
// applies the offset). A search of several takes turns through the tables,
|
|
70
|
+
// and where a row falls in that order depends on how many rows the others
|
|
71
|
+
// have, so each table is read from the start, as far as the page can reach.
|
|
72
|
+
const windowLimit = single ? args.limit + 1 : args.offset + args.limit + 1;
|
|
73
|
+
const windowOffset = single ? args.offset : 0;
|
|
74
|
+
const inline = single && args.limit + 1 <= INLINE_MAX_ROWS;
|
|
75
|
+
// The reads are independent, so they run together instead of one round trip
|
|
76
|
+
// after another (each also costs a watermark read when the table is cached).
|
|
77
|
+
// The client's per-origin limiter bounds how many are in flight. Each read has
|
|
78
|
+
// its own response-byte scope, so one table's large answer cannot spend the
|
|
79
|
+
// budget of another. Results, warnings and failures are merged in target
|
|
80
|
+
// order after the join, so the output does not depend on which finished first.
|
|
81
|
+
const outcomes = await Promise.all(selection.map(async (selected) => {
|
|
82
|
+
try {
|
|
83
|
+
return {
|
|
84
|
+
matches: await findWithFallback(client, signal, args, selected, term, windowOffset, windowLimit, inline),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
// Tables can fail (ACL issues, etc.) -- report, don't hide
|
|
89
|
+
if (signal?.aborted)
|
|
90
|
+
throw error;
|
|
91
|
+
return { error };
|
|
92
|
+
}
|
|
93
|
+
}));
|
|
94
|
+
const found = [];
|
|
95
|
+
const failures = [];
|
|
96
|
+
for (const [index, outcome] of outcomes.entries()) {
|
|
97
|
+
if ("error" in outcome) {
|
|
98
|
+
failures.push(outcome.error);
|
|
99
|
+
warnings.push(`${selection[index].target.table}: ${(0, utils_js_1.formatError)(outcome.error)}`);
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
found.push(outcome.matches);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// Every sub-search failed: that is a failure, not "no matches" --
|
|
106
|
+
// an empty success here would read as "nothing references this".
|
|
107
|
+
if (failures.length === selection.length) {
|
|
108
|
+
throw (0, tool_error_js_1.createCommonToolError)(failures);
|
|
109
|
+
}
|
|
110
|
+
// One more row than the page holds says whether there is a next page.
|
|
111
|
+
const page = single
|
|
112
|
+
? (found[0] ?? [])
|
|
113
|
+
: interleave(found).slice(args.offset, args.offset + args.limit + 1);
|
|
114
|
+
// The row that only says "there is more" is cut from the page, and so are the
|
|
115
|
+
// rows past what one response holds, so neither their scripts nor their names
|
|
116
|
+
// are read.
|
|
117
|
+
const returned = rowsTheResponseCanHold(page.slice(0, args.limit));
|
|
118
|
+
await Promise.all([
|
|
119
|
+
readBodies(client, signal, returned, warnings),
|
|
120
|
+
nameAtfSteps(client, signal, args, returned, warnings),
|
|
121
|
+
]);
|
|
122
|
+
return (0, utils_js_1.ok)((0, utils_js_1.withWarnings)(page.map((match) => toRow(match, term)), warnings));
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The tables this call searches: the one named, or every code table the
|
|
126
|
+
* profile may read. The dispatcher's access plan marks only the tables it
|
|
127
|
+
* authorized, with the fields it approved, so a table without that mark was
|
|
128
|
+
* refused by the table policy or the field policy and is skipped. A call that
|
|
129
|
+
* did not come through the dispatcher carries no marks and searches all of them.
|
|
130
|
+
*/
|
|
131
|
+
function selectTargets(args) {
|
|
132
|
+
if (args.table !== undefined) {
|
|
133
|
+
const target = (0, code_search_targets_js_1.codeSearchTarget)((0, table_policy_js_1.normalizeTableName)(args.table));
|
|
134
|
+
if (target === undefined)
|
|
135
|
+
throw new TypeError("table is not searchable");
|
|
136
|
+
return {
|
|
137
|
+
selection: [
|
|
138
|
+
{
|
|
139
|
+
target,
|
|
140
|
+
field: target.fixedField ? target.defaultField : args.field || target.defaultField,
|
|
141
|
+
named: true,
|
|
142
|
+
},
|
|
143
|
+
],
|
|
144
|
+
skipped: [],
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const all = code_search_targets_js_1.CODE_SEARCH_TARGETS.map((target) => ({
|
|
148
|
+
target,
|
|
149
|
+
field: target.defaultField,
|
|
150
|
+
named: false,
|
|
151
|
+
}));
|
|
152
|
+
const authorized = all.filter((entry) => (0, code_search_targets_js_1.codeSearchReads)(entry.target).every((table) => (0, field_policy_js_1.preparedReadableFields)(args, table) !== undefined));
|
|
153
|
+
if (authorized.length === 0)
|
|
154
|
+
return { selection: all, skipped: [] };
|
|
155
|
+
return {
|
|
156
|
+
selection: authorized,
|
|
157
|
+
skipped: all.filter((entry) => !authorized.includes(entry)).map((entry) => entry.target),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Name the tables a search left out. Fixed table names and one fixed command:
|
|
162
|
+
* nothing of the profile's rules, and nothing the caller sent. A target that
|
|
163
|
+
* reads several tables says which, since a grant on its own table is not enough.
|
|
164
|
+
*/
|
|
165
|
+
function skippedWarning(targets) {
|
|
166
|
+
const names = targets.map((target) => {
|
|
167
|
+
const reads = (0, code_search_targets_js_1.codeSearchReads)(target);
|
|
168
|
+
return reads.length > 1 ? `${target.table} (needs read on ${reads.join(", ")})` : target.table;
|
|
169
|
+
});
|
|
170
|
+
return (`Not searched, because this profile does not allow sn_codesearch to read ` +
|
|
171
|
+
`${names.length === 1 ? "it" : "them"}: ${names.join(", ")}. ` +
|
|
172
|
+
`To include ${names.length === 1 ? "it" : "one"}, run servicenow-mcp-setup grant ` +
|
|
173
|
+
`--profile <profile> --read <table> --tools sn_codesearch.`);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Find a table's matches. A page read with its scripts that still passes the
|
|
177
|
+
* response cap (a few very large scripts) is read again without them, in its own
|
|
178
|
+
* fresh scope, so the scripts are read in batches afterwards instead.
|
|
179
|
+
*/
|
|
180
|
+
async function findWithFallback(client, signal, args, selected, term, offset, limit, inline) {
|
|
28
181
|
try {
|
|
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
|
-
|
|
182
|
+
return await inFreshBudget(signal, () => findMatches(client, args, selected, term, offset, limit, inline));
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
if (!inline || signal?.aborted || !(0, client_js_1.isServiceNowResponseTooLarge)(error))
|
|
186
|
+
throw error;
|
|
187
|
+
return inFreshBudget(signal, () => findMatches(client, args, selected, term, offset, limit, false));
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The rows of one table that match, in sys_id order. With `inline`, each row
|
|
192
|
+
* carries the searched value too; otherwise only its identifier and name.
|
|
193
|
+
*/
|
|
194
|
+
async function findMatches(client, args, selected, term, offset, limit, inline) {
|
|
195
|
+
const { target, field } = selected;
|
|
196
|
+
const wanted = inline
|
|
197
|
+
? (0, code_search_targets_js_1.findProjection)(target, target.nameField, field)
|
|
198
|
+
: (0, code_search_targets_js_1.findProjection)(target, target.nameField, target.nameField);
|
|
199
|
+
const fallback = (0, field_policy_js_1.resolveReadableFields)(target.queryTable, {
|
|
200
|
+
fields: (0, code_search_targets_js_1.findProjection)(target, target.nameField, field).join(","),
|
|
201
|
+
});
|
|
202
|
+
const readableFields = (0, field_policy_js_1.preparedReadableFields)(args, target.queryTable) ?? fallback;
|
|
203
|
+
const likeField = `${(0, utils_js_1.escapeQueryValue)(field)}LIKE${term}`;
|
|
204
|
+
const resp = await client.get(`/api/now/table/${target.queryTable}`, {
|
|
205
|
+
// `sysparm_orderby` is not a Table API parameter; ordering is part of the
|
|
206
|
+
// encoded query. Without it the window is not a stable prefix of the
|
|
207
|
+
// table, and an offset can skip or repeat a record.
|
|
208
|
+
sysparm_query: `${target.fixedQuery === undefined ? "" : `${target.fixedQuery}^`}${likeField}^ORDERBYsys_id`,
|
|
209
|
+
sysparm_fields: wanted.join(","),
|
|
210
|
+
sysparm_limit: String(limit),
|
|
211
|
+
sysparm_offset: String(offset),
|
|
212
|
+
sysparm_no_count: "true",
|
|
213
|
+
// A reference or document field (an ATF value's `document_key`) arrives as
|
|
214
|
+
// `{ link, value }` unless asked for as its value alone.
|
|
215
|
+
sysparm_exclude_reference_link: "true",
|
|
216
|
+
});
|
|
217
|
+
const filtered = (0, field_policy_js_1.filterReadableRecord)(rowsOf(resp), readableFields);
|
|
218
|
+
const matches = [];
|
|
219
|
+
for (const candidate of Array.isArray(filtered) ? filtered : []) {
|
|
220
|
+
if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate))
|
|
221
|
+
continue;
|
|
222
|
+
const record = candidate;
|
|
223
|
+
// Defence in depth: the query already restricts these rows, and a row that
|
|
224
|
+
// does not say so itself is dropped rather than shown.
|
|
225
|
+
if (target.guard !== undefined && referenceId(record[target.guard.field], false) !== target.guard.value) {
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
// The name column is also what was searched when the caller searches it.
|
|
229
|
+
const searched = inline || field === target.nameField || field === "sys_id";
|
|
230
|
+
const sysId = String(record.sys_id ?? "");
|
|
231
|
+
// A target named by a lookup keeps the record it is about in its name field.
|
|
232
|
+
const named = target.lookups.length === 0;
|
|
233
|
+
matches.push({
|
|
234
|
+
selected,
|
|
235
|
+
rank: matches.length,
|
|
236
|
+
sysId,
|
|
237
|
+
recordId: named ? sysId : (referenceId(record[target.nameField]) ?? ""),
|
|
238
|
+
name: named ? String(record[target.nameField] || UNNAMED) : UNNAMED,
|
|
239
|
+
readable: readableFields,
|
|
240
|
+
...(searched && record[field] !== undefined ? { body: String(record[field]) } : {}),
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
return matches;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Take turns through the tables: each table's first match (script includes
|
|
247
|
+
* first), then each table's second, and so on, so no table crowds the others
|
|
248
|
+
* off the first page. The order depends only on the rows and the fixed table
|
|
249
|
+
* order, never on which read finished first.
|
|
250
|
+
*/
|
|
251
|
+
function interleave(perTable) {
|
|
252
|
+
return perTable
|
|
253
|
+
.flatMap((matches, order) => matches.map((match) => ({ match, order })))
|
|
254
|
+
.sort((left, right) => left.match.rank - right.match.rank || left.order - right.order)
|
|
255
|
+
.map(({ match }) => match);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Read the script of each row that has none yet, in batches of ids, each batch
|
|
259
|
+
* in its own response scope, within a budget for the whole call.
|
|
260
|
+
*
|
|
261
|
+
* Each batch has its own 1 MiB scope, so nothing else bounds the work: with
|
|
262
|
+
* large scripts every batch can pass the cap and be retried smaller. The budget
|
|
263
|
+
* does (BODY_MAX_REQUESTS requests, BODY_MAX_BYTES pulled, a failed attempt
|
|
264
|
+
* counted at the response cap, in-flight requests reserved at it). When it is
|
|
265
|
+
* spent the remaining rows keep an empty snippet and one warning says how many.
|
|
266
|
+
*
|
|
267
|
+
* A first batch of more than a few rows is read alone, and what it learns is kept: a batch that
|
|
268
|
+
* passes the cap makes the next ones half its size (a clean, small answer lets
|
|
269
|
+
* the size grow again), instead of every batch starting at 50 and failing. A
|
|
270
|
+
* batch of one that passes the cap marks its row. Batches are taken in page
|
|
271
|
+
* order but up to four run at once and finish in any order, so which rows are
|
|
272
|
+
* left without a snippet when the budget is spent depends on how the batches
|
|
273
|
+
* finished: it is often, but not always, the later rows. Every row is still
|
|
274
|
+
* returned, in order. Any other failure leaves those rows without a snippet and
|
|
275
|
+
* says why.
|
|
276
|
+
*/
|
|
277
|
+
async function readBodies(client, signal, page, warnings) {
|
|
278
|
+
const queue = page.filter((match) => match.body === undefined && SYS_ID.test(match.sysId));
|
|
279
|
+
if (queue.length === 0)
|
|
280
|
+
return;
|
|
281
|
+
const state = { requests: 0, bytes: 0, size: BATCH_ROWS };
|
|
282
|
+
const failed = new Map();
|
|
283
|
+
const spent = () => state.requests >= BODY_MAX_REQUESTS || state.bytes + RESPONSE_CAP_BYTES > BODY_MAX_BYTES;
|
|
284
|
+
const readOne = async () => {
|
|
285
|
+
if (queue.length === 0 || spent())
|
|
286
|
+
return false;
|
|
287
|
+
const batch = takeBatch(queue, state.size);
|
|
288
|
+
state.requests += 1;
|
|
289
|
+
state.bytes += RESPONSE_CAP_BYTES;
|
|
290
|
+
try {
|
|
291
|
+
const pulled = await readBatch(client, signal, batch);
|
|
292
|
+
state.bytes += pulled - RESPONSE_CAP_BYTES;
|
|
293
|
+
if (pulled < RESPONSE_CAP_BYTES / 4)
|
|
294
|
+
state.size = Math.min(BATCH_ROWS, state.size * 2);
|
|
295
|
+
}
|
|
296
|
+
catch (error) {
|
|
297
|
+
if (signal?.aborted)
|
|
298
|
+
throw error;
|
|
299
|
+
if ((0, client_js_1.isServiceNowResponseTooLarge)(error)) {
|
|
300
|
+
// The attempt may have pulled up to the cap: keep it counted.
|
|
301
|
+
if (batch.length === 1)
|
|
302
|
+
batch[0].tooLarge = true;
|
|
303
|
+
else {
|
|
304
|
+
const half = Math.max(1, Math.ceil(batch.length / 2));
|
|
305
|
+
state.size = Math.max(1, Math.min(state.size, half));
|
|
306
|
+
// These rows are read again in halves, and never regrouped into a
|
|
307
|
+
// batch as large as the one that failed: a later success must not
|
|
308
|
+
// bring one large script back into a big batch.
|
|
309
|
+
for (const match of batch)
|
|
310
|
+
match.ceiling = Math.min(match.ceiling ?? half, half);
|
|
311
|
+
queue.unshift(...batch);
|
|
84
312
|
}
|
|
85
|
-
return { matches };
|
|
86
|
-
}
|
|
87
|
-
catch (error) {
|
|
88
|
-
// Tables can fail (ACL issues, etc.) -- report, don't hide
|
|
89
|
-
return { error };
|
|
90
|
-
}
|
|
91
|
-
}));
|
|
92
|
-
for (const [index, outcome] of outcomes.entries()) {
|
|
93
|
-
if ("error" in outcome) {
|
|
94
|
-
failures.push(outcome.error);
|
|
95
|
-
warnings.push(`${targets[index].table}: ${(0, utils_js_1.formatError)(outcome.error)}`);
|
|
96
313
|
}
|
|
97
314
|
else {
|
|
98
|
-
|
|
315
|
+
state.bytes -= RESPONSE_CAP_BYTES;
|
|
316
|
+
const table = batch[0].selected.target.table;
|
|
317
|
+
if (!failed.has(table))
|
|
318
|
+
failed.set(table, error);
|
|
99
319
|
}
|
|
100
320
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
321
|
+
return true;
|
|
322
|
+
};
|
|
323
|
+
const worker = async () => {
|
|
324
|
+
while (await readOne()) {
|
|
325
|
+
// keep going until the queue or the budget is spent
|
|
105
326
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
allResults = allResults.slice(args.offset, args.offset + args.limit + 1);
|
|
113
|
-
return (0, utils_js_1.ok)((0, utils_js_1.withWarnings)(allResults, warnings));
|
|
327
|
+
};
|
|
328
|
+
// A batch of a few rows cannot pass the cap (the largest script seen is about
|
|
329
|
+
// a quarter of it), so only a larger first batch is read alone to learn from.
|
|
330
|
+
const firstTable = queue[0].selected.target.table;
|
|
331
|
+
if (queue.filter((match) => match.selected.target.table === firstTable).length > PROBE_ROWS) {
|
|
332
|
+
await readOne();
|
|
114
333
|
}
|
|
115
|
-
|
|
116
|
-
|
|
334
|
+
await Promise.all(Array.from({ length: BATCH_CONCURRENCY }, worker));
|
|
335
|
+
for (const [table, error] of failed) {
|
|
336
|
+
warnings.push(`${table}: snippets unavailable for some results. ${(0, utils_js_1.formatError)(error)}`);
|
|
337
|
+
}
|
|
338
|
+
const unread = queue.filter((match) => match.body === undefined && !match.tooLarge).length;
|
|
339
|
+
if (unread > 0 && failed.size === 0) {
|
|
340
|
+
warnings.push(`Script bodies were not read for ${unread} result${unread === 1 ? "" : "s"}: the read ` +
|
|
341
|
+
`budget for one search (${BODY_MAX_REQUESTS} requests, ${BODY_MAX_BYTES / (1024 * 1024)} MiB) was reached, ` +
|
|
342
|
+
`so their snippets are empty. Lower limit to read them.`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* The next batch: up to `size` rows of the table of the first queued row, in
|
|
347
|
+
* order, and no more than any row in it can take (see `ceiling`).
|
|
348
|
+
*/
|
|
349
|
+
function takeBatch(queue, size) {
|
|
350
|
+
const table = queue[0].selected.target.table;
|
|
351
|
+
const batch = [];
|
|
352
|
+
let room = size;
|
|
353
|
+
for (let at = 0; at < queue.length && batch.length < room;) {
|
|
354
|
+
const candidate = queue[at];
|
|
355
|
+
if (candidate.selected.target.table !== table) {
|
|
356
|
+
at += 1;
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
const next = Math.min(room, candidate.ceiling ?? room);
|
|
360
|
+
if (batch.length + 1 > next)
|
|
361
|
+
break;
|
|
362
|
+
room = next;
|
|
363
|
+
batch.push(...queue.splice(at, 1));
|
|
364
|
+
}
|
|
365
|
+
return batch;
|
|
366
|
+
}
|
|
367
|
+
/** Read one batch of scripts by id and return about how many bytes it pulled. */
|
|
368
|
+
async function readBatch(client, signal, matches) {
|
|
369
|
+
const { target, field } = matches[0].selected;
|
|
370
|
+
const resp = await inFreshBudget(signal, () => client.get(`/api/now/table/${target.queryTable}`, {
|
|
371
|
+
sysparm_query: `sys_idIN${matches.map((match) => match.sysId).join(",")}`,
|
|
372
|
+
sysparm_fields: (0, code_search_targets_js_1.searchProjection)("sys_id", field).join(","),
|
|
373
|
+
sysparm_limit: String(matches.length),
|
|
374
|
+
sysparm_no_count: "true",
|
|
375
|
+
sysparm_exclude_reference_link: "true",
|
|
376
|
+
}));
|
|
377
|
+
const filtered = (0, field_policy_js_1.filterReadableRecord)(rowsOf(resp), matches[0].readable);
|
|
378
|
+
const bodies = new Map();
|
|
379
|
+
let pulled = 0;
|
|
380
|
+
for (const candidate of Array.isArray(filtered) ? filtered : []) {
|
|
381
|
+
if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate))
|
|
382
|
+
continue;
|
|
383
|
+
const record = candidate;
|
|
384
|
+
if (typeof record.sys_id === "string" && record[field] !== undefined) {
|
|
385
|
+
const body = String(record[field]);
|
|
386
|
+
bodies.set(record.sys_id, body);
|
|
387
|
+
pulled += body.length + 64;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
for (const match of matches) {
|
|
391
|
+
const body = bodies.get(match.sysId);
|
|
392
|
+
if (body !== undefined)
|
|
393
|
+
match.body = body;
|
|
394
|
+
}
|
|
395
|
+
return pulled;
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* The rows of the page that the response can hold. The envelope keeps rows
|
|
399
|
+
* while their serialized size fits its byte limit and drops the rest, so a
|
|
400
|
+
* script read for a row past that point is a script nobody sees. Each row is
|
|
401
|
+
* counted at its size with a full-length snippet, a little over what it will be.
|
|
402
|
+
*/
|
|
403
|
+
function rowsTheResponseCanHold(page) {
|
|
404
|
+
let used = 0;
|
|
405
|
+
const held = [];
|
|
406
|
+
for (const match of page) {
|
|
407
|
+
used += JSON.stringify({
|
|
408
|
+
table: match.selected.target.table,
|
|
409
|
+
table_label: match.selected.target.label,
|
|
410
|
+
sys_id: match.recordId,
|
|
411
|
+
name: match.name,
|
|
412
|
+
snippet: "x".repeat(SNIPPET_ROOM),
|
|
413
|
+
line: 99_999,
|
|
414
|
+
}).length + (match.selected.target.lookups.length > 0 ? ATF_NAME_ROOM : 0);
|
|
415
|
+
if (used > utils_js_1.MAX_RESPONSE_BYTES_DEFAULT)
|
|
416
|
+
break;
|
|
417
|
+
held.push(match);
|
|
418
|
+
}
|
|
419
|
+
return held;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Say which test and step each ATF match belongs to. The match is a value that
|
|
423
|
+
* belongs to a step (its `document_key`); the steps are read by id for their
|
|
424
|
+
* test and order, then the tests for their names. Both are tables the access
|
|
425
|
+
* plan already authorized, read with the fields it approved. A step or test that
|
|
426
|
+
* cannot be read leaves the row with the name "unnamed" and says why.
|
|
427
|
+
*/
|
|
428
|
+
async function nameAtfSteps(client, signal, args, page, warnings) {
|
|
429
|
+
const matches = page.filter((match) => match.selected.target.lookups.length > 0 && SYS_ID.test(match.recordId));
|
|
430
|
+
if (matches.length === 0)
|
|
431
|
+
return;
|
|
432
|
+
const [stepLookup, testLookup] = matches[0].selected.target.lookups;
|
|
433
|
+
const steps = new Map();
|
|
434
|
+
const stepIds = [...new Set(matches.map((match) => match.recordId))];
|
|
435
|
+
const stepFailures = await runJobs(signal, chunks(stepIds, BATCH_ROWS).map((ids) => ({
|
|
436
|
+
table: stepLookup.table,
|
|
437
|
+
run: async () => {
|
|
438
|
+
for (const record of await readByIds(client, signal, args, stepLookup, ids)) {
|
|
439
|
+
if (typeof record.sys_id === "string") {
|
|
440
|
+
steps.set(record.sys_id, {
|
|
441
|
+
test: referenceId(record.test),
|
|
442
|
+
order: scalar(record.order),
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
},
|
|
447
|
+
})));
|
|
448
|
+
const tests = new Map();
|
|
449
|
+
const testIds = [
|
|
450
|
+
...new Set([...steps.values()].flatMap((step) => (step.test === undefined ? [] : [step.test]))),
|
|
451
|
+
];
|
|
452
|
+
const testFailures = await runJobs(signal, chunks(testIds, BATCH_ROWS).map((ids) => ({
|
|
453
|
+
table: testLookup.table,
|
|
454
|
+
run: async () => {
|
|
455
|
+
for (const record of await readByIds(client, signal, args, testLookup, ids)) {
|
|
456
|
+
if (typeof record.sys_id === "string" && typeof record.name === "string" && record.name) {
|
|
457
|
+
tests.set(record.sys_id, record.name);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
},
|
|
461
|
+
})));
|
|
462
|
+
for (const match of matches) {
|
|
463
|
+
const step = steps.get(match.recordId);
|
|
464
|
+
if (step === undefined)
|
|
465
|
+
continue;
|
|
466
|
+
const test = step.test === undefined ? undefined : tests.get(step.test);
|
|
467
|
+
const position = step.order === undefined ? "step" : `step ${step.order}`;
|
|
468
|
+
match.name = test === undefined ? position : `${test} > ${position}`;
|
|
469
|
+
}
|
|
470
|
+
for (const [table, error] of [...stepFailures, ...testFailures]) {
|
|
471
|
+
warnings.push(`${table}: names unavailable for some results. ${(0, utils_js_1.formatError)(error)}`);
|
|
117
472
|
}
|
|
118
473
|
}
|
|
474
|
+
/** The records of a lookup table with these ids, with only the fields the access plan approved. */
|
|
475
|
+
async function readByIds(client, signal, args, lookup, ids) {
|
|
476
|
+
const readable = (0, field_policy_js_1.preparedReadableFields)(args, lookup.table) ??
|
|
477
|
+
(0, field_policy_js_1.resolveReadableFields)(lookup.table, { fields: lookup.fields.join(",") });
|
|
478
|
+
const resp = await inFreshBudget(signal, () => client.get(`/api/now/table/${lookup.table}`, {
|
|
479
|
+
sysparm_query: `sys_idIN${ids.join(",")}`,
|
|
480
|
+
sysparm_fields: lookup.fields.join(","),
|
|
481
|
+
sysparm_limit: String(ids.length),
|
|
482
|
+
sysparm_no_count: "true",
|
|
483
|
+
sysparm_exclude_reference_link: "true",
|
|
484
|
+
}));
|
|
485
|
+
const filtered = (0, field_policy_js_1.filterReadableRecord)(rowsOf(resp), readable);
|
|
486
|
+
return (Array.isArray(filtered) ? filtered : []).filter((candidate) => typeof candidate === "object" && candidate !== null && !Array.isArray(candidate));
|
|
487
|
+
}
|
|
488
|
+
/** A reference's id, whether the instance sent it bare or as `{ value }`. */
|
|
489
|
+
function referenceId(value, requireSysId = true) {
|
|
490
|
+
const candidate = typeof value === "object" && value !== null ? value.value : value;
|
|
491
|
+
if (typeof candidate !== "string")
|
|
492
|
+
return undefined;
|
|
493
|
+
return !requireSysId || SYS_ID.test(candidate) ? candidate : undefined;
|
|
494
|
+
}
|
|
495
|
+
function scalar(value) {
|
|
496
|
+
return typeof value === "string" || typeof value === "number" ? String(value) : undefined;
|
|
497
|
+
}
|
|
498
|
+
function toRow(match, term) {
|
|
499
|
+
const { target } = match.selected;
|
|
500
|
+
const row = {
|
|
501
|
+
table: target.table,
|
|
502
|
+
table_label: match.selected.named ? target.table : target.label,
|
|
503
|
+
sys_id: match.recordId,
|
|
504
|
+
name: match.name,
|
|
505
|
+
};
|
|
506
|
+
if (match.body) {
|
|
507
|
+
const { text, line } = (0, code_search_snippet_js_1.snippetAround)(match.body, term);
|
|
508
|
+
row.snippet = text;
|
|
509
|
+
if (line !== undefined)
|
|
510
|
+
row.line = line;
|
|
511
|
+
}
|
|
512
|
+
else {
|
|
513
|
+
row.snippet = "";
|
|
514
|
+
if (match.tooLarge)
|
|
515
|
+
row.note = TOO_LARGE_NOTE;
|
|
516
|
+
}
|
|
517
|
+
return row;
|
|
518
|
+
}
|
|
519
|
+
function rowsOf(response) {
|
|
520
|
+
if (typeof response !== "object" || response === null)
|
|
521
|
+
return [];
|
|
522
|
+
const result = response.result;
|
|
523
|
+
return result || [];
|
|
524
|
+
}
|
|
525
|
+
function chunks(items, size) {
|
|
526
|
+
const out = [];
|
|
527
|
+
for (let at = 0; at < items.length; at += size)
|
|
528
|
+
out.push(items.slice(at, at + size));
|
|
529
|
+
return out;
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Run jobs with a few in flight, in the order given. A job that fails does not
|
|
533
|
+
* stop the others; the first failure of each table is returned. A cancelled
|
|
534
|
+
* call rethrows, since nothing after it should run.
|
|
535
|
+
*/
|
|
536
|
+
async function runJobs(signal, jobs) {
|
|
537
|
+
const failed = new Map();
|
|
538
|
+
let next = 0;
|
|
539
|
+
const worker = async () => {
|
|
540
|
+
while (next < jobs.length) {
|
|
541
|
+
const job = jobs[next];
|
|
542
|
+
next += 1;
|
|
543
|
+
try {
|
|
544
|
+
await job.run();
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
if (signal?.aborted)
|
|
548
|
+
throw error;
|
|
549
|
+
if (!failed.has(job.table))
|
|
550
|
+
failed.set(job.table, error);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
await Promise.all(Array.from({ length: Math.min(BATCH_CONCURRENCY, jobs.length) }, worker));
|
|
555
|
+
return failed;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Run `operation` in its own response-byte scope, bound to the call's signal.
|
|
559
|
+
* A read that passes the cap then costs only its own scope, and the next read
|
|
560
|
+
* starts with a full budget. Without a signal (a direct handler call) it runs in
|
|
561
|
+
* the caller's scope.
|
|
562
|
+
*/
|
|
563
|
+
function inFreshBudget(signal, operation) {
|
|
564
|
+
return signal instanceof AbortSignal
|
|
565
|
+
? (0, client_js_1.runWithServiceNowRequestSignal)(signal, operation)
|
|
566
|
+
: operation();
|
|
567
|
+
}
|
|
119
568
|
//# sourceMappingURL=codesearch.js.map
|