Skip to content

Commit d351a15

Browse files
authored
refactor(code-index): introduce workspace scope behind registry (#1766)
* refactor(code-index): introduce workspace scope behind registry Refs #1594 * test(code-index): cover registry retry after construction failure
1 parent 2225856 commit d351a15

4 files changed

Lines changed: 217 additions & 12 deletions

File tree

‎src/services/code-index/__tests__/code-index-manager-registry.spec.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as vscode from "vscode"
22
import { makeExtensionContext, makeTextDocument, makeTextEditor, makeUri } from "../../../test-utils/vscode"
33
import { CodeIndexManager } from "../manager"
44
import { CodeIndexManagerRegistry } from "../code-index-manager-registry"
5+
import { CodeIndexWorkspaceScope } from "../code-index-workspace-scope"
56

67
vi.mock("vscode", () => ({
78
workspace: { workspaceFolders: undefined, getWorkspaceFolder: vi.fn() },
@@ -107,18 +108,71 @@ describe("CodeIndexManagerRegistry", () => {
107108
expect(CodeIndexManagerRegistry.getAllInstances()).toEqual([a, b])
108109
})
109110

111+
it("does not cache a scope when manager construction fails and permits retry for the same path", () => {
112+
const error = new Error("construction failed")
113+
vi.mocked(CodeIndexManager).mockImplementationOnce(function () {
114+
throw error
115+
})
116+
117+
expect(() => CodeIndexManagerRegistry.getOrCreate(context, "/first")).toThrow(error)
118+
expect(CodeIndexManagerRegistry.getAllInstances()).toEqual([])
119+
120+
const manager = CodeIndexManagerRegistry.getOrCreate(context, "/first")
121+
expect(manager).toBe(vi.mocked(CodeIndexManager).mock.results[1].value)
122+
expect(CodeIndexManagerRegistry.getAllInstances()).toEqual([manager])
123+
expect(CodeIndexManagerRegistry.getOrCreate(context, "/first")).toBe(manager)
124+
expect(CodeIndexManager).toHaveBeenCalledTimes(2)
125+
})
126+
110127
it("returns a snapshot that cannot mutate the cache", () => {
111128
expect(CodeIndexManagerRegistry.getAllInstances()).toEqual([])
112129
const manager = CodeIndexManagerRegistry.getOrCreate(context)
113130
CodeIndexManagerRegistry.getAllInstances().pop()
114131
expect(CodeIndexManagerRegistry.getAllInstances()).toEqual([manager])
115132
})
116133

134+
it("logs each disposal failure, continues cleanup and permits recreation", () => {
135+
const logError = vi.spyOn(console, "error").mockImplementation(() => {})
136+
const first = CodeIndexManagerRegistry.getOrCreate(context, "/first")!
137+
const second = CodeIndexManagerRegistry.getOrCreate(context, "/second")!
138+
const third = CodeIndexManagerRegistry.getOrCreate(context, "/third")!
139+
const error = new Error("cleanup failed")
140+
vi.mocked(first.dispose).mockImplementationOnce(() => {
141+
throw error
142+
})
143+
vi.mocked(second.dispose).mockImplementationOnce(() => {
144+
throw "second cleanup failed"
145+
})
146+
147+
expect(() => CodeIndexManagerRegistry.disposeAll()).not.toThrow()
148+
for (const manager of [first, second, third]) {
149+
expect(manager.dispose).toHaveBeenCalledExactlyOnceWith()
150+
}
151+
expect(logError).toHaveBeenCalledTimes(2)
152+
expect(logError).toHaveBeenNthCalledWith(
153+
1,
154+
"[CodeIndexManagerRegistry] Failed to dispose workspace scope for /first:",
155+
error,
156+
)
157+
expect(logError).toHaveBeenNthCalledWith(
158+
2,
159+
"[CodeIndexManagerRegistry] Failed to dispose workspace scope for /second:",
160+
"second cleanup failed",
161+
)
162+
expect(CodeIndexManagerRegistry.getAllInstances()).toEqual([])
163+
CodeIndexManagerRegistry.disposeAll()
164+
expect(logError).toHaveBeenCalledTimes(2)
165+
expect(first.dispose).toHaveBeenCalledTimes(1)
166+
expect(CodeIndexManagerRegistry.getOrCreate(context, "/first")).not.toBe(first)
167+
})
168+
117169
it("disposes every manager, supports repeated cleanup and recreates instances", () => {
170+
const disposeScope = vi.spyOn(CodeIndexWorkspaceScope.prototype, "dispose")
118171
const a = CodeIndexManagerRegistry.getOrCreate(context, "/first")!
119172
const b = CodeIndexManagerRegistry.getOrCreate(context, "/second")!
120173
CodeIndexManagerRegistry.disposeAll()
121174
CodeIndexManagerRegistry.disposeAll()
175+
expect(disposeScope).toHaveBeenCalledTimes(2)
122176
expect(a.dispose).toHaveBeenCalledTimes(1)
123177
expect(b.dispose).toHaveBeenCalledTimes(1)
124178
expect(CodeIndexManagerRegistry.getAllInstances()).toEqual([])
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import { makeExtensionContext, makeUri } from "../../../test-utils/vscode"
2+
import { CodeIndexManager } from "../manager"
3+
import { CodeIndexWorkspaceScope } from "../code-index-workspace-scope"
4+
5+
vi.mock("../manager", () => ({
6+
CodeIndexManager: vi.fn().mockImplementation(function () {
7+
return { initialize: vi.fn(), dispose: vi.fn() }
8+
}),
9+
}))
10+
11+
describe("CodeIndexWorkspaceScope", () => {
12+
beforeEach(() => vi.clearAllMocks())
13+
14+
it("guards generic values and preserves defined falsy values", () => {
15+
const scope = new CodeIndexWorkspaceScope("/workspace", makeUri("/workspace"), makeExtensionContext())
16+
expect(() => scope["ensureInitialized"](42)).toThrow("Code index workspace scope is not initialized")
17+
scope.init()
18+
expect(() => scope["ensureInitialized"](undefined)).toThrow("Code index workspace scope is not initialized")
19+
expect(scope["ensureInitialized"](false)).toBe(false)
20+
expect(scope["ensureInitialized"](0)).toBe(0)
21+
expect(scope["ensureInitialized"]("")).toBe("")
22+
})
23+
24+
it("creates its manager only on init without starting configuration initialization", () => {
25+
const context = makeExtensionContext()
26+
const uri = makeUri("/workspace")
27+
const scope = new CodeIndexWorkspaceScope(uri.fsPath, uri, context)
28+
29+
expect(CodeIndexManager).not.toHaveBeenCalled()
30+
expect(() => scope.codeIndexManager).toThrow("Code index workspace scope is not initialized")
31+
expect(scope.init()).toBeUndefined()
32+
const manager = scope.codeIndexManager
33+
34+
expect(CodeIndexManager).toHaveBeenCalledExactlyOnceWith(uri.fsPath, uri, context)
35+
expect(scope.codeIndexManager).toBe(manager)
36+
expect(() => scope.init()).toThrow("Code index workspace scope is already initialized")
37+
expect(scope.codeIndexManager).toBe(manager)
38+
expect(CodeIndexManager).toHaveBeenCalledTimes(1)
39+
expect(manager.initialize).not.toHaveBeenCalled()
40+
})
41+
42+
it("synchronously disposes its manager", () => {
43+
const scope = new CodeIndexWorkspaceScope("/workspace", makeUri("/workspace"), makeExtensionContext())
44+
scope.init()
45+
const manager = scope.codeIndexManager
46+
47+
expect(scope.dispose()).toBeUndefined()
48+
expect(() => scope.codeIndexManager).toThrow("Code index workspace scope is not initialized")
49+
scope.dispose()
50+
expect(manager.dispose).toHaveBeenCalledExactlyOnceWith()
51+
})
52+
53+
it("can dispose before dependency creation without constructing a manager", () => {
54+
const scope = new CodeIndexWorkspaceScope("/workspace", makeUri("/workspace"), makeExtensionContext())
55+
scope.dispose()
56+
expect(() => scope.codeIndexManager).toThrow("Code index workspace scope is not initialized")
57+
expect(CodeIndexManager).not.toHaveBeenCalled()
58+
})
59+
60+
it("creates a fresh manager when initialized after disposal", () => {
61+
const scope = new CodeIndexWorkspaceScope("/workspace", makeUri("/workspace"), makeExtensionContext())
62+
scope.init()
63+
const previous = scope.codeIndexManager
64+
scope.dispose()
65+
scope.init()
66+
const current = scope.codeIndexManager
67+
expect(current).not.toBe(previous)
68+
expect(scope.codeIndexManager).toBe(current)
69+
expect(CodeIndexManager).toHaveBeenCalledTimes(2)
70+
expect(current.dispose).not.toHaveBeenCalled()
71+
})
72+
73+
it("clears its reference even when manager disposal throws", () => {
74+
const scope = new CodeIndexWorkspaceScope("/workspace", makeUri("/workspace"), makeExtensionContext())
75+
scope.init()
76+
const manager = scope.codeIndexManager
77+
const error = new Error("disposal failed")
78+
vi.mocked(manager.dispose).mockImplementationOnce(() => {
79+
throw error
80+
})
81+
expect(() => scope.dispose()).toThrow(error)
82+
expect(() => scope.codeIndexManager).toThrow("Code index workspace scope is not initialized")
83+
scope.dispose()
84+
expect(manager.dispose).toHaveBeenCalledTimes(1)
85+
})
86+
87+
it("remains uninitialized when construction fails and permits retry", () => {
88+
const scope = new CodeIndexWorkspaceScope("/workspace", makeUri("/workspace"), makeExtensionContext())
89+
const error = new Error("construction failed")
90+
vi.mocked(CodeIndexManager).mockImplementationOnce(function () {
91+
throw error
92+
})
93+
94+
expect(() => scope.init()).toThrow(error)
95+
expect(() => scope.codeIndexManager).toThrow("Code index workspace scope is not initialized")
96+
expect(scope.init()).toBeUndefined()
97+
expect(scope.codeIndexManager).toBe(vi.mocked(CodeIndexManager).mock.results[1].value)
98+
expect(CodeIndexManager).toHaveBeenCalledTimes(2)
99+
})
100+
})

‎src/services/code-index/code-index-manager-registry.ts‎

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import * as vscode from "vscode"
2-
import { CodeIndexManager } from "./manager"
2+
import type { CodeIndexManager } from "./manager"
3+
import { CodeIndexWorkspaceScope } from "./code-index-workspace-scope"
34

4-
/** Resolves workspaces and owns their cached CodeIndexManager instances. */
5+
/** Owns workspace scopes while preserving the manager-facing API. */
56
export class CodeIndexManagerRegistry {
6-
private static instances = new Map<string, CodeIndexManager>()
7+
private static codeIndexWorkspaceScopes = new Map<string, CodeIndexWorkspaceScope>()
78

89
public static getOrCreate(context: vscode.ExtensionContext, workspacePath?: string): CodeIndexManager | undefined {
910
const folder = this.resolveWorkspaceFolder(workspacePath)
@@ -12,27 +13,35 @@ export class CodeIndexManagerRegistry {
1213
return undefined
1314
}
1415

15-
const existing = this.instances.get(resolvedPath)
16+
const existing = this.codeIndexWorkspaceScopes.get(resolvedPath)
1617
if (existing) {
17-
return existing
18+
return existing.codeIndexManager
1819
}
1920

2021
// Preserve real workspace URIs, including remote schemes and authorities.
2122
const folderUri = folder?.uri ?? vscode.Uri.file(resolvedPath)
22-
const manager = new CodeIndexManager(resolvedPath, folderUri, context)
23-
this.instances.set(resolvedPath, manager)
24-
return manager
23+
const codeIndexWorkspaceScope = new CodeIndexWorkspaceScope(resolvedPath, folderUri, context)
24+
codeIndexWorkspaceScope.init()
25+
this.codeIndexWorkspaceScopes.set(resolvedPath, codeIndexWorkspaceScope)
26+
return codeIndexWorkspaceScope.codeIndexManager
2527
}
2628

2729
public static getAllInstances(): CodeIndexManager[] {
28-
return Array.from(this.instances.values())
30+
return Array.from(this.codeIndexWorkspaceScopes.values(), (scope) => scope.codeIndexManager)
2931
}
3032

3133
public static disposeAll(): void {
32-
for (const instance of this.instances.values()) {
33-
instance.dispose()
34+
for (const [workspacePath, codeIndexWorkspaceScope] of this.codeIndexWorkspaceScopes) {
35+
try {
36+
codeIndexWorkspaceScope.dispose()
37+
} catch (error) {
38+
console.error(
39+
`[CodeIndexManagerRegistry] Failed to dispose workspace scope for ${workspacePath}:`,
40+
error,
41+
)
42+
}
3443
}
35-
this.instances.clear()
44+
this.codeIndexWorkspaceScopes.clear()
3645
}
3746

3847
private static resolveWorkspaceFolder(workspacePath?: string): vscode.WorkspaceFolder | undefined {
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import type * as vscode from "vscode"
2+
3+
import { CodeIndexManager } from "./manager"
4+
5+
/** Owns code-index services for one workspace; initialization remains with existing callers. */
6+
export class CodeIndexWorkspaceScope implements vscode.Disposable {
7+
private _codeIndexManager?: CodeIndexManager
8+
private _isInitialized = false
9+
10+
public constructor(
11+
private readonly workspacePath: string,
12+
private readonly folderUri: vscode.Uri,
13+
private readonly context: vscode.ExtensionContext,
14+
) {}
15+
16+
public get codeIndexManager(): CodeIndexManager {
17+
return this.ensureInitialized(this._codeIndexManager)
18+
}
19+
20+
private ensureInitialized<T>(value: T | undefined): T {
21+
if (!this._isInitialized || value === undefined) {
22+
throw new Error("Code index workspace scope is not initialized")
23+
}
24+
return value
25+
}
26+
27+
/** Creates the manager without loading configuration or starting indexing. */
28+
public init(): void {
29+
if (this._isInitialized) {
30+
throw new Error("Code index workspace scope is already initialized")
31+
}
32+
this._codeIndexManager = new CodeIndexManager(this.workspacePath, this.folderUri, this.context)
33+
this._isInitialized = true
34+
}
35+
36+
public dispose(): void {
37+
const manager = this._codeIndexManager
38+
this._codeIndexManager = undefined
39+
this._isInitialized = false
40+
manager?.dispose()
41+
}
42+
}

0 commit comments

Comments
 (0)