Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,15 @@ notes, but they do not trigger or gate the submodule updates.

### Optional configuration

For an additive activation entry point with explicit resource ownership, see
the [activation facade example](typescript/README.md#opt-in-activation-facade).
`activateToolExtension(context, { serverInfo, toolConfig })` returns a small
runtime handle; initialization remains deferred, not client-ready. Await
`runtime.deactivate()` for facade cleanup and existing client-stop behavior.
It preserves caller-owned subscriptions, but does not drain every legacy
in-flight restart or isolate the module-global logger/status. Existing manual
composition remains supported.

For an opt-in typed settings contract without changing runtime behavior, see
the [typed tool definition example](typescript/README.md#typed-tool-definitions).
Existing `ToolConfig` callers do not need to migrate.
Expand Down
63 changes: 63 additions & 0 deletions typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,69 @@ published package or a supported bare-module import.
See the [main README](../README.md#consuming-in-extensions) for build order,
consumer type-checking and bundling instructions.

## Opt-in activation facade

For conventional tools, `activateToolExtension` composes the existing shared
helpers. It accepts explicit `IServerInfo` and either a legacy `ToolConfig` or
a `ToolDefinition<TSettings>`; it does not load a manifest or infer tool policy.
For example, in the consuming extension's `src/extension.ts`:

```typescript
import { ExtensionContext } from 'vscode';
import {
activateToolExtension,
loadServerDefaults,
ToolExtensionRuntime,
} from '../external/vscode-common-python-lsp/typescript/dist';
import { toolDefinition } from './toolDefinition';

let runtime: ToolExtensionRuntime | undefined;

export function activate(context: ExtensionContext): void {
runtime = activateToolExtension(context, {
serverInfo: loadServerDefaults(context.extensionPath),
toolConfig: toolDefinition,
});
}

export async function deactivate(): Promise<void> {
await runtime?.deactivate();
runtime = undefined;
}
```

`toolDefinition` supplies the extension's existing policies and server script
path (see the typed example below). Build the pinned shared checkout before
type-checking and bundle its public entry and dependencies as described in the
main README.

The facade installs common listeners and, for formatters, the placeholder
synchronously, then initializes with `setImmediate`. **The returned handle is
not a client-ready promise**: Python resolution and client startup remain
deferred. Common listeners are present before Python can emit its initial
interpreter event.

The facade owns its output channel, logger registration, Python provider,
tool context, commands, watchers and listeners. It adds one cleanup disposable
to `context.subscriptions`; it does not remove or dispose unrelated caller
subscriptions. Context disposal initiates shutdown; `await runtime.deactivate()`
observes it. Both paths are idempotent. Shutdown cancels pending initialization,
disposes the tool context, and delegates client stopping to `deactivateServer`.
If initialization already started, shutdown waits for that `initialize()` call
to settle and disposes any late subscriptions immediately; unresolved Python
API acquisition can therefore delay shutdown. Logging stays available during
this cleanup. Synchronous activation failures roll back owned resources and
are rethrown; asynchronous initialization/cleanup failures are caught and logged.

This is composition, not a new restart scheduler. As with the low-level APIs,
`runServer()` may resolve after scheduling a delayed retry, and shutdown does
**not** drain every in-flight restart/start (including startup triggered by a
Python event). No stronger client-readiness or full-quiescence guarantee is
implied. Logger and status are still module-global: this is not independent
multi-tool-instance isolation. Existing low-level activation APIs remain
available unchanged for custom composition; no consumer migration or custom
lifecycle hooks are required.

## Typed tool definitions

Adoption is optional. Annotate a definition with `ToolDefinition<TSettings>` to
Expand Down
6 changes: 5 additions & 1 deletion typescript/src/activation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ export interface RegisterSubscriptionsOptions {
* this call.
*/
export function registerCommonSubscriptions(
context: vscode.ExtensionContext,
context: Pick<vscode.ExtensionContext, 'subscriptions'>,
options: RegisterSubscriptionsOptions,
): void {
const { serverInfo, outputChannel, toolConfig, toolContext, pythonProvider } = options;
Expand All @@ -517,6 +517,8 @@ export function registerCommonSubscriptions(
outputChannel.onDidChangeLogLevel(async (e) => {
await changeLogLevel(e, vscode.env.logLevel);
}),
);
context.subscriptions.push(
vscode.env.onDidChangeLogLevel(async (e) => {
await changeLogLevel(outputChannel.logLevel, e);
}),
Expand All @@ -534,6 +536,8 @@ export function registerCommonSubscriptions(
registerCommand(`${serverId}.showLogs`, async () => {
outputChannel.show();
}),
);
context.subscriptions.push(
registerCommand(`${serverId}.restart`, async () => {
await safeRunServer(toolContext, 'restart command');
}),
Expand Down
76 changes: 44 additions & 32 deletions typescript/src/configWatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,41 +28,53 @@ export function createConfigFileWatchers(
toolName: string,
onConfigChanged: () => Promise<void>,
): Disposable[] {
return configFiles.map((pattern) => {
const watcher = workspace.createFileSystemWatcher(`**/${pattern}`);
let disposed = false;
let pending: Promise<void> | undefined;
const watchers: Disposable[] = [];
try {
for (const pattern of configFiles) {
const watcher = workspace.createFileSystemWatcher(`**/${pattern}`);
const registrations: Disposable[] = [watcher];
let disposed = false;
let pending: Promise<void> | undefined;

const handleEvent = (event: string) => {
if (disposed) {
return;
}
traceLog(`${toolName} config file ${event}: ${pattern}`);
const run = () =>
onConfigChanged().catch((e) => traceError(`Config file ${event} handler failed`, e));

const nextPending = (pending ? pending.then(run, run) : run()).finally(() => {
if (pending === nextPending) {
pending = undefined;
const handleEvent = (event: string) => {
if (disposed) {
return;
}
});
traceLog(`${toolName} config file ${event}: ${pattern}`);
const run = () => onConfigChanged().catch((e) => traceError(`Config file ${event} handler failed`, e));

pending = nextPending;
};
const nextPending = (pending ? pending.then(run, run) : run()).finally(() => {
if (pending === nextPending) {
pending = undefined;
}
});

const changeDisposable = watcher.onDidChange(() => handleEvent('changed'));
const createDisposable = watcher.onDidCreate(() => handleEvent('created'));
const deleteDisposable = watcher.onDidDelete(() => handleEvent('deleted'));
pending = nextPending;
};

return {
dispose(): void {
disposed = true;
pending = undefined;
changeDisposable.dispose();
createDisposable.dispose();
deleteDisposable.dispose();
watcher.dispose();
},
};
});
watchers.push({
dispose(): void {
disposed = true;
pending = undefined;
for (const disposable of registrations.splice(0).reverse()) {
try {
disposable.dispose();
} catch (error) {
traceError('Config watcher cleanup failed', error);
}
}
},
});
registrations.push(watcher.onDidChange(() => handleEvent('changed')));
registrations.push(watcher.onDidCreate(() => handleEvent('created')));
registrations.push(watcher.onDidDelete(() => handleEvent('deleted')));
}
return watchers;
} catch (error) {
// A caller cannot own watchers that this factory never returned.
for (const watcher of watchers.reverse()) {
watcher.dispose();
}
throw error;
}
}
3 changes: 3 additions & 0 deletions typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,6 @@ export {
RegisterSubscriptionsOptions,
ToolExtensionContext,
} from './activation';

// Opt-in activation facade
export { activateToolExtension, ActivateToolExtensionOptions, ToolExtensionRuntime } from './toolExtension';
19 changes: 16 additions & 3 deletions typescript/src/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,29 @@ import { LanguageStatusItem, Disposable, l10n, LanguageStatusSeverity } from 'vs
import { Command } from 'vscode-languageclient';
import { createLanguageStatusItem } from './vscodeapi';
import { getDocumentSelector } from './utilities';
import { traceError } from './logging';

let _status: LanguageStatusItem | undefined;
export function registerLanguageStatusItem(id: string, name: string, command: string): Disposable {
_status?.dispose();

const status = createLanguageStatusItem(id, getDocumentSelector());
_status = status;
status.name = name;
status.text = name;
status.command = Command.create(l10n.t('Open logs'), command);
try {
status.name = name;
status.text = name;
status.command = Command.create(l10n.t('Open logs'), command);
} catch (error) {
if (_status === status) {
_status = undefined;
}
try {
status.dispose();
} catch (cleanupError) {
traceError('Language status cleanup failed', cleanupError);
}
throw error;
}

return {
dispose: () => {
Expand Down
155 changes: 155 additions & 0 deletions typescript/src/toolExtension.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import * as vscode from 'vscode';
import { createToolContext, deactivateServer, registerCommonSubscriptions, ToolExtensionContext } from './activation';
import { registerLogger } from './logging';
import { PythonEnvironmentsProvider } from './python';
import { IServerInfo, ToolConfig } from './types';
import { createOutputChannel } from './vscodeapi';

/** Explicit tool metadata and policy for {@link activateToolExtension}. */
export interface ActivateToolExtensionOptions {
serverInfo: IServerInfo;
/** Accepts legacy ToolConfig and structurally compatible ToolDefinition values. */
toolConfig: ToolConfig;
}

/** The facade's lifetime handle, not a client-ready notification. */
export interface ToolExtensionRuntime {
/**
* Idempotently cancel deferred initialization and dispose facade-owned resources.
*
* Stops the client via deactivateServer and waits for an already-started
* initialize() to settle, disposing late subscriptions too. This does not
* drain every in-flight restart or delayed retry in the legacy lifecycle.
* Cleanup failures are logged rather than rejected.
*/
deactivate(): Promise<void>;
}

/**
* Compose the shared runtime without changing the existing tool lifecycle.
*
* Common listeners and a formatter placeholder (when enabled) are installed
* synchronously. Initialization is deferred with setImmediate: returning this
* handle does not mean Python is resolved or the language client is Running.
*
* Owns its output channel, logger, Python provider, tool context and subscriptions;
* the caller's other subscriptions are untouched. Context disposal initiates the
* same cleanup as deactivate(); explicitly await deactivate() to observe completion.
* The existing module-global logger/status still preclude independent tool instances.
*/
export function activateToolExtension(
context: vscode.ExtensionContext,
options: ActivateToolExtensionOptions,
): ToolExtensionRuntime {
let outputChannel: vscode.LogOutputChannel | undefined;
let logger: vscode.Disposable | undefined;
let toolContext: ToolExtensionContext | undefined;
let scheduled: NodeJS.Immediate | undefined;
let initialization: Promise<void> = Promise.resolve();
let closed = false;
let finishShutdown!: () => void;
const shutdown = new Promise<void>((resolve) => {
finishShutdown = resolve;
});
const subscriptions: vscode.Disposable[] = [];
const pendingDisposals: Promise<void>[] = [];

function report(message: string, error: unknown): void {
try {
outputChannel?.error(`${message}: ${error}`);
} catch {
// A broken output channel must not turn cleanup into an unhandled rejection.
}
}

async function dispose(disposable: vscode.Disposable | undefined): Promise<void> {
try {
await disposable?.dispose();
} catch (error) {
report('Tool extension cleanup failed', error);
}
}

// Legacy initialization appends to this array after awaits. Once closed,
// dispose additions immediately instead of retaining unowned subscriptions.
subscriptions.push = (...items) => {
if (closed) {
for (const item of items) {
pendingDisposals.push(dispose(item));
}
} else {
Array.prototype.push.apply(subscriptions, items);
}
return subscriptions.length;
};

async function teardown(): Promise<void> {
// Dispose the context first so events/late initialization cannot revive it.
const stopping = deactivateServer(toolContext).catch((error) =>
report('Tool extension shutdown failed', error),
);
for (const disposable of subscriptions.splice(0).reverse()) {
pendingDisposals.push(dispose(disposable));
}
await Promise.all([stopping, initialization]);
while (pendingDisposals.length > 0) {
await Promise.all(pendingDisposals.splice(0));
}
// Keep logging available until initialization and late cleanup have settled.
await dispose(logger);
await dispose(outputChannel);
}

function deactivate(): Promise<void> {
if (!closed) {
closed = true;
if (scheduled) {
clearImmediate(scheduled);
scheduled = undefined;
}
void teardown().then(finishShutdown, (error) => {
report('Tool extension shutdown failed', error);
finishShutdown();
});
}
return shutdown;
}

try {
const { serverInfo, toolConfig } = options;
outputChannel = createOutputChannel(serverInfo.name);
logger = registerLogger(outputChannel);
const pythonProvider = new PythonEnvironmentsProvider(toolConfig);
subscriptions.push(pythonProvider);
toolContext = createToolContext({
serverInfo,
outputChannel,
toolConfig,
pythonProvider,
});
registerCommonSubscriptions(
{ subscriptions },
{ serverInfo, outputChannel, toolConfig, toolContext, pythonProvider },
);
context.subscriptions.push({ dispose: () => void deactivate() });
scheduled = setImmediate(() => {
scheduled = undefined;
initialization = Promise.resolve()
.then(() => {
if (!closed) {
return toolContext?.initialize(subscriptions);
}
return undefined;
})
.catch((error) => report('Tool extension initialization failed', error));
});
return { deactivate };
} catch (error) {
report('Tool extension activation failed', error);
void deactivate();
throw error;
}
}
Loading
Loading