@dbx-tools/appkit 0.9.189 → 0.9.193

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/src/databricks.ts CHANGED
@@ -17,11 +17,7 @@ import {
17
17
  } from "@databricks/appkit";
18
18
  import type { CancellationToken } from "@databricks/sdk-experimental";
19
19
  import { Context } from "@databricks/sdk-experimental";
20
- import {
21
- type AuthClient,
22
- type DatabricksAuthOptions,
23
- createAuthClient,
24
- } from "@dbx-tools/auth";
20
+ import { type AuthClient, type DatabricksAuthOptions, createAuthClient } from "@dbx-tools/auth";
25
21
  import { tieAbortSignal } from "@dbx-tools/shared-core";
26
22
 
27
23
  const workspaceAuth = new WeakMap<WorkspaceClient, AuthClient>();
@@ -485,8 +485,7 @@ export async function applyLakebaseEnv(
485
485
  applyLakebaseToEnv(resolved);
486
486
  const configuredUser = process.env.PGUSER || process.env.DATABRICKS_CLIENT_ID;
487
487
  const user =
488
- configuredUser ??
489
- (await getUsernameWithApiLookup({ workspaceClient: await getClient() }));
488
+ configuredUser ?? (await getUsernameWithApiLookup({ workspaceClient: await getClient() }));
490
489
  if (user) process.env.PGUSER ??= user;
491
490
  return { resolved, ...(user ? { user } : {}) };
492
491
  }
package/src/provision.ts CHANGED
@@ -1,36 +1,68 @@
1
1
  /**
2
- * Lakebase cache-schema grant fix-up.
2
+ * Lakebase grant provisioning for AppKit and consuming applications.
3
3
  *
4
- * AppKit's persistent cache (`CacheManager` -> `PersistentStorage`) uses a
5
- * schema `appkit` and a table `appkit.appkit_cache_entries`. When the connecting
6
- * Databricks identity lacks privileges on that schema, the cache migration
7
- * throws, and because AppKit is typically run with `cache.strictPersistence:
8
- * true`, the cache is silently switched to a disabled in-memory stub - so every
9
- * persistent read (chart long-poll, history, etc.) misses and 404s.
4
+ * AppKit's persistent cache uses the `appkit` schema. Local development can
5
+ * grant the resolved application role access before AppKit initializes, and
6
+ * consuming applications can add schema-wide or table-specific targets. A
7
+ * schema target is attempted first; explicit tables under it remain fallbacks
8
+ * and run only when the schema-wide transaction cannot be applied.
10
9
  *
11
- * This grants the connecting role full rights on the cache schema, but only when
12
- * the schema ALREADY EXISTS - it never creates the schema itself. Run from a
13
- * LOCAL identity that owns the schema (or holds grant option on it); it is
14
- * skipped inside a Databricks App, where the app SP cannot grant and its
15
- * Postgres role does not exist until its first connection.
16
- *
17
- * Must run AFTER {@link applyLakebaseToEnv} has written the resolved connection
18
- * to `process.env` (so `createLakebasePool` picks up host / database / endpoint)
19
- * and BEFORE `createApp` initializes the cache.
10
+ * Provisioning never creates schemas or tables. It is skipped inside a
11
+ * Databricks App, where the app service principal cannot grant and its
12
+ * PostgreSQL role does not exist until its first connection.
20
13
  *
21
14
  * @module
22
15
  */
23
16
 
24
17
  import { createLakebasePool, ValidationError } from "@databricks/appkit";
18
+ import { configUtils } from "@dbx-tools/core";
25
19
  import { postgresConnectionOptions, quotePostgresIdentifier } from "@dbx-tools/postgres";
26
- import { log, isDatabricksAppEnv, toError, type Logger } from "@dbx-tools/shared-core";
20
+ import { log, isDatabricksAppEnv, parseList, toError, type Logger } from "@dbx-tools/shared-core";
21
+ import { z } from "zod";
27
22
 
28
23
  import { createWorkspaceClient } from "./databricks.ts";
29
24
 
30
25
  const defaultLogger = log.logger("provision");
31
26
 
