-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathadapter-registry.ts
More file actions
525 lines (466 loc) · 16.9 KB
/
Copy pathadapter-registry.ts
File metadata and controls
525 lines (466 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/**
* Implementation of the Adapter Registry for managing debug adapters
*
* @since 2.0.0
*/
import { EventEmitter } from 'events';
import { adapterLogPathFor } from '../proxy/session-log-layout.js';
import {
IAdapterRegistry,
IAdapterFactory,
AdapterDependencies,
AdapterInfo,
AdapterNotFoundError,
DuplicateRegistrationError,
FactoryValidationError,
AdapterRegistryConfig,
AdapterFactoryMap,
ActiveAdapterMap
} from '@debugmcp/shared';
import { IDebugAdapter, AdapterConfig } from '@debugmcp/shared';
import type { AdapterMetadata as SharedAdapterMetadata, AdapterManifestEntry, FactoryLoadResult } from '@debugmcp/shared';
import { AdapterLoader } from './adapter-loader.js';
import type { AdapterMetadata } from './adapter-loader.js';
import { isContainerRuntime } from '../utils/container-path-utils.js';
import { getErrorMessage } from '../errors/debug-errors.js';
import { disposeAdapterSafely } from './adapter-disposal.js';
/**
* Default registry configuration
*/
const DEFAULT_CONFIG: Required<AdapterRegistryConfig> = {
validateOnRegister: true,
allowOverride: false,
maxInstancesPerLanguage: 10,
autoDispose: true,
autoDisposeTimeout: 300000, // 5 minutes
enableDynamicLoading: false,
// No injected sink → discovery warnings are dropped. Deliberately NOT a
// per-instance createLogger(): HTTP mode builds a registry per session and
// a per-instance winston logger pipes each into the process-lifetime
// shared transport with no detach path (the issue-#404 leak class).
logger: {},
};
/**
* Implementation of the adapter registry
*/
export class AdapterRegistry extends EventEmitter implements IAdapterRegistry {
private readonly factories: AdapterFactoryMap = new Map();
private readonly activeAdapters: ActiveAdapterMap = new Map();
private readonly config: Required<AdapterRegistryConfig>;
private readonly disposeTimers = new Map<IDebugAdapter, NodeJS.Timeout>();
private readonly registrationTimestamps = new Map<string, Date>();
private readonly loader = new AdapterLoader();
// Dynamic loading is opt-in via constructor config or MCP_CONTAINER=true env var
private readonly dynamicEnabled: boolean;
private warn(message: string): void {
this.config.logger.warn?.(message);
}
constructor(config: AdapterRegistryConfig = {}) {
super();
this.config = { ...DEFAULT_CONFIG, ...config };
// Enable dynamic loading only when explicitly requested (default false to
// keep legacy behavior in tests). Read from the raw config param, not
// this.config, so an unset field still falls back to the env check.
this.dynamicEnabled = Boolean(
config.enableDynamicLoading ?? isContainerRuntime()
);
// Safety handler: prevent crash from async dispose error events
// (e.g. adapter.dispose() failures in unregister/disposeAll/setupAutoDispose)
this.on('error', () => {});
}
/**
* Register a new adapter factory for a language
*/
async register(language: string, factory: IAdapterFactory): Promise<void> {
// Check for duplicate registration
if (this.factories.has(language) && !this.config.allowOverride) {
throw new DuplicateRegistrationError(language);
}
// Validate factory if configured
if (this.config.validateOnRegister) {
const validationResult = await factory.validate();
if (!validationResult.valid) {
throw new FactoryValidationError(language, validationResult);
}
}
// Register the factory
this.factories.set(language, factory);
this.registrationTimestamps.set(language, new Date());
this.emit('factoryRegistered', language, factory.getMetadata());
}
/**
* Unregister an adapter factory
*/
unregister(language: string): boolean {
const factory = this.factories.get(language);
if (!factory) {
return false;
}
// Dispose all active adapters for this language
const activeSet = this.activeAdapters.get(language);
if (activeSet) {
for (const adapter of activeSet) {
void disposeAdapterSafely(adapter, (error) => {
this.emit('error', new Error(`Failed to dispose adapter: ${getErrorMessage(error)}`));
});
this.clearDisposeTimer(adapter);
}
this.activeAdapters.delete(language);
}
// Remove the factory
this.factories.delete(language);
this.emit('factoryUnregistered', language);
return true;
}
/**
* Create a new adapter instance for the specified language
*/
async create(language: string, config: AdapterConfig): Promise<IDebugAdapter> {
let factory = this.factories.get(language);
if (!factory) {
if (this.dynamicEnabled) {
try {
const loadedFactory = await this.loader.loadAdapter(language);
// Register but also use the loadedFactory directly to avoid undefined from map lookup
await this.register(language, loadedFactory);
factory = loadedFactory;
} catch (err) {
// Re-throw registration errors as-is; only convert loader failures to AdapterNotFoundError
if (err instanceof AdapterNotFoundError) throw err;
if (this.factories.has(language)) throw err;
const available = await this.listLanguages().catch(() => this.getSupportedLanguages());
throw new AdapterNotFoundError(language, available);
}
} else {
// Legacy behavior: not dynamically loading -> throw not found using registered languages only
throw new AdapterNotFoundError(language, this.getSupportedLanguages());
}
}
// Check instance limit
const activeSet = this.activeAdapters.get(language) || new Set();
if (activeSet.size >= this.config.maxInstancesPerLanguage) {
throw new Error(
`Maximum adapter instances (${this.config.maxInstancesPerLanguage}) reached for language: ${language}`
);
}
// Create dependencies for the adapter
const dependencies = await this.createDependencies(config);
// Create the adapter
const adapter = factory.createAdapter(dependencies);
// Initialize the adapter. initialize() gates on the local toolchain, which
// direct-connect attach (a plain TCP connection to a remote DAP socket)
// does not need — skip it so attach works on toolchain-less hosts (issue #331).
const skipEnvironmentInit =
config.attachMode === true &&
factory.getMetadata().modes?.attach === 'direct-connect';
if (!skipEnvironmentInit) {
await adapter.initialize();
}
// Track the active adapter
if (!this.activeAdapters.has(language)) {
this.activeAdapters.set(language, new Set());
}
this.activeAdapters.get(language)!.add(adapter);
// Set up auto-dispose if configured
if (this.config.autoDispose) {
this.setupAutoDispose(adapter);
}
// Listen for adapter disposal
adapter.once('disposed', () => {
const set = this.activeAdapters.get(language);
if (set) {
set.delete(adapter);
if (set.size === 0) {
this.activeAdapters.delete(language);
}
}
});
this.emit('adapterCreated', language, adapter);
return adapter;
}
/**
* Get list of all supported languages
*/
getSupportedLanguages(): string[] {
return Array.from(this.factories.keys());
}
/**
* Check if a language is supported
*/
isLanguageSupported(language: string): boolean {
return this.factories.has(language);
}
/**
* Get metadata about a registered adapter
*/
getAdapterInfo(language: string): AdapterInfo | undefined {
const factory = this.factories.get(language);
if (!factory) {
return undefined;
}
const metadata = factory.getMetadata();
const activeSet = this.activeAdapters.get(language);
return {
...metadata,
language,
available: true,
activeInstances: activeSet?.size || 0,
registeredAt: this.registrationTimestamps.get(language) || new Date(),
};
}
/**
* Get all registered adapter information
*/
getAllAdapterInfo(): Map<string, AdapterInfo> {
const result = new Map<string, AdapterInfo>();
for (const [language] of this.factories) {
const info = this.getAdapterInfo(language);
if (info) {
result.set(language, info);
}
}
return result;
}
/**
* List all known languages from static registration and dynamic discovery
*/
async listLanguages(): Promise<string[]> {
const registered = this.getSupportedLanguages();
if (!this.dynamicEnabled) {
// Without dynamic loading, advertise the statically registered adapters.
return registered;
}
const installed = new Set<string>();
try {
const adapters = await this.loader.listAvailableAdapters();
for (const adapter of adapters) {
// Include adapters that are marked as installed, OR are in the known list
// (adapters load on-demand, so availability check might fail initially)
if (adapter.installed) {
installed.add(adapter.name);
}
}
} catch (error) {
// Fall back to registered adapters (bundled environments embed them),
// but leave a breadcrumb — a broken loader should not be silent.
this.warn(
`[AdapterRegistry] listLanguages: loader discovery failed, falling back to registered adapters: ${
error instanceof Error ? error.message : String(error)
}`
);
}
// Always include statically registered adapters so bundled builds expose them.
for (const language of registered) {
installed.add(language);
}
return Array.from(installed);
}
/**
* List detailed adapter metadata (known + install status)
*/
async listAvailableAdapters(): Promise<AdapterManifestEntry[]> {
const registered = new Set(this.getSupportedLanguages());
const buildEntry = (language: string): AdapterMetadata => {
// A registered plain-JS factory can throw from getMetadata(); one bad
// factory must not reject the whole listing (doctor would lose every
// verdict). Same defense probeLanguageEntry applies per entry.
let attach: AdapterMetadata['attach'] = 'none';
try {
attach = this.factories.get(language)?.getMetadata().modes?.attach ?? 'none';
} catch (error) {
this.warn(
`[AdapterRegistry] getMetadata() threw for registered '${language}'; listing it with attach 'none'. ${
error instanceof Error ? error.message : String(error)
}`
);
}
return {
name: language,
packageName: `@debugmcp/adapter-${language}`,
description: undefined,
installed: true,
attach
};
};
if (!this.dynamicEnabled) {
// Provide minimal metadata from registered factories
return Array.from(registered).map(buildEntry);
}
const results = new Map<string, AdapterMetadata>();
try {
const adapters = await this.loader.listAvailableAdapters();
for (const adapter of adapters) {
const installed = registered.has(adapter.name) ? true : adapter.installed;
results.set(adapter.name, { ...adapter, installed });
registered.delete(adapter.name);
}
} catch (error) {
// Fall back to registered adapters, but leave a breadcrumb.
this.warn(
`[AdapterRegistry] listAvailableAdapters: loader discovery failed, falling back to registered adapters: ${
error instanceof Error ? error.message : String(error)
}`
);
}
for (const language of registered) {
results.set(language, buildEntry(language));
}
return Array.from(results.values());
}
/**
* Get the factory for a language without creating an adapter instance,
* with the load failure preserved (issue #435 part 4): checks registered
* factories first, then the loader cache, then attempts a dynamic load
* (when enabled). Never throws — a failed load comes back as loadError so
* the availability probe can surface the real import error instead of
* "the registry returned no factory".
*/
async getFactoryResult(language: string): Promise<FactoryLoadResult> {
const registered = this.factories.get(language);
if (registered) {
return { factory: registered };
}
const cached = this.loader.getCachedFactory(language);
if (cached) {
return { factory: cached };
}
if (!this.dynamicEnabled) {
return { dynamicLoadingDisabled: true };
}
try {
return { factory: await this.loader.loadAdapter(language) };
} catch (error) {
return { loadError: error instanceof Error ? error : new Error(String(error)) };
}
}
/**
* Get the factory for a language without creating an adapter instance.
* Fail-open contract: returns undefined whenever no factory can be
* produced, whatever the reason — use getFactoryResult when the reason
* matters.
*/
async getFactory(language: string): Promise<IAdapterFactory | undefined> {
return (await this.getFactoryResult(language)).factory;
}
/**
* Get a language's factory-declared metadata (including per-mode capabilities)
* without creating an adapter instance.
*/
async getFactoryMetadata(language: string): Promise<SharedAdapterMetadata | undefined> {
const factory = await this.getFactory(language);
return factory?.getMetadata();
}
/**
* Dispose all created adapters, clear factories, and reset registry
*/
async disposeAll(): Promise<void> {
const disposePromises: Promise<void>[] = [];
// Dispose all active adapters
for (const [language, activeSet] of this.activeAdapters) {
for (const adapter of activeSet) {
disposePromises.push(
disposeAdapterSafely(adapter, (error) => {
this.emit('error', new Error(`Failed to dispose adapter for ${language}: ${getErrorMessage(error)}`));
})
);
}
}
// Clear all dispose timers
for (const timer of this.disposeTimers.values()) {
clearTimeout(timer);
}
this.disposeTimers.clear();
// Wait for all disposals to complete
await Promise.all(disposePromises);
// Clear all tracking
this.activeAdapters.clear();
this.factories.clear();
this.emit('registryDisposed');
}
/**
* Get count of active adapter instances
*/
getActiveAdapterCount(): number {
let count = 0;
for (const activeSet of this.activeAdapters.values()) {
count += activeSet.size;
}
return count;
}
/**
* Create dependencies for adapter creation
*/
private async createDependencies(config: AdapterConfig): Promise<AdapterDependencies> {
const { createProductionDependencies } = await import('../container/dependencies.js');
const logFile = config.logDir && config.sessionId
? adapterLogPathFor(config.logDir, config.sessionId)
: undefined;
const deps = createProductionDependencies({
logLevel: 'debug',
...(logFile ? { logFile } : {})
});
return {
fileSystem: deps.fileSystem,
logger: deps.logger,
environment: deps.environment,
networkManager: deps.networkManager,
};
}
/**
* Set up auto-dispose for an adapter
*/
private setupAutoDispose(adapter: IDebugAdapter): void {
this.clearDisposeTimer(adapter);
// Listen for adapter state changes
adapter.on('stateChanged', (oldState, newState) => {
if (newState === 'disconnected' || newState === 'error') {
// Clear any existing dispose timer before scheduling a new one
this.clearDisposeTimer(adapter);
// Start dispose timer
const timer = setTimeout(() => {
void disposeAdapterSafely(adapter, (error) => {
this.emit('error', new Error(`Auto-dispose failed: ${getErrorMessage(error)}`));
});
}, this.config.autoDisposeTimeout);
this.disposeTimers.set(adapter, timer);
} else if (newState === 'connected' || newState === 'debugging') {
// Cancel dispose timer if adapter becomes active again
this.clearDisposeTimer(adapter);
}
});
}
private clearDisposeTimer(adapter: IDebugAdapter): void {
const timer = this.disposeTimers.get(adapter);
if (timer) {
clearTimeout(timer);
this.disposeTimers.delete(adapter);
}
}
}
/**
* Singleton storage for the adapter registry
*/
let registryInstance: AdapterRegistry | null = null;
/**
* Get or create the singleton adapter registry instance
*/
export function getAdapterRegistry(config?: AdapterRegistryConfig): AdapterRegistry {
if (!registryInstance) {
registryInstance = new AdapterRegistry(config);
} else if (config) {
console.warn('[AdapterRegistry] getAdapterRegistry called with config but singleton already exists; config ignored');
}
return registryInstance;
}
/**
* Reset the singleton instance (mainly for testing)
*/
export async function resetAdapterRegistry(): Promise<void> {
if (registryInstance) {
const instance = registryInstance;
registryInstance = null;
await instance.disposeAll().catch(() => {
// Ignore errors during reset
});
}
}