Skip to content

Commit 5489a42

Browse files
committed
chore: add docs
1 parent 4c838c0 commit 5489a42

File tree

11 files changed

+183
-13
lines changed

11 files changed

+183
-13
lines changed

CLAUDE.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ const result = await pool.query('SELECT * FROM users');
257257
```
258258

259259
**ORM Integration:**
260-
Works with Drizzle, Prisma, TypeORM - see [Lakebase Integration Docs](docs/docs/integrations/lakebase.md) for examples.
260+
Works with Drizzle, Prisma, TypeORM - see the [`@databricks/lakebase` README](https://github.com/databricks/appkit/blob/main/packages/lakebase/README.md) for examples.
261261

262262
**Architecture:**
263263
- Connector files: `packages/appkit/src/connectors/lakebase/`
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Type Alias: LakebasePluginExports
2+
3+
```ts
4+
type LakebasePluginExports = ReturnType<LakebasePlugin["exports"]>;
5+
```
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Type Alias: ServerPluginExports
2+
3+
```ts
4+
type ServerPluginExports = ReturnType<ServerPlugin["exports"]>;
5+
```

docs/docs/api/appkit/index.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ plugin architecture, and React integration.
5252
| ------ | ------ |
5353
| [ConfigSchema](TypeAlias.ConfigSchema.md) | Configuration schema definition for plugin config. Re-exported from the standard JSON Schema Draft 7 types. |
5454
| [IAppRouter](TypeAlias.IAppRouter.md) | Express router type for plugin route registration |
55+
| [LakebasePluginExports](TypeAlias.LakebasePluginExports.md) | - |
5556
| [ResourcePermission](TypeAlias.ResourcePermission.md) | Union of all possible permission levels across all resource types. |
57+
| [ServerPluginExports](TypeAlias.ServerPluginExports.md) | - |
5658

5759
## Variables
5860

docs/docs/api/appkit/typedoc-sidebar.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,10 +173,20 @@ const typedocSidebar: SidebarsConfig = {
173173
id: "api/appkit/TypeAlias.IAppRouter",
174174
label: "IAppRouter"
175175
},
176+
{
177+
type: "doc",
178+
id: "api/appkit/TypeAlias.LakebasePluginExports",
179+
label: "LakebasePluginExports"
180+
},
176181
{
177182
type: "doc",
178183
id: "api/appkit/TypeAlias.ResourcePermission",
179184
label: "ResourcePermission"
185+
},
186+
{
187+
type: "doc",
188+
id: "api/appkit/TypeAlias.ServerPluginExports",
189+
label: "ServerPluginExports"
180190
}
181191
]
182192
},

docs/docs/plugins.md

Lines changed: 87 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -143,19 +143,101 @@ The analytics plugin exposes these endpoints (mounted under `/api/analytics`):
143143
- `format: "JSON"` (default) returns JSON rows
144144
- `format: "ARROW"` returns an Arrow "statement_id" payload over SSE, then the client fetches binary Arrow from `/api/analytics/arrow-result/:jobId`
145145

146-
### Execution context and `asUser(req)`
146+
147+
### Lakebase plugin
148+
149+
Provides a PostgreSQL connection pool for Databricks Lakebase Autoscaling with automatic OAuth token refresh.
150+
151+
**Key features:**
152+
- Standard `pg.Pool` compatible with any PostgreSQL library or ORM
153+
- Automatic OAuth token refresh (1-hour tokens, 2-minute refresh buffer)
154+
- Token caching to minimize API calls
155+
- Built-in OpenTelemetry instrumentation (query duration, pool connections, token refresh)
156+
157+
#### Basic usage
158+
159+
```ts
160+
import { createApp, lakebase, server } from "@databricks/appkit";
161+
162+
await createApp({
163+
plugins: [server(), lakebase()],
164+
});
165+
```
166+
167+
#### Environment variables
168+
169+
The three required environment variables:
170+
171+
| Variable | Description |
172+
|---|---|
173+
| `PGHOST` | Lakebase host |
174+
| `PGDATABASE` | Database name |
175+
| `LAKEBASE_ENDPOINT` | Endpoint resource path (e.g. `projects/.../branches/.../endpoints/...`) |
176+
177+
When deploying as a Databricks App, `LAKEBASE_ENDPOINT` can be injected automatically via `valueFrom` in your app config:
178+
179+
```yaml
180+
env:
181+
- name: LAKEBASE_ENDPOINT
182+
valueFrom: postgres
183+
```
184+
185+
For the full configuration reference (SSL, pool size, timeouts, logging, ORM examples), see the [`@databricks/lakebase` README](https://github.com/databricks/appkit/blob/main/packages/lakebase/README.md).
186+
187+
#### Accessing the pool
188+
189+
After initialization, access Lakebase through the `AppKit.lakebase` object:
190+
191+
```ts
192+
const AppKit = await createApp({
193+
plugins: [server(), lakebase()],
194+
});
195+
196+
// Direct query (parameterized)
197+
const result = await AppKit.lakebase.query(
198+
"SELECT * FROM orders WHERE user_id = $1",
199+
[userId],
200+
);
201+
202+
// Raw pg.Pool (for ORMs or advanced usage)
203+
const pool = AppKit.lakebase.pool;
204+
205+
// ORM-ready config objects
206+
const ormConfig = AppKit.lakebase.getOrmConfig(); // { host, port, database, ... }
207+
const pgConfig = AppKit.lakebase.getPgConfig(); // pg.PoolConfig
208+
```
209+
210+
#### Configuration options
211+
212+
Pass a `pool` object to override any defaults:
213+
214+
```ts
215+
await createApp({
216+
plugins: [
217+
lakebase({
218+
pool: {
219+
max: 10, // Max pool connections (default: 10)
220+
connectionTimeoutMillis: 5000, // Connection timeout ms (default: 10000)
221+
idleTimeoutMillis: 30000, // Idle connection timeout ms (default: 30000)
222+
},
223+
}),
224+
],
225+
});
226+
```
227+
228+
## Execution context and `asUser(req)`
147229

148230
AppKit manages Databricks authentication via two contexts:
149231

150232
- **ServiceContext** (singleton): Initialized at app startup with service principal credentials
151233
- **ExecutionContext**: Determined at runtime - either service principal or user context
152234

153-
#### Headers for user context
235+
### Headers for user context
154236

155237
- `x-forwarded-user`: required in production; identifies the user
156238
- `x-forwarded-access-token`: required for user token passthrough
157239

158-
#### Using `asUser(req)` for user-scoped operations
240+
### Using `asUser(req)` for user-scoped operations
159241

160242
The `asUser(req)` pattern allows plugins to execute operations using the requesting user's credentials:
161243

@@ -174,7 +256,7 @@ router.post("/system/data", async (req, res) => {
174256
});
175257
```
176258