32
- /** AppKit persistent-cache schema (see AppKit's `PersistentStorage`). */
33
- const CACHE_SCHEMA = "appkit";
27
+ /** Logical config key for additional Lakebase provisioning targets. */
28
+ export const LAKEBASE_PROVISION_TARGETS_CONFIG_KEY = "APPKIT_LAKEBASE_PROVISION_TARGETS";
29
+
30
+ /** Targets always provisioned before consuming-application additions. */
31
+ export const DEFAULT_LAKEBASE_PROVISION_TARGETS = ["appkit", "mastra_instance"] as const;
32
+
33
+ const POSTGRES_IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]{0,62}$/;
34
+
35
+ /** A PostgreSQL `schema` or `schema.table` provisioning target. */
36
+ export const LakebaseProvisionTargetSchema = z
37
+ .string()
38
+ .trim()
39
+ .min(1)
40
+ .superRefine((value, context) => {
41
+ const identifiers = value.split(".");
42
+ if (
43
+ identifiers.length > 2 ||
44
+ identifiers.some((identifier) => !POSTGRES_IDENTIFIER_PATTERN.test(identifier))
45
+ ) {
46
+ context.addIssue({
47
+ code: "custom",
48
+ message: "Expected a PostgreSQL schema or schema.table target",
49
+ });
50
+ }
51
+ })
52
+ .describe("PostgreSQL schema or schema.table to grant to the resolved application role.");
53
+
54
+ /** PostgreSQL schema or table provisioning target. */
55
+ export type LakebaseProvisionTarget = z.infer<typeof LakebaseProvisionTargetSchema>;
56
+
57
+ /** Parsed target used by the in-process provisioning plan. */
58
+ interface ParsedProvisionTarget {
59
+ /** Original normalized target. */
60
+ readonly value: LakebaseProvisionTarget;
61
+ /** PostgreSQL schema name. */
62
+ readonly schema: string;
63
+ /** PostgreSQL table name, absent for a schema-wide target. */
64
+ readonly table?: string;
65
+ }
34
66
 
35
67
  /**
36
68
  * Characters a Lakebase Postgres role can legitimately contain: workspace
@@ -46,64 +78,187 @@ const ROLE_PATTERN = /^[A-Za-z0-9._@+-]{1,255}$/;
46
78
  const CONNECT_TIMEOUT_MS = 10_000;
47
79
  const STATEMENT_TIMEOUT_MS = 15_000;
48
80
 
81
+ function parseTarget(target: string): ParsedProvisionTarget {
82
+ const value = LakebaseProvisionTargetSchema.parse(target);
83
+ const [schema, table] = value.split(".");
84
+ return { value, schema: schema!, ...(table ? { table } : {}) };
85
+ }
86
+
49
87
  /**
50
- * Idempotent grants that make the (already-existing) AppKit cache schema fully
51
- * usable by `role`. The `ALTER DEFAULT PRIVILEGES` lines cover the cache table
52
- * whenever the schema owner creates it later.
88
+ * Resolve the built-in AppKit target plus configured and environment targets.
53
89
  *
54
- * Throws a {@link ValidationError} when `role` is not a plausible Postgres role
55
- * name, since the value lands in an identifier position.
90
+ * The option and `DBX_TOOLS_APPKIT_LAKEBASE_PROVISION_TARGETS` are additive.
91
+ * Exact duplicates are removed. A table under a configured schema remains in
92
+ * the plan as a fallback: provisioning skips it after a successful schema-wide
93
+ * transaction and attempts it only when that broader grant fails.
56
94
  */
