-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathextension.ts
More file actions
676 lines (613 loc) · 28.8 KB
/
Copy pathextension.ts
File metadata and controls
676 lines (613 loc) · 28.8 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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
import * as vscode from "vscode";
/** First things first, setup Sentry to catch errors during activation and beyond
* `process.env.SENTRY_DSN` is fetched & defined during production builds only for Confluent official release process
* */
import {
closeSentryClient,
initSentry,
sentryCaptureEvent,
sentryCaptureException,
} from "./telemetry/sentryClient";
if (process.env.SENTRY_DSN) {
initSentry();
}
import { handleNewOrUpdatedExtensionInstallation } from "./activation/compareVersions";
import { ConfluentCloudAuthProvider } from "./authn/ccloudProvider";
import { getCCloudAuthSession } from "./authn/utils";
import { disableCCloudStatusPolling, enableCCloudStatusPolling } from "./ccloudStatus/polling";
import { PARTICIPANT_ID } from "./chat/constants";
import { chatHandler } from "./chat/participant";
import { handleFeedback } from "./chat/telemetry";
import { registerChatTools } from "./chat/tools/registration";
import { FlinkSqlCodelensProvider } from "./codelens/flinkSqlProvider";
import { registerCommandWithLogging } from "./commands";
import { registerConnectionCommands } from "./commands/connections";
import { registerTopicsViewCommands } from "./commands/topicsView";
import { registerDebugCommands } from "./commands/debugtools";
import { registerDiffCommands } from "./commands/diffs";
import { registerDockerCommands } from "./commands/docker";
import { registerDocumentCommands } from "./commands/documents";
import { registerEnvironmentCommands } from "./commands/environments";
import { registerExtraCommands } from "./commands/extra";
import { registerFlinkArtifactCommands } from "./commands/flinkArtifacts";
import { registerFlinkComputePoolCommands } from "./commands/flinkComputePools";
import { registerFlinkDatabaseViewCommands } from "./commands/flinkDatabaseView";
import { registerFlinkStatementCommands } from "./commands/flinkStatements";
import { registerFlinkUDFCommands } from "./commands/flinkUDFs";
import { registerKafkaClusterCommands } from "./commands/kafkaClusters";
import { registerMedusaCodeLensCommands } from "./commands/medusaCodeLens";
import { registerOrganizationCommands } from "./commands/organizations";
import { registerNewResourceViewCommands } from "./commands/resources";
import { registerProjectGenerationCommands } from "./commands/scaffold";
import { registerSchemaRegistryCommands } from "./commands/schemaRegistry";
import { registerSchemaCommands } from "./commands/schemas";
import { registerSearchCommands } from "./commands/search";
import { registerSupportCommands } from "./commands/support";
import { registerTopicCommands } from "./commands/topics";
import { registerUriCommands } from "./commands/uris";
import { setProjectScaffoldListener } from "./commands/utils/scaffoldUtils";
import { AUTH_PROVIDER_ID, AUTH_PROVIDER_LABEL } from "./constants";
import { activateMessageViewer } from "./consume";
import { setExtensionContext } from "./context/extension";
import { observabilityContext } from "./context/observability";
import { ContextValues, setContextValue } from "./context/values";
import { JSON_DIAGNOSTIC_COLLECTION } from "./diagnostics/constants";
import { DirectConnectionManager } from "./directConnectManager";
import { EventListener } from "./docker/eventListener";
import { registerLocalResourceWorkflows } from "./docker/workflows/workflowInitialization";
import { DocumentMetadataManager } from "./documentMetadataManager";
import { FlinkStatementDocumentProvider } from "./documentProviders/flinkStatement";
import { MESSAGE_URI_SCHEME, MessageDocumentProvider } from "./documentProviders/message";
import { SCHEMA_URI_SCHEME, SchemaDocumentProvider } from "./documentProviders/schema";
import { logError } from "./errors";
import {
ENABLE_CHAT_PARTICIPANT,
ENABLE_FLINK_CCLOUD_LANGUAGE_SERVER,
} from "./extensionSettings/constants";
import { createConfigChangeListener } from "./extensionSettings/listener";
import { updatePreferences } from "./extensionSettings/sidecarSync";
import {
disposeLaunchDarklyClient,
getLaunchDarklyClient,
resetFlagDefaults,
} from "./featureFlags/client";
import {
checkForExtensionDisabledReason,
showExtensionDisabledNotification,
} from "./featureFlags/evaluation";
import { FLINK_SQL_LANGUAGE_ID } from "./flinkSql/constants";
import { initializeFlinkLanguageClientManager } from "./flinkSql/flinkLanguageClientManager";
import { FlinkStatementManager } from "./flinkSql/flinkStatementManager";
import { setFlinkWorkspaceListener } from "./flinkSql/flinkWorkspace";
import { IconNames } from "./icons";
import { constructResourceLoaderSingletons } from "./loaders";
import { cleanupOldLogFiles, EXTENSION_OUTPUT_CHANNEL, Logger } from "./logging";
import { FlinkStatementResultsPanelProvider } from "./panelProviders/flinkStatementResults";
import { getSidecar, getSidecarManager } from "./sidecar";
import { createLocalConnection, getLocalConnection } from "./sidecar/connections/local";
import { ConnectionStateWatcher } from "./sidecar/connections/watcher";
import { closeFormattedSidecarLogStream, SIDECAR_OUTPUT_CHANNEL } from "./sidecar/logging";
import { WebsocketManager } from "./sidecar/websocketManager";
import { getCCloudStatusBarItem } from "./statusBar/ccloudItem";
import { SecretStorageKeys } from "./storage/constants";
import { migrateStorageIfNeeded } from "./storage/migrationManager";
import { logUsage, UserEvent } from "./telemetry/events";
import { sendTelemetryIdentifyEvent } from "./telemetry/telemetry";
import { getTelemetryLogger } from "./telemetry/telemetryLogger";
import { UriEventHandler } from "./uriHandler";
import { WriteableTmpDir } from "./utils/file";
import type { RefreshableTreeViewProvider } from "./viewProviders/baseModels/base";
import { FlinkDatabaseViewProvider } from "./viewProviders/flinkDatabase";
import { FlinkStatementsViewProvider } from "./viewProviders/flinkStatements";
import { HelpCenterViewProvider } from "./viewProviders/helpCenter";
import { ResourceViewProvider } from "./viewProviders/resources";
import { SchemasViewProvider } from "./viewProviders/schemas";
import { TopicViewProvider } from "./viewProviders/topics";
import { SEARCH_DECORATION_PROVIDER } from "./viewProviders/utils/search";
const logger = new Logger("extension");
// This method is called when your extension is activated based on the activation events
// defined in package.json
// ref: https://code.visualstudio.com/api/references/activation-events
export async function activate(
context: vscode.ExtensionContext,
): Promise<vscode.ExtensionContext | undefined> {
const extVersion = context.extension.packageJSON.version;
observabilityContext.extensionVersion = extVersion;
observabilityContext.extensionActivated = false;
// determine the writeable tmpdir for the extension to use. Must be done prior
// to starting the sidecar, as it will use this tmpdir for sidecar logfile.
const result = await WriteableTmpDir.getInstance().determine();
if (result.errors.length) {
sentryCaptureException(new Error("No writeable tmpdir found."), {
captureContext: {
extra: {
attemptedDirs: result.dirs.join("; "),
errorsEncountered: result.errors.map((e) => e.message).join("; "),
},
},
});
// if we can't find a writeable tmpdir, we can't log anything, which is bad
throw new Error("Can't activate extension: unable to find a writeable tmpdir");
}
logger.info(
`Extension version ${context.extension.id} activate() triggered for version "${extVersion}".`,
);
logUsage(UserEvent.ExtensionActivation, { status: "started" });
try {
context = await _activateExtension(context);
const message = `Extension version "${extVersion}" fully activated`;
logger.info(message);
observabilityContext.extensionActivated = true;
logUsage(UserEvent.ExtensionActivation, { status: "completed" });
sentryCaptureEvent({ message, level: "info" });
} catch (e) {
logger.error(`Error activating extension version "${extVersion}":`, e);
// if the extension is failing to activate for whatever reason, we need to know about it to fix it
sentryCaptureException(e);
logUsage(UserEvent.ExtensionActivation, { status: "failed" });
throw e;
}
// XXX: used to provide the ExtensionContext for tests; do not remove
if (context.extensionMode === vscode.ExtensionMode.Test) {
return context;
}
}
/**
* Activate the extension by setting up all the necessary components and registering commands.
* @remarks This is the try/catch wrapped function called from the extension's .activate() method
* to ensure that any errors are caught and logged properly.
*/
async function _activateExtension(
context: vscode.ExtensionContext,
): Promise<vscode.ExtensionContext> {
// must be done first to allow any other downstream callers to call `getExtensionContext()`
// (e.g. for globalState/workspaceState/secrets storage, webviews for extension root path, etc)
setExtensionContext(context);
// register the log output channels, debugging commands, and support commands to ensure we have
// visibility into the extension and sidecar logs and can download support .zip and/or file issues
context.subscriptions.push(
EXTENSION_OUTPUT_CHANNEL,
SIDECAR_OUTPUT_CHANNEL,
...registerDebugCommands(),
...registerSupportCommands(),
);
// automatically display and focus the Confluent extension output channel in development mode
// to avoid needing to keep the main window & Debug Console tab open alongside the extension dev
// host window during debugging
if (process.env.LOGGING_MODE === "development") {
vscode.commands.executeCommand("confluent.showOutputChannel");
}
// set up initial feature flags and the LD client
await setupFeatureFlags();
// configure extension access to secrets and global/workspace states, and set the initial context
// values for the VS Code UI to inform the `when` clauses in package.json
await Promise.all([setupStorage(), setupContextValues()]);
logger.info("Storage and context values initialized");
// verify we can connect to the correct version of the sidecar, which may require automatically
// killing any (old) sidecar process and starting a new one, going through the handshake, etc.
logger.info("Starting/checking the sidecar...");
await getSidecar();
logger.info("Sidecar ready for use.");
// Rehydrate sidecar with local + any direct connections from the secret storage. Do this before
// setting up the resource view provider.
await rehydrateConnections();
// set up the preferences listener to keep the sidecar in sync with the user/workspace settings
const settingsListener: vscode.Disposable = await setupPreferences();
context.subscriptions.push(settingsListener);
// set up the different view providers
const resourceViewProvider = ResourceViewProvider.getInstance();
const topicViewProvider = TopicViewProvider.getInstance();
const schemasViewProvider = SchemasViewProvider.getInstance();
const statementsViewProvider = FlinkStatementsViewProvider.getInstance();
const flinkDatabaseViewProvider = FlinkDatabaseViewProvider.getInstance();
const helpCenterViewProvider = new HelpCenterViewProvider();
// ...and any panel view providers
const flinkStatementResultsPanelProvider = FlinkStatementResultsPanelProvider.getInstance();
const viewProviderDisposables: vscode.Disposable[] = [
resourceViewProvider,
topicViewProvider,
schemasViewProvider,
helpCenterViewProvider,
statementsViewProvider,
flinkDatabaseViewProvider,
flinkStatementResultsPanelProvider,
];
logger.info("View providers initialized");
// explicitly "reset" the Topics & Schemas views so no resources linger during reactivation/update
await Promise.all([topicViewProvider.reset(), schemasViewProvider.reset()]);
// Register refresh commands for our refreshable resource view providers.
const refreshCommands: vscode.Disposable[] = [];
for (const instance of getRefreshableViewProviders()) {
refreshCommands.push(
registerCommandWithLogging(
`confluent.${instance.kind}.refresh`,
async (): Promise<boolean> => {
await instance.refresh(true);
return true;
},
),
);
}
// Register the project scaffold listener
const projectScaffoldListener = setProjectScaffoldListener();
context.subscriptions.push(projectScaffoldListener);
// Register the Flink workspace listener
const flinkWorkspaceListener = setFlinkWorkspaceListener();
context.subscriptions.push(flinkWorkspaceListener);
// register all the commands (apart from the view providers' refresh commands, which are handled above)
const registeredCommands: vscode.Disposable[] = [
...refreshCommands,
...registerConnectionCommands(),
...registerOrganizationCommands(),
...registerKafkaClusterCommands(),
...registerEnvironmentCommands(),
...registerSchemaRegistryCommands(),
...registerSchemaCommands(),
...registerTopicCommands(),
...registerTopicsViewCommands(),
...registerDiffCommands(),
...registerExtraCommands(),
...registerDockerCommands(),
...registerProjectGenerationCommands(),
...registerFlinkComputePoolCommands(),
...registerFlinkStatementCommands(),
...registerFlinkDatabaseViewCommands(),
...registerFlinkUDFCommands(),
...registerDocumentCommands(),
...registerMedusaCodeLensCommands(),
...registerSearchCommands(),
...registerFlinkArtifactCommands(),
...registerNewResourceViewCommands(),
...registerUriCommands(),
];
logger.info("Commands registered");
// Construct the singletons, let them register their event listeners
context.subscriptions.push(getSidecarManager());
context.subscriptions.push(...constructResourceLoaderSingletons());
// if the Flink CCloud language server setting is enabled, get the client manager ready for use
// (Needs to be done _before_ setupAuthProvider() so that the manager can
// handle the ccloudConnected event which may be fired during auth setup
// if this is a second+ workspace being activated in when already ccloud authed.)
if (ENABLE_FLINK_CCLOUD_LANGUAGE_SERVER.value) {
const flinkLanguageClientManager = initializeFlinkLanguageClientManager();
context.subscriptions.push(flinkLanguageClientManager);
}
const uriHandler: vscode.Disposable = vscode.window.registerUriHandler(
UriEventHandler.getInstance(),
);
// If the user is already authenticated to ccloud (this being not the first
// workspace activated), this will eventually cause ccloudConnected to be fired.
const authProviderDisposables: vscode.Disposable[] = await setupAuthProvider();
const documentProviders: vscode.Disposable[] = setupDocumentProviders();
context.subscriptions.push(
uriHandler,
WebsocketManager.getInstance(),
FlinkStatementManager.getInstance(),
...authProviderDisposables,
...viewProviderDisposables,
...registeredCommands,
...documentProviders,
);
// Just handling command registration and setting disposables
activateMessageViewer(context);
// register the local resource workflows so they can be used by the resource loaders
registerLocalResourceWorkflows();
// set up the local Docker event listener singleton and start watching for system events
EventListener.getInstance().start();
// reset the Docker credentials secret so `src/docker/configs.ts` can pull it fresh
void context.secrets.delete(SecretStorageKeys.DOCKER_CREDS_SECRET_KEY);
// Watch for sidecar pushing connection state changes over websocket.
// (side effect of causing the watcher to be created)
ConnectionStateWatcher.getInstance();
const directConnectionManager = DirectConnectionManager.getInstance();
context.subscriptions.push(directConnectionManager);
// ensure our diagnostic collection(s) are cleared when the extension is deactivated
context.subscriptions.push(JSON_DIAGNOSTIC_COLLECTION);
// register the search decoration provider for the tree views so any matches can be highlighted
// with a dot to the right of the item label+description area
context.subscriptions.push(
vscode.window.registerFileDecorationProvider(SEARCH_DECORATION_PROVIDER),
);
// register the Copilot chat participant
const chatParticipant = vscode.chat.createChatParticipant(PARTICIPANT_ID, chatHandler);
const feedbackListener: vscode.Disposable = chatParticipant.onDidReceiveFeedback(handleFeedback);
chatParticipant.iconPath = new vscode.ThemeIcon(IconNames.CONFLUENT_LOGO);
context.subscriptions.push(chatParticipant, feedbackListener, ...registerChatTools());
// track the status bar for CCloud notices (fetched from the Statuspage Status API)
enableCCloudStatusPolling();
context.subscriptions.push(getCCloudStatusBarItem());
const docManager = DocumentMetadataManager.getInstance();
context.subscriptions.push(docManager);
const flinkProvider = FlinkSqlCodelensProvider.getInstance();
context.subscriptions.push(
vscode.languages.registerCodeLensProvider(FLINK_SQL_LANGUAGE_ID, flinkProvider),
flinkProvider,
);
// one-time cleanup of old log files from before the rotating log file stream was implemented
cleanupOldLogFiles();
await handleNewOrUpdatedExtensionInstallation();
// XXX: used for testing; do not remove
return context;
}
/** Configure any starting contextValues to use for view/menu controls during activation. */
async function setupContextValues() {
// indicate to the UI that we are running in an end-to-end testing environment, since we can't
// easily use the "testing" extension mode like we can for Mocha tests
const e2eTestEnvironment = setContextValue(
ContextValues.E2E_TESTING,
process.env.CONFLUENT_VSCODE_E2E_TESTING === "true",
);
// EXPERIMENTAL/PREVIEW: set default values for any early opt-in/-out functionality
const chatParticipantEnabled = setContextValue(
ContextValues.chatParticipantEnabled,
ENABLE_CHAT_PARTICIPANT.value,
);
// require re-selecting a cluster for the Topics/Schemas views on extension (re)start
const kafkaClusterSelected = setContextValue(ContextValues.kafkaClusterSelected, false);
const schemaRegistrySelected = setContextValue(ContextValues.schemaRegistrySelected, false);
// constants for easier `when` clause matching in package.json; not updated dynamically
const openInCCloudResources = setContextValue(ContextValues.CCLOUD_RESOURCES, [
"ccloud-environment",
"flinkable-ccloud-environment",
"ccloud-kafka-cluster",
"ccloud-flinkable-kafka-cluster",
"ccloud-kafka-topic",
"ccloud-kafka-topic-with-schema",
// consumer groups and consumers have dynamic context values based on state; can't include here
"ccloud-schema-registry",
"ccloud-flink-compute-pool",
"ccloud-flink-statement",
"ccloud-flink-statement-not-viewable",
]);
// allow for easier matching using "in" clauses for our Resources/Topics/Schemas views
const viewsWithResources = setContextValue(ContextValues.VIEWS_WITH_RESOURCES, [
"confluent-resources",
"confluent-topics",
"confluent-schemas",
"confluent-flink-statements",
"confluent-flink-database",
]);
// enables the "Copy ID" command; these resources must have the "id" property
const resourcesWithIds = setContextValue(ContextValues.RESOURCES_WITH_ID, [
"ccloud-environment", // direct/local environments only have internal IDs
"flinkable-ccloud-environment",
"ccloud-kafka-cluster",
"ccloud-flinkable-kafka-cluster",
// consumer groups and consumers have dynamic context values based on state; can't include here
"ccloud-schema-registry", // only ID, no name
"ccloud-flink-compute-pool",
"ccloud-flink-artifact",
"local-kafka-cluster",
"local-schema-registry",
"direct-kafka-cluster",
"direct-schema-registry",
]);
// enables the "Copy Name" command; these resources must have the "name" property
const resourcesWithNames = setContextValue(ContextValues.RESOURCES_WITH_NAMES, [
"ccloud-environment",
"flinkable-ccloud-environment",
"ccloud-kafka-cluster",
"ccloud-flinkable-kafka-cluster",
"ccloud-flink-compute-pool",
"ccloud-flink-artifact",
"ccloud-flink-udf",
"ccloud-flink-relation-base-table",
"ccloud-flink-relation-view",
"ccloud-flink-relation-external-table",
"ccloud-flink-relation-system-table",
"ccloud-flink-column",
"ccloud-flink-type-field",
"ccloud-flink-type-field-synthetic",
"local-kafka-cluster",
"direct-kafka-cluster",
// topics and Flink statements also have names, but their context values vary wildly and must be regex-matched
]);
/**
* CCloud and Local Kafka Clusters and all Schema Registries have REST URI / URLs
* (Direct Kafka clusters might be running the REST gateway, but we can't guarantee it)
*/
const resourcesWithURIs = setContextValue(ContextValues.RESOURCES_WITH_URIS, [
"ccloud-kafka-cluster",
"ccloud-flinkable-kafka-cluster",
"ccloud-schema-registry",
"local-kafka-cluster",
"local-schema-registry",
"direct-schema-registry",
]);
const diffableResources = setContextValue(ContextValues.DIFFABLE_RESOURCES, [
SCHEMA_URI_SCHEME,
MESSAGE_URI_SCHEME,
]);
// Default to Docker daemon not being available until proven otherwise
const dockerAvailable = setContextValue(ContextValues.dockerServiceAvailable, false);
await Promise.all([
e2eTestEnvironment,
chatParticipantEnabled,
kafkaClusterSelected,
schemaRegistrySelected,
openInCCloudResources,
viewsWithResources,
resourcesWithIds,
resourcesWithNames,
resourcesWithURIs,
diffableResources,
dockerAvailable,
]);
}
/**
* Pass initial {@link vscode.WorkspaceConfiguration} settings to the sidecar's Preferences API on
* startup to ensure the sidecar is in sync with the extension's settings before other requests are made.
* @returns A {@link vscode.Disposable} for the extension settings listener
*/
async function setupPreferences(): Promise<vscode.Disposable> {
// pass initial configs to the sidecar on startup
await updatePreferences();
logger.info("Initial preferences passed to sidecar");
return createConfigChangeListener();
}
/**
* Set up the feature flags for the extension. This includes setting the defaults, initializing the
* LaunchDarkly client, and checking if the extension is enabled or disabled.
*/
async function setupFeatureFlags(): Promise<void> {
// if the client initializes properly, it will set the initial flag values. otherwise, we'll use
// the local defaults from `setFlagDefaults()`
resetFlagDefaults();
const client = await getLaunchDarklyClient();
if (client) {
// wait a few seconds for the LD client to initialize for the first time, because if we
// continue to use the client before it's ready, it will return the default values for all flags
const initialized = await Promise.race([
client
.waitForInitialization()
.then(() => true)
.catch((error) => {
logger.error("Feature flag client failed to initialize:", error);
return false;
}),
new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 3000)),
]);
logger.info(`Feature flag client initialization ${initialized ? "completed" : "failed"}`);
}
const disabledMessage: string | undefined = await checkForExtensionDisabledReason();
if (disabledMessage) {
void showExtensionDisabledNotification(disabledMessage);
throw new Error(disabledMessage);
}
}
/** Return view provider + name fragment pairs for auto-registering refresh() commands. */
export function getRefreshableViewProviders(): RefreshableTreeViewProvider[] {
// When adding a new refreshable view, also update the test block
// "Refreshable views tests" in extension.test.ts.
const refreshables = [
ResourceViewProvider.getInstance(),
TopicViewProvider.getInstance(),
SchemasViewProvider.getInstance(),
FlinkStatementsViewProvider.getInstance(),
FlinkDatabaseViewProvider.getInstance(),
];
return refreshables;
}
/**
* Handle any necessary migrations for globalState/workspaceState/secrets that need to happen
* before the extension can proceed.
*/
async function setupStorage(): Promise<void> {
await migrateStorageIfNeeded();
logger.info("Extension state/storage migrations completed");
}
/**
* Register the Confluent Cloud authentication provider with the VS Code authentication API, set up
* the initial connection state context values, and attempt to get a session to trigger the initial
* auth badge for signing in.
* @returns A {@link vscode.Disposable} for the auth provider
*/
async function setupAuthProvider(): Promise<vscode.Disposable[]> {
const provider = ConfluentCloudAuthProvider.getInstance();
const providerDisposable = vscode.authentication.registerAuthenticationProvider(
AUTH_PROVIDER_ID,
AUTH_PROVIDER_LABEL,
provider,
{
supportsMultipleAccounts: false, // this is the default, but just to be explicit
},
);
// set the initial connection states of our main views; these will be adjusted by the following:
// - ccloudConnectionAvailable: `true/false` if the auth provider has a valid CCloud connection
// - localKafkaClusterAvailable: `true/false` if the Resources view loads/refreshes and we can
// discover a local Kafka cluster
// - localSchemaRegistryAvailable: `true/false` if the Resources view loads/refreshes and we can
// discover a local Schema Registry
await Promise.all([
setContextValue(ContextValues.ccloudConnectionAvailable, false),
setContextValue(ContextValues.localKafkaClusterAvailable, false),
setContextValue(ContextValues.localSchemaRegistryAvailable, false),
]);
// attempt to get a session to trigger the initial auth badge for signing in
const cloudSession = await getCCloudAuthSession();
// Send an Identify event to Segment and LaunchDarkly with the session info if available
if (cloudSession) {
sendTelemetryIdentifyEvent({
eventName: UserEvent.ExtensionActivation,
userInfo: undefined,
session: cloudSession,
});
const launchDarklyClient = await getLaunchDarklyClient();
if (launchDarklyClient) {
await launchDarklyClient.identify({ key: cloudSession.account.id });
}
}
logger.info("Confluent Cloud auth provider registered");
return [providerDisposable, provider];
}
/** Set up the document providers for custom URI schemes. */
function setupDocumentProviders(): vscode.Disposable[] {
const disposables: vscode.Disposable[] = [];
// any document providers set here must provide their own `scheme` to register with
const providerClasses = [
SchemaDocumentProvider,
MessageDocumentProvider,
FlinkStatementDocumentProvider,
];
for (const providerClass of providerClasses) {
const provider = new providerClass();
disposables.push(
vscode.workspace.registerTextDocumentContentProvider(provider.scheme, provider),
);
}
logger.info("Document providers registered");
return disposables;
}
export function deactivate() {
// dispose of the telemetry logger
try {
getTelemetryLogger().dispose();
} catch (e) {
const msg = "Error disposing telemetry logger during extension deactivation";
logError(new Error(msg, { cause: e }), msg, { extra: {} });
}
void closeSentryClient();
disposeLaunchDarklyClient();
disableCCloudStatusPolling();
// close the sidecar log file stream, if it exists
closeFormattedSidecarLogStream();
// close the file stream used with EXTENSION_OUTPUT_CHANNEL -- needs to be done last to avoid any other cleanup logging attempting to write to the file stream
EXTENSION_OUTPUT_CHANNEL.dispose();
console.info("Extension deactivated");
}
/**
* Rehydrate the direct connections from the secret storage at startup time, informing
* the sidecar about them.
*
* Also go ahead and create the local connection in the sidecar if it doesn't exist yet
* (as would be the case if opening a second workspace talking to the sidecar).
*/
export async function rehydrateConnections(): Promise<void> {
const createConnectionPromises = [
// Rehydrate the direct connections from secret storage.
async () => {
try {
await DirectConnectionManager.getInstance().rehydrateConnections();
} catch (error) {
logger.error("Failed to rehydrate direct connections", { error });
}
},
// Create the local connection if it doesn't exist yet.
// (Must happen before we try to GraphQL query it, for instance.)
async () => {
if (!(await getLocalConnection())) {
try {
await createLocalConnection();
} catch (error) {
logger.error("Failed to create local connection for rehydration", { error });
}
}
},
// Do not need to pre-create the distinquished ccloud connection, as its creation is
// explicitly handled in the auth provider, and no codepath should try to GraphQL query
// it unless hasCCloudAuthSession() is true, which will only be the case if the
// ccloud connection exists and is valid.
];
await Promise.all(createConnectionPromises.map((fn) => fn()));
logger.info("Rehydrated direct connections and created local connection if needed");
}