177-
#### Context helper functions
259+
### Context helper functions
178260

179261
Exported from `@databricks/appkit`:
180262

@@ -184,7 +266,7 @@ Exported from `@databricks/appkit`:
184266
- `getWorkspaceId()`: `Promise<string>` (from `DATABRICKS_WORKSPACE_ID` or fetched)
185267
- `isInUserContext()`: Returns `true` if currently executing in user context
186268

187-
#### Development mode behavior
269+
### Development mode behavior
188270

189271
In local development (`NODE_ENV=development`), if `asUser(req)` is called without a user token, it logs a warning and falls back to the service principal.
190272

packages/appkit/src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ export {
4747
// Plugin authoring
4848
export { Plugin, toPlugin } from "./plugin";
4949
export { analytics, lakebase, server } from "./plugins";
50+
export type { LakebasePluginExports } from "./plugins/lakebase";
51+
export type { ServerPluginExports } from "./plugins/server";
5052
// Registry types and utilities for plugin manifests
5153
export type {
5254
ConfigSchema,

packages/appkit/src/plugins/lakebase/lakebase.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,27 @@ import type { ILakebaseConfig } from "./types";
1111

1212
const logger = createLogger("lakebase");
1313

14+
/**
15+
* AppKit plugin for Databricks Lakebase Autoscaling.
16+
*
17+
* Wraps `@databricks/lakebase` to provide a standard `pg.Pool` with automatic
18+
* OAuth token refresh, integrated with AppKit's logger and OpenTelemetry setup.
19+
*
20+
* @example
21+
* ```ts
22+
* import { createApp, lakebase, server } from "@databricks/appkit";
23+
*
24+
* const AppKit = await createApp({
25+
* plugins: [server(), lakebase()],
26+
* });
27+
*
28+
* const result = await AppKit.lakebase.query("SELECT * FROM users WHERE id = $1", [userId]);
29+
* ```
30+
*/
1431
export class LakebasePlugin extends Plugin {
1532
name = "lakebase";
1633

34+
/** Plugin manifest declaring metadata and resource requirements */
1735
static manifest = lakebaseManifest;
1836

1937
protected declare config: ILakebaseConfig;
@@ -24,11 +42,31 @@ export class LakebasePlugin extends Plugin {
2442
this.config = config;
2543
}
2644

45+
/**
46+
* Initializes the Lakebase connection pool.
47+
* Called automatically by AppKit during the plugin setup phase.
48+
*/
2749
async setup() {
2850
this.pool = createLakebasePool(this.config.pool);
2951
logger.info("Lakebase pool initialized");
3052
}
3153

54+
/**
55+
* Executes a parameterized SQL query against the Lakebase pool.
56+
*
57+
* @param text - SQL query string, using `$1`, `$2`, ... placeholders
58+
* @param values - Parameter values corresponding to placeholders
59+
* @returns Query result with typed rows
60+
* @throws If the pool has not been initialized (i.e. `setup()` was not called)
61+
*
62+
* @example
63+
* ```ts
64+
* const result = await AppKit.lakebase.query<{ id: number; name: string }>(
65+
* "SELECT id, name FROM users WHERE active = $1",
66+
* [true],
67+
* );
68+
* ```
69+
*/
3270
async query<T extends pg.QueryResultRow = any>(
3371
text: string,
3472
values?: unknown[],
@@ -39,6 +77,10 @@ export class LakebasePlugin extends Plugin {
3977
return this.pool.query<T>(text, values);
4078
}
4179

80+
/**
81+
* Gracefully drains and closes the connection pool.
82+
* Called automatically by AppKit during shutdown.
83+
*/
4284
abortActiveOperations(): void {
4385
super.abortActiveOperations();
4486
if (this.pool) {
@@ -50,6 +92,14 @@ export class LakebasePlugin extends Plugin {
5092
}
5193
}
5294

95+
/**
96+
* Returns the plugin's public API, accessible via `AppKit.lakebase`.
97+
*
98+
* - `pool` — The raw `pg.Pool` instance, for use with ORMs or advanced scenarios
99+
* - `query` — Convenience method for executing parameterized SQL queries
100+
* - `getOrmConfig()` — Returns a config object compatible with Drizzle, TypeORM, Sequelize, etc.
101+
* - `getPgConfig()` — Returns a `pg.PoolConfig` object for manual pool construction
102+
*/
53103
exports() {
54104
return {
55105
pool: this.pool!,
@@ -60,6 +110,8 @@ export class LakebasePlugin extends Plugin {
60110
}
61111
}
62112

113+
export type LakebasePluginExports = ReturnType<LakebasePlugin["exports"]>;
114+
63115
/**
64116
* @internal
65117
*/
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,20 @@
11
import type { BasePluginConfig } from "shared";
22
import type { LakebasePoolConfig } from "../../connectors/lakebase";
33

4+
/**
5+
* Configuration for the Lakebase plugin.
6+
*
7+
* The minimum required setup is via environment variables — no `pool` config
8+
* is needed if `PGHOST`, `PGDATABASE`, and `LAKEBASE_ENDPOINT` are set.
9+
*
10+
* @see {@link https://github.com/databricks/appkit/blob/main/packages/lakebase/README.md} for the full configuration reference.
11+
*/
412
export interface ILakebaseConfig extends BasePluginConfig {
13+
/**
14+
* Optional overrides for the underlying `pg.Pool` configuration.
15+
* All fields are optional and fall back to environment variables or defaults.
16+
*
17+
* Common overrides: `max` (pool size), `connectionTimeoutMillis`, `idleTimeoutMillis`.
18+
*/
519
pool?: Partial<LakebasePoolConfig>;
620
}

packages/appkit/src/plugins/server/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,8 @@ export class ServerPlugin extends Plugin {
349349
}
350350
}
351351

352+
export type ServerPluginExports = ReturnType<ServerPlugin["exports"]>;
353+
352354
const EXCLUDED_PLUGINS = [ServerPlugin.name];
353355

354356
/**

0 commit comments

Comments
 (0)