-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathdeploymentManager.ts
More file actions
294 lines (264 loc) · 8.41 KB
/
deploymentManager.ts
File metadata and controls
294 lines (264 loc) · 8.41 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
import { CoderApi } from "../api/coderApi";
import { type ServiceContainer } from "../core/container";
import { type ContextManager } from "../core/contextManager";
import { type MementoManager } from "../core/mementoManager";
import { type SecretsManager } from "../core/secretsManager";
import { type Logger } from "../logging/logger";
import { type OAuthSessionManager } from "../oauth/sessionManager";
import { type WorkspaceProvider } from "../workspace/workspacesProvider";
import {
DeploymentSchema,
type Deployment,
type DeploymentWithAuth,
} from "./types";
import type { User } from "coder/site/src/api/typesGenerated";
import type * as vscode from "vscode";
/**
* Manages deployment state for the extension.
*
* Centralizes:
* - In-memory deployment state (url, label, token, user)
* - Client credential updates
* - OAuth session management
* - Auth listener registration
* - Context updates (coder.authenticated, coder.isOwner)
* - Workspace provider refresh
* - Cross-window sync handling
*/
export class DeploymentManager implements vscode.Disposable {
private readonly secretsManager: SecretsManager;
private readonly mementoManager: MementoManager;
private readonly contextManager: ContextManager;
private readonly logger: Logger;
#deployment: Deployment | null = null;
#authListenerDisposable: vscode.Disposable | undefined;
#crossWindowSyncDisposable: vscode.Disposable | undefined;
private constructor(
serviceContainer: ServiceContainer,
private readonly client: CoderApi,
private readonly oauthSessionManager: OAuthSessionManager,
private readonly workspaceProviders: WorkspaceProvider[],
) {
this.secretsManager = serviceContainer.getSecretsManager();
this.mementoManager = serviceContainer.getMementoManager();
this.contextManager = serviceContainer.getContextManager();
this.logger = serviceContainer.getLogger();
}
public static create(
serviceContainer: ServiceContainer,
client: CoderApi,
oauthSessionManager: OAuthSessionManager,
workspaceProviders: WorkspaceProvider[],
): DeploymentManager {
const manager = new DeploymentManager(
serviceContainer,
client,
oauthSessionManager,
workspaceProviders,
);
manager.subscribeToCrossWindowChanges();
return manager;
}
/**
* Get the current deployment state.
*/
public getCurrentDeployment(): Deployment | null {
return this.#deployment;
}
/**
* Check if we have an authenticated deployment (does not guarantee that the current auth data is valid).
*/
public isAuthenticated(): boolean {
return this.contextManager.get("coder.authenticated");
}
/**
* Attempt to change to a deployment after validating authentication.
* Only changes deployment if authentication succeeds.
* Returns true if deployment was changed, false otherwise.
*/
public async setDeploymentIfValid(
deployment: Deployment & { token?: string },
): Promise<boolean> {
const token =
deployment.token ??
(await this.secretsManager.getSessionAuth(deployment.safeHostname))
?.token;
const tempClient = CoderApi.create(deployment.url, token, this.logger);
try {
const user = await tempClient.getAuthenticatedUser();
// Authentication succeeded - now change the deployment
await this.setDeployment({
...deployment,
token,
user,
});
return true;
} catch (e) {
this.logger.warn("Failed to authenticate with deployment:", e);
return false;
} finally {
tempClient.dispose();
}
}
/**
* Change to a fully authenticated deployment (with user).
* Use this when you already have the user from a successful login.
*/
public async setDeployment(
deployment: DeploymentWithAuth & { user: User },
): Promise<void> {
this.logger.debug("Setting deployment", {
hostname: deployment.safeHostname,
user: deployment.user.username,
});
this.#deployment = { ...deployment };
// Updates client credentials
if (deployment.token === undefined) {
this.client.setHost(deployment.url);
} else {
this.client.setCredentials(deployment.url, deployment.token);
}
// Register auth listener before setDeployment so background token refresh
// can update client credentials via the listener
this.registerAuthListener();
// Contexts must be set before refresh (providers check isAuthenticated)
this.updateAuthContexts(deployment.user);
this.updateExperimentContexts();
this.refreshWorkspaces();
const deploymentWithoutAuth: Deployment =
DeploymentSchema.parse(deployment);
await this.oauthSessionManager.setDeployment(deploymentWithoutAuth);
await this.persistDeployment(deploymentWithoutAuth);
}
/**
* Clears the current deployment.
*/
public async clearDeployment(): Promise<void> {
this.logger.debug("Clearing deployment", this.#deployment?.safeHostname);
this.suspendSession();
this.#authListenerDisposable?.dispose();
this.#authListenerDisposable = undefined;
this.#deployment = null;
await this.secretsManager.setCurrentDeployment(undefined);
}
/**
* Suspend session: shows logged-out state but keeps deployment for easy re-login.
* Auth listener remains active so recovery can happen automatically if tokens update.
*/
public suspendSession(): void {
this.oauthSessionManager.clearDeployment();
this.client.setCredentials(undefined, undefined);
this.updateAuthContexts(undefined);
this.contextManager.set("coder.agentsEnabled", false);
this.clearWorkspaces();
}
/**
* Clear all workspace providers without fetching.
*/
private clearWorkspaces(): void {
for (const provider of this.workspaceProviders) {
provider.clear();
}
}
public dispose(): void {
this.#authListenerDisposable?.dispose();
this.#crossWindowSyncDisposable?.dispose();
}
/**
* Register auth listener for the current deployment.
* Updates credentials when they change (token refresh, cross-window sync).
* Also handles recovery from suspended session state.
*/
private registerAuthListener(): void {
if (!this.#deployment) {
return;
}
// Capture hostname at registration time for the guard clause
const safeHostname = this.#deployment.safeHostname;
this.#authListenerDisposable?.dispose();
this.logger.debug("Registering auth listener for hostname", safeHostname);
this.#authListenerDisposable = this.secretsManager.onDidChangeSessionAuth(
safeHostname,
async (auth) => {
if (this.#deployment?.safeHostname !== safeHostname) {
return;
}
if (auth) {
if (this.isAuthenticated()) {
this.client.setCredentials(auth.url, auth.token);
} else {
this.logger.debug(
"Token updated after session suspended, recovering",
);
await this.setDeploymentIfValid({
url: auth.url,
safeHostname,
token: auth.token,
});
}
} else {
await this.clearDeployment();
}
},
);
}
private subscribeToCrossWindowChanges(): void {
this.#crossWindowSyncDisposable =
this.secretsManager.onDidChangeCurrentDeployment(
async ({ deployment }) => {
if (this.isAuthenticated()) {
// Ignore if we are already authenticated
return;
}
if (deployment) {
this.logger.info("Deployment changed from another window");
await this.setDeploymentIfValid(deployment);
}
},
);
}
/**
* Update authentication-related contexts.
*/
private updateAuthContexts(user: User | undefined): void {
this.contextManager.set("coder.authenticated", Boolean(user));
const isOwner = user?.roles.some((r) => r.name === "owner") ?? false;
this.contextManager.set("coder.isOwner", isOwner);
}
/**
* Fetch enabled experiments and update context keys.
* Runs in the background so it does not block login.
*/
private updateExperimentContexts(): void {
this.client
.getExperiments()
.then((experiments) => {
if (!this.isAuthenticated()) {
return;
}
this.contextManager.set(
"coder.agentsEnabled",
experiments.includes("agents"),
);
})
.catch((err) => {
this.logger.warn("Failed to fetch experiments", err);
this.contextManager.set("coder.agentsEnabled", false);
});
}
/**
* Refresh all workspace providers asynchronously.
*/
private refreshWorkspaces(): void {
for (const provider of this.workspaceProviders) {
void provider.fetchAndRefresh();
}
}
/**
* Persist deployment to storage for cross-window sync.
*/
private async persistDeployment(deployment: Deployment): Promise<void> {
await this.secretsManager.setCurrentDeployment(deployment);
await this.mementoManager.addToUrlHistory(deployment.url);
}
}