@dbx-tools/appkit 0.9.214 → 0.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -442
- package/index.ts +10 -5
- package/lib/index.d.ts +10 -5
- package/lib/index.js +9 -5
- package/lib/src/appkit.d.ts +5 -6
- package/lib/src/appkit.js +9 -7
- package/lib/src/cache-storage.js +3 -3
- package/lib/src/debug/plugin.d.ts +2 -12
- package/lib/src/debug/plugin.js +4 -4
- package/lib/src/event-stream.d.ts +33 -0
- package/lib/src/event-stream.js +35 -0
- package/lib/src/http.d.ts +10 -0
- package/lib/src/http.js +20 -0
- package/lib/src/identity.d.ts +0 -12
- package/lib/src/identity.js +3 -70
- package/lib/src/interceptor.d.ts +2 -12
- package/lib/src/interceptor.js +4 -4
- package/lib/src/lakebase-resolver.js +18 -215
- package/lib/src/openapi-tool.js +3 -3
- package/lib/src/provision.js +3 -3
- package/lib/src/telemetry.d.ts +1 -1
- package/lib/src/telemetry.js +2 -2
- package/lib/src/workspace-client.d.ts +40 -0
- package/lib/src/workspace-client.js +290 -0
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/package.json +15 -15
- package/src/appkit.ts +12 -10
- package/src/cache-storage.ts +2 -2
- package/src/debug/plugin.ts +3 -2
- package/src/event-stream.ts +60 -0
- package/src/http.ts +20 -0
- package/src/identity.ts +1 -72
- package/src/interceptor.ts +9 -3
- package/src/lakebase-resolver.ts +34 -285
- package/src/openapi-tool.ts +2 -2
- package/src/provision.ts +2 -3
- package/src/telemetry.ts +1 -1
- package/src/workspace-client.ts +415 -0
- package/lib/src/databricks.d.ts +0 -63
- package/lib/src/databricks.js +0 -107
- package/src/databricks.ts +0 -151
package/src/identity.ts
CHANGED
|
@@ -51,12 +51,9 @@
|
|
|
51
51
|
* @module
|
|
52
52
|
*/
|
|
53
53
|
|
|
54
|
-
import { ConfigurationError
|
|
54
|
+
import { ConfigurationError } from "@databricks/appkit";
|
|
55
55
|
import { string, ENV_ONLY } from "@dbx-tools/core";
|
|
56
56
|
import {
|
|
57
|
-
log,
|
|
58
|
-
toError,
|
|
59
|
-
isLevelEnabled,
|
|
60
57
|
trimToNull,
|
|
61
58
|
ACCESS_TOKEN_HEADER,
|
|
62
59
|
USER_ID_HEADER,
|
|
@@ -148,71 +145,3 @@ export function useServicePrincipal(mode: IdentityMode, req?: HeaderBearing): bo
|
|
|
148
145
|
if (mode === "user") return false;
|
|
149
146
|
return requestAccessToken(req) === undefined;
|
|
150
147
|
}
|
|
151
|
-
|
|
152
|
-
const logger = log.logger("appkit");
|
|
153
|
-
const skippedAsUser = new Set<string>();
|
|
154
|
-
const AS_USER_SKIP_WARN = "Skipping user impersonation";
|
|
155
|
-
const AS_USER_PATCHED = Symbol.for("dbx-tools.appkit.asUserDevLog");
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* In development, keep AppKit `asUser` behavior. The first missing-token skip
|
|
159
|
-
* for a forwarded email or user id uses AppKit's own warn; later skips for
|
|
160
|
-
* that user, and every skip with no forwarded identity, are silent. Request
|
|
161
|
-
* objects are not a stable key: each plugin call typically has its own `req`.
|
|
162
|
-
*
|
|
163
|
-
* No-op outside development, when `Plugin.asUser` is missing or not a
|
|
164
|
-
* function, or if the prototype cannot be rewritten. Failures never throw:
|
|
165
|
-
* AppKit keeps its original `asUser`. Extra arguments are forwarded so a
|
|
166
|
-
* later signature change still reaches the original method.
|
|
167
|
-
*/
|
|
168
|
-
export function installAsUserDevelopmentPatch(): void {
|
|
169
|
-
if (process.env.NODE_ENV !== "development") return;
|
|
170
|
-
try {
|
|
171
|
-
const proto = Plugin.prototype as unknown as Record<PropertyKey, unknown>;
|
|
172
|
-
if (proto[AS_USER_PATCHED] === true) return;
|
|
173
|
-
const original = proto.asUser;
|
|
174
|
-
if (typeof original !== "function") return;
|
|
175
|
-
proto[AS_USER_PATCHED] = true;
|
|
176
|
-
proto.asUser = function patchedAsUser(this: unknown, req: unknown, ...rest: unknown[]) {
|
|
177
|
-
const headers = asHeaderBearing(req);
|
|
178
|
-
const args = [req, ...rest];
|
|
179
|
-
if (!headers || requestAccessToken(headers) !== undefined) {
|
|
180
|
-
return Function.prototype.apply.call(original, this, args);
|
|
181
|
-
}
|
|
182
|
-
return withAsUserSkipWarnSuppressed(headers, () =>
|
|
183
|
-
Function.prototype.apply.call(original, this, args),
|
|
184
|
-
);
|
|
185
|
-
};
|
|
186
|
-
} catch (error) {
|
|
187
|
-
logger.debug("asUser development patch skipped", { error: toError(error) });
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
function asHeaderBearing(req: unknown): HeaderBearing | undefined {
|
|
192
|
-
if (req === null || typeof req !== "object") return undefined;
|
|
193
|
-
if (typeof (req as HeaderBearing).header !== "function") return undefined;
|
|
194
|
-
return req as HeaderBearing;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function withAsUserSkipWarnSuppressed<T>(req: HeaderBearing, fn: () => T): T {
|
|
198
|
-
const user = requestUserEmail(req) ?? requestUserId(req);
|
|
199
|
-
if (user && !skippedAsUser.has(user)) {
|
|
200
|
-
skippedAsUser.add(user);
|
|
201
|
-
return fn();
|
|
202
|
-
}
|
|
203
|
-
const warn = console.warn;
|
|
204
|
-
console.warn = (...args: unknown[]) => {
|
|
205
|
-
if (
|
|
206
|
-
!isLevelEnabled("debug") &&
|
|
207
|
-
args.some((value) => typeof value === "string" && value.includes(AS_USER_SKIP_WARN))
|
|
208
|
-
) {
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
|
-
warn.apply(console, args as Parameters<typeof console.warn>);
|
|
212
|
-
};
|
|
213
|
-
try {
|
|
214
|
-
return fn();
|
|
215
|
-
} finally {
|
|
216
|
-
console.warn = warn;
|
|
217
|
-
}
|
|
218
|
-
}
|
package/src/interceptor.ts
CHANGED
|
@@ -19,7 +19,13 @@
|
|
|
19
19
|
* @module
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
defineManifest,
|
|
24
|
+
Plugin,
|
|
25
|
+
toPlugin,
|
|
26
|
+
type BasePluginConfig,
|
|
27
|
+
type PluginManifest,
|
|
28
|
+
} from "@databricks/appkit";
|
|
23
29
|
import { log, toError } from "@dbx-tools/shared-core";
|
|
24
30
|
import type { LakebaseConnection } from "./lakebase-resolver.ts";
|
|
25
31
|
|
|
@@ -163,14 +169,14 @@ function hasOnLifecycle(context: unknown): context is LifecycleContextLike {
|
|
|
163
169
|
* events. It owns no routes, config surface, or exports.
|
|
164
170
|
*/
|
|
165
171
|
export class LifecycleBridgePlugin extends Plugin<LifecycleBridgeConfig> {
|
|
166
|
-
static manifest = {
|
|
172
|
+
static manifest = defineManifest<"dbxToolsLifecycleBridge">({
|
|
167
173
|
name: "dbxToolsLifecycleBridge",
|
|
168
174
|
displayName: "Lifecycle Bridge",
|
|
169
175
|
description: "Relays AppKit lifecycle events to the createApp interceptor context.",
|
|
170
176
|
stability: "beta",
|
|
171
177
|
hidden: true,
|
|
172
178
|
resources: { required: [], optional: [] },
|
|
173
|
-
} satisfies PluginManifest<"dbxToolsLifecycleBridge"
|
|
179
|
+
} satisfies PluginManifest<"dbxToolsLifecycleBridge">);
|
|
174
180
|
|
|
175
181
|
override async setup(): Promise<void> {
|
|
176
182
|
const runtime = this.config.runtime;
|
package/src/lakebase-resolver.ts
CHANGED
|
@@ -40,8 +40,8 @@ import {
|
|
|
40
40
|
ExecutionError,
|
|
41
41
|
getUsernameWithApiLookup,
|
|
42
42
|
type LakebasePool,
|
|
43
|
-
type WorkspaceClient as AppKitWorkspaceClient,
|
|
44
43
|
ValidationError,
|
|
44
|
+
type WorkspaceClient,
|
|
45
45
|
} from "@databricks/appkit";
|
|
46
46
|
import { projectUtils, resolveValue } from "@dbx-tools/core";
|
|
47
47
|
import {
|
|
@@ -55,26 +55,19 @@ import {
|
|
|
55
55
|
import {
|
|
56
56
|
log,
|
|
57
57
|
sleep,
|
|
58
|
-
toError,
|
|
59
|
-
isRecord,
|
|
60
58
|
tcpPortSchema,
|
|
61
59
|
databricksEnvironmentNames,
|
|
62
60
|
toSlugWithOptions,
|
|
63
61
|
MAX_TCP_PORT,
|
|
64
62
|
} from "@dbx-tools/shared-core";
|
|
65
|
-
import {
|
|
66
|
-
|
|
67
|
-
import { createWorkspaceClient, toContext } from "./databricks.ts";
|
|
63
|
+
import { createWorkspaceClient } from "./workspace-client.ts";
|
|
68
64
|
|
|
69
65
|
const logger = log.logger("lakebase-resolver");
|
|
70
|
-
const API_BASE = "/api/2.0/postgres";
|
|
71
66
|
const DEFAULT_PORT = 5432;
|
|
72
67
|
const DEFAULT_SSL_MODE: SslMode = "require";
|
|
73
68
|
const DEFAULT_PG_VERSION = 17;
|
|
74
69
|
/** Lakebase project ids: `^[a-z][a-z0-9-]{0,61}[a-z0-9]$`. */
|
|
75
70
|
const PROJECT_ID_MAX_LEN = 63;
|
|
76
|
-
const OPERATION_TIMEOUT_MS = 5 * 60_000;
|
|
77
|
-
const OPERATION_POLL_MS = 2_000;
|
|
78
71
|
const ENDPOINT_READY_TIMEOUT_MS = 5 * 60_000;
|
|
79
72
|
const ENDPOINT_READY_POLL_MS = 2_000;
|
|
80
73
|
/** Ceiling on a single backoff step, so a long wait still polls regularly. */
|
|
@@ -134,110 +127,15 @@ export function captureServicePrincipalPool(pool: LakebasePool): LakebasePool {
|
|
|
134
127
|
return routingPool.activePool?.call(pool) ?? pool;
|
|
135
128
|
}
|
|
136
129
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
});
|
|
147
|
-
type Project = z.infer<typeof projectSchema>;
|
|
148
|
-
|
|
149
|
-
const endpointSchema = z.object({
|
|
150
|
-
name: z
|
|
151
|
-
.string()
|
|
152
|
-
.optional()
|
|
153
|
-
.describe("Full resource path: projects/{p}/branches/{b}/endpoints/{e}."),
|
|
154
|
-
uid: z.string().optional().describe("Stable endpoint uid assigned by Lakebase."),
|
|
155
|
-
status: z
|
|
156
|
-
.object({
|
|
157
|
-
endpoint_type: z
|
|
158
|
-
.string()
|
|
159
|
-
.optional()
|
|
160
|
-
.describe("Endpoint role, such as ENDPOINT_TYPE_READ_WRITE."),
|
|
161
|
-
hosts: z
|
|
162
|
-
.object({
|
|
163
|
-
host: z.string().optional().describe("Writable primary hostname."),
|
|
164
|
-
read_only_host: z
|
|
165
|
-
.string()
|
|
166
|
-
.optional()
|
|
167
|
-
.describe("Read-only replica hostname when present."),
|
|
168
|
-
})
|
|
169
|
-
.optional()
|
|
170
|
-
.describe("Resolved hostnames. hosts.host is the writable primary."),
|
|
171
|
-
current_state: z
|
|
172
|
-
.string()
|
|
173
|
-
.optional()
|
|
174
|
-
.describe("Compute state: INITIALIZING, STARTING, READY, IDLE, and later values."),
|
|
175
|
-
})
|
|
176
|
-
.optional()
|
|
177
|
-
.describe("Server-side state. Runtime hostnames live here, not in the spec block."),
|
|
178
|
-
});
|
|
179
|
-
type Endpoint = z.infer<typeof endpointSchema>;
|
|
180
|
-
|
|
181
|
-
const branchSchema = z.object({
|
|
182
|
-
name: z.string().optional().describe("Full resource path: projects/{p}/branches/{b}."),
|
|
183
|
-
status: z
|
|
184
|
-
.object({
|
|
185
|
-
default: z
|
|
186
|
-
.boolean()
|
|
187
|
-
.optional()
|
|
188
|
-
.describe("True for the project's default branch, such as production."),
|
|
189
|
-
current_state: z.string().optional().describe("Branch compute state reported by Lakebase."),
|
|
190
|
-
})
|
|
191
|
-
.optional(),
|
|
192
|
-
});
|
|
193
|
-
type Branch = z.infer<typeof branchSchema>;
|
|
194
|
-
|
|
195
|
-
const databaseSchema = z.object({
|
|
196
|
-
name: z
|
|
197
|
-
.string()
|
|
198
|
-
.optional()
|
|
199
|
-
.describe("Full resource path: projects/{p}/branches/{b}/databases/{d}."),
|
|
200
|
-
status: z
|
|
201
|
-
.object({
|
|
202
|
-
postgres_database: z
|
|
203
|
-
.string()
|
|
204
|
-
.optional()
|
|
205
|
-
.describe(
|
|
206
|
-
"Actual Postgres database name used as PGDATABASE. May differ from the resource id.",
|
|
207
|
-
),
|
|
208
|
-
})
|
|
209
|
-
.optional(),
|
|
210
|
-
});
|
|
211
|
-
type Database = z.infer<typeof databaseSchema>;
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* Lakebase REST list responses follow the Google AIP convention:
|
|
215
|
-
* `{ <plural-resource>: T[], next_page_token?: string }`. We only read
|
|
216
|
-
* the first page; for auto-config's "pick something sensible" semantics the
|
|
217
|
-
* cap is fine.
|
|
218
|
-
*/
|
|
219
|
-
const listResponseSchema = z.object({
|
|
220
|
-
next_page_token: z
|
|
221
|
-
.string()
|
|
222
|
-
.optional()
|
|
223
|
-
.describe("AIP page token. Only the first page is consumed."),
|
|
224
|
-
projects: z.array(projectSchema).optional(),
|
|
225
|
-
branches: z.array(branchSchema).optional(),
|
|
226
|
-
endpoints: z.array(endpointSchema).optional(),
|
|
227
|
-
databases: z.array(databaseSchema).optional(),
|
|
228
|
-
});
|
|
229
|
-
|
|
230
|
-
/**
|
|
231
|
-
* Long-running operation envelope returned by mutating REST calls.
|
|
232
|
-
* `done: true` means terminal; check `error` before reading `response`.
|
|
233
|
-
*/
|
|
234
|
-
const operationSchema = z.object({
|
|
235
|
-
name: z.string().optional().describe("Operation resource name."),
|
|
236
|
-
done: z.boolean().optional().describe("True when the operation is terminal."),
|
|
237
|
-
error: z.unknown().optional().describe("Error payload present when the operation failed."),
|
|
238
|
-
response: z.unknown().optional().describe("Result payload present when the operation succeeded."),
|
|
239
|
-
});
|
|
240
|
-
type Operation = z.infer<typeof operationSchema>;
|
|
130
|
+
type PostgresClient = WorkspaceClient["postgres"];
|
|
131
|
+
type Project = NonNullable<Awaited<ReturnType<PostgresClient["listProjects"]>>["projects"]>[number];
|
|
132
|
+
type Branch = NonNullable<Awaited<ReturnType<PostgresClient["listBranches"]>>["branches"]>[number];
|
|
133
|
+
type Endpoint = NonNullable<
|
|
134
|
+
Awaited<ReturnType<PostgresClient["listEndpoints"]>>["endpoints"]
|
|
135
|
+
>[number];
|
|
136
|
+
type Database = NonNullable<
|
|
137
|
+
Awaited<ReturnType<PostgresClient["listDatabases"]>>["databases"]
|
|
138
|
+
>[number];
|
|
241
139
|
|
|
242
140
|
/** `PGPORT` must land inside the TCP port range. */
|
|
243
141
|
const portSchema = tcpPortSchema;
|
|
@@ -490,93 +388,17 @@ export async function applyLakebaseEnv(
|
|
|
490
388
|
return { resolved, ...(user ? { user } : {}) };
|
|
491
389
|
}
|
|
492
390
|
|
|
493
|
-
type WorkspaceClient = ReturnType<AppKitWorkspaceClient["toLegacyWorkspaceClient"]>;
|
|
494
391
|
type WorkspaceClientResolver = () => Promise<WorkspaceClient>;
|
|
495
392
|
|
|
496
393
|
/** Resolve one auth-backed SDK client lazily and reuse it across this operation. */
|
|
497
394
|
function workspaceClientResolver(config?: LakebaseResolverInputs): WorkspaceClientResolver {
|
|
498
395
|
let pending: Promise<WorkspaceClient> | undefined;
|
|
499
396
|
return () =>
|
|
500
|
-
(pending ??= createWorkspaceClient({ profile: config?.bundleProfile })
|
|
501
|
-
client.toLegacyWorkspaceClient(),
|
|
502
|
-
));
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
/** The SDK `Context` accepted by the workspace client's own copy of the SDK. */
|
|
506
|
-
type ApiRequestContext = NonNullable<Parameters<WorkspaceClient["apiClient"]["request"]>[1]>;
|
|
507
|
-
|
|
508
|
-
/**
|
|
509
|
-
* Adapt an {@link AbortSignal} into the api client's cancellation context.
|
|
510
|
-
* AppKit resolves a different copy of `@databricks/sdk-experimental` than this
|
|
511
|
-
* package does, and `Context` carries a private field, so the two declarations
|
|
512
|
-
* are nominally incompatible even though the api client only reads
|
|
513
|
-
* `cancellationToken` and `logger` off the object.
|
|
514
|
-
*/
|
|
515
|
-
function requestContext(signal: AbortSignal | undefined): ApiRequestContext | undefined {
|
|
516
|
-
return signal ? (toContext(signal) as unknown as ApiRequestContext) : undefined;
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
/**
|
|
520
|
-
* Validate a Lakebase REST body. The full payload is logged rather than thrown
|
|
521
|
-
* so a client never receives upstream detail.
|
|
522
|
-
*/
|
|
523
|
-
function parseResponse<T>(schema: z.ZodType<T>, path: string, body: unknown): T {
|
|
524
|
-
const parsed = schema.safeParse(body);
|
|
525
|
-
if (parsed.success) return parsed.data;
|
|
526
|
-
logger.error("autopg: unexpected Lakebase API response", {
|
|
527
|
-
path,
|
|
528
|
-
issues: parsed.error.issues,
|
|
529
|
-
});
|
|
530
|
-
throw new ExecutionError("Lakebase API returned an unexpected response", { context: { path } });
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
/** GET helper that validates the JSON body and forwards cancellation. */
|
|
534
|
-
async function getJson<T>(
|
|
535
|
-
ws: WorkspaceClient,
|
|
536
|
-
path: string,
|
|
537
|
-
schema: z.ZodType<T>,
|
|
538
|
-
signal?: AbortSignal,
|
|
539
|
-
): Promise<T> {
|
|
540
|
-
const res = await ws.apiClient.request(
|
|
541
|
-
{
|
|
542
|
-
path,
|
|
543
|
-
method: "GET",
|
|
544
|
-
headers: new Headers({ Accept: "application/json" }),
|
|
545
|
-
raw: false,
|
|
546
|
-
},
|
|
547
|
-
requestContext(signal),
|
|
548
|
-
);
|
|
549
|
-
return parseResponse(schema, path, res);
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
/** POST helper for create / mutate calls; validates the JSON body. */
|
|
553
|
-
async function postJson<T>(
|
|
554
|
-
ws: WorkspaceClient,
|
|
555
|
-
path: string,
|
|
556
|
-
schema: z.ZodType<T>,
|
|
557
|
-
body: unknown,
|
|
558
|
-
query?: Record<string, string>,
|
|
559
|
-
signal?: AbortSignal,
|
|
560
|
-
): Promise<T> {
|
|
561
|
-
const res = await ws.apiClient.request(
|
|
562
|
-
{
|
|
563
|
-
path,
|
|
564
|
-
method: "POST",
|
|
565
|
-
query,
|
|
566
|
-
headers: new Headers({
|
|
567
|
-
Accept: "application/json",
|
|
568
|
-
"Content-Type": "application/json",
|
|
569
|
-
}),
|
|
570
|
-
raw: false,
|
|
571
|
-
payload: body,
|
|
572
|
-
},
|
|
573
|
-
requestContext(signal),
|
|
574
|
-
);
|
|
575
|
-
return parseResponse(schema, path, res);
|
|
397
|
+
(pending ??= Promise.resolve(createWorkspaceClient({ profile: config?.bundleProfile })));
|
|
576
398
|
}
|
|
577
399
|
|
|
578
400
|
async function listProjects(ws: WorkspaceClient, signal?: AbortSignal): Promise<Project[]> {
|
|
579
|
-
const res = await
|
|
401
|
+
const res = await ws.postgres.listProjects({}, { signal });
|
|
580
402
|
return res.projects ?? [];
|
|
581
403
|
}
|
|
582
404
|
|
|
@@ -585,12 +407,7 @@ async function listBranches(
|
|
|
585
407
|
project: string,
|
|
586
408
|
signal?: AbortSignal,
|
|
587
409
|
): Promise<Branch[]> {
|
|
588
|
-
const res = await
|
|
589
|
-
ws,
|
|
590
|
-
`${API_BASE}/projects/${project}/branches`,
|
|
591
|
-
listResponseSchema,
|
|
592
|
-
signal,
|
|
593
|
-
);
|
|
410
|
+
const res = await ws.postgres.listBranches({ parent: `projects/${project}` }, { signal });
|
|
594
411
|
return res.branches ?? [];
|
|
595
412
|
}
|
|
596
413
|
|
|
@@ -600,11 +417,9 @@ async function listEndpoints(
|
|
|
600
417
|
branch: string,
|
|
601
418
|
signal?: AbortSignal,
|
|
602
419
|
): Promise<Endpoint[]> {
|
|
603
|
-
const res = await
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
listResponseSchema,
|
|
607
|
-
signal,
|
|
420
|
+
const res = await ws.postgres.listEndpoints(
|
|
421
|
+
{ parent: `projects/${project}/branches/${branch}` },
|
|
422
|
+
{ signal },
|
|
608
423
|
);
|
|
609
424
|
return res.endpoints ?? [];
|
|
610
425
|
}
|
|
@@ -615,11 +430,9 @@ async function listDatabases(
|
|
|
615
430
|
branch: string,
|
|
616
431
|
signal?: AbortSignal,
|
|
617
432
|
): Promise<Database[]> {
|
|
618
|
-
const res = await
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
listResponseSchema,
|
|
622
|
-
signal,
|
|
433
|
+
const res = await ws.postgres.listDatabases(
|
|
434
|
+
{ parent: `projects/${project}/branches/${branch}` },
|
|
435
|
+
{ signal },
|
|
623
436
|
);
|
|
624
437
|
return res.databases ?? [];
|
|
625
438
|
}
|
|
@@ -631,11 +444,9 @@ async function getEndpoint(
|
|
|
631
444
|
endpointId: string,
|
|
632
445
|
signal?: AbortSignal,
|
|
633
446
|
): Promise<Endpoint> {
|
|
634
|
-
return
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
endpointSchema,
|
|
638
|
-
signal,
|
|
447
|
+
return ws.postgres.getEndpoint(
|
|
448
|
+
{ name: `projects/${project}/branches/${branch}/endpoints/${endpointId}` },
|
|
449
|
+
{ signal },
|
|
639
450
|
);
|
|
640
451
|
}
|
|
641
452
|
|
|
@@ -763,15 +574,14 @@ async function ensureProject(
|
|
|
763
574
|
): Promise<string> {
|
|
764
575
|
logger.warn("autopg: no projects found; creating", { project: projectId });
|
|
765
576
|
try {
|
|
766
|
-
const
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
{
|
|
772
|
-
signal,
|
|
577
|
+
const operation = await ws.postgres.createProject(
|
|
578
|
+
{
|
|
579
|
+
projectId,
|
|
580
|
+
project: { spec: { pgVersion: DEFAULT_PG_VERSION } },
|
|
581
|
+
},
|
|
582
|
+
{ signal },
|
|
773
583
|
);
|
|
774
|
-
await
|
|
584
|
+
await operation.wait({ signal, timeout: ENDPOINT_READY_TIMEOUT_MS });
|
|
775
585
|
logger.info("autopg: created project", { project: projectId });
|
|
776
586
|
} catch (err) {
|
|
777
587
|
if (!isAlreadyExistsError(err)) throw err;
|
|
@@ -805,67 +615,6 @@ function isAlreadyExistsError(error: unknown): boolean {
|
|
|
805
615
|
return false;
|
|
806
616
|
}
|
|
807
617
|
|
|
808
|
-
/**
|
|
809
|
-
* Reduce a Lakebase operation failure to an error safe to propagate: the
|
|
810
|
-
* operation name plus whatever code the payload carries. The payload itself can
|
|
811
|
-
* echo request context, so it goes to the log instead.
|
|
812
|
-
*/
|
|
813
|
-
function operationFailed(opName: string, opError: unknown): ExecutionError {
|
|
814
|
-
logger.error("autopg: operation failed", {
|
|
815
|
-
operation: opName,
|
|
816
|
-
error: toError(opError),
|
|
817
|
-
});
|
|
818
|
-
const code = isRecord(opError) ? (opError.code ?? opError.reason) : undefined;
|
|
819
|
-
return new ExecutionError(`Lakebase operation failed: ${opName}`, {
|
|
820
|
-
context: {
|
|
821
|
-
operation: opName,
|
|
822
|
-
errorCode: typeof code === "string" || typeof code === "number" ? String(code) : "unknown",
|
|
823
|
-
},
|
|
824
|
-
});
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
/**
|
|
828
|
-
* Poll a Lakebase long-running operation until `done: true`. Returns
|
|
829
|
-
* the final operation envelope (which may carry `response` or `error`).
|
|
830
|
-
*
|
|
831
|
-
* Throws when:
|
|
832
|
-
* - the response carries an `error` field;
|
|
833
|
-
* - `op.name` is missing (nothing to poll);
|
|
834
|
-
* - the timeout elapses before `done: true`;
|
|
835
|
-
* - `signal` aborts mid-wait.
|
|
836
|
-
*/
|
|
837
|
-
async function waitForOperation(
|
|
838
|
-
ws: WorkspaceClient,
|
|
839
|
-
op: Operation,
|
|
840
|
-
signal?: AbortSignal,
|
|
841
|
-
): Promise<Operation> {
|
|
842
|
-
if (op.done) {
|
|
843
|
-
if (op.error) {
|
|
844
|
-
throw operationFailed(op.name ?? "unknown", op.error);
|
|
845
|
-
}
|
|
846
|
-
return op;
|
|
847
|
-
}
|
|
848
|
-
const opName = op.name;
|
|
849
|
-
if (!opName) {
|
|
850
|
-
throw ExecutionError.missingData("operation name");
|
|
851
|
-
}
|
|
852
|
-
const start = Date.now();
|
|
853
|
-
for (let attempt = 0; Date.now() - start < OPERATION_TIMEOUT_MS; attempt++) {
|
|
854
|
-
await pollDelay(attempt, OPERATION_POLL_MS, signal);
|
|
855
|
-
const current = await getJson(ws, `${API_BASE}/${opName}`, operationSchema, signal);
|
|
856
|
-
logger.debug("autopg: operation status", { op: opName, done: current.done });
|
|
857
|
-
if (current.done) {
|
|
858
|
-
if (current.error) {
|
|
859
|
-
throw operationFailed(opName, current.error);
|
|
860
|
-
}
|
|
861
|
-
return current;
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
throw new ExecutionError(`Lakebase operation did not complete: ${opName}`, {
|
|
865
|
-
context: { operation: opName, timeoutMs: OPERATION_TIMEOUT_MS },
|
|
866
|
-
});
|
|
867
|
-
}
|
|
868
|
-
|
|
869
618
|
/**
|
|
870
619
|
* Poll `getEndpoint` until the compute reports a usable
|
|
871
620
|
* `status.current_state`. `READY` and `IDLE` are both acceptable -
|
|
@@ -883,7 +632,7 @@ async function waitEndpointReady(
|
|
|
883
632
|
let last: Endpoint | null = null;
|
|
884
633
|
for (let attempt = 0; Date.now() - start < ENDPOINT_READY_TIMEOUT_MS; attempt++) {
|
|
885
634
|
last = await getEndpoint(ws, project, branch, endpointId, signal);
|
|
886
|
-
const state = last.status?.
|
|
635
|
+
const state = last.status?.currentState;
|
|
887
636
|
if (state && CONNECTABLE_ENDPOINT_STATES.has(state)) return last;
|
|
888
637
|
if (last.status?.hosts?.host && state !== INITIALIZING_ENDPOINT_STATE) {
|
|
889
638
|
// Compute is in some other state (STARTING, etc.) but hostname is
|
|
@@ -900,7 +649,7 @@ async function waitEndpointReady(
|
|
|
900
649
|
branch,
|
|
901
650
|
endpointId,
|
|
902
651
|
timeoutMs: ENDPOINT_READY_TIMEOUT_MS,
|
|
903
|
-
lastState: last?.status?.
|
|
652
|
+
lastState: last?.status?.currentState ?? "unknown",
|
|
904
653
|
},
|
|
905
654
|
});
|
|
906
655
|
}
|
|
@@ -962,7 +711,7 @@ async function pickEndpoint(
|
|
|
962
711
|
);
|
|
963
712
|
}
|
|
964
713
|
const primary =
|
|
965
|
-
endpoints.find((e) => e.status?.
|
|
714
|
+
endpoints.find((e) => e.status?.endpointType === READ_WRITE_ENDPOINT_TYPE) ??
|
|
966
715
|
(endpoints.length === 1 ? endpoints[0] : undefined);
|
|
967
716
|
if (!primary?.name) {
|
|
968
717
|
const names = endpoints.map((e) => e.name).filter(Boolean);
|
|
@@ -999,7 +748,7 @@ async function pickDatabase(
|
|
|
999
748
|
);
|
|
1000
749
|
}
|
|
1001
750
|
const names = databases
|
|
1002
|
-
.map((d) => d.status?.
|
|
751
|
+
.map((d) => d.status?.postgresDatabase)
|
|
1003
752
|
.filter((n): n is string => Boolean(n));
|
|
1004
753
|
const choice =
|
|
1005
754
|
names.find((n) => n === DEFAULT_DATABASE) ?? (names.length === 1 ? names[0] : undefined);
|
package/src/openapi-tool.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import {
|
|
7
|
+
import { readJsonFile } from "@dbx-tools/core";
|
|
8
8
|
import { isRecord } from "@dbx-tools/shared-core";
|
|
9
9
|
import { urlBuilder, type UrlBuilder } from "@dbx-tools/shared-core";
|
|
10
10
|
import type { JSONSchema7 } from "json-schema";
|
|
@@ -152,7 +152,7 @@ async function fetchDocument(url: URL, options: OpenApiToolsOptions): Promise<un
|
|
|
152
152
|
}
|
|
153
153
|
|
|
154
154
|
async function readDocument(path: string, signal?: AbortSignal): Promise<unknown> {
|
|
155
|
-
return
|
|
155
|
+
return readJsonFile(path, { signal });
|
|
156
156
|
}
|
|
157
157
|
|
|
158
158
|
function operationTool(
|
package/src/provision.ts
CHANGED
|
@@ -16,12 +16,11 @@
|
|
|
16
16
|
|
|
17
17
|
import { createLakebasePool, ValidationError } from "@databricks/appkit";
|
|
18
18
|
import { configUtils } from "@dbx-tools/core";
|
|
19
|
+
import { createWorkspaceClient } from "@dbx-tools/databricks";
|
|
19
20
|
import { postgresConnectionOptions, quotePostgresIdentifier } from "@dbx-tools/postgres";
|
|
20
21
|
import { log, isDatabricksAppEnv, parseList, toError, type Logger } from "@dbx-tools/shared-core";
|
|
21
22
|
import { z } from "zod";
|
|
22
23
|
|
|
23
|
-
import { createWorkspaceClient } from "./databricks.ts";
|
|
24
|
-
|
|
25
24
|
const defaultLogger = log.logger("provision");
|
|
26
25
|
|
|
27
26
|
/** Logical config key for additional Lakebase provisioning targets. */
|
|
@@ -259,7 +258,7 @@ export async function provisionLakebaseAccess(
|
|
|
259
258
|
// (host/database/endpoint) but not the identity, so createLakebasePool's
|
|
260
259
|
// synchronous username lookup would otherwise throw. The auth-backed AppKit
|
|
261
260
|
// client retains dbx-tools profile selection and interactive CLI recovery.
|
|
262
|
-
const workspaceClient =
|
|
261
|
+
const workspaceClient = await createWorkspaceClient();
|
|
263
262
|
const pool = createLakebasePool(
|
|
264
263
|
postgresConnectionOptions({
|
|
265
264
|
user: role,
|
package/src/telemetry.ts
CHANGED
|
@@ -163,7 +163,7 @@ function requireNativeTracerProvider(manager: NativeTelemetryManager): TracerPro
|
|
|
163
163
|
|
|
164
164
|
/**
|
|
165
165
|
* Extend AppKit's native HTTP request filter without registering a second HTTP
|
|
166
|
-
* instrumentation. AppKit
|
|
166
|
+
* instrumentation. AppKit owns the instrumentation but does not expose a
|
|
167
167
|
* public filter option, so this compatibility hook mutates its existing
|
|
168
168
|
* singleton before `createApp()` registers it.
|
|
169
169
|
*/
|