@gitkraken/core-gitlens 0.38.0 → 0.38.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,194 @@
1
+ import { isNotFound } from "../../git/watching/watchGroup.js";
2
+ import { stat } from "node:fs/promises";
3
+ import { Worker } from "node:worker_threads";
4
+ //#region ../git-cli/src/exec/statWorkers.ts
5
+ /**
6
+ * Stats each path it's sent, synchronously, and answers them as one message: a thread making a batch's stats back to
7
+ * back spends far less than the round trip each asynchronous stat makes to libuv's pool. Evaluated as a script, so the
8
+ * package ships no file of its own for it. `throwIfNoEntry: false` answers `undefined` for a path that isn't there,
9
+ * as Node also does for one under a file. Reads as {@link statLocal} does
10
+ */
11
+ const statWorkerSource = `
12
+ const { statSync } = require('node:fs');
13
+ const { parentPort } = require('node:worker_threads');
14
+ parentPort.on('message', paths => {
15
+ parentPort.postMessage(
16
+ paths.map(path => {
17
+ try {
18
+ const stat = statSync(path, { throwIfNoEntry: false });
19
+ return stat == null ? 'missing' : { mtime: stat.mtimeMs, size: stat.size };
20
+ } catch (ex) {
21
+ return ex != null && (ex.code === 'ENOENT' || ex.code === 'ENOTDIR') ? 'missing' : 'unreadable';
22
+ }
23
+ }),
24
+ );
25
+ });
26
+ `;
27
+ /** How long a worker beyond the first stays idle before it's stopped */
28
+ const defaultIdleTimeoutMs = 3e4;
29
+ /** What `maxWorkers` reads as when it isn't a number, as `UnwatchedCacheValidatorOptions.maxFsThreads` does */
30
+ const defaultMaxWorkers = 2;
31
+ /** Workers at most, whatever `maxWorkers` asks for: a batch serves as well on the calling thread past it */
32
+ const maxPoolWorkers = 4;
33
+ /**
34
+ * `path`'s modification time (ms since the epoch) and size, read from the local file system; `undefined` when it isn't
35
+ * there, or is under a path that is a file. Rejects when the stat failed otherwise
36
+ */
37
+ async function statLocal(path) {
38
+ try {
39
+ const s = await stat(path);
40
+ return {
41
+ mtime: s.mtimeMs,
42
+ size: s.size
43
+ };
44
+ } catch (ex) {
45
+ if (isNotFound(ex) || ex?.code === "ENOTDIR") return void 0;
46
+ throw ex;
47
+ }
48
+ }
49
+ /**
50
+ * Worker threads that stat many paths as one call (see `UnwatchedCacheValidatorOptions.statMany`). A batch takes an
51
+ * idle running worker. When none is free, the batch is served on the calling thread, one asynchronous stat at a time,
52
+ * and, while fewer than `maxWorkers` run and none is starting, a worker is started in the background for the batches
53
+ * after it, so no read waits for a worker to start. A worker whose batch never returns (a hung mount) stays busy and
54
+ * is never handed another; one that fails or exits rejects its batch and leaves the pool, and one that does so without a
55
+ * batch rejects the next one. A busy worker keeps the process alive, as a pending file-system call does; an idle or
56
+ * starting one doesn't. One idle worker is kept; the others are stopped once idle for `idleTimeoutMs`.
57
+ */
58
+ var StatWorkerPool = class {
59
+ workers = /* @__PURE__ */ new Set();
60
+ maxWorkers;
61
+ idleTimeoutMs;
62
+ /** Why the last worker to fail without a batch failed, until a batch is rejected with it */
63
+ idleFailure;
64
+ disposed = false;
65
+ constructor(options) {
66
+ const maxWorkers = Math.floor(options.maxWorkers);
67
+ this.maxWorkers = Math.min(Number.isNaN(maxWorkers) ? defaultMaxWorkers : Math.max(1, maxWorkers), maxPoolWorkers);
68
+ this.idleTimeoutMs = options.idleTimeoutMs ?? defaultIdleTimeoutMs;
69
+ }
70
+ dispose() {
71
+ this.disposed = true;
72
+ for (const pooled of [...this.workers]) this.drop(pooled, /* @__PURE__ */ new Error("The stat worker pool was disposed"));
73
+ }
74
+ /** One reading per path, in order; rejects when a worker failed the batch, or once disposed. Never throws */
75
+ statMany(paths) {
76
+ if (this.disposed) return Promise.reject(/* @__PURE__ */ new Error("The stat worker pool was disposed"));
77
+ if (this.idleFailure != null) {
78
+ const failure = this.idleFailure;
79
+ this.idleFailure = void 0;
80
+ return Promise.reject(failure);
81
+ }
82
+ let pooled;
83
+ let starting = false;
84
+ for (const candidate of this.workers) if (!candidate.online) starting = true;
85
+ else if (candidate.batch == null) {
86
+ pooled = candidate;
87
+ break;
88
+ }
89
+ if (pooled == null) {
90
+ if (!starting && this.workers.size < this.maxWorkers) try {
91
+ this.spawn();
92
+ } catch (ex) {
93
+ return Promise.reject(ex instanceof Error ? ex : new Error(String(ex)));
94
+ }
95
+ return statOnCallingThread(paths);
96
+ }
97
+ const worker = pooled;
98
+ return new Promise((resolve, reject) => {
99
+ if (worker.idleTimer != null) {
100
+ clearTimeout(worker.idleTimer);
101
+ worker.idleTimer = void 0;
102
+ }
103
+ worker.batch = {
104
+ resolve,
105
+ reject
106
+ };
107
+ worker.worker.ref();
108
+ try {
109
+ worker.worker.postMessage(paths);
110
+ } catch (ex) {
111
+ this.drop(worker, ex instanceof Error ? ex : new Error(String(ex)));
112
+ }
113
+ });
114
+ }
115
+ /** Starts a worker that answers each batch of paths it's sent with one {@link BatchedStat} per path, in order */
116
+ createWorker() {
117
+ return new Worker(statWorkerSource, {
118
+ eval: true,
119
+ execArgv: []
120
+ });
121
+ }
122
+ spawn() {
123
+ const worker = this.createWorker();
124
+ const pooled = {
125
+ worker,
126
+ online: false,
127
+ batch: void 0,
128
+ idleTimer: void 0
129
+ };
130
+ this.workers.add(pooled);
131
+ worker.unref();
132
+ worker.on("online", () => {
133
+ if (!this.workers.has(pooled)) return;
134
+ pooled.online = true;
135
+ this.startIdleTimer(pooled);
136
+ });
137
+ worker.on("message", (readings) => {
138
+ const batch = pooled.batch;
139
+ if (batch == null) return;
140
+ pooled.batch = void 0;
141
+ worker.unref();
142
+ this.startIdleTimer(pooled);
143
+ batch.resolve(readings);
144
+ });
145
+ const fail = (reason) => {
146
+ if (pooled.batch == null && this.workers.has(pooled)) this.idleFailure = reason;
147
+ this.drop(pooled, reason);
148
+ };
149
+ worker.on("messageerror", fail);
150
+ worker.on("error", fail);
151
+ worker.on("exit", (code) => fail(/* @__PURE__ */ new Error(`The stat worker exited with code ${code}`)));
152
+ }
153
+ /** Stops an idle worker once it stayed idle for {@link idleTimeoutMs}, unless it's the only idle one */
154
+ startIdleTimer(pooled) {
155
+ const timer = setTimeout(() => {
156
+ pooled.idleTimer = void 0;
157
+ if (pooled.batch != null) return;
158
+ let idle = 0;
159
+ for (const candidate of this.workers) if (candidate.online && candidate.batch == null) idle++;
160
+ if (idle > 1) this.drop(pooled, /* @__PURE__ */ new Error("The stat worker was idle"));
161
+ }, this.idleTimeoutMs);
162
+ timer.unref();
163
+ pooled.idleTimer = timer;
164
+ }
165
+ /** Takes `pooled` out of the pool and stops it, rejecting its batch in flight with `reason` */
166
+ drop(pooled, reason) {
167
+ if (!this.workers.delete(pooled)) return;
168
+ if (pooled.idleTimer != null) {
169
+ clearTimeout(pooled.idleTimer);
170
+ pooled.idleTimer = void 0;
171
+ }
172
+ const batch = pooled.batch;
173
+ pooled.batch = void 0;
174
+ batch?.reject(reason);
175
+ pooled.worker.terminate().catch(() => {});
176
+ }
177
+ };
178
+ /**
179
+ * Reads each path with {@link statLocal}, one at a time, so the batch holds one of Node's file-system threads at a
180
+ * time, as the gate it went through counts it
181
+ */
182
+ async function statOnCallingThread(paths) {
183
+ const readings = [];
184
+ for (const path of paths) try {
185
+ readings.push(await statLocal(path) ?? "missing");
186
+ } catch {
187
+ readings.push("unreadable");
188
+ }
189
+ return readings;
190
+ }
191
+ //#endregion
192
+ export { StatWorkerPool, statLocal };
193
+
194
+ //# sourceMappingURL=statWorkers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statWorkers.js","names":[],"sources":["../../../../git-cli/src/exec/statWorkers.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { Worker } from 'node:worker_threads';\nimport type { BatchedStat } from '@gitlens/git/watching/unwatchedCacheValidator.js';\nimport { isNotFound } from '@gitlens/git/watching/watchGroup.js';\n\n/**\n * Stats each path it's sent, synchronously, and answers them as one message: a thread making a batch's stats back to\n * back spends far less than the round trip each asynchronous stat makes to libuv's pool. Evaluated as a script, so the\n * package ships no file of its own for it. `throwIfNoEntry: false` answers `undefined` for a path that isn't there,\n * as Node also does for one under a file. Reads as {@link statLocal} does\n */\nconst statWorkerSource = `\nconst { statSync } = require('node:fs');\nconst { parentPort } = require('node:worker_threads');\nparentPort.on('message', paths => {\n\tparentPort.postMessage(\n\t\tpaths.map(path => {\n\t\t\ttry {\n\t\t\t\tconst stat = statSync(path, { throwIfNoEntry: false });\n\t\t\t\treturn stat == null ? 'missing' : { mtime: stat.mtimeMs, size: stat.size };\n\t\t\t} catch (ex) {\n\t\t\t\treturn ex != null && (ex.code === 'ENOENT' || ex.code === 'ENOTDIR') ? 'missing' : 'unreadable';\n\t\t\t}\n\t\t}),\n\t);\n});\n`;\n\n/** How long a worker beyond the first stays idle before it's stopped */\nconst defaultIdleTimeoutMs = 30_000;\n/** What `maxWorkers` reads as when it isn't a number, as `UnwatchedCacheValidatorOptions.maxFsThreads` does */\nconst defaultMaxWorkers = 2;\n/** Workers at most, whatever `maxWorkers` asks for: a batch serves as well on the calling thread past it */\nconst maxPoolWorkers = 4;\n\n/**\n * `path`'s modification time (ms since the epoch) and size, read from the local file system; `undefined` when it isn't\n * there, or is under a path that is a file. Rejects when the stat failed otherwise\n */\nexport async function statLocal(path: string): Promise<{ mtime: number; size: number } | undefined> {\n\ttry {\n\t\tconst s = await stat(path);\n\t\treturn { mtime: s.mtimeMs, size: s.size };\n\t} catch (ex) {\n\t\tif (isNotFound(ex) || (ex as { code?: unknown } | undefined)?.code === 'ENOTDIR') return undefined;\n\n\t\tthrow ex;\n\t}\n}\n\ninterface PooledWorker {\n\treadonly worker: Worker;\n\t/** Whether it's running (its `online` event fired); only then is it handed a batch */\n\tonline: boolean;\n\t/** What settles the batch in flight; `undefined` while idle */\n\tbatch:\n\t\t| { readonly resolve: (readings: readonly BatchedStat[]) => void; readonly reject: (ex: Error) => void }\n\t\t| undefined;\n\tidleTimer: ReturnType<typeof setTimeout> | undefined;\n}\n\nexport interface StatWorkerPoolOptions {\n\t/**\n\t * Workers at most, each serving one batch at a time, hung and starting ones included; at most 4, and read as\n\t * `UnwatchedCacheValidatorOptions.maxFsThreads` is (2 when it isn't a number, at least 1)\n\t */\n\treadonly maxWorkers: number;\n\t/** How long a worker beyond the first stays idle before it's stopped. Default: 30 seconds */\n\treadonly idleTimeoutMs?: number;\n}\n\n/**\n * Worker threads that stat many paths as one call (see `UnwatchedCacheValidatorOptions.statMany`). A batch takes an\n * idle running worker. When none is free, the batch is served on the calling thread, one asynchronous stat at a time,\n * and, while fewer than `maxWorkers` run and none is starting, a worker is started in the background for the batches\n * after it, so no read waits for a worker to start. A worker whose batch never returns (a hung mount) stays busy and\n * is never handed another; one that fails or exits rejects its batch and leaves the pool, and one that does so without a\n * batch rejects the next one. A busy worker keeps the process alive, as a pending file-system call does; an idle or\n * starting one doesn't. One idle worker is kept; the others are stopped once idle for `idleTimeoutMs`.\n */\nexport class StatWorkerPool {\n\tprivate readonly workers = new Set<PooledWorker>();\n\tprivate readonly maxWorkers: number;\n\tprivate readonly idleTimeoutMs: number;\n\t/** Why the last worker to fail without a batch failed, until a batch is rejected with it */\n\tprivate idleFailure: Error | undefined;\n\tprivate disposed = false;\n\n\tconstructor(options: StatWorkerPoolOptions) {\n\t\tconst maxWorkers = Math.floor(options.maxWorkers);\n\t\tthis.maxWorkers = Math.min(\n\t\t\tNumber.isNaN(maxWorkers) ? defaultMaxWorkers : Math.max(1, maxWorkers),\n\t\t\tmaxPoolWorkers,\n\t\t);\n\t\tthis.idleTimeoutMs = options.idleTimeoutMs ?? defaultIdleTimeoutMs;\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tfor (const pooled of [...this.workers]) {\n\t\t\tthis.drop(pooled, new Error('The stat worker pool was disposed'));\n\t\t}\n\t}\n\n\t/** One reading per path, in order; rejects when a worker failed the batch, or once disposed. Never throws */\n\tstatMany(paths: readonly string[]): Promise<readonly BatchedStat[]> {\n\t\tif (this.disposed) return Promise.reject(new Error('The stat worker pool was disposed'));\n\n\t\t// Rejected rather than served on the calling thread, so a worker that can't run isn't started again for each batch\n\t\tif (this.idleFailure != null) {\n\t\t\tconst failure = this.idleFailure;\n\t\t\tthis.idleFailure = undefined;\n\t\t\treturn Promise.reject(failure);\n\t\t}\n\n\t\tlet pooled: PooledWorker | undefined;\n\t\tlet starting = false;\n\t\tfor (const candidate of this.workers) {\n\t\t\tif (!candidate.online) {\n\t\t\t\tstarting = true;\n\t\t\t} else if (candidate.batch == null) {\n\t\t\t\tpooled = candidate;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (pooled == null) {\n\t\t\tif (!starting && this.workers.size < this.maxWorkers) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.spawn();\n\t\t\t\t} catch (ex) {\n\t\t\t\t\treturn Promise.reject(ex instanceof Error ? ex : new Error(String(ex)));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn statOnCallingThread(paths);\n\t\t}\n\n\t\tconst worker = pooled;\n\t\treturn new Promise<readonly BatchedStat[]>((resolve, reject) => {\n\t\t\tif (worker.idleTimer != null) {\n\t\t\t\tclearTimeout(worker.idleTimer);\n\t\t\t\tworker.idleTimer = undefined;\n\t\t\t}\n\t\t\t// Claimed before anything is awaited, so a call meanwhile takes another worker\n\t\t\tworker.batch = { resolve: resolve, reject: reject };\n\t\t\tworker.worker.ref();\n\t\t\ttry {\n\t\t\t\tworker.worker.postMessage(paths);\n\t\t\t} catch (ex) {\n\t\t\t\tthis.drop(worker, ex instanceof Error ? ex : new Error(String(ex)));\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Starts a worker that answers each batch of paths it's sent with one {@link BatchedStat} per path, in order */\n\tprotected createWorker(): Worker {\n\t\t// No `execArgv` of the host's (a loader, an inspector), which only slows a worker down that needs none of it\n\t\treturn new Worker(statWorkerSource, { eval: true, execArgv: [] });\n\t}\n\n\tprivate spawn(): void {\n\t\tconst worker = this.createWorker();\n\t\tconst pooled: PooledWorker = { worker: worker, online: false, batch: undefined, idleTimer: undefined };\n\t\tthis.workers.add(pooled);\n\t\tworker.unref();\n\n\t\tworker.on('online', () => {\n\t\t\tif (!this.workers.has(pooled)) return;\n\n\t\t\tpooled.online = true;\n\t\t\tthis.startIdleTimer(pooled);\n\t\t});\n\t\tworker.on('message', (readings: readonly BatchedStat[]) => {\n\t\t\tconst batch = pooled.batch;\n\t\t\tif (batch == null) return;\n\n\t\t\tpooled.batch = undefined;\n\t\t\tworker.unref();\n\t\t\tthis.startIdleTimer(pooled);\n\t\t\tbatch.resolve(readings);\n\t\t});\n\t\tconst fail = (reason: Error): void => {\n\t\t\tif (pooled.batch == null && this.workers.has(pooled)) {\n\t\t\t\tthis.idleFailure = reason;\n\t\t\t}\n\t\t\tthis.drop(pooled, reason);\n\t\t};\n\t\tworker.on('messageerror', fail);\n\t\tworker.on('error', fail);\n\t\tworker.on('exit', code => fail(new Error(`The stat worker exited with code ${code}`)));\n\t}\n\n\t/** Stops an idle worker once it stayed idle for {@link idleTimeoutMs}, unless it's the only idle one */\n\tprivate startIdleTimer(pooled: PooledWorker): void {\n\t\tconst timer = setTimeout(() => {\n\t\t\tpooled.idleTimer = undefined;\n\t\t\tif (pooled.batch != null) return;\n\n\t\t\tlet idle = 0;\n\t\t\tfor (const candidate of this.workers) {\n\t\t\t\tif (candidate.online && candidate.batch == null) {\n\t\t\t\t\tidle++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (idle > 1) {\n\t\t\t\tthis.drop(pooled, new Error('The stat worker was idle'));\n\t\t\t}\n\t\t}, this.idleTimeoutMs);\n\t\ttimer.unref();\n\t\tpooled.idleTimer = timer;\n\t}\n\n\t/** Takes `pooled` out of the pool and stops it, rejecting its batch in flight with `reason` */\n\tprivate drop(pooled: PooledWorker, reason: Error): void {\n\t\tif (!this.workers.delete(pooled)) return;\n\n\t\tif (pooled.idleTimer != null) {\n\t\t\tclearTimeout(pooled.idleTimer);\n\t\t\tpooled.idleTimer = undefined;\n\t\t}\n\t\tconst batch = pooled.batch;\n\t\tpooled.batch = undefined;\n\t\tbatch?.reject(reason);\n\t\tvoid pooled.worker.terminate().catch(() => {});\n\t}\n}\n\n/**\n * Reads each path with {@link statLocal}, one at a time, so the batch holds one of Node's file-system threads at a\n * time, as the gate it went through counts it\n */\nasync function statOnCallingThread(paths: readonly string[]): Promise<readonly BatchedStat[]> {\n\tconst readings: BatchedStat[] = [];\n\tfor (const path of paths) {\n\t\ttry {\n\t\t\treadings.push((await statLocal(path)) ?? 'missing');\n\t\t} catch {\n\t\t\treadings.push('unreadable');\n\t\t}\n\t}\n\treturn readings;\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAM,mBAAmB;;;;;;;;;;;;;;;;;AAkBzB,MAAM,uBAAuB;;AAE7B,MAAM,oBAAoB;;AAE1B,MAAM,iBAAiB;;;;;AAMvB,eAAsB,UAAU,MAAoE;CACnG,IAAI;EACH,MAAM,IAAI,MAAM,KAAK,IAAI;EACzB,OAAO;GAAE,OAAO,EAAE;GAAS,MAAM,EAAE;EAAK;CACzC,SAAS,IAAI;EACZ,IAAI,WAAW,EAAE,KAAM,IAAuC,SAAS,WAAW,OAAO,KAAA;EAEzF,MAAM;CACP;AACD;;;;;;;;;;AAgCA,IAAa,iBAAb,MAA4B;CAC3B,0BAA2B,IAAI,IAAkB;CACjD;CACA;;CAEA;CACA,WAAmB;CAEnB,YAAY,SAAgC;EAC3C,MAAM,aAAa,KAAK,MAAM,QAAQ,UAAU;EAChD,KAAK,aAAa,KAAK,IACtB,OAAO,MAAM,UAAU,IAAI,oBAAoB,KAAK,IAAI,GAAG,UAAU,GACrE,cACD;EACA,KAAK,gBAAgB,QAAQ,iBAAiB;CAC/C;CAEA,UAAgB;EACf,KAAK,WAAW;EAChB,KAAK,MAAM,UAAU,CAAC,GAAG,KAAK,OAAO,GACpC,KAAK,KAAK,wBAAQ,IAAI,MAAM,mCAAmC,CAAC;CAElE;;CAGA,SAAS,OAA2D;EACnE,IAAI,KAAK,UAAU,OAAO,QAAQ,uBAAO,IAAI,MAAM,mCAAmC,CAAC;EAGvF,IAAI,KAAK,eAAe,MAAM;GAC7B,MAAM,UAAU,KAAK;GACrB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D,QAAQ;EACP,SAAS,KAAK,YAAY;CAC3B;CAED,OAAO;AACR"}
@@ -56,10 +56,13 @@ export interface CliGitServiceOptions {
56
56
  * submodule, `--separate-git-dir`, `core.worktree`) isn't validated until a read resolves it, its files looked at
