dsh-ris-ide 1.7.1 → 1.7.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/lib/client-codemirror.js +18 -0
- package/lib/client.js +463 -46
- package/lib/index.js +464 -3
- package/package.json +1 -1
- package/test/client-viewer.test.mjs +292 -4
- package/test/host-search.test.mjs +125 -1
- package/test/host-tail.test.mjs +62 -0
package/lib/index.js
CHANGED
|
@@ -266,6 +266,25 @@ const SEARCH_PATH = `${ROUTE_PREFIX}/search`
|
|
|
266
266
|
* a plain filesystem walk when there is no git (or git is not installed).
|
|
267
267
|
*/
|
|
268
268
|
const CONTENT_SEARCH_PATH = `${ROUTE_PREFIX}/search-content`
|
|
269
|
+
/**
|
|
270
|
+
* Streaming twins of the two searches: ONE NDJSON response, one frame per page,
|
|
271
|
+
* so the dropdown paints the first matches while the other repo roots are still
|
|
272
|
+
* being listed. The non-streaming routes stay (compatibility + fallback when a
|
|
273
|
+
* browser lacks readable streams).
|
|
274
|
+
*/
|
|
275
|
+
const SEARCH_STREAM_PATH = `${ROUTE_PREFIX}/search/stream`
|
|
276
|
+
const CONTENT_SEARCH_STREAM_PATH = `${ROUTE_PREFIX}/search-content/stream`
|
|
277
|
+
/** Rows per streamed page when the client does not ask for a size. */
|
|
278
|
+
export const SEARCH_STREAM_PAGE_DEFAULT = 40
|
|
279
|
+
/** Largest page a client may ask for. */
|
|
280
|
+
export const SEARCH_STREAM_PAGE_MAX = 500
|
|
281
|
+
/**
|
|
282
|
+
* How many repo roots may run `git` at the same time. The roots are independent
|
|
283
|
+
* processes and this workspace has 32 of them: sequential `ls-files` measured
|
|
284
|
+
* 1.0 s, the same calls with all roots in flight 0.09 s — the wall clock is
|
|
285
|
+
* spawn latency, not file count, so running them together is the whole fix.
|
|
286
|
+
*/
|
|
287
|
+
export const SEARCH_STREAM_CONCURRENCY = 6
|
|
269
288
|
/**
|
|
270
289
|
* Run ONE Maven test (`-Dtest=<name>`) in one module and keep its console in
|
|
271
290
|
* memory, so the IDE can start it and poll without a fake terminal.
|
|
@@ -377,6 +396,13 @@ const DEFAULT_STOP_GRACE_MS = 5000
|
|
|
377
396
|
const MAX_STOP_GRACE_MS = 60000
|
|
378
397
|
/** Cap on one JSON request body (the stop request carries two short strings). */
|
|
379
398
|
const MAX_BODY_BYTES = 64 * 1024
|
|
399
|
+
/**
|
|
400
|
+
* Cap on one `POST /fs/write` body: an editor save carries the WHOLE file, so the
|
|
401
|
+
* generic 64 KB JSON cap rejected every save of a file above ~64 KB ("request body
|
|
402
|
+
* too large"). Text edits are opened whole below `FS_MAX_TEXT_BYTES` (512 KB) and
|
|
403
|
+
* chunked above it, so 8 MB covers every editable document with room to spare.
|
|
404
|
+
*/
|
|
405
|
+
const FS_WRITE_MAX_BODY_BYTES = 8 * 1024 * 1024
|
|
380
406
|
|
|
381
407
|
/** One routable failure with a machine code and an HTTP status. */
|
|
382
408
|
export class TailError extends Error {
|
|
@@ -660,6 +686,15 @@ function dispatchRequest(ctx, req, res, options) {
|
|
|
660
686
|
serveSafely(res, () => serveContentSearch(ctx, req, res, options))
|
|
661
687
|
return
|
|
662
688
|
}
|
|
689
|
+
if (pathname === SEARCH_STREAM_PATH || pathname === CONTENT_SEARCH_STREAM_PATH) {
|
|
690
|
+
if (method !== 'GET') {
|
|
691
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
692
|
+
return
|
|
693
|
+
}
|
|
694
|
+
// Not serveSafely: the handler streams and owns its own error frames.
|
|
695
|
+
void serveSearchStream(ctx, req, res, options, pathname === CONTENT_SEARCH_STREAM_PATH)
|
|
696
|
+
return
|
|
697
|
+
}
|
|
663
698
|
if (pathname === OPENS_PATH) {
|
|
664
699
|
if (method !== 'GET') {
|
|
665
700
|
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
@@ -1031,6 +1066,355 @@ async function serveContentSearch(ctx, req, res, options) {
|
|
|
1031
1066
|
}
|
|
1032
1067
|
}
|
|
1033
1068
|
|
|
1069
|
+
/**
|
|
1070
|
+
* Spawn one git command and hand its stdout to `onText` as it arrives — the
|
|
1071
|
+
* streaming twin of {@link runGit}. `git grep`/`git ls-files` exit 1 for "no
|
|
1072
|
+
* match", which is an answer, not a failure. A client that navigated away leaves
|
|
1073
|
+
* `stream.aborted` set: the child is killed and no more text is delivered.
|
|
1074
|
+
* @param args - git arguments.
|
|
1075
|
+
* @param cwd - working directory (one repo root).
|
|
1076
|
+
* @param onText - called with each stdout chunk.
|
|
1077
|
+
* @param stream - `{ aborted, children }` control object (see serveSearchStream).
|
|
1078
|
+
* @returns {Promise<void>} resolves when the child is gone.
|
|
1079
|
+
*/
|
|
1080
|
+
function streamGitStdout(args, cwd, onText, stream) {
|
|
1081
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
1082
|
+
const child = spawn('git', args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
1083
|
+
if (stream !== undefined) stream.children.add(child)
|
|
1084
|
+
let stderr = ''
|
|
1085
|
+
let settled = false
|
|
1086
|
+
child.stdout?.setEncoding('utf8')
|
|
1087
|
+
child.stdout?.on('data', (chunk) => {
|
|
1088
|
+
if (stream !== undefined && stream.aborted === true) return
|
|
1089
|
+
onText(chunk)
|
|
1090
|
+
})
|
|
1091
|
+
child.stderr?.on('data', (chunk) => { if (stderr.length < 8192) stderr += chunk.toString('utf8') })
|
|
1092
|
+
const settle = (error) => {
|
|
1093
|
+
if (settled) return
|
|
1094
|
+
settled = true
|
|
1095
|
+
if (stream !== undefined) stream.children.delete(child)
|
|
1096
|
+
if (error === undefined) resolvePromise()
|
|
1097
|
+
else rejectPromise(error)
|
|
1098
|
+
}
|
|
1099
|
+
child.on('error', (error) => {
|
|
1100
|
+
if (isMissingExecutable(error)) gitMissing = true
|
|
1101
|
+
settle(error)
|
|
1102
|
+
})
|
|
1103
|
+
child.on('close', (code) => {
|
|
1104
|
+
// Killed on purpose (row budget spent / client gone) is an ANSWER, not an
|
|
1105
|
+
// error: treating it as one made every fallback walk the whole root again.
|
|
1106
|
+
if (child.killed === true) settle(undefined)
|
|
1107
|
+
else if (stream !== undefined && stream.aborted === true) settle(undefined)
|
|
1108
|
+
else if (code === 0 || code === 1) settle(undefined)
|
|
1109
|
+
else settle(new Error(stderr || `git exited with ${code}`))
|
|
1110
|
+
})
|
|
1111
|
+
})
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/**
|
|
1115
|
+
* SIGTERM every git child of one streamed search. Called when the row budget is
|
|
1116
|
+
* spent (nobody waits for the rest) and when the client disconnects.
|
|
1117
|
+
* @param stream - `{ children: Set<ChildProcess> }`, or undefined in unit tests.
|
|
1118
|
+
*/
|
|
1119
|
+
function killStreamChildren(stream) {
|
|
1120
|
+
if (stream === undefined || stream === null) return
|
|
1121
|
+
for (const child of stream.children) {
|
|
1122
|
+
try { child.kill('SIGTERM') } catch { /* already gone */ }
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* Emit streamed matches in ROOT ORDER while the roots are searched concurrently.
|
|
1128
|
+
*
|
|
1129
|
+
* The sequential search visits the workspace root first and then the child repos
|
|
1130
|
+
* alphabetically; buffering per root and only flushing the head root keeps that
|
|
1131
|
+
* ranking exactly, so pages never reshuffle the dropdown. A page leaves as soon
|
|
1132
|
+
* as `pageSize` rows of the emitting root are buffered — the first page therefore
|
|
1133
|
+
* arrives after the fastest root instead of after the slowest.
|
|
1134
|
+
*
|
|
1135
|
+
* `maxItems` (the caller's `limit`) is counted on the EMITTED order, not on the
|
|
1136
|
+
* arrival order: roots answer concurrently, so a root late in the ranking must
|
|
1137
|
+
* not steal the budget from an earlier one. Hitting it closes the emitter and
|
|
1138
|
+
* fires `onFull` (the caller kills the git children there).
|
|
1139
|
+
* @param rootCount - number of roots (one buffer each).
|
|
1140
|
+
* @param pageSize - rows per emitted page.
|
|
1141
|
+
* @param emit - receives one page (non-empty array).
|
|
1142
|
+
* @param [options] - `{ maxItems, onFull }`.
|
|
1143
|
+
* @returns `{ push, finish, close, isClosed, isFull, total }`.
|
|
1144
|
+
*/
|
|
1145
|
+
function createOrderedPages(rootCount, pageSize, emit, options = {}) {
|
|
1146
|
+
const maxItems = Number.isFinite(options.maxItems) && options.maxItems > 0 ? options.maxItems : Infinity
|
|
1147
|
+
const onFull = typeof options.onFull === 'function' ? options.onFull : () => {}
|
|
1148
|
+
const buffers = []
|
|
1149
|
+
const finished = []
|
|
1150
|
+
for (let index = 0; index < rootCount; index += 1) { buffers.push([]); finished.push(false) }
|
|
1151
|
+
let head = 0
|
|
1152
|
+
let total = 0
|
|
1153
|
+
let full = false
|
|
1154
|
+
let closed = false
|
|
1155
|
+
/** Deliver `items` as pages, never more than the remaining budget. */
|
|
1156
|
+
function deliver(items) {
|
|
1157
|
+
let offset = 0
|
|
1158
|
+
while (offset < items.length && full !== true) {
|
|
1159
|
+
const take = Math.min(pageSize, items.length - offset, maxItems - total)
|
|
1160
|
+
if (take <= 0) break
|
|
1161
|
+
const page = items.slice(offset, offset + take)
|
|
1162
|
+
offset += take
|
|
1163
|
+
total += take
|
|
1164
|
+
emit(page)
|
|
1165
|
+
if (total >= maxItems) full = true
|
|
1166
|
+
}
|
|
1167
|
+
if (full === true && closed !== true) {
|
|
1168
|
+
closed = true
|
|
1169
|
+
onFull()
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
function flush() {
|
|
1173
|
+
while (!closed && head < rootCount) {
|
|
1174
|
+
const buffer = buffers[head]
|
|
1175
|
+
while (buffer.length >= pageSize) deliver(buffer.splice(0, pageSize))
|
|
1176
|
+
if (finished[head] !== true) return
|
|
1177
|
+
if (buffer.length > 0) deliver(buffer.splice(0, buffer.length))
|
|
1178
|
+
head += 1
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
return {
|
|
1182
|
+
push(index, items) {
|
|
1183
|
+
if (closed) return
|
|
1184
|
+
const buffer = buffers[index]
|
|
1185
|
+
for (const item of items) buffer.push(item)
|
|
1186
|
+
flush()
|
|
1187
|
+
},
|
|
1188
|
+
finish(index) {
|
|
1189
|
+
if (closed) return
|
|
1190
|
+
finished[index] = true
|
|
1191
|
+
flush()
|
|
1192
|
+
},
|
|
1193
|
+
close() {
|
|
1194
|
+
if (closed) return
|
|
1195
|
+
// Abort path: flush what was already accepted (in root order) so a caller
|
|
1196
|
+
// that closed early still sees the rows it asked for, then stop.
|
|
1197
|
+
for (let index = head; index < rootCount; index += 1) {
|
|
1198
|
+
const buffer = buffers[index]
|
|
1199
|
+
while (buffer.length > 0 && full !== true) deliver(buffer.splice(0, Math.min(pageSize, buffer.length)))
|
|
1200
|
+
}
|
|
1201
|
+
closed = true
|
|
1202
|
+
},
|
|
1203
|
+
isClosed() { return closed },
|
|
1204
|
+
isFull() { return full },
|
|
1205
|
+
total() { return total },
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
/**
|
|
1210
|
+
* Run `worker(root, index)` for every root with at most `concurrency` in flight.
|
|
1211
|
+
* A worker must handle its own errors — one broken repo must not cancel the rest.
|
|
1212
|
+
* @param roots - repo roots.
|
|
1213
|
+
* @param concurrency - maximum simultaneous workers.
|
|
1214
|
+
* @param worker - async `(root, index)`.
|
|
1215
|
+
* @returns {Promise<void>} resolves when every root was visited.
|
|
1216
|
+
*/
|
|
1217
|
+
async function forEachRootInParallel(roots, concurrency, worker) {
|
|
1218
|
+
let next = 0
|
|
1219
|
+
async function lane() {
|
|
1220
|
+
while (next < roots.length) {
|
|
1221
|
+
const index = next
|
|
1222
|
+
next += 1
|
|
1223
|
+
await worker(roots[index], index)
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
const lanes = []
|
|
1227
|
+
const width = Math.max(1, Math.min(concurrency, roots.length))
|
|
1228
|
+
for (let index = 0; index < width; index += 1) lanes.push(lane())
|
|
1229
|
+
await Promise.all(lanes)
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
/**
|
|
1233
|
+
* Streaming filename search: the same matches, ignore rules and ordering as
|
|
1234
|
+
* {@link searchWorkspaceFiles}, delivered page by page while the roots are
|
|
1235
|
+
* listed in parallel.
|
|
1236
|
+
* @param cwd - workspace root (only for the no-git fallback).
|
|
1237
|
+
* @param roots - repo roots from {@link searchRoots}.
|
|
1238
|
+
* @param query - case-insensitive substring of the path or basename.
|
|
1239
|
+
* @param options - `{ limit, pageSize, onPage, stream }`.
|
|
1240
|
+
* @returns `{ files, count, truncated }` when the walk is complete.
|
|
1241
|
+
*/
|
|
1242
|
+
async function searchWorkspaceFilesStream(cwd, roots, query, options) {
|
|
1243
|
+
const { limit, pageSize, onPage, stream } = options
|
|
1244
|
+
const needle = String(query ?? '').toLowerCase()
|
|
1245
|
+
let files = 0
|
|
1246
|
+
let truncated = false
|
|
1247
|
+
// The `limit` is counted on the EMITTED (root-ordered) rows: see createOrderedPages.
|
|
1248
|
+
const emitter = createOrderedPages(roots.length, pageSize, onPage, {
|
|
1249
|
+
maxItems: limit,
|
|
1250
|
+
onFull: () => { truncated = true; killStreamChildren(stream) },
|
|
1251
|
+
})
|
|
1252
|
+
const take = (index, path) => {
|
|
1253
|
+
files += 1
|
|
1254
|
+
if (needle !== '' && path.toLowerCase().indexOf(needle) === -1) return
|
|
1255
|
+
emitter.push(index, [path])
|
|
1256
|
+
}
|
|
1257
|
+
if (roots.length === 0 || gitMissing === true) {
|
|
1258
|
+
// No repo anywhere (or no git binary): walk and page the fallback listing.
|
|
1259
|
+
const all = await listRawFiles(cwd)
|
|
1260
|
+
const matches = []
|
|
1261
|
+
for (const path of all) {
|
|
1262
|
+
files += 1
|
|
1263
|
+
if (needle !== '' && path.toLowerCase().indexOf(needle) === -1) continue
|
|
1264
|
+
matches.push(path)
|
|
1265
|
+
if (matches.length >= limit) { truncated = true; break }
|
|
1266
|
+
}
|
|
1267
|
+
for (let offset = 0; offset < matches.length; offset += pageSize) onPage(matches.slice(offset, offset + pageSize))
|
|
1268
|
+
return { files, count: matches.length, truncated }
|
|
1269
|
+
}
|
|
1270
|
+
await forEachRootInParallel(roots, SEARCH_STREAM_CONCURRENCY, async (root, index) => {
|
|
1271
|
+
if (emitter.isClosed()) { emitter.finish(index); return }
|
|
1272
|
+
let rest = ''
|
|
1273
|
+
const consume = (relativePath) => {
|
|
1274
|
+
if (relativePath === '' || emitter.isClosed()) return
|
|
1275
|
+
take(index, join(root, relativePath))
|
|
1276
|
+
}
|
|
1277
|
+
try {
|
|
1278
|
+
await streamGitStdout(['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--'], root, (chunk) => {
|
|
1279
|
+
const parts = `${rest}${chunk}`.split('\0')
|
|
1280
|
+
rest = parts.pop() ?? ''
|
|
1281
|
+
for (const relativePath of parts) consume(relativePath)
|
|
1282
|
+
}, stream)
|
|
1283
|
+
} catch {
|
|
1284
|
+
// git disappeared mid-search: walking this root keeps the answer usable.
|
|
1285
|
+
const all = await listRawFiles(root)
|
|
1286
|
+
for (const path of all) {
|
|
1287
|
+
if (emitter.isClosed()) break
|
|
1288
|
+
take(index, path)
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
consume(rest)
|
|
1292
|
+
emitter.finish(index)
|
|
1293
|
+
})
|
|
1294
|
+
return { files, count: emitter.total(), truncated }
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
/**
|
|
1298
|
+
* Streaming content search: one `git grep` per repo root, run in parallel, with
|
|
1299
|
+
* the same literal matching / per-file cap / ordering as
|
|
1300
|
+
* {@link searchWorkspaceContent}.
|
|
1301
|
+
* @param cwd - workspace root (fallback walk).
|
|
1302
|
+
* @param roots - repo roots.
|
|
1303
|
+
* @param query - literal text.
|
|
1304
|
+
* @param options - `{ limit, perFile, pageSize, onPage, stream }`.
|
|
1305
|
+
* @returns `{ files, count, truncated }` when every root answered.
|
|
1306
|
+
*/
|
|
1307
|
+
async function searchWorkspaceContentStream(cwd, roots, query, options) {
|
|
1308
|
+
const { limit, perFile, pageSize, onPage, stream } = options
|
|
1309
|
+
const needle = String(query ?? '')
|
|
1310
|
+
const paths = new Set()
|
|
1311
|
+
let truncated = false
|
|
1312
|
+
// Same rule as the filename search: the limit applies to the emitted root order.
|
|
1313
|
+
const emitter = createOrderedPages(roots.length, pageSize, onPage, {
|
|
1314
|
+
maxItems: limit,
|
|
1315
|
+
onFull: () => { truncated = true; killStreamChildren(stream) },
|
|
1316
|
+
})
|
|
1317
|
+
const take = (index, hit) => {
|
|
1318
|
+
paths.add(hit.path)
|
|
1319
|
+
emitter.push(index, [hit])
|
|
1320
|
+
}
|
|
1321
|
+
if (roots.length === 0 || gitMissing === true) {
|
|
1322
|
+
const fallback = await searchContentRaw(cwd, needle, limit, perFile)
|
|
1323
|
+
const hits = fallback.hits
|
|
1324
|
+
for (let offset = 0; offset < hits.length; offset += pageSize) onPage(hits.slice(offset, offset + pageSize))
|
|
1325
|
+
return { files: fallback.files, count: hits.length, truncated: fallback.truncated }
|
|
1326
|
+
}
|
|
1327
|
+
await forEachRootInParallel(roots, SEARCH_STREAM_CONCURRENCY, async (root, index) => {
|
|
1328
|
+
if (emitter.isClosed()) { emitter.finish(index); return }
|
|
1329
|
+
let rest = ''
|
|
1330
|
+
const consume = (raw) => {
|
|
1331
|
+
if (raw === '' || emitter.isClosed()) return
|
|
1332
|
+
const hit = parseGitGrepLine(root, raw)
|
|
1333
|
+
if (hit !== undefined) take(index, hit)
|
|
1334
|
+
}
|
|
1335
|
+
try {
|
|
1336
|
+
await streamGitStdout(['grep', '-n', '-I', '--no-color', '-F', '-m', String(perFile), '-e', needle, '--'], root, (chunk) => {
|
|
1337
|
+
const lines = `${rest}${chunk}`.split('\n')
|
|
1338
|
+
rest = lines.pop() ?? ''
|
|
1339
|
+
for (const raw of lines) consume(raw)
|
|
1340
|
+
}, stream)
|
|
1341
|
+
} catch {
|
|
1342
|
+
// A failing root is skipped, never fatal (same rule as the batch search).
|
|
1343
|
+
}
|
|
1344
|
+
consume(rest)
|
|
1345
|
+
emitter.finish(index)
|
|
1346
|
+
})
|
|
1347
|
+
return { files: paths.size, count: emitter.total(), truncated }
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/**
|
|
1351
|
+
* One STREAMED search: NDJSON frames over a chunked response.
|
|
1352
|
+
*
|
|
1353
|
+
* Frames: `{type:'start',root,roots}` then `{type:'page',items:[...]}` (one per
|
|
1354
|
+
* page, in root order) and finally `{type:'done',files,matches,truncated}` —
|
|
1355
|
+
* or `{type:'error',code,message}` when the search failed after the headers.
|
|
1356
|
+
* A client disconnect aborts the git children of this request.
|
|
1357
|
+
* @param ctx - Host context (session cwd lookup).
|
|
1358
|
+
* @param req - Node request face.
|
|
1359
|
+
* @param res - Node response face.
|
|
1360
|
+
* @param options - `{ restrictToCwd }` (see {@link apply}).
|
|
1361
|
+
* @param content - `true` for content hits, `false` for filenames.
|
|
1362
|
+
*/
|
|
1363
|
+
async function serveSearchStream(ctx, req, res, options, content) {
|
|
1364
|
+
let finished = false
|
|
1365
|
+
const stream = { aborted: false, children: new Set() }
|
|
1366
|
+
const write = (payload) => {
|
|
1367
|
+
if (finished === true || res.writableEnded === true) return
|
|
1368
|
+
res.write(`${JSON.stringify(payload)}\n`)
|
|
1369
|
+
}
|
|
1370
|
+
const finish = (payload) => {
|
|
1371
|
+
if (finished === true) return
|
|
1372
|
+
finished = true
|
|
1373
|
+
if (res.writableEnded === true) return
|
|
1374
|
+
res.end(`${JSON.stringify(payload)}\n`)
|
|
1375
|
+
}
|
|
1376
|
+
try {
|
|
1377
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
1378
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
1379
|
+
const sessionId = url.searchParams.get('sessionId') ?? ''
|
|
1380
|
+
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
1381
|
+
const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd'))
|
|
1382
|
+
const query = url.searchParams.get('q') ?? ''
|
|
1383
|
+
if (content && query.trim() === '') throw new TailError('bad-request', 'q (the text to search for) is required', 400)
|
|
1384
|
+
const rawLimit = Number(url.searchParams.get('limit') ?? '300')
|
|
1385
|
+
const limit = content
|
|
1386
|
+
? (Number.isFinite(rawLimit) ? Math.min(Math.max(1, Math.floor(rawLimit)), CONTENT_SEARCH_MAX_HITS) : 300)
|
|
1387
|
+
: (Number.isFinite(rawLimit) ? Math.min(Math.max(1, Math.floor(rawLimit)), 2000) : 300)
|
|
1388
|
+
const rawPerFile = Number(url.searchParams.get('perFile') ?? '8')
|
|
1389
|
+
const perFile = Number.isFinite(rawPerFile) ? Math.min(Math.max(1, Math.floor(rawPerFile)), CONTENT_SEARCH_MAX_PER_FILE) : 8
|
|
1390
|
+
const rawPageSize = Number(url.searchParams.get('pageSize') ?? String(SEARCH_STREAM_PAGE_DEFAULT))
|
|
1391
|
+
const pageSize = Number.isFinite(rawPageSize) ? Math.min(Math.max(1, Math.floor(rawPageSize)), SEARCH_STREAM_PAGE_MAX) : SEARCH_STREAM_PAGE_DEFAULT
|
|
1392
|
+
const roots = await searchRoots(cwd)
|
|
1393
|
+
res.writeHead(200, {
|
|
1394
|
+
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
1395
|
+
'cache-control': 'no-store',
|
|
1396
|
+
'x-accel-buffering': 'no',
|
|
1397
|
+
})
|
|
1398
|
+
res.on('close', () => {
|
|
1399
|
+
if (finished === true) return
|
|
1400
|
+
stream.aborted = true
|
|
1401
|
+
for (const child of stream.children) {
|
|
1402
|
+
try { child.kill('SIGTERM') } catch { /* already gone */ }
|
|
1403
|
+
}
|
|
1404
|
+
})
|
|
1405
|
+
write({ type: 'start', root: cwd, repoCount: roots.length })
|
|
1406
|
+
const onPage = (items) => write({ type: 'page', items })
|
|
1407
|
+
const result = content
|
|
1408
|
+
? await searchWorkspaceContentStream(cwd, roots, query, { limit, perFile, pageSize, onPage, stream })
|
|
1409
|
+
: await searchWorkspaceFilesStream(cwd, roots, query, { limit, pageSize, onPage, stream })
|
|
1410
|
+
finish({ type: 'done', files: result.files, matches: result.count, truncated: result.truncated })
|
|
1411
|
+
} catch (error) {
|
|
1412
|
+
if (finished === true) return
|
|
1413
|
+
if (res.writableEnded !== true && res.headersSent !== true) { writeTailError(res, error); return }
|
|
1414
|
+
finish({ type: 'error', code: error?.code ?? 'error', message: error?.message ?? 'search failed' })
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1034
1418
|
/** Cache of one repo root's allowed file paths (gitignore-aware), 5s TTL. */
|
|
1035
1419
|
const TREE_ALLOWED_CACHE = new Map()
|
|
1036
1420
|
/** Repo listing caches invalidated in the last second (coalesces save storms). */
|
|
@@ -1486,6 +1870,10 @@ async function listIdeTree(target, cwd, options) {
|
|
|
1486
1870
|
const ignoredDirs = await ignoredTreeDirs(repo ?? '', unknownDirs)
|
|
1487
1871
|
const entries = []
|
|
1488
1872
|
for (const dirent of dirents) {
|
|
1873
|
+
// A chunked save stages the document in `<file>.dsh-ris-ide-saving` next to
|
|
1874
|
+
// its target (same directory ⇒ the rename is atomic). It exists for a few
|
|
1875
|
+
// milliseconds, and after a crash it may linger: never show it as a tree row.
|
|
1876
|
+
if (dirent.name.endsWith(FS_WRITE_TEMP_SUFFIX)) continue
|
|
1489
1877
|
// `.dsh-ris-ide/` holds the undo trash, the dependency-source cache and the
|
|
1490
1878
|
// clipboard staging batches: implementation details, never tree rows — and
|
|
1491
1879
|
// hidden in BOTH filter modes, like the trash row it replaced.
|
|
@@ -2197,12 +2585,12 @@ function delay(ms) {
|
|
|
2197
2585
|
* @param req - Node request face (async iterable).
|
|
2198
2586
|
* @returns the parsed object (empty object for an empty body).
|
|
2199
2587
|
*/
|
|
2200
|
-
async function readJsonBody(req) {
|
|
2588
|
+
async function readJsonBody(req, limitBytes = MAX_BODY_BYTES, tooLargeMessage = 'request body too large') {
|
|
2201
2589
|
let size = 0
|
|
2202
2590
|
const chunks = []
|
|
2203
2591
|
for await (const chunk of req) {
|
|
2204
2592
|
size += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length
|
|
2205
|
-
if (size >
|
|
2593
|
+
if (size > limitBytes) throw new TailError('bad-request', tooLargeMessage, 413)
|
|
2206
2594
|
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
|
|
2207
2595
|
}
|
|
2208
2596
|
if (size === 0) return {}
|
|
@@ -3657,6 +4045,42 @@ async function serveTextWindow(res, target, info, url) {
|
|
|
3657
4045
|
writeJson(res, 200, { ok: true, kind: 'text-window', offset: from, next, eof: next >= info.size, size: info.size, mtimeMs: info.mtimeMs, text })
|
|
3658
4046
|
}
|
|
3659
4047
|
|
|
4048
|
+
/** Suffix of the sibling file a chunked save is staged in before the rename. */
|
|
4049
|
+
const FS_WRITE_TEMP_SUFFIX = '.dsh-ris-ide-saving'
|
|
4050
|
+
|
|
4051
|
+
/**
|
|
4052
|
+
* Write ONE chunk of a chunked `POST /fs/write`.
|
|
4053
|
+
*
|
|
4054
|
+
* The chunks land in `<target>.dsh-ris-ide-saving` at their byte offset (so a
|
|
4055
|
+
* retried chunk overwrites itself instead of appending twice) and only the chunk
|
|
4056
|
+
* with `final !== false` truncates to `offset + bytes` and renames the temp file
|
|
4057
|
+
* over the target. A reader therefore sees the old file or the new one, never a
|
|
4058
|
+
* half-written mixed document, and a failed save leaves the target untouched.
|
|
4059
|
+
*
|
|
4060
|
+
* @param target - absolute path the editor is saving.
|
|
4061
|
+
* @param body - `{content, offset, final}` from the request.
|
|
4062
|
+
*/
|
|
4063
|
+
async function writeChunk(target, body) {
|
|
4064
|
+
const offset = body.offset
|
|
4065
|
+
if (!Number.isInteger(offset) || offset < 0) throw new TailError('bad-request', 'offset must be a non-negative integer', 400)
|
|
4066
|
+
const buffer = Buffer.from(body.content, 'utf8')
|
|
4067
|
+
const staging = `${target}${FS_WRITE_TEMP_SUFFIX}`
|
|
4068
|
+
if (offset === 0) await writeFile(staging, '')
|
|
4069
|
+
// Chunks must be contiguous: a lost chunk would otherwise leave zero bytes in
|
|
4070
|
+
// the middle of the document, which is worse than refusing the save.
|
|
4071
|
+
const present = offset === 0 ? { size: 0 } : await stat(staging).catch(() => undefined)
|
|
4072
|
+
if (present === undefined) throw new TailError('chunk-out-of-order', 'the previous chunk never arrived; save again', 409)
|
|
4073
|
+
if (present.size !== offset) throw new TailError('chunk-out-of-order', 'a chunk is missing; save again', 409)
|
|
4074
|
+
const handle = await open(staging, 'r+')
|
|
4075
|
+
try {
|
|
4076
|
+
await handle.write(buffer, 0, buffer.length, offset)
|
|
4077
|
+
if (body.final !== false) await handle.truncate(offset + buffer.length)
|
|
4078
|
+
} finally {
|
|
4079
|
+
await handle.close()
|
|
4080
|
+
}
|
|
4081
|
+
if (body.final !== false) await rename(staging, target)
|
|
4082
|
+
}
|
|
4083
|
+
|
|
3660
4084
|
/**
|
|
3661
4085
|
* The IDE's own workspace file API — no `dsh-better-sidebar` involved.
|
|
3662
4086
|
*
|
|
@@ -3664,6 +4088,9 @@ async function serveTextWindow(res, target, info, url) {
|
|
|
3664
4088
|
* or `{ok:true, kind:'binary'|'too-large', size, message}` (the caller decides
|
|
3665
4089
|
* how to render those).
|
|
3666
4090
|
* - `POST /fs/write` `{sessionId, path, cwd?, content}` → `{ok, mtimeMs}`.
|
|
4091
|
+
* With `{offset, final}` it is ONE CHUNK of a chunked save: the bytes are written
|
|
4092
|
+
* at `offset` into a sibling temp file and the LAST chunk renames it over the
|
|
4093
|
+
* target, so a save is never seen half-written and has no practical size cap.
|
|
3667
4094
|
* - `GET /fs/file?sessionId&path` → raw bytes with the media content-type.
|
|
3668
4095
|
*
|
|
3669
4096
|
* All three are loopback-fenced and resolve the path exactly like `/tail` does.
|
|
@@ -3674,7 +4101,12 @@ async function serveFs(ctx, req, res, options) {
|
|
|
3674
4101
|
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
3675
4102
|
const pathname = url.pathname
|
|
3676
4103
|
if (pathname === FS_WRITE_PATH) {
|
|
3677
|
-
|
|
4104
|
+
// A save carries the entire document: give this one route its own (much
|
|
4105
|
+
// larger) cap and say so in Chinese when even that is exceeded.
|
|
4106
|
+
const writeCap = typeof options?.maxWriteBytes === 'number' && options.maxWriteBytes > 0
|
|
4107
|
+
? options.maxWriteBytes
|
|
4108
|
+
: FS_WRITE_MAX_BODY_BYTES
|
|
4109
|
+
const body = await readJsonBody(req, writeCap, `文件太大(超过 ${Math.floor(writeCap / (1024 * 1024))} MB),不能在这里保存;请改用其他编辑器`)
|
|
3678
4110
|
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
|
|
3679
4111
|
const raw = typeof body.path === 'string' ? body.path : ''
|
|
3680
4112
|
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
@@ -3684,6 +4116,21 @@ async function serveFs(ctx, req, res, options) {
|
|
|
3684
4116
|
const target = resolvePath(cwd, raw, options?.restrictToCwd === true)
|
|
3685
4117
|
const info = await stat(target).catch(() => undefined)
|
|
3686
4118
|
if (info !== undefined && !info.isFile()) throw new TailError('not-a-file', `"${target}" is not a regular file`, 400)
|
|
4119
|
+
// Chunked saves are marked by `offset`; every other request keeps the old
|
|
4120
|
+
// one-shot behaviour. Both paths end with a rename-free / rename-based
|
|
4121
|
+
// write of exactly the bytes the editor held.
|
|
4122
|
+
if (typeof body.offset === 'number' && Number.isFinite(body.offset)) {
|
|
4123
|
+
await writeChunk(target, body)
|
|
4124
|
+
const afterChunk = await stat(target).catch(() => undefined)
|
|
4125
|
+
writeJson(res, 200, {
|
|
4126
|
+
ok: true,
|
|
4127
|
+
path: target,
|
|
4128
|
+
chunked: true,
|
|
4129
|
+
final: body.final !== false,
|
|
4130
|
+
mtimeMs: afterChunk === undefined ? undefined : afterChunk.mtimeMs,
|
|
4131
|
+
})
|
|
4132
|
+
return
|
|
4133
|
+
}
|
|
3687
4134
|
await writeFile(target, body.content, 'utf8')
|
|
3688
4135
|
const after = await stat(target).catch(() => undefined)
|
|
3689
4136
|
writeJson(res, 200, { ok: true, path: target, mtimeMs: after === undefined ? undefined : after.mtimeMs })
|
|
@@ -7501,6 +7948,17 @@ export const __test = {
|
|
|
7501
7948
|
CONTENT_SEARCH_PATH,
|
|
7502
7949
|
searchWorkspaceContent,
|
|
7503
7950
|
serveContentSearch,
|
|
7951
|
+
// streamed (paged) variants: NDJSON frames while the repo roots are searched in parallel
|
|
7952
|
+
SEARCH_STREAM_PATH,
|
|
7953
|
+
CONTENT_SEARCH_STREAM_PATH,
|
|
7954
|
+
SEARCH_STREAM_PAGE_DEFAULT,
|
|
7955
|
+
SEARCH_STREAM_PAGE_MAX,
|
|
7956
|
+
SEARCH_STREAM_CONCURRENCY,
|
|
7957
|
+
searchWorkspaceFilesStream,
|
|
7958
|
+
searchWorkspaceContentStream,
|
|
7959
|
+
serveSearchStream,
|
|
7960
|
+
createOrderedPages,
|
|
7961
|
+
streamGitStdout,
|
|
7504
7962
|
// one-module `mvn test` runner (poll the console through GET ?id=)
|
|
7505
7963
|
RUN_TEST_PATH,
|
|
7506
7964
|
serveRunTestStart,
|
|
@@ -7695,6 +8153,9 @@ export const __test = {
|
|
|
7695
8153
|
ROUTE_PREFIX,
|
|
7696
8154
|
DEFAULT_BYTES,
|
|
7697
8155
|
HARD_MAX_BYTES,
|
|
8156
|
+
FS_WRITE_MAX_BODY_BYTES,
|
|
8157
|
+
FS_WRITE_TEMP_SUFFIX,
|
|
8158
|
+
writeChunk,
|
|
7698
8159
|
MIN_BYTES,
|
|
7699
8160
|
PID_SUFFIX,
|
|
7700
8161
|
DEFAULT_STOP_GRACE_MS,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-ris-ide",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "RIS-IDE local dev panel for the DSH web GUI: live log tail, one-click start/stop of workspace programs, JDWP debugging, file tree + editor, and a standalone IDE window that carries no session history. · DSH 右侧栏本地开发面板:日志实时跟随、一键启停本地程序、Java 断点调试、文件树与编辑器、独立 IDE 窗口。",
|
|
6
6
|
"keywords": [
|