57
- export function cacheGrantStatements(role: string): readonly string[] {
95
+ export function resolveLakebaseProvisionTargets(
96
+ configured?: readonly string[],
97
+ ): LakebaseProvisionTarget[] {
98
+ const environment = configUtils.list(undefined, LAKEBASE_PROVISION_TARGETS_CONFIG_KEY);
99
+ const normalized = [
100
+ ...DEFAULT_LAKEBASE_PROVISION_TARGETS,
101
+ ...parseList(configured),
102
+ ...environment,
103
+ ].map((target) => LakebaseProvisionTargetSchema.parse(target));
104
+ return [...new Set(normalized)];
105
+ }
106
+
107
+ function validateRole(role: string): void {
58
108
  if (!ROLE_PATTERN.test(role)) {
59
109
  throw ValidationError.invalidValue("role", role, "a Postgres role name");
60
110
  }
61
- const schema = quotePostgresIdentifier(CACHE_SCHEMA);
62
- const target = quotePostgresIdentifier(role);
111
+ }
112
+
113
+ /**
114
+ * Idempotent grants for one schema or table target.
115
+ *
116
+ * Schema grants include existing and future tables and sequences. A table
117
+ * target grants only that table so it can succeed when the caller owns the
118
+ * table but cannot modify schema-wide privileges.
119
+ */
120
+ export function lakebaseGrantStatements(target: string, role: string): readonly string[] {
121
+ validateRole(role);
122
+ const parsed = parseTarget(target);
123
+ const schema = quotePostgresIdentifier(parsed.schema);
124
+ const grantee = quotePostgresIdentifier(role);
125
+ if (parsed.table) {
126
+ const table = `${schema}.${quotePostgresIdentifier(parsed.table)}`;
127
+ return [`GRANT ALL PRIVILEGES ON TABLE ${table} TO ${grantee}`];
128
+ }
63
129
  return [
64
- `GRANT USAGE, CREATE ON SCHEMA ${schema} TO ${target}`,
65
- `GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA ${schema} TO ${target}`,
66
- `GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA ${schema} TO ${target}`,
67
- `ALTER DEFAULT PRIVILEGES IN SCHEMA ${schema} GRANT ALL ON TABLES TO ${target}`,
68
- `ALTER DEFAULT PRIVILEGES IN SCHEMA ${schema} GRANT ALL ON SEQUENCES TO ${target}`,
130
+ `GRANT USAGE, CREATE ON SCHEMA ${schema} TO ${grantee}`,
131
+ `GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA ${schema} TO ${grantee}`,
132
+ `GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA ${schema} TO ${grantee}`,
133
+ `ALTER DEFAULT PRIVILEGES IN SCHEMA ${schema} GRANT ALL ON TABLES TO ${grantee}`,
134
+ `ALTER DEFAULT PRIVILEGES IN SCHEMA ${schema} GRANT ALL ON SEQUENCES TO ${grantee}`,
69
135
  ];
70
136
  }
71
137
 
138
+ /** Minimal PostgreSQL client used by the in-process provisioning plan. */
139
+ export interface LakebaseProvisionClient {
140
+ /** Execute one parameterized or transaction-control statement. */
141
+ query(text: string, values?: unknown[]): Promise<{ readonly rowCount: number | null }>;
142
+ }
143
+
144
+ async function targetExists(client: LakebaseProvisionClient, target: ParsedProvisionTarget) {
145
+ if (!target.table) {
146
+ const found = await client.query(
147
+ "SELECT 1 FROM information_schema.schemata WHERE schema_name = $1",
148
+ [target.schema],
149
+ );
150
+ return found.rowCount !== 0;
151
+ }
152
+ const found = await client.query(
153
+ "SELECT 1 FROM pg_catalog.pg_class AS table_class JOIN pg_catalog.pg_namespace AS table_schema ON table_schema.oid = table_class.relnamespace WHERE table_schema.nspname = $1 AND table_class.relname = $2 AND table_class.relkind IN ('r', 'p', 'v', 'm', 'f')",
154
+ [target.schema, target.table],
155
+ );
156
+ return found.rowCount !== 0;
157
+ }
158
+
159
+ async function provisionTarget(
160
+ client: LakebaseProvisionClient,
161
+ target: ParsedProvisionTarget,
162
+ role: string,
163
+ logger: Logger,
164
+ ): Promise<boolean> {
165
+ try {
166
+ if (!(await targetExists(client, target))) {
167
+ logger.debug("autopg: skip absent provisioning target", { target: target.value });
168
+ return false;
169
+ }
170
+ await client.query("BEGIN");
171
+ try {
172
+ for (const sql of lakebaseGrantStatements(target.value, role)) {
173
+ await client.query(sql);
174
+ }
175
+ await client.query("COMMIT");
176
+ } catch (error) {
177
+ await client.query("ROLLBACK").catch(() => {});
178
+ throw error;
179
+ }
180
+ logger.info("autopg: granted Lakebase target", { target: target.value, role });
181
+ return true;
182
+ } catch (error) {
183
+ logger.warn("autopg: Lakebase target provisioning failed (continuing)", {
184
+ target: target.value,
185
+ error: toError(error),
186
+ });
187
+ return false;
188
+ }
189
+ }
190
+
72
191
  /**
73
- * Grant `role` rights on the AppKit cache schema, but only when that schema
74
- * already exists.
192
+ * Apply a resolved target list through an existing PostgreSQL client.
75
193
  *
76
- * No-ops inside a Databricks App env, when `role` is undefined, or when the
77
- * schema is absent. Best-effort otherwise: any failure (e.g. the local identity
78
- * doesn't own the schema) is logged and swallowed so it never blocks startup -
79
- * a disabled cache is degraded, not fatal.
194
+ * Schema targets run first. Tables under a successfully granted schema are
195
+ * skipped; if the schema transaction fails, those table targets remain
196
+ * independent fallbacks. Missing schemas and tables are debug-logged and
197
+ * skipped without issuing grant statements.
198
+ */
199
+ export async function applyLakebaseProvisionTargets(
200
+ client: LakebaseProvisionClient,
201
+ role: string,
202
+ targets: readonly string[],
203
+ logger: Logger = defaultLogger,
204
+ ): Promise<void> {
205
+ validateRole(role);
206
+ const parsed = [...new Set(targets)].map(parseTarget);
207
+ const schemas = parsed.filter((target) => !target.table);
208
+ const tables = parsed.filter((target) => target.table);
209
+ const provisionedSchemas = new Set<string>();
210
+ for (const target of schemas) {
211
+ if (await provisionTarget(client, target, role, logger)) {
212
+ provisionedSchemas.add(target.schema);
213
+ }
214
+ }
215
+ for (const target of tables) {
216
+ if (provisionedSchemas.has(target.schema)) {
217
+ logger.debug("autopg: skip table covered by schema grant", { target: target.value });
218
+ continue;
219
+ }
220
+ await provisionTarget(client, target, role, logger);
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Grant `role` rights on existing Lakebase schemas and tables.
226
+ *
227
+ * Schema targets run before table targets. A successful schema-wide transaction
228
+ * suppresses its table targets; if it fails, each explicit table is attempted
229
+ * independently. Failures are logged and never block startup.
80
230
  *
81
- * @param role - Postgres role to grant to and connect as (the resolved
82
- * workspace-client identity); skips when undefined.
231
+ * @param role - Postgres role to grant to and connect as; skips when undefined.
232
+ * @param targets - Existing schemas or schema.table targets to grant.
83
233
  * @param logger - Logger to report progress on. Defaults to this module's.
84
234
  *
85
235
  * @example
86
236
  * import { provision } from "@dbx-tools/appkit";
87
237
  *
88
- * await provision.provisionCacheSchema("app-service-principal@databricks.com");
238
+ * await provision.provisionLakebaseAccess(
239
+ * "app-service-principal@databricks.com",
240
+ * ["appkit", "reporting", "operations.events"],
241
+ * );
89
242
  */
90
- export async function provisionCacheSchema(
243
+ export async function provisionLakebaseAccess(
91
244
  role: string | undefined,
245
+ targets: readonly string[] = DEFAULT_LAKEBASE_PROVISION_TARGETS,
92
246
  logger: Logger = defaultLogger,
93
247
  ): Promise<void> {
94
248
  if (isDatabricksAppEnv()) {
95
- logger.debug("autopg: skip cache provisioning (inside a Databricks App)");
249
+ logger.debug("autopg: skip Lakebase provisioning (inside a Databricks App)");
96
250
  return;
97
251
  }
98
252
  if (!role) {
99
- logger.warn("autopg: skip cache provisioning (could not resolve connecting role)");
253
+ logger.warn("autopg: skip Lakebase provisioning (could not resolve connecting role)");
100
254
  return;
101
255
  }
102
- // Pass `user` explicitly: autopg resolves the connection target
103
- // (host/database/endpoint) but not the identity, so `createLakebasePool`'s
256
+ validateRole(role);
257
+
258
+ // Pass `user` explicitly: auto-configuration resolves the connection target
259
+ // (host/database/endpoint) but not the identity, so createLakebasePool's
104
260
  // synchronous username lookup would otherwise throw. The auth-backed AppKit
105
- // client uses the SDK version `createLakebasePool` expects while retaining
106
- // dbx-tools profile selection and interactive CLI recovery.
261
+ // client retains dbx-tools profile selection and interactive CLI recovery.
107
262
  const workspaceClient = (await createWorkspaceClient()).toLegacyWorkspaceClient();
108
263
  const pool = createLakebasePool(
109
264
  postgresConnectionOptions({
@@ -113,25 +268,11 @@ export async function provisionCacheSchema(
113
268
  statement_timeout: STATEMENT_TIMEOUT_MS,
114
269
  }),
115
270
  );
271
+ const client = await pool.connect();
116
272
  try {
117
- const found = await pool.query(
118
- "SELECT 1 FROM information_schema.schemata WHERE schema_name = $1",
119
- [CACHE_SCHEMA],
120
- );
121
- if (found.rowCount === 0) {
122
- logger.debug("autopg: skip cache provisioning (schema absent)", { schema: CACHE_SCHEMA });
123
- return;
124
- }
125
- for (const sql of cacheGrantStatements(role)) {
126
- await pool.query(sql);
127
- }
128
- logger.info("autopg: granted cache schema", { schema: CACHE_SCHEMA, role });
129
- } catch (err) {
130
- logger.warn("autopg: cache provisioning failed (continuing)", {
131
- schema: CACHE_SCHEMA,
132
- error: toError(err),
133
- });
273
+ await applyLakebaseProvisionTargets(client, role, targets, logger);
134
274
  } finally {
275
+ client.release();
135
276
  await pool.end().catch(() => {});
136
277
  }
137
278
  }