57
57
  * again every 30 seconds. What moves in a worktree under an {@link ignoredWorktreeFolders} folder clears nothing. Without a
58
58
  * {@link watchingProvider}, every repository counts as unwatched. A read waits at most `timeoutMs` (default 1000)
59
- * for the stats, then is served from the cache, and the stats run one at a time per repository and two at once
60
- * overall. A stat on a hung mount holds one of Node's file-system threads until it returns; one outstanding past
61
- * `timeoutMs` lets other repositories' stats go on, as long as the stats hold all but two of the threads
62
- * (`UV_THREADPOOL_SIZE`, default 4), which leaves the host two. Off by default.
59
+ * for the stats, then is served from the cache. Its stats, listings and file reads are made straight on the local
60
+ * file system rather than through `context.fs`, and the stats a repository's git dirs need together as one batch
61
+ * on a worker thread (on the calling thread while no worker is free). The calls run one at a time per repository
62
+ * and two at once overall. A call on a hung mount holds its thread (a worker's, or one of Node's file-system
63
+ * threads) until it returns; one outstanding past `timeoutMs` lets other repositories' calls go on, as long as the
64
+ * calls hold no more threads than Node's file-system pool has less two (`UV_THREADPOOL_SIZE`, default 4), which
65
+ * leaves the host two. Off by default.
63
66
  */
64
67
  validateUnwatchedCaches?: boolean | {
65
68
  readonly timeoutMs?: number;
@@ -1,10 +1,13 @@
1
1
  import { fileUri } from "../utils/uri.js";
2
+ import { FileType } from "../git/context.js";
2
3
  import { isNotFound } from "../git/watching/watchGroup.js";
3
4
  import { GitService } from "../git/service.js";
4
5
  import { CliGitProvider } from "./cliGitProvider.js";
5
6
  import { UnwatchedCacheValidator } from "../git/watching/unwatchedCacheValidator.js";
6
7
  import { findGitPath } from "./exec/locator.js";
8
+ import { StatWorkerPool, statLocal } from "./exec/statWorkers.js";
7
9
  import { env } from "node:process";
10
+ import { readFile, readdir } from "node:fs/promises";
8
11
  //#region ../git-cli/src/service.ts
9
12
  /**
10
13
  * Creates a ready-to-use {@link GitService} backed by the CLI git provider.
@@ -41,11 +44,14 @@ import { env } from "node:process";
41
44
  * ```
42
45
  */
43
46
  function createCliGitService(options) {
47
+ const maxFsThreads = getThreadPoolSize() - 2;
48
+ const statWorkers = options.validateUnwatchedCaches ? new StatWorkerPool({ maxWorkers: maxFsThreads }) : void 0;
44
49
  const service = GitService.createSingleton(options.watchingProvider, {
45
50
  watchPolling: options.watchPolling,
46
51
  verifyBaseRemeasure: options.verifyBaseRemeasure,
47
52
  readFile: (path) => options.context.fs.readFile(fileUri(path)),
48
- readDirectory: (path) => options.context.fs.readDirectory(fileUri(path))
53
+ readDirectory: (path) => options.context.fs.readDirectory(fileUri(path)),
54
+ disposables: statWorkers != null ? [statWorkers] : void 0
49
55
  });
50
56
  const locator = options.locator ?? (() => findGitPath(options.gitPath ?? null));
51
57
  const provider = new CliGitProvider({
@@ -57,28 +63,19 @@ function createCliGitService(options) {
57
63
  refreshIndexAfterWrites: options.refreshIndexAfterWrites
58
64
  });
59
65
  service.register(provider, () => true);
60
- if (options.validateUnwatchedCaches) {
61
- const fs = options.context.fs;
66
+ if (statWorkers != null) {
62
67
  const validator = new UnwatchedCacheValidator({
63
68
  cache: provider.cache,
64
69
  timeoutMs: typeof options.validateUnwatchedCaches === "object" ? options.validateUnwatchedCaches.timeoutMs : void 0,
65
- maxFsThreads: getThreadPoolSize() - 2,
66
- stat: async (path) => {
67
- try {
68
- const stat = await fs.stat(fileUri(path));
69
- return stat != null ? {
70
- mtime: stat.mtime,
71
- size: stat.size
72
- } : void 0;
73
- } catch (ex) {
74
- if (isNotFound(ex)) return void 0;
75
- throw ex;
76
- }
70
+ maxFsThreads,
71
+ statMany: (paths) => statWorkers.statMany(paths),
72
+ stat: statLocal,
73
+ readDirectory: async (path) => {
74
+ return (await readdir(path, { withFileTypes: true })).map((e) => [e.name, (e.isDirectory() ? FileType.Directory : FileType.File) | (e.isSymbolicLink() ? FileType.SymbolicLink : 0)]);
77
75
  },
78
- readDirectory: (path) => fs.readDirectory(fileUri(path)),
79
76
  readFile: async (path) => {
80
77
  try {
81
- return await fs.readFile(fileUri(path));
78
+ return await readFile(path);
82
79
  } catch (ex) {
83
80
  if (isNotFound(ex)) return void 0;
84
81
  throw ex;
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","names":[],"sources":["../../../git-cli/src/service.ts"],"sourcesContent":["import { env } from 'node:process';\nimport { GitService } from '@gitlens/git/service.js';\nimport type { FileWatchingProvider } from '@gitlens/git/watching/provider.js';\nimport { UnwatchedCacheValidator } from '@gitlens/git/watching/unwatchedCacheValidator.js';\nimport { isNotFound } from '@gitlens/git/watching/watchGroup.js';\nimport type { WatchPollingOptions } from '@gitlens/git/watching/watchService.js';\nimport type { WorktreeSummaryServiceOptions } from '@gitlens/git/watching/worktreeSummary.js';\nimport { fileUri } from '@gitlens/utils/uri.js';\nimport type { CliGitProviderOptions } from './cliGitProvider.js';\nimport { CliGitProvider } from './cliGitProvider.js';\nimport type { GitLocation } from './exec/locator.js';\nimport { findGitPath } from './exec/locator.js';\n\n/**\n * Options for {@link createCliGitService}.\n */\nexport interface CliGitServiceOptions {\n\t/**\n\t * Path(s) to the git binary.\n\t * Auto-detected if omitted (searches PATH, platform-specific locations).\n\t * Ignored when {@link locator} is provided.\n\t */\n\tgitPath?: string | string[];\n\n\t/**\n\t * Custom git binary resolver. When provided, used instead of the\n\t * default `findGitPath(gitPath)` lookup.\n\t */\n\tlocator?: () => Promise<GitLocation>;\n\n\t/** Host-provided context hooks (cache events, workspace, integrations, telemetry, fs) */\n\tcontext: CliGitProviderOptions['context'];\n\n\t/**\n\t * Git execution options passed through to the underlying Git executor. `gitOptions.isTrusted(repoPath)` is the\n\t * per-repository trust gate: a `false` answer rejects git runs in that path with `WorkspaceUntrustedError` before\n\t * any process starts. It applies only when `context.workspace.isTrusted` is unset; that flag wins when present.\n\t */\n\tgitOptions?: CliGitProviderOptions['gitOptions'];\n\n\t/** Use an existing Cache instance, or one will be created */\n\tcache?: CliGitProviderOptions['cache'];\n\n\t/** Folders, relative to a repository's common git dir, whose worktrees core acts as if didn't exist */\n\tignoredWorktreeFolders?: CliGitProviderOptions['ignoredWorktreeFolders'];\n\n\t/** Refreshes a checkout's index after core's own writes rewrote it (see `CliGitProviderOptions`); off by default */\n\trefreshIndexAfterWrites?: CliGitProviderOptions['refreshIndexAfterWrites'];\n\n\t/**\n\t * Filesystem watching provider. When provided, the {@link GitService}\n\t * will watch repositories for changes (file creates, edits, deletes).\n\t */\n\twatchingProvider?: FileWatchingProvider;\n\n\t/**\n\t * Polls in place of (or beside) the watchers {@link watchingProvider} reports it can't trust. When omitted, no\n\t * watcher is asked.\n\t */\n\twatchPolling?: WatchPollingOptions;\n\n\t/**\n\t * Keeps the caches that never expire (branches, current branch, refs, tags, remotes, worktrees, stashes, gk config,\n\t * paused operation, and what derives from them) fresh for repositories whose `.git` directory nothing watches:\n\t * before such a read, stats the files a watcher would have reported, and lists the ref directories and worktree\n\t * admin entries, applying what moved as a watcher event would. Files git writes by rename are read only once the\n\t * directory they're in moved, so a read of an idle repository costs a stat per git dir, per ref directory, per\n\t * linked worktree and per file git writes in place, at most once per 250ms per repository; a watched one costs\n\t * nothing, unless its watch is suspended, which holds what it hears until it resumes. Never runs git: a repository\n\t * whose git dir nothing resolved yet is read from its own files, and one whose files can't show it (bare, a\n\t * submodule, `--separate-git-dir`, `core.worktree`) isn't validated until a read resolves it, its files looked at\n\t * again every 30 seconds. What moves in a worktree under an {@link ignoredWorktreeFolders} folder clears nothing. Without a\n\t * {@link watchingProvider}, every repository counts as unwatched. A read waits at most `timeoutMs` (default 1000)\n\t * for the stats, then is served from the cache, and the stats run one at a time per repository and two at once\n\t * overall. A stat on a hung mount holds one of Node's file-system threads until it returns; one outstanding past\n\t * `timeoutMs` lets other repositories' stats go on, as long as the stats hold all but two of the threads\n\t * (`UV_THREADPOOL_SIZE`, default 4), which leaves the host two. Off by default.\n\t */\n\tvalidateUnwatchedCaches?: boolean | { readonly timeoutMs?: number };\n\n\t/** For tests only; production never passes it (see `WorktreeSummaryServiceOptions.verifyBaseRemeasure`) */\n\tverifyBaseRemeasure?: WorktreeSummaryServiceOptions['verifyBaseRemeasure'];\n}\n\n/**\n * Creates a ready-to-use {@link GitService} backed by the CLI git provider.\n *\n * This is the primary entry point for standalone (non-VS Code) consumers\n * of the `@gitlens/git-cli` library. It creates a singleton {@link GitService},\n * wires up a {@link CliGitProvider}, and registers it for all repository paths.\n *\n * @example\n * ```typescript\n * const git = createCliGitService({ context: {} });\n *\n * const repo = git.forRepo('/path/to/repo')!;\n * const branches = await repo.branches.getBranches();\n * const status = await repo.status.getStatus();\n * await repo.ops!.fetch({ remote: 'origin' });\n *\n * git.dispose(); // cleans up provider, cache, and module-level state\n * ```\n *\n * The cache shares a repository's data between its checkouts only once each checkout is registered\n * (`cache.registerRepoPath`). A host that registers checkouts in the background can have each one registered before\n * its first read through `forRepo` by setting a registrar once it has the service (see\n * `Cache.setRepoPathRegistrar`; `undefined` declines a path):\n *\n * ```typescript\n * cache.setRepoPathRegistrar(path =>\n * \tisKnownCheckout(path)\n * \t\t? git.forRepo(path)!.config.getGitDir!().then(gitDir => {\n * \t\t\t\tif (gitDir != null) cache.registerRepoPath(fileUri(path), gitDir);\n * \t\t\t})\n * \t\t: undefined,\n * );\n * ```\n */\nexport function createCliGitService(options: CliGitServiceOptions): GitService {\n\tconst service = GitService.createSingleton(options.watchingProvider, {\n\t\twatchPolling: options.watchPolling,\n\t\tverifyBaseRemeasure: options.verifyBaseRemeasure,\n\t\t// The host's file system reads the shared `.git/config` the watch service compares reports of\n\t\treadFile: path => options.context.fs.readFile(fileUri(path)),\n\t\t// And lists the directory the admin entries of its worktrees are in\n\t\treadDirectory: path => options.context.fs.readDirectory(fileUri(path)),\n\t});\n\n\tconst locator = options.locator ?? (() => findGitPath(options.gitPath ?? null));\n\tconst provider = new CliGitProvider({\n\t\tcontext: options.context,\n\t\tlocator: locator,\n\t\tgitOptions: options.gitOptions,\n\t\tcache: options.cache,\n\t\tignoredWorktreeFolders: options.ignoredWorktreeFolders,\n\t\trefreshIndexAfterWrites: options.refreshIndexAfterWrites,\n\t});\n\n\tservice.register(provider, () => true);\n\n\tif (options.validateUnwatchedCaches) {\n\t\tconst fs = options.context.fs;\n\t\tconst validator = new UnwatchedCacheValidator({\n\t\t\tcache: provider.cache,\n\t\t\ttimeoutMs:\n\t\t\t\ttypeof options.validateUnwatchedCaches === 'object'\n\t\t\t\t\t? options.validateUnwatchedCaches.timeoutMs\n\t\t\t\t\t: undefined,\n\t\t\tmaxFsThreads: getThreadPoolSize() - 2,\n\t\t\tstat: async path => {\n\t\t\t\ttry {\n\t\t\t\t\tconst stat = await fs.stat(fileUri(path));\n\t\t\t\t\treturn stat != null ? { mtime: stat.mtime, size: stat.size } : undefined;\n\t\t\t\t} catch (ex) {\n\t\t\t\t\tif (isNotFound(ex)) return undefined;\n\n\t\t\t\t\tthrow ex;\n\t\t\t\t}\n\t\t\t},\n\t\t\treadDirectory: path => fs.readDirectory(fileUri(path)),\n\t\t\treadFile: async path => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await fs.readFile(fileUri(path));\n\t\t\t\t} catch (ex) {\n\t\t\t\t\tif (isNotFound(ex)) return undefined;\n\n\t\t\t\t\tthrow ex;\n\t\t\t\t}\n\t\t\t},\n\t\t\t// Only for a path whose git dir is cached, which it finds the common git dir from without running git\n\t\t\tgetIgnoredWorktreeRoots: repoPath =>\n\t\t\t\tprovider.cache.gitDir.get(repoPath) != null\n\t\t\t\t\t? provider.getIgnoredWorktreeRoots(repoPath)\n\t\t\t\t\t: Promise.resolve([]),\n\t\t\tresolveGitDir: repoPath => provider.config.resolveGitDirWithoutGit(repoPath),\n\t\t\t// The watch service keys repositories as the cache does (`getRepositoryKey` normalizes a file path alike)\n\t\t\tisWatched: repoPath => service.watchService?.isRepoWatched(repoPath) ?? false,\n\t\t});\n\t\tprovider.cache.setReadValidator(\n\t\t\trepoPath => validator.validate(repoPath),\n\t\t\t() => validator.getResourceUsage(),\n\t\t);\n\t\tservice.watchService?.onDidChangeRepoWatched(e => {\n\t\t\tif (e.watched) {\n\t\t\t\tvalidator.onWatched(e.repoPath);\n\t\t\t} else {\n\t\t\t\tvalidator.onUnwatched(e.repoPath);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Advance the provider cache's status generation clock from the watch session's global events — the standalone\n\t// analogue of what the VS Code host wires in `GitProviderService`. Without this, a consumer that passes a\n\t// `watchingProvider` and drives watch sessions gets FS events but a FROZEN clock, so `dedupeByStatusGeneration`\n\t// degrades to the pre-change/post-change stale-join this branch exists to fix. Standalone has no `Repository`\n\t// models, so there are no force-fired `closed`/`lastFetched` bypassing the session for the global repo event to\n\t// miss. Subscriptions are torn down with the service (its `watchService`'s emitters are disposed on dispose).\n\tservice.watchService?.onDidChangeWorkingTree(repoPath => provider.cache.onWorkingTreeChanged(repoPath));\n\t// Announced kinds were evicted when core announced its write; evicting them again would discard what the host\n\t// re-read since\n\tservice.watchService?.onDidChangeRepository(e => {\n\t\tconst changes = e.getUnannouncedChanges();\n\t\tif (changes.length) {\n\t\t\tprovider.cache.onRepositoryChanged(e.repoPath, changes, {\n\t\t\t\tmovedWorktrees: e.movedWorktrees,\n\t\t\t\tobservedAt: e.observedAt,\n\t\t\t});\n\t\t}\n\t});\n\t// FETCH_HEAD maps to no session change, and there's no `Repository` model here to force-fire `lastFetched` (as\n\t// the VS Code host does), so bridge it straight to the cache or the last-fetched time is never re-read.\n\tservice.watchService?.onDidChangeFetchHead(repoPath =>\n\t\tprovider.cache.onRepositoryChanged(repoPath, ['lastFetched']),\n\t);\n\treturn service;\n}\n\n/** The size of libuv's thread pool, which runs Node's file-system calls, as libuv reads it at its first use */\nfunction getThreadPoolSize(): number {\n\tconst size = Number.parseInt(env.UV_THREADPOOL_SIZE ?? '', 10);\n\treturn Number.isNaN(size) ? 4 : Math.min(Math.max(size, 1), 1024);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAQ,KAAK,OACpC,SAAS,wBAAwB,QAAQ,IACzC,QAAQ,QAAQ,CAAC,CAAC;GACtB,gBAAe,aAAY,SAAS,OAAO,wBAAwB,QAAQ;GAE3E,YAAW,aAAY,QAAQ,cAAc,cAAc,QAAQ,KAAK;EACzE,CAAC;EACD,SAAS,MAAM,kBACd,aAAY,UAAU,SAAS,QAAQ,SACjC,UAAU,iBAAiB,CAClC;EACA,QAAQ,cAAc,wBAAuB,MAAK;GACjD,IAAI,EAAE,SACL,UAAU,UAAU,EAAE,QAAQ;QAE9B,UAAU,YAAY,EAAE,QAAQ;EAElC,CAAC;CACF;CAQA,QAAQ,cAAc,wBAAuB,aAAY,SAAS,MAAM,qBAAqB,QAAQ,CAAC;CAGtG,QAAQ,cAAc,uBAAsB,MAAK;EAChD,MAAM,UAAU,EAAE,sBAAsB;EACxC,IAAI,QAAQ,QACX,SAAS,MAAM,oBAAoB,EAAE,UAAU,SAAS;GACvD,gBAAgB,EAAE;GAClB,YAAY,EAAE;EACf,CAAC;CAEH,CAAC;CAGD,QAAQ,cAAc,sBAAqB,aAC1C,SAAS,MAAM,oBAAoB,UAAU,CAAC,aAAa,CAAC,CAC7D;CACA,OAAO;AACR;;AAGA,SAAS,oBAA4B;CACpC,MAAM,OAAO,OAAO,SAAS,IAAI,sBAAsB,IAAI,EAAE;CAC7D,OAAO,OAAO,MAAM,IAAI,IAAI,IAAI,KAAK,IAAI,KAAK,IAAI,MAAM,CAAC,GAAG,IAAI;AACjE"}
1
+ {"version":3,"file":"service.js","names":[],"sources":["../../../git-cli/src/service.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport { env } from 'node:process';\nimport { FileType } from '@gitlens/git/context.js';\nimport { GitService } from '@gitlens/git/service.js';\nimport type { FileWatchingProvider } from '@gitlens/git/watching/provider.js';\nimport { UnwatchedCacheValidator } from '@gitlens/git/watching/unwatchedCacheValidator.js';\nimport { isNotFound } from '@gitlens/git/watching/watchGroup.js';\nimport type { WatchPollingOptions } from '@gitlens/git/watching/watchService.js';\nimport type { WorktreeSummaryServiceOptions } from '@gitlens/git/watching/worktreeSummary.js';\nimport { fileUri } from '@gitlens/utils/uri.js';\nimport type { CliGitProviderOptions } from './cliGitProvider.js';\nimport { CliGitProvider } from './cliGitProvider.js';\nimport type { GitLocation } from './exec/locator.js';\nimport { findGitPath } from './exec/locator.js';\nimport { statLocal, StatWorkerPool } from './exec/statWorkers.js';\n\n/**\n * Options for {@link createCliGitService}.\n */\nexport interface CliGitServiceOptions {\n\t/**\n\t * Path(s) to the git binary.\n\t * Auto-detected if omitted (searches PATH, platform-specific locations).\n\t * Ignored when {@link locator} is provided.\n\t */\n\tgitPath?: string | string[];\n\n\t/**\n\t * Custom git binary resolver. When provided, used instead of the\n\t * default `findGitPath(gitPath)` lookup.\n\t */\n\tlocator?: () => Promise<GitLocation>;\n\n\t/** Host-provided context hooks (cache events, workspace, integrations, telemetry, fs) */\n\tcontext: CliGitProviderOptions['context'];\n\n\t/**\n\t * Git execution options passed through to the underlying Git executor. `gitOptions.isTrusted(repoPath)` is the\n\t * per-repository trust gate: a `false` answer rejects git runs in that path with `WorkspaceUntrustedError` before\n\t * any process starts. It applies only when `context.workspace.isTrusted` is unset; that flag wins when present.\n\t */\n\tgitOptions?: CliGitProviderOptions['gitOptions'];\n\n\t/** Use an existing Cache instance, or one will be created */\n\tcache?: CliGitProviderOptions['cache'];\n\n\t/** Folders, relative to a repository's common git dir, whose worktrees core acts as if didn't exist */\n\tignoredWorktreeFolders?: CliGitProviderOptions['ignoredWorktreeFolders'];\n\n\t/** Refreshes a checkout's index after core's own writes rewrote it (see `CliGitProviderOptions`); off by default */\n\trefreshIndexAfterWrites?: CliGitProviderOptions['refreshIndexAfterWrites'];\n\n\t/**\n\t * Filesystem watching provider. When provided, the {@link GitService}\n\t * will watch repositories for changes (file creates, edits, deletes).\n\t */\n\twatchingProvider?: FileWatchingProvider;\n\n\t/**\n\t * Polls in place of (or beside) the watchers {@link watchingProvider} reports it can't trust. When omitted, no\n\t * watcher is asked.\n\t */\n\twatchPolling?: WatchPollingOptions;\n\n\t/**\n\t * Keeps the caches that never expire (branches, current branch, refs, tags, remotes, worktrees, stashes, gk config,\n\t * paused operation, and what derives from them) fresh for repositories whose `.git` directory nothing watches:\n\t * before such a read, stats the files a watcher would have reported, and lists the ref directories and worktree\n\t * admin entries, applying what moved as a watcher event would. Files git writes by rename are read only once the\n\t * directory they're in moved, so a read of an idle repository costs a stat per git dir, per ref directory, per\n\t * linked worktree and per file git writes in place, at most once per 250ms per repository; a watched one costs\n\t * nothing, unless its watch is suspended, which holds what it hears until it resumes. Never runs git: a repository\n\t * whose git dir nothing resolved yet is read from its own files, and one whose files can't show it (bare, a\n\t * submodule, `--separate-git-dir`, `core.worktree`) isn't validated until a read resolves it, its files looked at\n\t * again every 30 seconds. What moves in a worktree under an {@link ignoredWorktreeFolders} folder clears nothing. Without a\n\t * {@link watchingProvider}, every repository counts as unwatched. A read waits at most `timeoutMs` (default 1000)\n\t * for the stats, then is served from the cache. Its stats, listings and file reads are made straight on the local\n\t * file system rather than through `context.fs`, and the stats a repository's git dirs need together as one batch\n\t * on a worker thread (on the calling thread while no worker is free). The calls run one at a time per repository\n\t * and two at once overall. A call on a hung mount holds its thread (a worker's, or one of Node's file-system\n\t * threads) until it returns; one outstanding past `timeoutMs` lets other repositories' calls go on, as long as the\n\t * calls hold no more threads than Node's file-system pool has less two (`UV_THREADPOOL_SIZE`, default 4), which\n\t * leaves the host two. Off by default.\n\t */\n\tvalidateUnwatchedCaches?: boolean | { readonly timeoutMs?: number };\n\n\t/** For tests only; production never passes it (see `WorktreeSummaryServiceOptions.verifyBaseRemeasure`) */\n\tverifyBaseRemeasure?: WorktreeSummaryServiceOptions['verifyBaseRemeasure'];\n}\n\n/**\n * Creates a ready-to-use {@link GitService} backed by the CLI git provider.\n *\n * This is the primary entry point for standalone (non-VS Code) consumers\n * of the `@gitlens/git-cli` library. It creates a singleton {@link GitService},\n * wires up a {@link CliGitProvider}, and registers it for all repository paths.\n *\n * @example\n * ```typescript\n * const git = createCliGitService({ context: {} });\n *\n * const repo = git.forRepo('/path/to/repo')!;\n * const branches = await repo.branches.getBranches();\n * const status = await repo.status.getStatus();\n * await repo.ops!.fetch({ remote: 'origin' });\n *\n * git.dispose(); // cleans up provider, cache, and module-level state\n * ```\n *\n * The cache shares a repository's data between its checkouts only once each checkout is registered\n * (`cache.registerRepoPath`). A host that registers checkouts in the background can have each one registered before\n * its first read through `forRepo` by setting a registrar once it has the service (see\n * `Cache.setRepoPathRegistrar`; `undefined` declines a path):\n *\n * ```typescript\n * cache.setRepoPathRegistrar(path =>\n * \tisKnownCheckout(path)\n * \t\t? git.forRepo(path)!.config.getGitDir!().then(gitDir => {\n * \t\t\t\tif (gitDir != null) cache.registerRepoPath(fileUri(path), gitDir);\n * \t\t\t})\n * \t\t: undefined,\n * );\n * ```\n */\nexport function createCliGitService(options: CliGitServiceOptions): GitService {\n\tconst maxFsThreads = getThreadPoolSize() - 2;\n\tconst statWorkers = options.validateUnwatchedCaches ? new StatWorkerPool({ maxWorkers: maxFsThreads }) : undefined;\n\tconst service = GitService.createSingleton(options.watchingProvider, {\n\t\twatchPolling: options.watchPolling,\n\t\tverifyBaseRemeasure: options.verifyBaseRemeasure,\n\t\t// The host's file system reads the shared `.git/config` the watch service compares reports of\n\t\treadFile: path => options.context.fs.readFile(fileUri(path)),\n\t\t// And lists the directory the admin entries of its worktrees are in\n\t\treadDirectory: path => options.context.fs.readDirectory(fileUri(path)),\n\t\tdisposables: statWorkers != null ? [statWorkers] : undefined,\n\t});\n\n\tconst locator = options.locator ?? (() => findGitPath(options.gitPath ?? null));\n\tconst provider = new CliGitProvider({\n\t\tcontext: options.context,\n\t\tlocator: locator,\n\t\tgitOptions: options.gitOptions,\n\t\tcache: options.cache,\n\t\tignoredWorktreeFolders: options.ignoredWorktreeFolders,\n\t\trefreshIndexAfterWrites: options.refreshIndexAfterWrites,\n\t});\n\n\tservice.register(provider, () => true);\n\n\tif (statWorkers != null) {\n\t\tconst validator = new UnwatchedCacheValidator({\n\t\t\tcache: provider.cache,\n\t\t\ttimeoutMs:\n\t\t\t\ttypeof options.validateUnwatchedCaches === 'object'\n\t\t\t\t\t? options.validateUnwatchedCaches.timeoutMs\n\t\t\t\t\t: undefined,\n\t\t\tmaxFsThreads: maxFsThreads,\n\t\t\t// Straight from the local file system, as git reads these paths: a worker thread can't call the host's\n\t\t\t// `context.fs`, and a path read one way must read the same the other, or a batch that failed (whose paths\n\t\t\t// are read one at a time) would report as moved what only read differently. Listings and file reads too, so\n\t\t\t// the validator reads one file system\n\t\t\tstatMany: paths => statWorkers.statMany(paths),\n\t\t\tstat: statLocal,\n\t\t\treadDirectory: async path => {\n\t\t\t\tconst entries = await readdir(path, { withFileTypes: true });\n\t\t\t\treturn entries.map(\n\t\t\t\t\te =>\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\te.name,\n\t\t\t\t\t\t\t(e.isDirectory() ? FileType.Directory : FileType.File) |\n\t\t\t\t\t\t\t\t(e.isSymbolicLink() ? FileType.SymbolicLink : 0),\n\t\t\t\t\t\t] as const,\n\t\t\t\t);\n\t\t\t},\n\t\t\treadFile: async path => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await readFile(path);\n\t\t\t\t} catch (ex) {\n\t\t\t\t\tif (isNotFound(ex)) return undefined;\n\n\t\t\t\t\tthrow ex;\n\t\t\t\t}\n\t\t\t},\n\t\t\t// Only for a path whose git dir is cached, which it finds the common git dir from without running git\n\t\t\tgetIgnoredWorktreeRoots: repoPath =>\n\t\t\t\tprovider.cache.gitDir.get(repoPath) != null\n\t\t\t\t\t? provider.getIgnoredWorktreeRoots(repoPath)\n\t\t\t\t\t: Promise.resolve([]),\n\t\t\tresolveGitDir: repoPath => provider.config.resolveGitDirWithoutGit(repoPath),\n\t\t\t// The watch service keys repositories as the cache does (`getRepositoryKey` normalizes a file path alike)\n\t\t\tisWatched: repoPath => service.watchService?.isRepoWatched(repoPath) ?? false,\n\t\t});\n\t\tprovider.cache.setReadValidator(\n\t\t\trepoPath => validator.validate(repoPath),\n\t\t\t() => validator.getResourceUsage(),\n\t\t);\n\t\tservice.watchService?.onDidChangeRepoWatched(e => {\n\t\t\tif (e.watched) {\n\t\t\t\tvalidator.onWatched(e.repoPath);\n\t\t\t} else {\n\t\t\t\tvalidator.onUnwatched(e.repoPath);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Advance the provider cache's status generation clock from the watch session's global events — the standalone\n\t// analogue of what the VS Code host wires in `GitProviderService`. Without this, a consumer that passes a\n\t// `watchingProvider` and drives watch sessions gets FS events but a FROZEN clock, so `dedupeByStatusGeneration`\n\t// degrades to the pre-change/post-change stale-join this branch exists to fix. Standalone has no `Repository`\n\t// models, so there are no force-fired `closed`/`lastFetched` bypassing the session for the global repo event to\n\t// miss. Subscriptions are torn down with the service (its `watchService`'s emitters are disposed on dispose).\n\tservice.watchService?.onDidChangeWorkingTree(repoPath => provider.cache.onWorkingTreeChanged(repoPath));\n\t// Announced kinds were evicted when core announced its write; evicting them again would discard what the host\n\t// re-read since\n\tservice.watchService?.onDidChangeRepository(e => {\n\t\tconst changes = e.getUnannouncedChanges();\n\t\tif (changes.length) {\n\t\t\tprovider.cache.onRepositoryChanged(e.repoPath, changes, {\n\t\t\t\tmovedWorktrees: e.movedWorktrees,\n\t\t\t\tobservedAt: e.observedAt,\n\t\t\t});\n\t\t}\n\t});\n\t// FETCH_HEAD maps to no session change, and there's no `Repository` model here to force-fire `lastFetched` (as\n\t// the VS Code host does), so bridge it straight to the cache or the last-fetched time is never re-read.\n\tservice.watchService?.onDidChangeFetchHead(repoPath =>\n\t\tprovider.cache.onRepositoryChanged(repoPath, ['lastFetched']),\n\t);\n\treturn service;\n}\n\n/** The size of libuv's thread pool, which runs Node's file-system calls, as libuv reads it at its first use */\nfunction getThreadPoolSize(): number {\n\tconst size = Number.parseInt(env.UV_THREADPOOL_SIZE ?? '', 10);\n\treturn Number.isNaN(size) ? 4 :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,SAAS,IAAI;KACZ,IAAI,WAAW,EAAE,GAAG,OAAO,KAAA;KAE3B,MAAM;IACP;GACD;GAEA,0BAAyB,aACxB,SAAS,MAAM,OAAO,IAAI,QAAQ,KAAK,OACpC,SAAS,wBAAwB,QAAQ,IACzC,QAAQ,QAAQ,CAAC,CAAC;GACtB,gBAAe,aAAY,SAAS,OAAO,wBAAwB,QAAQ;GAE3E,YAAW,aAAY,QAAQ,cAAc,cAAc,QAAQ,KAAK;EACzE,CAAC;EACD,SAAS,MAAM,kBACd,aAAY,UAAU,SAAS,QAAQ,SACjC,UAAU,iBAAiB,CAClC;EACA,QAAQ,cAAc,wBAAuB,MAAK;GACjD,IAAI,EAAE,SACL,UAAU,UAAU,EAAE,QAAQ;QAE9B,UAAU,YAAY,EAAE,QAAQ;EAElC,CAAC;CACF;CAQA,QAAQ,cAAc,wBAAuB,aAAY,SAAS,MAAM,qBAAqB,QAAQ,CAAC;CAGtG,QAAQ,cAAc,uBAAsB,MAAK;EAChD,MAAM,UAAU,EAAE,sBAAsB;EACxC,IAAI,QAAQ,QACX,SAAS,MAAM,oBAAoB,EAAE,UAAU,SAAS;GACvD,gBAAgB,EAAE;GAClB,YAAY,EAAE;EACf,CAAC;CAEH,CAAC;CAGD,QAAQ,cAAc,sBAAqB,aAC1C,SAAS,MAAM,oBAAoB,UAAU,CAAC,aAAa,CAAC,CAC7D;CACA,OAAO;AACR;;AAGA,SAAS,oBAA4B;CACpC,MAAM,OAAO,OAAO,SAAS,IAAI,sBAAsB,IAAI,EAAE;CAC7D,OAAO,OAAO,MAAM,IAAI,IAAI,IAAI,KAAK,IAAI,KAAK,IAAI,MAAM,CAAC,GAAG,IAAI;AACjE"}
@@ -1,5 +1,4 @@
1
1
  import { IssueSorting } from "../../../git/models/issue.js";
2
- import "../providerFilters.js";
3
2
  //#region ../plus/integrations/src/providers/issueSorts.d.ts
4
3
  /** GitHub and GHE: one `search` channel serves all three issue reads, so all three order the same way. */
5
4
  export declare const githubIssueSorts: IssueSorting[];
@@ -42,15 +42,6 @@ export declare class JiraIntegration extends IssuesIntegration<IssuesCloudHostIn
42
42
  * from it in `_autolinks` (#6176). Cleared with `_projects`, whose generation then refuses those same writes.
43
43
  */
44
44
  private readonly _projectEvictions;
45
- /**
46
- * Moves whenever `_autolinks` is dropped for a list a build reads, so a build that then fails keeps no fallback
47
- * over lists it didn't read; the next render builds from them instead (#6183). Rule: every writer that stores a
48
- * different project list for a site must bump it and retire the token's build, through {@link onProjectListStored};
49
- * the same list stored again does neither while a complete set is kept (#6184). The connect's clear bumps it too.
50
- * Site-list stores deliberately don't: a build's own site store would then refuse its own fallback. Drops and
51
- * evictions need no bump: they fail a build's `isCurrent`.
52
- */
53
- private _autolinksResets;
54
45
  autolinks(): Promise<(AutolinkReference | DynamicAutolinkReference)[]>;
55
46
  /**
56
47
  * One build per token at a time: concurrent renders share it rather than each re-reading sites and projects. A
@@ -59,20 +50,8 @@ export declare class JiraIntegration extends IssuesIntegration<IssuesCloudHostIn
59
50
  */
60
51
  private buildAutolinks;
61
52
  private buildAutolinksCore;
62
- /**
63
- * A site's project list was stored. A different one drops the autolinks built from the lists, so a build that then
64
- * fails keeps no fallback, and retires the build in flight, which may hold the list as it was. The same one again
65
- * keeps a complete set and the build in flight; otherwise it drops the incomplete set kept, if any, so the next
66
- * render builds from the lists again, and still fences a failing build's fallback (#6183, #6184). Other tokens' sets
67
- * and builds stay; only `_autolinksResets`, shared by all tokens, also stops their failing builds' fallback.
68
- *
69
- * A known limit: a build whose own read stores a different list, or a site's first one (with nothing seeded since a
70
- * start, a clear or an eviction, every first store reads as different), retires itself too. A render in the
71
- * microtasks before that build resumes then starts a second one rather than joining it; that one builds from the
72
- * cache, reading again only the sites the first couldn't read whole. A loss of the sharing core had, with no effect
73
- * on what is kept, and none on an identical list, which retires nothing.
74
- */
75
- private onProjectListStored;
53
+ private deriveAutolinks;
54
+ private onDiscoveryStored;
76
55
  protected getProviderAccountForResource(session: ProviderAuthenticationSession, resource: JiraOrganizationDescriptor): Promise<Account | undefined>;
77
56
  /** Atlassian's account id is the same on every site, so the first site answers for all of them. */
78
57
  protected getProviderCurrentAccount(session: ProviderAuthenticationSession): Promise<Account | undefined>;
@@ -90,15 +69,15 @@ export declare class JiraIntegration extends IssuesIntegration<IssuesCloudHostIn
90
69
  */
91
70
  private readonly _organizations;
92
71
  private readonly _projects;
93
- protected getProviderResourcesForUser(session: ProviderAuthenticationSession, force?: boolean): Promise<JiraOrganizationDescriptor[] | undefined>;
72
+ protected getProviderResourcesForUser(session: ProviderAuthenticationSession, force?: boolean, reader?: () => Promise<unknown> | undefined): Promise<JiraOrganizationDescriptor[] | undefined>;
94
73
  protected getProviderUncachedResourcesForUser(session: ProviderAuthenticationSession): Promise<JiraOrganizationDescriptor[] | undefined>;
95
74
  private readOrganizations;
96
75
  protected getProviderProjectsForResources(session: ProviderAuthenticationSession, resources: JiraOrganizationDescriptor[], force?: boolean): Promise<JiraProjectDescriptor[] | undefined>;
97
- protected getProviderProjectsForResourcesWithMetadata(session: ProviderAuthenticationSession, resources: JiraOrganizationDescriptor[], force?: boolean): Promise<ProviderApiCollectionResult<JiraProjectDescriptor>>;
76
+ protected getProviderProjectsForResourcesWithMetadata(session: ProviderAuthenticationSession, resources: JiraOrganizationDescriptor[], force?: boolean, reader?: () => Promise<unknown> | undefined): Promise<ProviderApiCollectionResult<JiraProjectDescriptor>>;
98
77
  protected getProviderUncachedProjectsForResourcesWithMetadata(session: ProviderAuthenticationSession, resources: JiraOrganizationDescriptor[]): Promise<ProviderApiCollectionResult<JiraProjectDescriptor>>;
99
78
  /**
100
79
  * Reads the projects of each resource from the provider, apart by whether a resource's list came back complete:
101
- * only a complete one may be cached as the resource's project set.
80
+ * incomplete lists remain available for decoration but cannot satisfy a fresh discovery read.
102
81
  */
103
82
  private readProjects;
104
83
  protected getProviderIssuesForProject(session: ProviderAuthenticationSession, project: JiraProjectDescriptor, options?: IssuesForProjectOptions): Promise<IssueShape[] | undefined>;