diff --git a/docs/docs/api/appkit/Function.createApp.md b/docs/docs/api/appkit/Function.createApp.md index bc656537d..7465e295e 100644 --- a/docs/docs/api/appkit/Function.createApp.md +++ b/docs/docs/api/appkit/Function.createApp.md @@ -8,7 +8,7 @@ function createApp(config: { onPluginsReady?: (appkit: PluginMap) => void | Promise; plugins?: T; telemetry?: TelemetryConfig; -}): Promise>; +}): Promise>; ``` Bootstraps AppKit with the provided configuration. @@ -29,19 +29,19 @@ with an `asUser(req)` method for user-scoped execution. ## Parameters -| Parameter | Type | -| ------ | ------ | -| `config` | \{ `cache?`: [`CacheConfig`](Interface.CacheConfig.md); `client?`: [`WorkspaceClient`](Interface.WorkspaceClient.md); `disableInternalTelemetry?`: `boolean`; `onPluginsReady?`: (`appkit`: `PluginMap`\<`T`\>) => `void` \| `Promise`\<`void`\>; `plugins?`: `T`; `telemetry?`: [`TelemetryConfig`](Interface.TelemetryConfig.md); \} | -| `config.cache?` | [`CacheConfig`](Interface.CacheConfig.md) | -| `config.client?` | [`WorkspaceClient`](Interface.WorkspaceClient.md) | -| `config.disableInternalTelemetry?` | `boolean` | -| `config.onPluginsReady?` | (`appkit`: `PluginMap`\<`T`\>) => `void` \| `Promise`\<`void`\> | -| `config.plugins?` | `T` | -| `config.telemetry?` | [`TelemetryConfig`](Interface.TelemetryConfig.md) | +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `config` | \{ `cache?`: [`CacheConfig`](Interface.CacheConfig.md); `client?`: [`WorkspaceClient`](Interface.WorkspaceClient.md); `disableInternalTelemetry?`: `boolean`; `onPluginsReady?`: (`appkit`: `PluginMap`\<`T`\>) => `void` \| `Promise`\<`void`\>; `plugins?`: `T`; `telemetry?`: [`TelemetryConfig`](Interface.TelemetryConfig.md); \} | - | +| `config.cache?` | [`CacheConfig`](Interface.CacheConfig.md) | - | +| `config.client?` | [`WorkspaceClient`](Interface.WorkspaceClient.md) | - | +| `config.disableInternalTelemetry?` | `boolean` | - | +| `config.onPluginsReady?` | (`appkit`: `PluginMap`\<`T`\>) => `void` \| `Promise`\<`void`\> | Runs after plugin setup but **before** the server starts. Typed `PluginMap`, not the `AppHandle` this function returns: the runtime value is the same object, but teardown is not wired up yet, so `close()` here would silently no-op. The narrower type is deliberate. | +| `config.plugins?` | `T` | - | +| `config.telemetry?` | [`TelemetryConfig`](Interface.TelemetryConfig.md) | - | ## Returns -`Promise`\<`PluginMap`\<`T`\>\> +`Promise`\<[`AppHandle`](TypeAlias.AppHandle.md)\<`T`\>\> A `PluginMap` keyed by plugin name with typed exports diff --git a/docs/docs/api/appkit/Function.createWorkspaceClient.md b/docs/docs/api/appkit/Function.createWorkspaceClient.md index 8ad87f41d..de3f98837 100644 --- a/docs/docs/api/appkit/Function.createWorkspaceClient.md +++ b/docs/docs/api/appkit/Function.createWorkspaceClient.md @@ -18,8 +18,8 @@ Host resolution: | Parameter | Type | | ------ | ------ | -| `opts` | [`WorkspaceClientOptions`](Interface.WorkspaceClientOptions.md) | +| `opts` | `WorkspaceClientOptions` | ## Returns -[`WorkspaceClient`](Interface.WorkspaceClient.md) +`WorkspaceClient` diff --git a/docs/docs/api/appkit/Interface.WorkspaceClientOptions.md b/docs/docs/api/appkit/Interface.WorkspaceClientOptions.md index 29ef96aac..56229ac37 100644 --- a/docs/docs/api/appkit/Interface.WorkspaceClientOptions.md +++ b/docs/docs/api/appkit/Interface.WorkspaceClientOptions.md @@ -38,6 +38,16 @@ Databricks host, e.g. https://my-workspace.cloud.databricks.com. Defaults to DAT *** +### profile? + +```ts +optional profile: string; +``` + +`~/.databrickscfg` profile name. Used when no host/token is provided. + +*** + ### token? ```ts diff --git a/docs/docs/api/appkit/TypeAlias.AppHandle.md b/docs/docs/api/appkit/TypeAlias.AppHandle.md new file mode 100644 index 000000000..6d7c304fb --- /dev/null +++ b/docs/docs/api/appkit/TypeAlias.AppHandle.md @@ -0,0 +1,56 @@ +# Type Alias: AppHandle\ + +```ts +type AppHandle = PluginMap & { + [asyncDispose]: Promise; + close: Promise; +}; +``` + +What `createApp()` returns: every plugin's exports keyed by manifest name, +plus the app's own teardown handle. + +`close()` releases what AppKit acquired — sockets, timers, pools, cache, and +telemetry — without terminating the process, so a host can embed AppKit and a +test can boot more than once in a file. + +`Symbol.asyncDispose` is exposed alongside it because a plugin's manifest name +can never be a symbol: `await using app = await createApp(...)` is safe even +if a plugin were somehow named `close`. + +## Type Declaration + +### \[asyncDispose\]() + +```ts +asyncDispose: Promise; +``` + +#### Returns + +`Promise`\<`void`\> + +### close() + +```ts +close(options?: { + timeoutMs?: number; +}): Promise; +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options?` | \{ `timeoutMs?`: `number`; \} | - | +| `options.timeoutMs?` | `number` | Overall teardown budget. Defaults to AppKit's programmatic budget, which is shorter than the signal path's. | + +#### Returns + +`Promise`\<`void`\> + +## Type Parameters + +| Type Parameter | +| ------ | +| `U` *extends* readonly [`PluginData`](TypeAlias.PluginData.md)\<`PluginConstructor`, `unknown`, `string`\>[] | diff --git a/docs/docs/api/appkit/index.md b/docs/docs/api/appkit/index.md index f39a52db2..873a84cd1 100644 --- a/docs/docs/api/appkit/index.md +++ b/docs/docs/api/appkit/index.md @@ -104,6 +104,7 @@ surface with `@databricks/appkit/beta`. Not meant for application imports. | [AgentTool](TypeAlias.AgentTool.md) | Any tool an agent can invoke: inline function tools (`tool()`), hosted MCP tools (`mcpServer()` / raw hosted), toolkit references from plugins (`analytics().toolkit()`), or adapter-hosted Supervisor-API tools (`supervisorTools.*`). | | [AgentTools](TypeAlias.AgentTools.md) | Per-agent tool record. String keys map to inline tools, toolkit entries, hosted tools, etc. | | [AgentToolsFn](TypeAlias.AgentToolsFn.md) | Function form of `AgentDefinition.tools`. Receives the typed [Plugins](TypeAlias.Plugins.md) map and returns a tool record. Invoked exactly once at setup (or once per `runAgent` call in standalone mode); the result is cached as the agent's resolved tool record. | +| [AppHandle](TypeAlias.AppHandle.md) | What `createApp()` returns: every plugin's exports keyed by manifest name, plus the app's own teardown handle. | | [BaseSystemPromptOption](TypeAlias.BaseSystemPromptOption.md) | - | | [ConfigSchema](TypeAlias.ConfigSchema.md) | Configuration schema definition for plugin config. Re-exported from the standard JSON Schema Draft 7 types. | | [ExecutionResult](TypeAlias.ExecutionResult.md) | Discriminated union for plugin execution results. | diff --git a/docs/docs/api/appkit/typedoc-sidebar.ts b/docs/docs/api/appkit/typedoc-sidebar.ts index 18a5333b1..f9253a963 100644 --- a/docs/docs/api/appkit/typedoc-sidebar.ts +++ b/docs/docs/api/appkit/typedoc-sidebar.ts @@ -433,6 +433,11 @@ const typedocSidebar: SidebarsConfig = { id: "api/appkit/TypeAlias.AgentToolsFn", label: "AgentToolsFn" }, + { + type: "doc", + id: "api/appkit/TypeAlias.AppHandle", + label: "AppHandle" + }, { type: "doc", id: "api/appkit/TypeAlias.BaseSystemPromptOption", diff --git a/docs/docs/plugins/custom-plugins.md b/docs/docs/plugins/custom-plugins.md index ccff2eff5..343734c97 100644 --- a/docs/docs/plugins/custom-plugins.md +++ b/docs/docs/plugins/custom-plugins.md @@ -78,6 +78,14 @@ export const myPlugin = toPlugin(MyPlugin); JSON is the canonical authoring surface — it is what `appkit plugin sync` reads when aggregating manifests for templates. For the full v2.0 manifest contract (resources, discovery descriptors, scaffolding rules), see [Plugin manifest](./manifest.md). +:::note Reserved plugin names +`close` cannot be used as a plugin `name`. Plugin exports are installed as own +properties on the object `createApp()` returns, and an own property shadows a +prototype method — so a plugin named `close` would silently replace the app +handle's own `close()` and break teardown. `createApp()` rejects it with a +`ConfigurationError` naming the plugin instead of failing quietly at shutdown. +::: + ## Config-dependent resources The manifest defines resources as either `required` (always needed) or `optional` (may be needed). diff --git a/docs/docs/plugins/testing.md b/docs/docs/plugins/testing.md index 8adb47132..9310eb817 100644 --- a/docs/docs/plugins/testing.md +++ b/docs/docs/plugins/testing.md @@ -10,14 +10,129 @@ AppKit ships a testing kit at `@databricks/appkit/testing` so you can test a plu Exercise a plugin's real code paths — route registration, cross-plugin tool dispatch, user-scoped (on-behalf-of) execution, and per-call timeouts — against a real `PluginContext` with only its outer edges faked. Nothing about the context is reimplemented, so a test can't drift from production behavior. -The kit has two entry points plus a set of fixture helpers: +The kit has three entry points plus a set of fixture helpers: -- **`createTestPluginContext()`** — build a real `PluginContext` with faked edges and attach it to a plugin. +- **`createTestApp({ plugins })`** — boot a real app and call it over real HTTP. Start here. +- **`createTestPluginContext()`** — build a real `PluginContext` with faked edges and attach it to a plugin, with no boot and no socket. - **`expectStream(...).toEmit(...)`** — assert the ordered event types a stream emits. -- **Fixtures** — `createMockRequest`, `createMockResponse`, `mockServiceContext`, and SQL response builders. +- **Fixtures** — `createMockRequest`, `createMockResponse`, `createMockWorkspaceClient`, `mockServiceContext`, and SQL response builders. The kit uses [Vitest](https://vitest.dev)'s `vi` for its mocks, so `vitest` is an **optional peer dependency**: you already have it (you're writing Vitest tests), and the kit resolves to your copy rather than bundling a second one. Because it's optional, it is not installed into apps that never import `@databricks/appkit/testing` — production installs stay free of the test framework. Any Vitest v3 or v4 works. +## Testing your plugin + +`createTestApp({ plugins })` boots a **real** AppKit app — real Express wiring, real routes, real resource validation — and hands you methods to call it like a client would: + +```ts +import { createTestApp, expectStream } from "@databricks/appkit/testing"; + +test("my plugin answers a request", async () => { + const app = await createTestApp({ plugins: [myPlugin()] }); + try { + const res = await app.post("/api/my-plugin/thing", { body: { q: 1 }, obo: true }); + expect(res.status).toBe(200); + await expectStream(res).toEmit("status", "result"); + } finally { + await app.close(); + } +}); +``` + +No workspace, no credentials, no network. The harness pins a non-development `NODE_ENV`, binds an ephemeral port, installs a fake workspace client, and keeps the cache in memory so nothing reaches out. + +Paths are the full mounted route. A plugin's prefix is `/api/` plus its manifest name in kebab-case, so a plugin named `mySearch` serves at `/api/my-search/…`. + +### Which harness? + +| | `createTestApp` | `createTestPluginContext` | +| --- | --- | --- | +| Boots the app | Yes | No | +| Binds a socket | Yes (ephemeral port) | No | +| Express middleware, error handler | Real | Not involved | +| Resource / env validation | Real, and strict | Not involved | +| Workspace client | Faked and injected | Fake it yourself with `mockServiceContext` | +| Needs `close()` | **Yes** | No | +| Speed | Fast, but pays for a socket | Fastest | + +Use `createTestApp` for a plugin's HTTP behaviour end to end. Use `createTestPluginContext` to unit-test wiring — route registration, tool dispatch, timeout composition. Name harness suites `*.integration.test.ts`, matching the existing convention. + +### Faking what your plugin reads + +Declare responses by dotted path — `"."` on AppKit's workspace-client facade: + +```ts +const app = await createTestApp({ + plugins: [myPlugin()], + responses: { + "jobs.getRun": { state: "TERMINATED", result_state: "SUCCESS" }, + "statementExecution.executeStatement": { status: { state: "SUCCEEDED" } }, + "apiClient.request": { results: [] }, + }, +}); +``` + +A function value receives the call arguments, so you can script per-argument behaviour or reject to test an error path. Any path you **don't** declare resolves `undefined` rather than crashing — see [Mocking Databricks services](#mocking-databricks-services) for the trade-off that buys. + +For the response *shapes*, follow the service types on the Databricks SDK — the kit doesn't validate them, so a wrong shape fails in your plugin, not in the fake. + +`app.client` is the very object your handler resolves at runtime — reached inside a plugin via `getExecutionContext().client` — so you can assert calls on it: + +```ts +import { getMockFn } from "@databricks/appkit/testing"; + +expect(getMockFn(app.client, "jobs.getRun")).toHaveBeenCalledWith({ run_id: 42 }); +``` + +`getMockFn` exists because facade accessors are typed against the SDK, so `expect(app.client.jobs.getRun).toHaveBeenCalled()` won't typecheck. + +### Requests + +`app.get/post/put/patch/delete(path, options?)` return a native `Response`, so `expectStream` composes directly with no bridge. + +- `body` — a non-string value is JSON-encoded with `content-type: application/json`. A string is sent as-is. +- `headers` — merged last, so they win over anything the harness set. +- `obo` — `true` for the default test user, or `{ userId, token, email }`. Same shorthand as `createMockRequest({ obo })`, so a handler using `asUser(req)` resolves that identity. +- `signal` — forwarded to `fetch`. + +### Teardown + +The harness binds a socket and installs signal handlers, so **every boot needs a `close()`**. `close()` releases the socket, runs your plugin's `shutdown()` hooks, drops AppKit's singletons, and restores `process.env` to its pre-boot state. It's idempotent. + +Use `try/finally`, or let the runtime do it: + +```ts +await using app = await createTestApp({ plugins: [myPlugin()] }); +// released at scope exit +``` + +Skip the `close()` and you'll leak a listener per boot — Node warns at about six. + +### Satisfying declared resources + +The harness runs the real validator with a strict posture, so a plugin whose manifest requires a resource fails the boot unless its env var is set. Supply it with `env`: + +```ts +// Throws: MY_WAREHOUSE_ID is required by the manifest. +await createTestApp({ plugins: [myPlugin()] }); + +// Boots. +await createTestApp({ plugins: [myPlugin()], env: { MY_WAREHOUSE_ID: "w-1" } }); +``` + +That makes "my plugin declares its resources correctly" a genuine assertion. `env` is restored on `close()`. + +:::note What this does not check +The harness validates that required resources' **environment variables are present**. It does **not** validate config *values* against your manifest's `config.schema` — no runtime validator exists for that yet. A test that boots successfully tells you your resource declarations and env are wired up; it says nothing about whether your config values are well-formed. +::: + +### Other options + +- `server: false` — no socket. Plugin setup, validation, and teardown still run; the request methods throw if called. Useful when you only care that a plugin boots. +- `client` — supply your own workspace client instead of the built-in fake. You then own its `currentUser.me()`: AppKit reads `currentUser.id` during boot and can't start without it. +- `nodeEnv` — defaults to `"test"`. `"development"` is **refused**: dev mode routes the harness's ephemeral port through `get-port`, which throws on port `0`, and it also boots a real Vite server and relaxes validation. +- `cache` — defaults to in-memory. Overriding it is what would let the cache reach the network, so leave it alone unless that's the point of the test. +- `closeTimeoutMs` — teardown budget. + ## `createTestPluginContext()` `PluginContext` is the mediator AppKit passes to every plugin — it buffers routes, tracks tool providers, and runs cross-plugin tool calls with user scoping and a timeout. `createTestPluginContext()` returns the **real** context with three edges faked: @@ -143,6 +258,10 @@ await expectStream(handler.stream(req), { timeout: 1000 }).toEmit("result"); ## Fixtures +AppKit has two contexts, and they're faked by different tools. `PluginContext` is the mediator between plugins — routes, tool dispatch, user scoping — and `createTestPluginContext()` gives you the real thing with faked edges. `ServiceContext` is the **data plane**: it resolves the workspace client, the service principal, and the warehouse ID that plugins reach through `getWorkspaceClient()`. + +The kit now covers both. `createTestApp` fakes the data plane for you by injecting a mock workspace client at the real seam; below that, `mockServiceContext` spies the singleton directly, and `createMockWorkspaceClient` builds the client either of them installs. + The kit re-exports the request/response/context fixtures AppKit uses internally: - `createMockRequest(overrides?)` / `createMockResponse()` — Express request/response doubles, including the streaming flags (`headersSent`, `writableEnded`). Pass `obo: true` (or `obo: { userId, token, email }`) to set the forwarded identity headers `asUser` requires, instead of hand-adding them. `createMockResponse()` also captures everything a handler writes; pass it to `expectStream` (or call `sseResponse()`) to assert a streaming route's SSE. (Plugins resolve the workspace client through `getWorkspaceClient()`, not the request — use `mockServiceContext` to control it.) @@ -160,10 +279,61 @@ The kit re-exports the request/response/context fixtures AppKit uses internally: - `createSuccessfulSQLResponse(rows, columns)` / `createFailedSQLResponse(message)` — build SQL Warehouse statement responses. - `setupDatabricksEnv(overrides?)` — set `DATABRICKS_HOST` / `DATABRICKS_WAREHOUSE_ID` to test values. - `resetTestCache()` — clear the shared cache singleton between (or within) tests; no-ops if the cache isn't initialized yet. +- `resetAppKitSingletons()` — drop AppKit's process-wide singletons so a later `createApp` builds fresh ones. `createTestApp`'s `close()` already does this; you need it only if you call `createApp` yourself. Close first, then reset — it drops pointers, it doesn't release resources. +- `createTestPlugin(factory, config?)` — instantiate a plugin from its factory with the same config merge AppKit applies. See [Full example](#full-example). + +## Mocking Databricks services + +Every core plugin's real work goes through `getWorkspaceClient()`. `createMockWorkspaceClient()` fakes that whole surface, so a plugin touching `jobs`, `genie`, `servingEndpoints`, or `files` is testable without hand-building a nested client: + +```ts +import { createMockWorkspaceClient, getMockFn } from "@databricks/appkit/testing"; + +const client = createMockWorkspaceClient({ + responses: { "jobs.getRun": { state: "TERMINATED" } }, + config: { host: "https://my-test-host.example.com" }, +}); + +await client.jobs.getRun({ run_id: 1 }); // → { state: "TERMINATED" } +await client.genie.getMessage({ id: "m-1" }); // → undefined, does not throw +``` + +`createTestApp` installs one of these for you, so reach for it directly only when you're driving a plugin through `createTestPluginContext` or `mockServiceContext`. + +How it works, and what to expect: + +- The **facade is typed**, so `client.jbos` is a compile error. AppKit owns that 9-member interface, so it's a closed set, not an open-ended chase of the SDK. +- Each **service** is a proxy that mints a memoized mock per method. `client.jobs.getRun === client.jobs.getRun`, so call assertions are stable, and `toLegacyWorkspaceClient()` shares the same functions — one `responses` entry covers both views. +- `config.host` is a real **string** (not a mock), because AppKit builds URLs from it. `apiClient.userAgent()` is synchronous for the same reason, and `apiClient.request` resolves `{}` so destructuring its result doesn't throw. +- Sensible defaults are built in: SQL statements succeed, warehouses report `RUNNING`, and `currentUser.me()` returns a service user. Pass `defaults: false` to script everything yourself. + +:::caution The honest catch +An undeclared method resolves `undefined` instead of throwing. That's the point — your plugin survives touching services the test doesn't care about — but it means a call whose response you *forgot* to declare silently returns `undefined` rather than failing loudly, so a test can pass for the wrong reason. + +TypeScript covers more of this than you might expect: because each accessor is typed against the SDK's own service class, both a misspelled **service** (`client.jbos`) and a misspelled **method** (`client.jobs.getRunz`) are compile errors. The gap is a *real* method with no declared response — and any call that bypasses the types with a cast. + +One more divergence to know about: a service's methods are minted on access, so they are **callable but not enumerable**. `typeof client.jobs.getRun` is `"function"`, but `'getRun' in client.jobs` is `false` and `Object.keys(client.jobs)` is `[]`. Plugin code that feature-detects with `in` or reflects over a service will therefore take a different branch than it does in production. This is a deliberate trade: reporting those keys would make `util.inspect` probe each one, minting a mock per probe, which is the runaway recursion the default traps avoid. + +Separately, `createLakebasePool({ workspaceClient })` will build a pool whose password callback resolves to a mock: the pool exists but cannot connect. A Lakebase test needs a real database or a purpose-built fake pool, not this. +::: ## Full example -Instantiate the plugin **class** directly with `new`. The `analytics()` / `agents()` factory functions you pass to `createApp` return a descriptor for the app to construct — for a unit test you want the instance itself. +For a plugin you wrote, instantiate the class directly with `new`. The `analytics()` / `agents()` factory functions you pass to `createApp` return a *descriptor* for the app to construct, not an instance. + +When you want an instance from one of those factories, use `createTestPlugin` rather than reaching through the descriptor: + +```ts +import { createTestPlugin } from "@databricks/appkit/testing"; + +const plugin = createTestPlugin(genie, { spaceId: "s-1" }); + +// Not this — it skips DEFAULT_CONFIG and forgets `name`, so the instance is +// configured differently from the one production builds: +// const plugin = new (genie({}).plugin)({ spaceId: "s-1" }); +``` + +`createTestPlugin` applies the same merge AppKit does at registration: `DEFAULT_CONFIG`, then your config, then the manifest `name`. It's for this unit-test path only — `createTestApp` takes descriptors and builds the instances itself. ```ts import { Plugin, type PluginManifest } from "@databricks/appkit"; diff --git a/docs/static/appkit-ui/styles.gen.css b/docs/static/appkit-ui/styles.gen.css index 9e1d5c0c0..579cdbecd 100644 --- a/docs/static/appkit-ui/styles.gen.css +++ b/docs/static/appkit-ui/styles.gen.css @@ -398,6 +398,9 @@ .\!m-0 { margin: calc(var(--spacing) * 0) !important; } + .m-1 { + margin: calc(var(--spacing) * 1); + } .-mx-1 { margin-inline: calc(var(--spacing) * -1); } @@ -714,6 +717,9 @@ .w-\(--sidebar-width\) { width: var(--sidebar-width); } + .w-1 { + width: calc(var(--spacing) * 1); + } .w-1\/2 { width: calc(1/2 * 100%); } diff --git a/packages/appkit/src/cache/index.ts b/packages/appkit/src/cache/index.ts index a98b7dff4..441540287 100644 --- a/packages/appkit/src/cache/index.ts +++ b/packages/appkit/src/cache/index.ts @@ -58,6 +58,8 @@ export class CacheManager { private readonly name: string = "cache-manager"; private static instance: CacheManager | null = null; private static initPromise: Promise | null = null; + /** Bumped by {@link reset} so an in-flight init cannot publish over it. */ + private static generation = 0; private storage: CacheStorage; private config: CacheConfig; @@ -126,9 +128,14 @@ export class CacheManager { } if (!CacheManager.initPromise) { + const generation = CacheManager.generation; CacheManager.initPromise = CacheManager.create(userConfig).then( (instance) => { - CacheManager.instance = instance; + // A reset() mid-flight discarded this manager before it existed: + // hand it to the awaiting caller, but do not publish it. + if (CacheManager.generation === generation) { + CacheManager.instance = instance; + } return instance; }, ); @@ -557,6 +564,21 @@ export class CacheManager { await this.storage.close(); } + /** + * Drop the singleton so the next {@link getInstance} builds a fresh manager. + * + * Both fields must clear — `getInstance()` falls back to `initPromise` when + * `instance` is null. A pointer drop, not teardown: call {@link close} first + * or the old storage leaks (a `pg.Pool` under `PersistentStorage`). + * + * @internal + */ + static reset(): void { + CacheManager.instance = null; + CacheManager.initPromise = null; + CacheManager.generation += 1; + } + /** * Check if the storage is healthy * @returns Promise of true if the storage is healthy, false otherwise diff --git a/packages/appkit/src/cache/tests/cache-manager-reset.test.ts b/packages/appkit/src/cache/tests/cache-manager-reset.test.ts new file mode 100644 index 000000000..1b6343d58 --- /dev/null +++ b/packages/appkit/src/cache/tests/cache-manager-reset.test.ts @@ -0,0 +1,115 @@ +import type { CacheEntry } from "shared"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; + +import { CacheManager } from ".."; +import { InitializationError } from "../../errors"; +import { InMemoryStorage } from "../storage/memory"; + +/** + * `getInstance()` returns the existing instance, so after `cache.close()` the + * singleton still points at closed storage — under `PersistentStorage` an ended + * `pg.Pool`. Every test passes explicit `storage` so nothing probes Lakebase. + */ +describe("CacheManager.reset", () => { + beforeEach(() => { + CacheManager.reset(); + }); + + afterEach(() => { + CacheManager.reset(); + }); + + function storage() { + return new InMemoryStorage({ enabled: true, maxSize: 100 } as never); + } + + test("the next getInstance() builds a fresh instance, not the closed one", async () => { + const first = await CacheManager.getInstance({ storage: storage() }); + await first.close(); + + CacheManager.reset(); + const second = await CacheManager.getInstance({ storage: storage() }); + + expect(second).not.toBe(first); + + // The point of the fix: the fresh instance's storage is live, so a + // write-then-read round-trips instead of hitting closed storage. + const key = second.generateKey(["reset-probe"], "test-user"); + await second.set(key, { ok: true }); + await expect(second.get(key)).resolves.toEqual({ ok: true }); + }); + + test("without a reset, getInstance() keeps returning the same instance", async () => { + // The regression guard for the *unchanged* path: a single boot with no reset + // must behave exactly as before. + const first = await CacheManager.getInstance({ storage: storage() }); + const second = await CacheManager.getInstance({ storage: storage() }); + + expect(second).toBe(first); + }); + + test("reset clears an in-flight initPromise, not just the instance", async () => { + // Start initialization but do not await it, so `instance` is still null and + // only `initPromise` is set. Clearing just `instance` would leave the next + // caller awaiting a promise that resolves to the discarded manager — + // getInstance() returns initPromise when instance is null. + const pending = CacheManager.getInstance({ storage: storage() }); + + CacheManager.reset(); + + const first = await pending; + const second = await CacheManager.getInstance({ storage: storage() }); + + expect(second).not.toBe(first); + }); + + test("getInstanceSync throws after a reset", async () => { + await CacheManager.getInstance({ storage: storage() }); + expect(() => CacheManager.getInstanceSync()).not.toThrow(); + + CacheManager.reset(); + + // Reset is a pointer drop, so the sync accessor is back to its + // not-initialized contract rather than handing out a stale manager. + expect(() => CacheManager.getInstanceSync()).toThrow(InitializationError); + }); + + test("without a reset, the next boot reuses storage the last teardown closed", async () => { + // Models PersistentStorage, whose close() is `pool.end()` — permanent. + // InMemoryStorage.close() merely clears a Map and stays usable, which is why + // an in-memory test cannot show this and why the bug hid for so long. + class EndableStorage extends InMemoryStorage { + private ended = false; + override async close(): Promise { + this.ended = true; + } + override async set(key: string, entry: CacheEntry): Promise { + if (this.ended) + throw new Error("Cannot use a pool after calling end()"); + return super.set(key, entry); + } + } + const endable = () => + new EndableStorage({ enabled: true, maxSize: 100 } as never); + + const first = await CacheManager.getInstance({ storage: endable() }); + await first.close(); + + // The bug, with no reset in between: getInstance() hands back the same + // manager, still pointing at storage that has been ended. + const stale = await CacheManager.getInstance({ storage: endable() }); + expect(stale).toBe(first); + await expect( + stale.set(stale.generateKey(["x"], "test-user"), { v: 1 }), + ).rejects.toThrow(/after calling end/); + + // The fix: reset drops the pointer, so the next boot builds over live + // storage and the same write succeeds. + CacheManager.reset(); + const fresh = await CacheManager.getInstance({ storage: endable() }); + expect(fresh).not.toBe(first); + const key = fresh.generateKey(["x"], "test-user"); + await fresh.set(key, { v: 1 }); + await expect(fresh.get(key)).resolves.toEqual({ v: 1 }); + }); +}); diff --git a/packages/appkit/src/core/appkit.ts b/packages/appkit/src/core/appkit.ts index 0ccfd64e9..fcce6270a 100644 --- a/packages/appkit/src/core/appkit.ts +++ b/packages/appkit/src/core/appkit.ts @@ -1,4 +1,5 @@ import type { + AppHandle, BasePlugin, CacheConfig, InputPluginMap, @@ -11,6 +12,7 @@ import type { import { version as productVersion } from "../../package.json"; import { CacheManager } from "../cache"; import { ServiceContext } from "../context"; +import { ConfigurationError } from "../errors"; import { isInternalTelemetryEnabled, TelemetryReporter, @@ -27,10 +29,24 @@ import { isToolProvider, PluginContext } from "./plugin-context"; const logger = createLogger("appkit"); +/** + * Names a plugin manifest may not use: `createAndRegisterPlugin` installs + * exports as **own** properties, and an own property shadows a prototype + * method. Only *silently* broken names belong here — a plugin named `close` + * would no-op teardown, whereas shadowing an internal method throws + * `TypeError` on the next registration and needs no guard. + */ +const RESERVED_PLUGIN_NAMES = new Set(["close"]); + export class AppKit { #pluginInstances: Record = {}; #setupPromises: Promise[] = []; #context: PluginContext; + /** + * Retained so {@link close} can reach the shutdown sequence. Assigned once + * every plugin has started; `close()` before that point is a no-op teardown. + */ + #lifecycle: LifecycleManager | undefined; private constructor(config: { plugins: TPlugins }) { const { plugins, ...globalConfig } = config; @@ -80,6 +96,15 @@ export class AppKit { pluginData: OptionalConfigPluginDef, extraData?: Record, ) { + if (RESERVED_PLUGIN_NAMES.has(name)) { + throw new ConfigurationError( + `Plugin name "${name}" is reserved by the app handle returned from ` + + "createApp(). Rename the plugin in its manifest — an own property " + + "would shadow the handle's method and silently break app teardown.", + { context: { pluginName: name } }, + ); + } + const { plugin: Plugin, config: pluginConfig } = pluginData; const baseConfig = { ...config, @@ -188,10 +213,11 @@ export class AppKit { telemetry?: TelemetryConfig; cache?: CacheConfig; client?: WorkspaceClient; + /** Narrower than `AppHandle` on purpose — see {@link createApp}. */ onPluginsReady?: (appkit: PluginMap) => void | Promise; disableInternalTelemetry?: boolean; } = {}, - ): Promise> { + ): Promise> { // Initialize core services TelemetryManager.initialize(config?.telemetry); await CacheManager.getInstance(config?.cache); @@ -225,7 +251,7 @@ export class AppKit { await Promise.all(instance.#setupPromises); await instance.#context.emitLifecycle("setup:complete"); - const handle = instance as unknown as PluginMap; + const handle = instance as unknown as AppHandle; if (config.onPluginsReady) { logger.debug("Running onPluginsReady hook"); @@ -246,11 +272,36 @@ export class AppKit { // plugin has started. Applies uniformly whether or not a server plugin // is present — server-less apps still get their telemetry flushed and // plugin shutdown() hooks run. - new LifecycleManager(instance.#context).installSignalHandlers(); + instance.#lifecycle = new LifecycleManager(instance.#context); + instance.#lifecycle.installSignalHandlers(); return handle; } + /** + * Release everything this app acquired — sockets, timers, pools, cache, + * telemetry — without terminating the process. Runs the same phases as a + * SIGTERM shutdown (plugin `abortActiveOperations` and `shutdown()` hooks, + * the `"shutdown"` lifecycle event, cache close, telemetry flush) and + * detaches the signal handlers this app installed. Idempotent: repeated + * calls await the same teardown. + * + * @param options.timeoutMs - Overall budget. Defaults to the shorter + * programmatic budget, not the production signal budget. + */ + async close(options: { timeoutMs?: number } = {}): Promise { + await this.#lifecycle?.close(options); + } + + /** + * Enables `await using app = await createApp(...)`, releasing the app at + * scope exit. Unshadowable, unlike {@link close} — a manifest name can + * never be a symbol. + */ + async [Symbol.asyncDispose](): Promise { + await this.close(); + } + private static bootstrapInternalTelemetry(): void { const serviceCtx = ServiceContext.get(); const reporter = TelemetryReporter.initialize({ @@ -382,9 +433,16 @@ export async function createApp< telemetry?: TelemetryConfig; cache?: CacheConfig; client?: WorkspaceClient; + /** + * Runs after plugin setup but **before** the server starts. + * + * Typed `PluginMap`, not the `AppHandle` this function returns: the + * runtime value is the same object, but teardown is not wired up yet, so + * `close()` here would silently no-op. The narrower type is deliberate. + */ onPluginsReady?: (appkit: PluginMap) => void | Promise; disableInternalTelemetry?: boolean; } = {}, -): Promise> { +): Promise> { return AppKit._createApp(config); } diff --git a/packages/appkit/src/core/lifecycle-manager.ts b/packages/appkit/src/core/lifecycle-manager.ts index 84dcb4a9e..28b77756d 100644 --- a/packages/appkit/src/core/lifecycle-manager.ts +++ b/packages/appkit/src/core/lifecycle-manager.ts @@ -5,6 +5,7 @@ import { TelemetryReporter } from "../internal-telemetry"; import { createLogger } from "../logging/logger"; import { TelemetryManager } from "../telemetry"; import type { PluginContext } from "./plugin-context"; +import { releaseCoreSingletons } from "./reset-singletons"; const logger = createLogger("lifecycle"); @@ -45,35 +46,49 @@ export class LifecycleManager { */ private static readonly PHASE_SHUTDOWN_TIMEOUT_MS = 2_000; + /** Shorter than the signal path's: a programmatic caller wants its await back. */ + private static readonly CLOSE_TIMEOUT_MS = 5_000; + /** - * Guards against re-entrant shutdown (e.g. SIGTERM followed by SIGINT). - * The flag set in `shutdown` must remain synchronous and first — any - * `await` before it would open a window for a second signal to re-enter - * the sequence. - */ - private isShuttingDown = false; - /** - * Name of the shutdown phase currently in flight, so the force-exit log - * can say where shutdown got stuck without extra bookkeeping. + * The in-flight teardown, memoized. A boolean guard would let a second caller + * return while teardown was still running — fine for a signal, wrong for + * `close()`, which must not resolve before resources are released. */ + private teardown: Promise | undefined; + /** Reported by the force-exit log so a stuck shutdown names its phase. */ private shutdownPhase = "not started"; + /** Retained so {@link close} removes its own listeners and nothing else. */ + private signalHandlers: [NodeJS.Signals, () => void][] = []; + /** Memoizes {@link close}, so the singleton release happens once. */ + private closed: Promise | undefined; constructor(private readonly context: PluginContext) {} + /** Install the SIGTERM/SIGINT handlers that trigger {@link shutdown}. */ + installSignalHandlers(): void { + this.signalHandlers = [ + ["SIGTERM", () => void this.shutdown()], + ["SIGINT", () => void this.shutdown()], + ]; + for (const [signal, handler] of this.signalHandlers) { + process.once(signal, handler); + } + } + /** - * Install the SIGTERM/SIGINT handlers that trigger {@link shutdown}. - * - * Uses `process.once` (not `on`) so a repeated signal cannot register the - * handler twice; re-entrancy from a *different* signal is guarded by - * `isShuttingDown` inside {@link shutdown}. + * Detach only this instance's handlers — never `removeAllListeners`, so an + * embedding host keeps its own. */ - installSignalHandlers(): void { - process.once("SIGTERM", () => this.shutdown()); - process.once("SIGINT", () => this.shutdown()); + removeSignalHandlers(): void { + for (const [signal, handler] of this.signalHandlers) { + process.removeListener(signal, handler); + } + this.signalHandlers = []; } /** - * Run the graceful-shutdown sequence and exit the process. + * Run the graceful-shutdown sequence and **exit the process**. See + * {@link close} for the non-exiting twin. * * Phases: * 1. stop the internal-telemetry reporter @@ -86,22 +101,15 @@ export class LifecycleManager { * Exits 0 on completion (and on the force-exit backstop): a deliberate * shutdown is not a crash. Exit 1 is reserved for an unexpected error * thrown by the sequence itself. + * + * A second signal now awaits the first teardown rather than returning at once; + * the first caller still exits, so this is unobservable in production. */ async shutdown(): Promise { - // Must stay synchronous and first: any await before the flag is set - // would let a second signal re-enter the shutdown sequence. - if (this.isShuttingDown) return; - this.isShuttingDown = true; - - logger.info("Starting graceful shutdown..."); - - let exitCode = 0; - - // Force exit once the overall budget is spent. Exit 0 is deliberate: - // a force-timeout still happens on a routine deploy (deliberate - // shutdown, not a crash), and orchestrators record nonzero exits on - // deploys as crashes. The error log below is the stuck-shutdown - // signal instead of the exit code. + // Exit 0 on force-timeout: a stuck deploy shutdown is not a crash, and + // orchestrators read nonzero deploy exits as one. The error log is the + // signal instead. Lives here, not in runPhases, because close() must not + // inherit it. const forceExitTimer = setTimeout(() => { logger.error( "Graceful shutdown did NOT complete within the %dms budget (phase in flight: %s); force-exiting with code 0.", @@ -110,13 +118,89 @@ export class LifecycleManager { ); process.exit(0); }, LifecycleManager.SHUTDOWN_TIMEOUT_MS); - // unref so this backstop timer never by itself keeps the process alive. - // Any real pending teardown (OTEL export timer, DB pool sockets, the - // still-open HTTP listener) is a ref'd handle that holds the loop open - // until this fires; if nothing is ref'd, there is nothing left to tear - // down and exiting early is correct. + // unref'd so the backstop alone never holds the process open; real pending + // teardown is ref'd and keeps the loop alive until this fires. forceExitTimer.unref(); + const exitCode = await this.runOnce(); + + clearTimeout(forceExitTimer); + process.exit(exitCode); + } + + /** + * Release everything AppKit acquired **without terminating the process** — + * same phases and per-phase budgets as {@link shutdown}, no `process.exit`. + * + * Handlers are detached before the first `await`, so the SIGTERM-mid-close + * window is near zero; if one does land there the signal wins and this promise + * never settles. Never throws — a hung phase is logged and `close()` resolves + * once its budget is spent, so an `afterEach` cannot hang. + */ + async close(options: { timeoutMs?: number } = {}): Promise { + // Memoized separately from the phases: `runOnce()` already guarantees the + // teardown body runs once, but the singleton reset below must also happen + // once. Without this a stale handle's second close() resets whatever app is + // live *now* — `await a.close(); createApp(); await a.close()` broke the + // second app. + this.closed ??= this.closeOnce(options); + return this.closed; + } + + private async closeOnce(options: { timeoutMs?: number }): Promise { + // Before the first await, so a later signal finds no AppKit listener. + this.removeSignalHandlers(); + + const timeoutMs = options.timeoutMs ?? LifecycleManager.CLOSE_TIMEOUT_MS; + + try { + await this.raceWithTimeout(this.runOnce(), timeoutMs, "close"); + } catch (err) { + logger.error( + "close() did not complete within the %dms budget (phase in flight: %s): %O", + timeoutMs, + this.shutdownPhase, + err, + ); + // Returning early leaves the singletons in place: the phases are still + // running and still own these instances, so dropping the pointers now + // would hand the next boot a half-released app. + return; + } + + // Here rather than in runPhases so the signal path skips it — the process is + // dying there, and dropping pointers is pure cost. + releaseCoreSingletons(); + } + + /** No `await` between read and assign — that gap is the re-entrancy window. */ + private runOnce(): Promise { + this.teardown ??= this.runPhases(); + return this.teardown; + } + + /** Run the phases and report an exit code; no process-termination concerns. */ + private async runPhases(): Promise { + logger.info("Starting graceful shutdown..."); + + // Captured before the first await and never re-read: close() may give up + // waiting and reset the singletons while these phases still run, so phase 5 + // would otherwise skip this app's pool or tear down the *next* app's. + let capturedCache: CacheManager | undefined; + try { + capturedCache = CacheManager.getInstanceSync(); + } catch { + // Never initialized — nothing to close in phase 5. + } + let capturedTelemetry: TelemetryManager | undefined; + try { + capturedTelemetry = TelemetryManager.getInstance(); + } catch { + // Unavailable or mocked away — nothing to flush. + } + + let exitCode = 0; + try { const plugins = Array.from(this.context.getPlugins().values()); @@ -174,7 +258,10 @@ export class LifecycleManager { // cache), so they run concurrently — each bounded so a stuck pool // drain or stalled OTLP export cannot eat the remaining budget. this.shutdownPhase = "cache storage close + telemetry flush"; - await Promise.all([this.closeCacheStorage(), this.flushTelemetry()]); + await Promise.all([ + this.closeCacheStorage(capturedCache), + this.flushTelemetry(capturedTelemetry), + ]); logger.info("Graceful shutdown complete"); } catch (err) { @@ -184,16 +271,14 @@ export class LifecycleManager { exitCode = 1; } - clearTimeout(forceExitTimer); - process.exit(exitCode); + return exitCode; } - /** Close the cache storage, bounded and error-isolated. */ - private async closeCacheStorage(): Promise { - let cache: CacheManager; - try { - cache = CacheManager.getInstanceSync(); - } catch { + /** Bounded and error-isolated. Takes the manager — see the capture in {@link runPhases}. */ + private async closeCacheStorage( + cache: CacheManager | undefined, + ): Promise { + if (!cache) { // Cache was never initialized — nothing to close. return; } @@ -208,11 +293,14 @@ export class LifecycleManager { } } - /** Flush and shut down the telemetry SDK, bounded and error-isolated. */ - private async flushTelemetry(): Promise { + /** Bounded and error-isolated. Takes the manager — see {@link closeCacheStorage}. */ + private async flushTelemetry( + telemetry: TelemetryManager | undefined, + ): Promise { + if (!telemetry) return; try { await this.raceWithTimeout( - TelemetryManager.getInstance().shutdown(), + telemetry.shutdown(), LifecycleManager.PHASE_SHUTDOWN_TIMEOUT_MS, "telemetry flush", ); diff --git a/packages/appkit/src/core/reset-singletons.ts b/packages/appkit/src/core/reset-singletons.ts new file mode 100644 index 000000000..122640b82 --- /dev/null +++ b/packages/appkit/src/core/reset-singletons.ts @@ -0,0 +1,59 @@ +import { CacheManager } from "../cache"; +import { ServiceContext } from "../context"; +import { TelemetryReporter } from "../internal-telemetry"; +import { createLogger } from "../logging/logger"; +import { TelemetryManager } from "../telemetry"; + +const logger = createLogger("lifecycle"); + +/** + * How many apps own the core singletons. Refcounted because they are + * process-wide: resetting per app would have booting B rebind A's + * `ServiceContext`, and closing A leave a still-live B with none. + */ +let owners = 0; + +/** + * Claim for a booting app, resetting only when it is the first — the reset + * clears leakage from a previous test, so a concurrent second app must not + * repeat it. + * @internal + */ +export function claimCoreSingletons(): void { + if (owners === 0) dropCoreSingletons(); + owners += 1; +} + +/** + * Release one app's claim, dropping the singletons once none are left. + * @internal + */ +export function releaseCoreSingletons(): void { + owners = Math.max(0, owners - 1); + if (owners === 0) dropCoreSingletons(); +} + +/** + * Drop the four singletons `AppKit._createApp` initializes, ignoring refcounts. + * + * Pointer drops, not teardown — close first or the old app's storage and + * exporters leak. A host that closes then calls `ServiceContext.get()` gets an + * `InitializationError`. + * @internal + */ +export function dropCoreSingletons(): void { + const resets: [string, () => void][] = [ + ["ServiceContext", () => ServiceContext.reset()], + ["CacheManager", () => CacheManager.reset()], + ["TelemetryReporter", () => TelemetryReporter._reset()], + ["TelemetryManager", () => TelemetryManager.reset()], + ]; + + for (const [name, reset] of resets) { + try { + reset(); + } catch (err) { + logger.error("Error resetting %s: %O", name, err); + } + } +} diff --git a/packages/appkit/src/core/tests/app-close.integration.test.ts b/packages/appkit/src/core/tests/app-close.integration.test.ts new file mode 100644 index 000000000..02b62b557 --- /dev/null +++ b/packages/appkit/src/core/tests/app-close.integration.test.ts @@ -0,0 +1,266 @@ +import { + getListeningPort, + mockServiceContext, + setupDatabricksEnv, +} from "@databricks/appkit/testing"; +import type { AppHandle, PluginManifest, PluginMap } from "shared"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; + +import { CacheManager } from "../../cache"; +import { ServiceContext } from "../../context/service-context"; +import { ConfigurationError } from "../../errors"; +import { Plugin, toPlugin } from "../../plugin"; +import { server as serverPlugin } from "../../plugins/server"; +import { createApp } from "../appkit"; + +/** + * Deliberately unmocked — the claim is that `close()` releases *real* resources, + * so a mocked lifecycle would assert nothing. `port: 0` keeps it parallel-safe. + */ + +/** Minimal plugin with a route, so there is something real to serve. */ +class ProbePlugin extends Plugin { + static manifest: PluginManifest = { + name: "probe", + displayName: "Probe", + version: "0.0.0", + description: "close() integration probe", + resources: { required: [] }, + } as unknown as PluginManifest; + + /** Set when the lifecycle actually ran this plugin's teardown. */ + shutdownCalls = 0; + + async shutdown(): Promise { + this.shutdownCalls += 1; + } + + exports() { + return { shutdownCalls: () => this.shutdownCalls }; + } +} +const probe = toPlugin(ProbePlugin); + +/** A plugin whose manifest name collides with the handle's own method. */ +class ClosePlugin extends Plugin { + static manifest: PluginManifest = { + name: "close", + displayName: "Close", + version: "0.0.0", + description: "reserved-name probe", + resources: { required: [] }, + } as unknown as PluginManifest; +} +const closeNamed = toPlugin(ClosePlugin); + +describe("app handle close()", () => { + let serviceContextMock: ReturnType; + + beforeEach(() => { + setupDatabricksEnv(); + ServiceContext.reset(); + serviceContextMock = mockServiceContext(); + }); + + afterEach(() => { + serviceContextMock?.restore(); + }); + + test("releases the bound socket and runs plugin teardown", async () => { + const termBaseline = process.listenerCount("SIGTERM"); + + const app = await createApp({ + plugins: [probe(), serverPlugin({ port: 0, host: "127.0.0.1" })], + }); + + // AppKit installed its handlers, so the count went up. + expect(process.listenerCount("SIGTERM")).toBe(termBaseline + 1); + + const port = await getListeningPort(app.server.getServer()); + const baseUrl = `http://127.0.0.1:${port}`; + await expect( + fetch(`${baseUrl}/health`).then((r) => r.status), + ).resolves.toBe(200); + + await app.close(); + + expect(app.probe.shutdownCalls()).toBe(1); + await expect(fetch(`${baseUrl}/health`)).rejects.toThrow(); + // Signal handlers came back off — what keeps repeated boots from tripping + // MaxListenersExceededWarning. + expect(process.listenerCount("SIGTERM")).toBe(termBaseline); + }); + + test("is idempotent at the app level", async () => { + const app = await createApp({ + plugins: [probe(), serverPlugin({ port: 0, host: "127.0.0.1" })], + }); + await getListeningPort(app.server.getServer()); + + await app.close(); + await expect(app.close()).resolves.toBeUndefined(); + + // The memo means the phases ran once, not twice. + expect(app.probe.shutdownCalls()).toBe(1); + }); + + test("plugin exports stay reachable by name alongside close()", async () => { + const app = await createApp({ + plugins: [probe(), serverPlugin({ port: 0, host: "127.0.0.1" })], + }); + await getListeningPort(app.server.getServer()); + + try { + // Adding `close` to the handle must not shadow or be shadowed by the + // plugin accessors installed with defineProperty. + expect(typeof app.close).toBe("function"); + expect(typeof app.server.getServer).toBe("function"); + expect(typeof app.probe.shutdownCalls).toBe("function"); + expect(typeof app[Symbol.asyncDispose]).toBe("function"); + } finally { + await app.close(); + } + }); + + test("a server-less app still closes cleanly", async () => { + // No server plugin at all: nothing bound a socket, but plugin hooks and the + // telemetry flush still have to run, and close() must not hang. + const app = await createApp({ plugins: [probe()] }); + + await expect(app.close()).resolves.toBeUndefined(); + expect(app.probe.shutdownCalls()).toBe(1); + }); + + test("await using releases the app at scope exit", async () => { + let captured: number | undefined; + let probeHandle: { shutdownCalls: () => number } | undefined; + + { + await using app = await createApp({ + plugins: [probe(), serverPlugin({ port: 0, host: "127.0.0.1" })], + }); + captured = await getListeningPort(app.server.getServer()); + probeHandle = app.probe; + await expect( + fetch(`http://127.0.0.1:${captured}/health`).then((r) => r.status), + ).resolves.toBe(200); + } + + // Scope exited, so asyncDispose ran the same teardown. + expect(probeHandle?.shutdownCalls()).toBe(1); + await expect( + fetch(`http://127.0.0.1:${captured}/health`), + ).rejects.toThrow(); + }); + + test("a plugin named close is rejected instead of silently shadowing", async () => { + // An own property wins over a prototype method, so without this guard the + // plugin would quietly replace teardown rather than fail. + await expect(createApp({ plugins: [closeNamed()] })).rejects.toThrow( + ConfigurationError, + ); + await expect(createApp({ plugins: [closeNamed()] })).rejects.toThrow( + /"close" is reserved|Plugin name "close" is reserved/, + ); + }); + + test("boot, close, boot again in one file — the second app gets a live cache", async () => { + // The stated driver for the whole close() effort: two real boots, two real + // sockets, one process. + // + // Note what this does *not* prove. The cache here is InMemoryStorage, whose + // close() merely clears a Map and stays usable, so this passes with or + // without the singleton resets. The reset's necessity is proven in + // cache/tests/cache-manager-reset.test.ts against storage whose close() is + // terminal, the way PersistentStorage's pool.end() is. + const termBaseline = process.listenerCount("SIGTERM"); + + const first = await createApp({ + plugins: [probe(), serverPlugin({ port: 0, host: "127.0.0.1" })], + }); + const firstPort = await getListeningPort(first.server.getServer()); + await expect( + fetch(`http://127.0.0.1:${firstPort}/health`).then((r) => r.status), + ).resolves.toBe(200); + await first.close(); + + // ServiceContext was reset by close(), so the mock has to be reinstalled — + // exactly what createTestApp will do for the caller. + serviceContextMock.restore(); + serviceContextMock = mockServiceContext(); + + const second = await createApp({ + plugins: [probe(), serverPlugin({ port: 0, host: "127.0.0.1" })], + }); + const secondPort = await getListeningPort(second.server.getServer()); + + expect(secondPort).not.toBe(firstPort); + await expect( + fetch(`http://127.0.0.1:${secondPort}/health`).then((r) => r.status), + ).resolves.toBe(200); + + // The second boot's cache round-trips a write. + const cache = CacheManager.getInstanceSync(); + const key = cache.generateKey(["second-boot"], "test-user"); + await cache.set(key, { alive: true }); + await expect(cache.get(key)).resolves.toEqual({ alive: true }); + + await second.close(); + + await expect( + fetch(`http://127.0.0.1:${secondPort}/health`), + ).rejects.toThrow(); + // Two boots and two closes leave no listener residue. + expect(process.listenerCount("SIGTERM")).toBe(termBaseline); + }); + /** + * Enforced by `tsc --noEmit`, not at runtime: the widening to `AppHandle` is + * only source-compatible if it stays assignable to `PluginMap`, and a + * regression there would break existing callers without failing any assertion. + */ + describe("createApp return-type widening is source-compatible", () => { + test("an AppHandle still satisfies a PluginMap annotation", async () => { + const app = await createApp({ plugins: [probe()] }); + try { + // The pre-widening annotation, unchanged. + const asPluginMap: PluginMap<[ReturnType]> = app; + expect(typeof asPluginMap.probe.shutdownCalls).toBe("function"); + + // And the added members are visible on the widened type. + const asHandle: AppHandle<[ReturnType]> = app; + expect(typeof asHandle.close).toBe("function"); + expect(typeof asHandle[Symbol.asyncDispose]).toBe("function"); + } finally { + await app.close(); + } + }); + }); + + test("a stale handle's second close() cannot reset a newer app", async () => { + // Only reachable through the raw handle: createTestApp's wrapper memoizes + // close(), which masked this. + const first = await createApp({ plugins: [probe()] }); + await first.close(); + + serviceContextMock.restore(); + serviceContextMock = mockServiceContext(); + const second = await createApp({ + plugins: [probe(), serverPlugin({ port: 0, host: "127.0.0.1" })], + }); + const port = await getListeningPort(second.server.getServer()); + + try { + // The phases are memoized, but the singleton release was not — so this + // second call used to drop the singletons the *second* app was using. + await first.close(); + + await expect( + fetch(`http://127.0.0.1:${port}/health`).then((r) => r.status), + ).resolves.toBe(200); + expect(() => CacheManager.getInstanceSync()).not.toThrow(); + expect(() => ServiceContext.get()).not.toThrow(); + } finally { + await second.close(); + } + }); +}); diff --git a/packages/appkit/src/core/tests/lifecycle-manager.test.ts b/packages/appkit/src/core/tests/lifecycle-manager.test.ts index 121e7eb5c..491856e58 100644 --- a/packages/appkit/src/core/tests/lifecycle-manager.test.ts +++ b/packages/appkit/src/core/tests/lifecycle-manager.test.ts @@ -29,6 +29,10 @@ vi.mock("../../telemetry", () => ({ }, })); +vi.mock("../reset-singletons", () => ({ + releaseCoreSingletons: vi.fn(), +})); + vi.mock("../../internal-telemetry", () => ({ TelemetryReporter: { getInstance: vi.fn().mockReturnValue(null), @@ -53,6 +57,7 @@ import { TelemetryReporter } from "../../internal-telemetry"; import { TelemetryManager } from "../../telemetry"; import { LifecycleManager } from "../lifecycle-manager"; import { PluginContext } from "../plugin-context"; +import { releaseCoreSingletons } from "../reset-singletons"; function contextWithPlugins(plugins: Record>) { const ctx = new PluginContext(); @@ -381,4 +386,296 @@ describe("LifecycleManager", () => { onceSpy.mockRestore(); }); }); + + describe("close (the programmatic path)", () => { + test("runs the full teardown sequence without exiting the process", async () => { + const stop = vi.fn(); + vi.mocked(TelemetryReporter.getInstance).mockReturnValue({ + stop, + } as never); + const cacheClose = vi.fn().mockResolvedValue(undefined); + vi.mocked(CacheManager.getInstanceSync).mockReturnValue({ + close: cacheClose, + } as never); + const telemetryShutdown = vi.fn().mockResolvedValue(undefined); + vi.mocked(TelemetryManager.getInstance).mockReturnValue({ + shutdown: telemetryShutdown, + } as never); + + const abortActiveOperations = vi.fn(); + const shutdown = vi.fn().mockResolvedValue(undefined); + const ctx = contextWithPlugins({ + alpha: { name: "alpha", abortActiveOperations, shutdown } as never, + }); + const emit = vi.spyOn(ctx, "emitLifecycle"); + const manager = new LifecycleManager(ctx); + + await manager.close(); + + expect(stop).toHaveBeenCalledTimes(1); + expect(abortActiveOperations).toHaveBeenCalledTimes(1); + expect(shutdown).toHaveBeenCalledTimes(1); + expect(emit).toHaveBeenCalledWith("shutdown"); + expect(cacheClose).toHaveBeenCalledTimes(1); + expect(telemetryShutdown).toHaveBeenCalledTimes(1); + + // The whole point of the split. + expect(exitSpy).not.toHaveBeenCalled(); + expect(releaseCoreSingletons).toHaveBeenCalledTimes(1); + }); + + test("is idempotent: teardown runs once and the second call awaits it", async () => { + let releaseShutdown: (() => void) | undefined; + // Set only once the plugin hook has actually finished. Asserting against + // this flag (rather than counting microtask ticks) is what makes the test + // sensitive to a guard that returns early while teardown is in flight. + let teardownFinished = false; + const shutdown = vi.fn( + () => + new Promise((resolve) => { + releaseShutdown = () => { + teardownFinished = true; + resolve(); + }; + }), + ); + const ctx = contextWithPlugins({ + alpha: { name: "alpha", shutdown } as never, + }); + const manager = new LifecycleManager(ctx); + + const observed: string[] = []; + const first = manager + .close() + .then(() => observed.push(`first:${teardownFinished}`)); + const second = manager + .close() + .then(() => observed.push(`second:${teardownFinished}`)); + + // A full macrotask turn, so a guard that resolves the second caller + // early has every chance to settle before the assertion below. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(observed).toEqual([]); + + releaseShutdown?.(); + await Promise.all([first, second]); + + // Both callers must observe a *completed* teardown. The old boolean + // guard resolved the second caller with teardown still running. + expect(observed).toEqual( + expect.arrayContaining(["first:true", "second:true"]), + ); + expect(shutdown).toHaveBeenCalledTimes(1); + expect(exitSpy).not.toHaveBeenCalled(); + }); + + test("a signal arriving after close() joins the same teardown, not a second one", async () => { + const shutdown = vi.fn().mockResolvedValue(undefined); + const ctx = contextWithPlugins({ + alpha: { name: "alpha", shutdown } as never, + }); + const manager = new LifecycleManager(ctx); + manager.installSignalHandlers(); + + await manager.close(); + // The signal path after a close: teardown is memoized, so the phases do + // not run twice even though shutdown() is still callable. + await manager.shutdown(); + + expect(shutdown).toHaveBeenCalledTimes(1); + }); + + test("close() after a signal-initiated teardown awaits the in-flight one", async () => { + let releaseShutdown: (() => void) | undefined; + // Sentinel rather than a tick count: `close()` reaches the memo through + // raceWithTimeout, so "how many microtasks until it would have settled" is + // not a property the test can rely on. + let teardownFinished = false; + const shutdown = vi.fn( + () => + new Promise((resolve) => { + releaseShutdown = () => { + teardownFinished = true; + resolve(); + }; + }), + ); + const ctx = contextWithPlugins({ + alpha: { name: "alpha", shutdown } as never, + }); + const manager = new LifecycleManager(ctx); + + const signalPath = manager.shutdown(); + await Promise.resolve(); + + let closeSawFinishedTeardown: boolean | undefined; + const closePath = manager.close().then(() => { + closeSawFinishedTeardown = teardownFinished; + }); + + // A full macrotask turn, so a close() that resolved early would have. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(closeSawFinishedTeardown).toBeUndefined(); + + releaseShutdown?.(); + await Promise.all([signalPath, closePath]); + + expect(shutdown).toHaveBeenCalledTimes(1); + // It joined the in-flight teardown rather than resolving alongside it. + expect(closeSawFinishedTeardown).toBe(true); + // The signal wanted the process dead, and still gets it. + expect(exitSpy).toHaveBeenCalledWith(0); + }); + + test("a rejecting plugin shutdown() is isolated and close() still resolves", async () => { + const ctx = contextWithPlugins({ + bad: { + name: "bad", + shutdown: vi.fn().mockRejectedValue(new Error("teardown blew up")), + } as never, + good: { + name: "good", + shutdown: vi.fn().mockResolvedValue(undefined), + } as never, + }); + const manager = new LifecycleManager(ctx); + + await expect(manager.close()).resolves.toBeUndefined(); + expect(mockLoggerError).toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + }); + + test("a hung teardown is bounded by close()'s budget, logged, and never exits", async () => { + vi.useFakeTimers(); + const ctx = contextWithPlugins({ + stuck: { + name: "stuck", + shutdown: vi.fn(() => new Promise(() => {})), + } as never, + }); + const manager = new LifecycleManager(ctx); + + const closing = manager.close({ timeoutMs: 50 }); + await vi.advanceTimersByTimeAsync(60); + await expect(closing).resolves.toBeUndefined(); + + // The error names the phase that was in flight, which is the whole + // reason the phase tracker is retained. + const logged = mockLoggerError.mock.calls + .map((c) => String(c[0])) + .join("\n"); + expect(logged).toContain("close() did not complete"); + const phases = mockLoggerError.mock.calls.flat().map(String).join(" "); + expect(phases).toContain("plugin shutdown() hooks"); + + // A hung teardown must not kill the process on the programmatic path. + expect(exitSpy).not.toHaveBeenCalled(); + + // And it must not drop the singletons: the phases are still running and + // still own those instances, so releasing here hands the next boot a + // half-released app. + expect(releaseCoreSingletons).not.toHaveBeenCalled(); + }); + }); + + describe("signal-handler ownership", () => { + test("close() removes only this manager's listeners", async () => { + const foreign = vi.fn(); + process.on("SIGTERM", foreign); + const baseline = process.listenerCount("SIGTERM"); + + const a = new LifecycleManager(contextWithPlugins({})); + const b = new LifecycleManager(contextWithPlugins({})); + a.installSignalHandlers(); + b.installSignalHandlers(); + expect(process.listenerCount("SIGTERM")).toBe(baseline + 2); + + await a.close(); + + // b's pair survives, and so does the unrelated host listener. + expect(process.listenerCount("SIGTERM")).toBe(baseline + 1); + + await b.close(); + expect(process.listenerCount("SIGTERM")).toBe(baseline); + expect(process.listeners("SIGTERM")).toContain(foreign); + + process.removeListener("SIGTERM", foreign); + }); + + test("listener counts return to the pre-install baseline", async () => { + const termBaseline = process.listenerCount("SIGTERM"); + const intBaseline = process.listenerCount("SIGINT"); + + const manager = new LifecycleManager(contextWithPlugins({})); + manager.installSignalHandlers(); + await manager.close(); + + // This is what keeps repeated boots in one test file from tripping + // MaxListenersExceededWarning at ~6 un-closed apps. + expect(process.listenerCount("SIGTERM")).toBe(termBaseline); + expect(process.listenerCount("SIGINT")).toBe(intBaseline); + }); + + test("removeSignalHandlers is safe when none were installed", () => { + const manager = new LifecycleManager(contextWithPlugins({})); + expect(() => manager.removeSignalHandlers()).not.toThrow(); + }); + }); + + describe("a teardown that outlives close()'s budget", () => { + test("phase 5 still closes the app's own cache and telemetry, not the next app's", async () => { + vi.useFakeTimers(); + + // The app being torn down owns these. + const ownCacheClose = vi.fn().mockResolvedValue(undefined); + const ownTelemetryShutdown = vi.fn().mockResolvedValue(undefined); + vi.mocked(CacheManager.getInstanceSync).mockReturnValue({ + close: ownCacheClose, + } as never); + vi.mocked(TelemetryManager.getInstance).mockReturnValue({ + shutdown: ownTelemetryShutdown, + } as never); + + // A plugin hook slower than close()'s budget but inside its own per-plugin + // budget — the files plugin's 10s drain reaches exactly this state. + let releaseHook: (() => void) | undefined; + const ctx = contextWithPlugins({ + slow: { + name: "slow", + shutdown: vi.fn( + () => + new Promise((resolve) => { + releaseHook = resolve; + }), + ), + } as never, + }); + const manager = new LifecycleManager(ctx); + + const closing = manager.close({ timeoutMs: 50 }); + await vi.advanceTimersByTimeAsync(60); + await expect(closing).resolves.toBeUndefined(); + + // close() has given up waiting. Simulate the next app booting into the + // static slots, so they now answer with a *different* app's resources. + const nextCacheClose = vi.fn().mockResolvedValue(undefined); + const nextTelemetryShutdown = vi.fn().mockResolvedValue(undefined); + vi.mocked(CacheManager.getInstanceSync).mockReturnValue({ + close: nextCacheClose, + } as never); + vi.mocked(TelemetryManager.getInstance).mockReturnValue({ + shutdown: nextTelemetryShutdown, + } as never); + + // Now let the orphaned teardown finish and reach phase 5. + releaseHook?.(); + await vi.advanceTimersByTimeAsync(10); + + // It must act on what it captured at the start, never on the current slots. + expect(ownCacheClose).toHaveBeenCalledTimes(1); + expect(ownTelemetryShutdown).toHaveBeenCalledTimes(1); + expect(nextCacheClose).not.toHaveBeenCalled(); + expect(nextTelemetryShutdown).not.toHaveBeenCalled(); + }); + }); }); diff --git a/packages/appkit/src/index.ts b/packages/appkit/src/index.ts index eac0b27b9..40fa658b8 100644 --- a/packages/appkit/src/index.ts +++ b/packages/appkit/src/index.ts @@ -7,6 +7,7 @@ // Types from shared export type { + AppHandle, BasePluginConfig, CacheConfig, IAppRouter, diff --git a/packages/appkit/src/plugins/agents/tests/dispatch-tool-call.test.ts b/packages/appkit/src/plugins/agents/tests/dispatch-tool-call.test.ts index 70a195f9c..6d23cf07a 100644 --- a/packages/appkit/src/plugins/agents/tests/dispatch-tool-call.test.ts +++ b/packages/appkit/src/plugins/agents/tests/dispatch-tool-call.test.ts @@ -2,7 +2,7 @@ import type express from "express"; import { beforeEach, describe, expect, test, vi } from "vitest"; import { CacheManager } from "../../../cache"; -import { createTestPluginContext } from "../../../testing"; +import { createMockRequest, createTestPluginContext } from "../../../testing"; import { AgentsPlugin } from "../agents"; /** @@ -36,25 +36,15 @@ beforeEach(() => { }; }); -function mockReq(): express.Request { - // Carry OBO headers so PluginContext.executeTool's asUser(req) resolves a - // user scope (the mock context enforces the real token precondition). - const headers: Record = { - "x-forwarded-access-token": "user-token", - "x-forwarded-user": "alice", - }; - return { - body: {}, - headers, - header: (name: string) => headers[name.toLowerCase()], - } as unknown as express.Request; -} - function makeRunState(plugin: AgentsPlugin) { const abortController = new AbortController(); const pushed: unknown[] = []; const runState = { - req: mockReq(), + // `obo` carries the forwarded identity headers so executeTool's asUser(req) + // resolves a user scope (the mock context enforces the token precondition). + req: createMockRequest({ + obo: { token: "user-token", userId: "alice" }, + }) as unknown as express.Request, userId: "alice", requestId: "stream-1", abortController, diff --git a/packages/appkit/src/plugins/agents/tests/route-handler-errors.test.ts b/packages/appkit/src/plugins/agents/tests/route-handler-errors.test.ts index 4aa069a61..1cf819e0c 100644 --- a/packages/appkit/src/plugins/agents/tests/route-handler-errors.test.ts +++ b/packages/appkit/src/plugins/agents/tests/route-handler-errors.test.ts @@ -2,9 +2,29 @@ import type express from "express"; import { beforeEach, describe, expect, test, vi } from "vitest"; import { CacheManager } from "../../../cache"; -import { createTestPluginContext } from "../../../testing"; +import { createMockRequest, createTestPluginContext } from "../../../testing"; import { AgentsPlugin } from "../agents"; +// Partial-mock the tracing module: traceAgent/traceTool still run their +// callbacks, but the trace id is deterministic and run-linking is a spy. +const linkTraceToRun = vi.hoisted(() => vi.fn()); +let mockTraceId: string | undefined; +vi.mock("../mlflow", () => ({ + initAgentTracing: vi.fn(async () => {}), + traceAgent: ( + _name: string, + _inputs: unknown, + fn: (span: { setOutputs: () => void }) => Promise, + ) => fn({ setOutputs: () => {} }), + traceTool: ( + _name: string, + _inputs: unknown, + fn: (span: { setOutputs: () => void }) => Promise, + ) => fn({ setOutputs: () => {} }), + currentTraceId: () => mockTraceId, + linkTraceToRun, +})); + /** * Surface-level guarantees on the agents plugin's HTTP route handlers when * downstream dependencies fail. Prior to PR #305 review finding #1+#2, @@ -21,6 +41,8 @@ import { AgentsPlugin } from "../agents"; */ beforeEach(() => { + linkTraceToRun.mockClear(); + mockTraceId = undefined; (CacheManager as any).instance = { get: vi.fn(), set: vi.fn(), @@ -33,15 +55,10 @@ beforeEach(() => { }); function mockReq(body: unknown, userId = "alice"): express.Request { - const headers: Record = { - "x-forwarded-user": userId, - "x-forwarded-access-token": "fake-token", - }; - return { + return createMockRequest({ body, - headers, - header: (name: string) => headers[name.toLowerCase()], - } as unknown as express.Request; + obo: { token: "fake-token", userId }, + }) as unknown as express.Request; } function mockRes() { @@ -61,12 +78,12 @@ function mockRes() { }; } -function seedPlugin(): AgentsPlugin { +function seedPlugin(adapter: unknown = { async *run() {} }): AgentsPlugin { const plugin = new AgentsPlugin({ dir: false }); (plugin as any).agents.set("default", { name: "default", instructions: "hi", - adapter: { async *run() {} }, + adapter, toolIndex: new Map(), }); (plugin as any).defaultAgentName = "default"; @@ -374,6 +391,70 @@ describe("POST /invocations & /responses — successful invoke", () => { text: "hello world", }); }); + + function seedEchoPlugin(): AgentsPlugin { + const plugin = seedPlugin({ + async *run() { + yield { type: "message_delta", content: "ok" }; + }, + }); + (plugin as any).threadStore = { + create: vi.fn().mockResolvedValue({ id: "t-new", messages: [] }), + addMessage: vi.fn(), + delete: vi.fn(), + }; + return plugin; + } + + async function invoke( + plugin: AgentsPlugin, + body: unknown, + ): Promise> { + const { res, json } = mockRes(); + await ( + plugin as unknown as { + _handleInvoke: ( + r: express.Request, + w: express.Response, + ) => Promise; + } + )._handleInvoke(mockReq(body), res); + return json.mock.calls[0]?.[0] as Record; + } + + test("links the trace to the run and echoes mlflow_trace_id when tracing is on", async () => { + mockTraceId = "tr-abc123"; + const plugin = seedEchoPlugin(); + + const payload = await invoke(plugin, { + input: "hi", + mlflowRunId: "run-99", + }); + + expect(linkTraceToRun).toHaveBeenCalledWith("run-99"); + expect(payload.mlflow_trace_id).toBe("tr-abc123"); + }); + + test("omits mlflow_trace_id and does not link when tracing is off", async () => { + mockTraceId = undefined; // currentTraceId() no-ops when disabled + const plugin = seedEchoPlugin(); + + const payload = await invoke(plugin, { input: "hi" }); + + expect(linkTraceToRun).not.toHaveBeenCalled(); + expect(payload).not.toHaveProperty("mlflow_trace_id"); + }); + + test("does not link when no run id is supplied even if tracing is on", async () => { + mockTraceId = "tr-standalone"; + const plugin = seedEchoPlugin(); + + const payload = await invoke(plugin, { input: "hi" }); + + expect(linkTraceToRun).not.toHaveBeenCalled(); + // Trace still exists and its id is surfaced — just not linked to a run. + expect(payload.mlflow_trace_id).toBe("tr-standalone"); + }); }); describe("/invocations and /responses are aliases", () => { diff --git a/packages/appkit/src/plugins/analytics/tests/analytics.integration.test.ts b/packages/appkit/src/plugins/analytics/tests/analytics.integration.test.ts index e099c8350..cf1475bd0 100644 --- a/packages/appkit/src/plugins/analytics/tests/analytics.integration.test.ts +++ b/packages/appkit/src/plugins/analytics/tests/analytics.integration.test.ts @@ -1,13 +1,11 @@ -import type { Server } from "node:http"; - import { - createConfigurableMockWorkspaceClient, createFailedSQLResponse, createSuccessfulSQLResponse, - mockServiceContext, + createTestApp, + getMockFn, parseSSEResponse, - setupDatabricksEnv, -} from "@tools/test-helpers"; + type TestApp, +} from "@databricks/appkit/testing"; import { sql } from "shared"; import { afterAll, @@ -20,85 +18,37 @@ import { } from "vitest"; import { AppManager } from "../../../app"; -import { ServiceContext } from "../../../context/service-context"; -import { createApp } from "../../../core"; -import { server as serverPlugin } from "../../server"; import { analytics } from "../index"; const getAppQuerySpy = vi.spyOn(AppManager.prototype, "getAppQuery"); -/** - * Wait for the supplied server to finish binding, then return the OS-assigned - * port. Required when the test passes `port: 0` to `serverPlugin` — - * `app.server.start()` returns as soon as `listen()` is invoked but before the - * bind completes, so `server.address()` returns `null` until the `listening` - * event fires. - */ -async function getListeningPort(server: Server): Promise { - const addr = server.address(); - if (addr && typeof addr === "object" && typeof addr.port === "number") { - return addr.port; - } - await new Promise((resolve, reject) => { - server.once("listening", () => resolve()); - server.once("error", (err) => reject(err)); - }); - const ready = server.address(); - if (!ready || typeof ready !== "object") { - throw new Error("Server is listening but address() returned null"); - } - return ready.port; -} - describe("Analytics Plugin Integration", () => { - let server: Server; - let baseUrl: string; - let serviceContextMock: Awaited>; - let mockClient: ReturnType; + let app: TestApp<[ReturnType]>; + /** The SQL mock the analytics route drives, via the harness's client. */ + let executeStatement: ReturnType; + let getStatement: ReturnType; beforeAll(async () => { - setupDatabricksEnv(); - ServiceContext.reset(); - - mockClient = createConfigurableMockWorkspaceClient(); - serviceContextMock = await mockServiceContext({ - serviceDatabricksClient: mockClient.client, - }); - - const app = await createApp({ - plugins: [ - // port: 0 → OS assigns an ephemeral port. Avoids EADDRINUSE / cross-test - // route bleed when another integration test (e.g. server.integration) - // holds a fixed port concurrently in the shared vitest worker pool. - serverPlugin({ - port: 0, - host: "127.0.0.1", - }), - analytics({}), - ], - }); - - server = app.server.getServer(); - const port = await getListeningPort(server); - baseUrl = `http://127.0.0.1:${port}`; + // The harness owns the env setup, the singleton resets, the mock client, the + // server plugin on an ephemeral port, and the teardown. + app = await createTestApp({ plugins: [analytics({})] }); + executeStatement = getMockFn( + app.client, + "statementExecution.executeStatement", + ); + getStatement = getMockFn(app.client, "statementExecution.getStatement"); }); afterAll(async () => { getAppQuerySpy?.mockRestore(); - serviceContextMock?.restore(); - if (server) { - await new Promise((resolve, reject) => { - server.close((err) => { - if (err) reject(err); - else resolve(); - }); - }); - } + await app?.close(); }); beforeEach(() => { - mockClient.mocks.executeStatement.mockReset(); - mockClient.mocks.getStatement.mockReset(); + // Reset drops the built-in canned SUCCEEDED default too, matching the + // "script it yourself" semantics this suite relied on before. + executeStatement.mockReset(); + getStatement.mockReset(); getAppQuerySpy.mockReset(); }); @@ -119,18 +69,13 @@ describe("Analytics Plugin Integration", () => { isAsUser: false, }); - mockClient.mocks.executeStatement.mockResolvedValueOnce( + executeStatement.mockResolvedValueOnce( createSuccessfulSQLResponse(mockData, mockColumns), ); - const response = await fetch( - `${baseUrl}/api/analytics/query/test_query`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ parameters: {} }), - }, - ); + const response = await app.post("/api/analytics/query/test_query", { + body: { parameters: {} }, + }); expect(response.status).toBe(200); expect(response.headers.get("Content-Type")).toBe( @@ -144,8 +89,8 @@ describe("Analytics Plugin Integration", () => { { name: "Bob", age: "25" }, ]); - expect(mockClient.mocks.executeStatement).toHaveBeenCalledTimes(1); - expect(mockClient.mocks.executeStatement).toHaveBeenCalledWith( + expect(executeStatement).toHaveBeenCalledTimes(1); + expect(executeStatement).toHaveBeenCalledWith( expect.objectContaining({ statement: testQuery, warehouse_id: "test-warehouse-id", @@ -162,26 +107,17 @@ describe("Analytics Plugin Integration", () => { isAsUser: false, }); - mockClient.mocks.executeStatement.mockResolvedValueOnce( + executeStatement.mockResolvedValueOnce( createSuccessfulSQLResponse([["Alice"]], [{ name: "name" }]), ); - const response = await fetch( - `${baseUrl}/api/analytics/query/user_query`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - parameters: { - user_id: sql.string("123"), - }, - }), - }, - ); + const response = await app.post("/api/analytics/query/user_query", { + body: { parameters: { user_id: sql.string("123") } }, + }); expect(response.status).toBe(200); - const callArgs = mockClient.mocks.executeStatement.mock.calls[0][0]; + const callArgs = executeStatement.mock.calls[0][0]; expect(callArgs.parameters).toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -198,20 +134,15 @@ describe("Analytics Plugin Integration", () => { test("should return 404 when query does not exist", async () => { getAppQuerySpy.mockResolvedValueOnce(null); - const response = await fetch( - `${baseUrl}/api/analytics/query/nonexistent`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ parameters: {} }), - }, - ); + const response = await app.post("/api/analytics/query/nonexistent", { + body: { parameters: {} }, + }); expect(response.status).toBe(404); const data = await response.json(); expect(data).toEqual({ error: "Query not found" }); - expect(mockClient.mocks.executeStatement).not.toHaveBeenCalled(); + expect(executeStatement).not.toHaveBeenCalled(); }); }); @@ -222,14 +153,12 @@ describe("Analytics Plugin Integration", () => { isAsUser: false, }); - mockClient.mocks.executeStatement.mockResolvedValue( + executeStatement.mockResolvedValue( createFailedSQLResponse("Table not found"), ); - const response = await fetch(`${baseUrl}/api/analytics/query/broken`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ parameters: {} }), + const response = await app.post("/api/analytics/query/broken", { + body: { parameters: {} }, }); expect(response.status).toBe(200); @@ -243,14 +172,10 @@ describe("Analytics Plugin Integration", () => { isAsUser: false, }); - mockClient.mocks.executeStatement.mockRejectedValue( - new Error("Network error"), - ); + executeStatement.mockRejectedValue(new Error("Network error")); - const response = await fetch(`${baseUrl}/api/analytics/query/error`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ parameters: {} }), + const response = await app.post("/api/analytics/query/error", { + body: { parameters: {} }, }); expect(response.status).toBe(200); @@ -268,33 +193,23 @@ describe("Analytics Plugin Integration", () => { isAsUser: false, }); - mockClient.mocks.executeStatement.mockResolvedValue( + executeStatement.mockResolvedValue( createSuccessfulSQLResponse([["cached_value"]], [{ name: "value" }]), ); - const response1 = await fetch( - `${baseUrl}/api/analytics/query/cache_test`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ parameters: {} }), - }, - ); + const response1 = await app.post("/api/analytics/query/cache_test", { + body: { parameters: {} }, + }); const data1 = await parseSSEResponse(response1); - const response2 = await fetch( - `${baseUrl}/api/analytics/query/cache_test`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ parameters: {} }), - }, - ); + const response2 = await app.post("/api/analytics/query/cache_test", { + body: { parameters: {} }, + }); const data2 = await parseSSEResponse(response2); expect(data1.data).toEqual([{ value: "cached_value" }]); expect(data2.data).toEqual([{ value: "cached_value" }]); - expect(mockClient.mocks.executeStatement).toHaveBeenCalledTimes(1); + expect(executeStatement).toHaveBeenCalledTimes(1); }); }); }); diff --git a/packages/appkit/src/plugins/analytics/tests/analytics.test.ts b/packages/appkit/src/plugins/analytics/tests/analytics.test.ts index 5101f9424..2151103eb 100644 --- a/packages/appkit/src/plugins/analytics/tests/analytics.test.ts +++ b/packages/appkit/src/plugins/analytics/tests/analytics.test.ts @@ -1708,7 +1708,6 @@ describe("Analytics Plugin", () => { expect(resultIdx).toBeGreaterThanOrEqual(0); expect(warehouseIdx).toBeLessThan(resultIdx); - // The status payload should include the RUNNING state. expect(mockRes.write).toHaveBeenCalledWith( expect.stringMatching(/"type":"warehouse_status".*"state":"RUNNING"/), ); diff --git a/packages/appkit/src/plugins/files/tests/plugin.integration.test.ts b/packages/appkit/src/plugins/files/tests/plugin.integration.test.ts index 3be68b315..0134c09e6 100644 --- a/packages/appkit/src/plugins/files/tests/plugin.integration.test.ts +++ b/packages/appkit/src/plugins/files/tests/plugin.integration.test.ts @@ -1,6 +1,10 @@ import http, { type Server } from "node:http"; -import { mockServiceContext, setupDatabricksEnv } from "@tools/test-helpers"; +import { + getListeningPort, + mockServiceContext, + setupDatabricksEnv, +} from "@databricks/appkit/testing"; import { afterAll, beforeAll, @@ -67,29 +71,6 @@ const MOCK_AUTH_HEADERS = { /** Volume key used in all integration tests. */ const VOL = "files"; -/** - * Wait for the supplied server to finish binding, then return the - * OS-assigned port. Required when tests pass `port: 0` to `serverPlugin` - * — `appkit.server.start()` returns as soon as `listen()` is invoked but - * before the bind completes, so `server.address()` returns `null` until - * the `listening` event fires. - */ -async function getListeningPort(server: Server): Promise { - const addr = server.address(); - if (addr && typeof addr === "object" && typeof addr.port === "number") { - return addr.port; - } - await new Promise((resolve, reject) => { - server.once("listening", () => resolve()); - server.once("error", (err) => reject(err)); - }); - const ready = server.address(); - if (!ready || typeof ready !== "object") { - throw new Error("Server is listening but address() returned null"); - } - return ready.port; -} - describe("Files Plugin Integration", () => { let server: Server; let baseUrl: string; diff --git a/packages/appkit/src/plugins/genie/tests/genie.test.ts b/packages/appkit/src/plugins/genie/tests/genie.test.ts index 2d867d335..2ada2ef3d 100644 --- a/packages/appkit/src/plugins/genie/tests/genie.test.ts +++ b/packages/appkit/src/plugins/genie/tests/genie.test.ts @@ -339,13 +339,14 @@ describe("Genie Plugin", () => { // the handler actually wrote (captured by the mock response). toEmit pins // the real event ORDER; collect() lets us also pin the key payload values // structurally, not by brittle substring match. - await expectStream(mockRes).toEmit( + const stream = expectStream(mockRes); + await stream.toEmit( "message_start", "status", "message_result", "query_result", ); - const events = await expectStream(mockRes).collect(); + const events = await stream.collect(); expect(events.find((e) => e.type === "message_start")).toMatchObject({ conversationId: "new-conv-id", }); diff --git a/packages/appkit/src/plugins/jobs/tests/plugin.test.ts b/packages/appkit/src/plugins/jobs/tests/plugin.test.ts index 783debc8a..c706d648b 100644 --- a/packages/appkit/src/plugins/jobs/tests/plugin.test.ts +++ b/packages/appkit/src/plugins/jobs/tests/plugin.test.ts @@ -12,38 +12,47 @@ import { import { mapParams } from "../params"; import { JobsPlugin, jobs } from "../plugin"; -const { mockClient, mockCacheInstance } = vi.hoisted(() => { - const mockJobsApi = { - runNow: vi.fn(), - submit: vi.fn(), - getRun: vi.fn(), - getRunOutput: vi.fn(), - cancelRun: vi.fn(), - listRuns: vi.fn(), - get: vi.fn(), - }; - - const mockClient = { - jobs: mockJobsApi, - config: { - host: "https://test.databricks.com", - authenticate: vi.fn(), - }, - }; +const { mockClient, jobsApi, mockCacheInstance } = await vi.hoisted( + async () => { + // The testing kit's fake, not a hand-rolled literal: the seven jobs methods, + // `config.host` as a real string, and `config.authenticate` all come for free, + // and any *other* service this plugin grows into resolves instead of throwing. + // Imported inside the hoisted factory because the factory runs before the + // file's own imports are evaluated. + const { createMockWorkspaceClient, getMockFn } = + await import("../../../testing/mock-workspace-client"); + + const mockClient = createMockWorkspaceClient(); + + // Facade accessors are typed against the legacy SDK, so `.mockResolvedValue` + // on them would not typecheck. `getMockFn` is the typed handle; it mints + // idempotently, so these are the very functions the plugin will call. + const jobsApi = { + runNow: getMockFn(mockClient, "jobs.runNow"), + submit: getMockFn(mockClient, "jobs.submit"), + getRun: getMockFn(mockClient, "jobs.getRun"), + getRunOutput: getMockFn(mockClient, "jobs.getRunOutput"), + cancelRun: getMockFn(mockClient, "jobs.cancelRun"), + listRuns: getMockFn(mockClient, "jobs.listRuns"), + get: getMockFn(mockClient, "jobs.get"), + }; - const mockCacheInstance = { - get: vi.fn(), - set: vi.fn(), - delete: vi.fn(), - getOrExecute: vi.fn( - async (_key: unknown[], fn: (signal?: AbortSignal) => Promise) => - fn(), - ), - generateKey: vi.fn(), - }; + const mockCacheInstance = { + get: vi.fn(), + set: vi.fn(), + delete: vi.fn(), + getOrExecute: vi.fn( + async ( + _key: unknown[], + fn: (signal?: AbortSignal) => Promise, + ) => fn(), + ), + generateKey: vi.fn(), + }; - return { mockJobsApi, mockClient, mockCacheInstance }; -}); + return { mockClient, jobsApi, mockCacheInstance }; + }, +); vi.mock("../../../workspace-client", async (importOriginal) => { const actual = @@ -290,7 +299,7 @@ describe("JobsPlugin", () => { test("runNow passes configured job_id to connector", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); const plugin = new JobsPlugin({}); const exported = plugin.exports(); @@ -298,7 +307,7 @@ describe("JobsPlugin", () => { await handle.runNow(); - expect(mockClient.jobs.runNow).toHaveBeenCalledWith( + expect(jobsApi.runNow).toHaveBeenCalledWith( expect.objectContaining({ job_id: 123 }), expect.anything(), ); @@ -307,7 +316,7 @@ describe("JobsPlugin", () => { test("runNow merges user params with configured job_id (no taskType)", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); const plugin = new JobsPlugin({}); const exported = plugin.exports(); @@ -317,7 +326,7 @@ describe("JobsPlugin", () => { notebook_params: { key: "value" }, }); - expect(mockClient.jobs.runNow).toHaveBeenCalledWith( + expect(jobsApi.runNow).toHaveBeenCalledWith( expect.objectContaining({ job_id: 123, notebook_params: { key: "value" }, @@ -349,7 +358,7 @@ describe("JobsPlugin", () => { test("runNow maps validated params to SDK fields when taskType is set", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); const plugin = new JobsPlugin({ jobs: { @@ -363,7 +372,7 @@ describe("JobsPlugin", () => { await handle.runNow({ key: "value" }); - expect(mockClient.jobs.runNow).toHaveBeenCalledWith( + expect(jobsApi.runNow).toHaveBeenCalledWith( expect.objectContaining({ job_id: 123, notebook_params: { key: "value" }, @@ -375,7 +384,7 @@ describe("JobsPlugin", () => { test("runNow skips validation when no schema is configured", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -388,7 +397,7 @@ describe("JobsPlugin", () => { test("getRun wraps call in execute", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.getRun.mockResolvedValue({ + jobsApi.getRun.mockResolvedValue({ run_id: 1, state: { life_cycle_state: "TERMINATED" }, }); @@ -415,7 +424,7 @@ describe("JobsPlugin", () => { test("getJob wraps call in execute", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.get.mockResolvedValue({ job_id: 123 }); + jobsApi.get.mockResolvedValue({ job_id: 123 }); const plugin = new JobsPlugin({}); const executeSpy = vi.spyOn(plugin as any, "execute"); @@ -439,7 +448,7 @@ describe("JobsPlugin", () => { test("listRuns clamps caller-supplied limit before calling the SDK", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.listRuns.mockReturnValue((async function* () {})()); + jobsApi.listRuns.mockReturnValue((async function* () {})()); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -447,7 +456,7 @@ describe("JobsPlugin", () => { await handle.listRuns({ limit: 10000 }); // SDK should receive the clamped limit, not the caller-supplied 10000. - expect(mockClient.jobs.listRuns).toHaveBeenCalledWith( + expect(jobsApi.listRuns).toHaveBeenCalledWith( expect.objectContaining({ limit: 100 }), expect.anything(), ); @@ -457,8 +466,8 @@ describe("JobsPlugin", () => { process.env.DATABRICKS_JOB_ETL = "123"; // Pre-flight getRun verifies the run belongs to the configured jobId. - mockClient.jobs.getRun.mockResolvedValue({ run_id: 1, job_id: 123 }); - mockClient.jobs.cancelRun.mockResolvedValue(undefined); + jobsApi.getRun.mockResolvedValue({ run_id: 1, job_id: 123 }); + jobsApi.cancelRun.mockResolvedValue(undefined); const plugin = new JobsPlugin({}); const executeSpy = vi.spyOn(plugin as any, "execute"); @@ -478,8 +487,8 @@ describe("JobsPlugin", () => { test("runAndWait yields status updates and terminates on TERMINATED", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); - mockClient.jobs.getRun + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.getRun .mockResolvedValueOnce({ run_id: 42, state: { life_cycle_state: "RUNNING" }, @@ -505,7 +514,7 @@ describe("JobsPlugin", () => { test("runAndWait throws when runNow returns no run_id", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({}); + jobsApi.runNow.mockResolvedValue({}); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -521,7 +530,7 @@ describe("JobsPlugin", () => { test("runNow returns error result on execute failure", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockRejectedValue(new Error("API timeout")); + jobsApi.runNow.mockRejectedValue(new Error("API timeout")); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -538,9 +547,7 @@ describe("JobsPlugin", () => { test("cancelRun returns error result on execute failure", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.cancelRun.mockRejectedValue( - new Error("Permission denied"), - ); + jobsApi.cancelRun.mockRejectedValue(new Error("Permission denied")); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -556,9 +563,7 @@ describe("JobsPlugin", () => { test("getRun returns error result on execute failure", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.getRun.mockRejectedValue( - new Error("Internal server error"), - ); + jobsApi.getRun.mockRejectedValue(new Error("Internal server error")); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -574,7 +579,7 @@ describe("JobsPlugin", () => { test("listRuns returns error result on execute failure", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.listRuns.mockImplementation(() => { + jobsApi.listRuns.mockImplementation(() => { throw new Error("Auth failure"); }); @@ -594,7 +599,7 @@ describe("JobsPlugin", () => { const error = new Error("Detailed internal failure: db connection reset"); (error as any).statusCode = 403; - mockClient.jobs.getRun.mockRejectedValue(error); + jobsApi.getRun.mockRejectedValue(error); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -611,7 +616,7 @@ describe("JobsPlugin", () => { test("successful operations return ok result with data", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -628,7 +633,7 @@ describe("JobsPlugin", () => { test("getRun returns 404 when run.job_id does not match configured jobId", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); + jobsApi.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -641,8 +646,8 @@ describe("JobsPlugin", () => { test("getRunOutput returns 404 when run belongs to another job", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); - mockClient.jobs.getRunOutput.mockResolvedValue({ logs: "nope" }); + jobsApi.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); + jobsApi.getRunOutput.mockResolvedValue({ logs: "nope" }); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -651,14 +656,14 @@ describe("JobsPlugin", () => { expect(result.ok).toBe(false); if (!result.ok) expect(result.status).toBe(404); // Should never have called getRunOutput on the upstream SDK - expect(mockClient.jobs.getRunOutput).not.toHaveBeenCalled(); + expect(jobsApi.getRunOutput).not.toHaveBeenCalled(); }); test("cancelRun returns 404 when run belongs to another job", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); - mockClient.jobs.cancelRun.mockResolvedValue(undefined); + jobsApi.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); + jobsApi.cancelRun.mockResolvedValue(undefined); const plugin = new JobsPlugin({}); const handle = plugin.exports()("etl"); @@ -666,13 +671,13 @@ describe("JobsPlugin", () => { const result = await handle.cancelRun(99); expect(result.ok).toBe(false); if (!result.ok) expect(result.status).toBe(404); - expect(mockClient.jobs.cancelRun).not.toHaveBeenCalled(); + expect(jobsApi.cancelRun).not.toHaveBeenCalled(); }); test("getRun succeeds when run.job_id matches configured jobId", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.getRun.mockResolvedValue({ + jobsApi.getRun.mockResolvedValue({ run_id: 42, job_id: 123, state: { life_cycle_state: "TERMINATED" }, @@ -696,7 +701,7 @@ describe("JobsPlugin", () => { const { JobsConnector } = await import("../../../connectors/jobs"); const connector = new JobsConnector({}); - mockClient.jobs.get.mockResolvedValue({ job_id: 123 }); + jobsApi.get.mockResolvedValue({ job_id: 123 }); const controller = new AbortController(); await connector.getJob( @@ -718,8 +723,8 @@ describe("JobsPlugin", () => { test("runAndWait stops polling when signal is aborted", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); - mockClient.jobs.getRun.mockResolvedValue({ + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.getRun.mockResolvedValue({ run_id: 42, state: { life_cycle_state: "RUNNING" }, }); @@ -829,21 +834,21 @@ describe("JobsPlugin", () => { process.env.DATABRICKS_JOB_ETL = "100"; process.env.DATABRICKS_JOB_ML = "200"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 1 }); + jobsApi.runNow.mockResolvedValue({ run_id: 1 }); const plugin = new JobsPlugin({}); const exported = plugin.exports(); await exported("etl").runNow(); - expect(mockClient.jobs.runNow).toHaveBeenCalledWith( + expect(jobsApi.runNow).toHaveBeenCalledWith( expect.objectContaining({ job_id: 100 }), expect.anything(), ); - mockClient.jobs.runNow.mockClear(); + jobsApi.runNow.mockClear(); await exported("ml").runNow(); - expect(mockClient.jobs.runNow).toHaveBeenCalledWith( + expect(jobsApi.runNow).toHaveBeenCalledWith( expect.objectContaining({ job_id: 200 }), expect.anything(), ); @@ -1081,7 +1086,7 @@ describe("injectRoutes", () => { test("returns runId on successful non-streaming run", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); @@ -1203,7 +1208,7 @@ describe("injectRoutes", () => { { run_id: 1, state: { life_cycle_state: "TERMINATED" } }, { run_id: 2, state: { life_cycle_state: "RUNNING" } }, ]; - mockClient.jobs.listRuns.mockReturnValue( + jobsApi.listRuns.mockReturnValue( (async function* () { for (const run of mockRuns) yield run; })(), @@ -1241,7 +1246,7 @@ describe("injectRoutes", () => { test("passes limit query param to listRuns", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.listRuns.mockReturnValue((async function* () {})()); + jobsApi.listRuns.mockReturnValue((async function* () {})()); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); @@ -1268,7 +1273,7 @@ describe("injectRoutes", () => { await handler(mockReq, mockRes); // Verify the connector was called with limit 5 - expect(mockClient.jobs.listRuns).toHaveBeenCalledWith( + expect(jobsApi.listRuns).toHaveBeenCalledWith( expect.objectContaining({ limit: 5 }), expect.anything(), ); @@ -1284,7 +1289,7 @@ describe("injectRoutes", () => { job_id: 123, state: { life_cycle_state: "TERMINATED" }, }; - mockClient.jobs.getRun.mockResolvedValue(mockRun); + jobsApi.getRun.mockResolvedValue(mockRun); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); @@ -1351,7 +1356,7 @@ describe("injectRoutes", () => { process.env.DATABRICKS_JOB_ETL = "123"; // Run exists upstream but is owned by job 456, not the configured 123. - mockClient.jobs.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); + jobsApi.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); @@ -1393,7 +1398,7 @@ describe("injectRoutes", () => { run_id: 42, state: { life_cycle_state: "TERMINATED" }, }; - mockClient.jobs.listRuns.mockReturnValue( + jobsApi.listRuns.mockReturnValue( (async function* () { yield mockRun; })(), @@ -1432,7 +1437,7 @@ describe("injectRoutes", () => { test("returns null status when no runs exist", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.listRuns.mockReturnValue((async function* () {})()); + jobsApi.listRuns.mockReturnValue((async function* () {})()); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); @@ -1469,8 +1474,8 @@ describe("injectRoutes", () => { test("cancels run and returns 204", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.getRun.mockResolvedValue({ run_id: 42, job_id: 123 }); - mockClient.jobs.cancelRun.mockResolvedValue(undefined); + jobsApi.getRun.mockResolvedValue({ run_id: 42, job_id: 123 }); + jobsApi.cancelRun.mockResolvedValue(undefined); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); @@ -1540,8 +1545,8 @@ describe("injectRoutes", () => { process.env.DATABRICKS_JOB_ETL = "123"; // Pre-flight getRun reports a run owned by a different job. - mockClient.jobs.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); - mockClient.jobs.cancelRun.mockResolvedValue(undefined); + jobsApi.getRun.mockResolvedValue({ run_id: 99, job_id: 456 }); + jobsApi.cancelRun.mockResolvedValue(undefined); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); @@ -1570,7 +1575,7 @@ describe("injectRoutes", () => { expect(mockRes.status).toHaveBeenCalledWith(404); // Must not fall through to the cancel call or the 204. - expect(mockClient.jobs.cancelRun).not.toHaveBeenCalled(); + expect(jobsApi.cancelRun).not.toHaveBeenCalled(); expect(mockRes.end).not.toHaveBeenCalled(); }); @@ -1722,7 +1727,7 @@ describe("injectRoutes", () => { test("allows exactly MAX_UNVALIDATED_PARAM_KEYS (50) keys without schema", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); const plugin = new JobsPlugin({ jobs: { etl: { taskType: "notebook" } }, @@ -1760,13 +1765,13 @@ describe("injectRoutes", () => { // 50 keys is under the cap — request proceeds to the SDK. expect(mockRes.json).toHaveBeenCalledWith({ runId: 42 }); - expect(mockClient.jobs.runNow).toHaveBeenCalled(); + expect(jobsApi.runNow).toHaveBeenCalled(); }); test("allows undefined params", async () => { process.env.DATABRICKS_JOB_ETL = "123"; - mockClient.jobs.runNow.mockResolvedValue({ run_id: 42 }); + jobsApi.runNow.mockResolvedValue({ run_id: 42 }); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); @@ -1807,7 +1812,7 @@ describe("injectRoutes", () => { const error = new Error("Sensitive internal detail: token expired"); (error as any).statusCode = 403; - mockClient.jobs.runNow.mockRejectedValue(error); + jobsApi.runNow.mockRejectedValue(error); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); @@ -1849,7 +1854,7 @@ describe("injectRoutes", () => { const error = new Error("Unauthorized"); (error as any).statusCode = 401; - mockClient.jobs.listRuns.mockImplementation(() => { + jobsApi.listRuns.mockImplementation(() => { throw error; }); @@ -1884,10 +1889,10 @@ describe("injectRoutes", () => { process.env.DATABRICKS_JOB_ETL = "123"; // Pre-flight succeeds so we reach the actual cancel call. - mockClient.jobs.getRun.mockResolvedValue({ run_id: 42, job_id: 123 }); + jobsApi.getRun.mockResolvedValue({ run_id: 42, job_id: 123 }); const error = new Error("Forbidden"); (error as any).statusCode = 403; - mockClient.jobs.cancelRun.mockRejectedValue(error); + jobsApi.cancelRun.mockRejectedValue(error); const plugin = new JobsPlugin({}); const routeSpy = vi.spyOn(plugin as any, "route"); diff --git a/packages/appkit/src/plugins/server/tests/server.integration.test.ts b/packages/appkit/src/plugins/server/tests/server.integration.test.ts index 6502af8ee..51036cbee 100644 --- a/packages/appkit/src/plugins/server/tests/server.integration.test.ts +++ b/packages/appkit/src/plugins/server/tests/server.integration.test.ts @@ -1,6 +1,10 @@ import type { Server } from "node:http"; -import { mockServiceContext, setupDatabricksEnv } from "@tools/test-helpers"; +import { + getListeningPort, + mockServiceContext, + setupDatabricksEnv, +} from "@databricks/appkit/testing"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; // Set required env vars BEFORE imports that use them @@ -20,7 +24,9 @@ describe("ServerPlugin Integration", () => { let server: Server; let baseUrl: string; let serviceContextMock: Awaited>; - const TEST_PORT = 9876; // Use non-standard port to avoid conflicts + // This block alone pins a port, because it asserts the server honours a + // configured one. Every other block below uses an ephemeral port. + const TEST_PORT = 9876; beforeAll(async () => { setupDatabricksEnv(); @@ -37,7 +43,7 @@ describe("ServerPlugin Integration", () => { }); server = app.server.getServer(); - baseUrl = `http://127.0.0.1:${TEST_PORT}`; + baseUrl = `http://127.0.0.1:${await getListeningPort(server)}`; // Wait a bit for server to be ready await new Promise((resolve) => setTimeout(resolve, 100)); @@ -90,7 +96,6 @@ describe("ServerPlugin with custom plugin", () => { let server: Server; let baseUrl: string; let serviceContextMock: Awaited>; - const TEST_PORT = 9877; beforeAll(async () => { setupDatabricksEnv(); @@ -122,7 +127,7 @@ describe("ServerPlugin with custom plugin", () => { const app = await createApp({ plugins: [ serverPlugin({ - port: TEST_PORT, + port: 0, host: "127.0.0.1", }), testPlugin({}), @@ -130,9 +135,7 @@ describe("ServerPlugin with custom plugin", () => { }); server = app.server.getServer(); - baseUrl = `http://127.0.0.1:${TEST_PORT}`; - - await new Promise((resolve) => setTimeout(resolve, 100)); + baseUrl = `http://127.0.0.1:${await getListeningPort(server)}`; }); afterAll(async () => { @@ -174,7 +177,6 @@ describe("ServerPlugin with extend() via onPluginsReady", () => { let server: Server; let baseUrl: string; let serviceContextMock: Awaited>; - const TEST_PORT = 9878; beforeAll(async () => { setupDatabricksEnv(); @@ -184,7 +186,7 @@ describe("ServerPlugin with extend() via onPluginsReady", () => { const app = await createApp({ plugins: [ serverPlugin({ - port: TEST_PORT, + port: 0, host: "127.0.0.1", }), ], @@ -198,9 +200,7 @@ describe("ServerPlugin with extend() via onPluginsReady", () => { }); server = app.server.getServer(); - baseUrl = `http://127.0.0.1:${TEST_PORT}`; - - await new Promise((resolve) => setTimeout(resolve, 100)); + baseUrl = `http://127.0.0.1:${await getListeningPort(server)}`; }); afterAll(async () => { @@ -229,7 +229,6 @@ describe("createApp with async onPluginsReady callback", () => { let server: Server; let baseUrl: string; let serviceContextMock: Awaited>; - const TEST_PORT = 9885; beforeAll(async () => { setupDatabricksEnv(); @@ -239,7 +238,7 @@ describe("createApp with async onPluginsReady callback", () => { const app = await createApp({ plugins: [ serverPlugin({ - port: TEST_PORT, + port: 0, host: "127.0.0.1", }), ], @@ -254,9 +253,7 @@ describe("createApp with async onPluginsReady callback", () => { }); server = app.server.getServer(); - baseUrl = `http://127.0.0.1:${TEST_PORT}`; - - await new Promise((resolve) => setTimeout(resolve, 100)); + baseUrl = `http://127.0.0.1:${await getListeningPort(server)}`; }); afterAll(async () => { @@ -286,7 +283,6 @@ describe("ServerPlugin error handling for rejected async handlers", () => { let baseUrl: string; let serviceContextMock: Awaited>; let originalNodeEnv: string | undefined; - const TEST_PORT = 9879; const unhandledRejections: unknown[] = []; // Only count rejections raised by this suite's handlers — other suites in // the same worker may legitimately produce unrelated rejections. @@ -377,7 +373,7 @@ describe("ServerPlugin error handling for rejected async handlers", () => { const app = await createApp({ plugins: [ serverPlugin({ - port: TEST_PORT, + port: 0, host: "127.0.0.1", }), throwingPlugin({}), @@ -385,9 +381,7 @@ describe("ServerPlugin error handling for rejected async handlers", () => { }); server = app.server.getServer(); - baseUrl = `http://127.0.0.1:${TEST_PORT}`; - - await new Promise((resolve) => setTimeout(resolve, 100)); + baseUrl = `http://127.0.0.1:${await getListeningPort(server)}`; }); afterAll(async () => { diff --git a/packages/appkit/src/telemetry/telemetry-manager.ts b/packages/appkit/src/telemetry/telemetry-manager.ts index b19cd1a07..2a4852e12 100644 --- a/packages/appkit/src/telemetry/telemetry-manager.ts +++ b/packages/appkit/src/telemetry/telemetry-manager.ts @@ -162,10 +162,17 @@ export class TelemetryManager { /** * Flush and shut down the OpenTelemetry SDK. * - * Idempotent: the SDK reference is cleared synchronously and concurrent - * or repeated calls await the same in-flight flush. Awaited by the core - * lifecycle manager during graceful shutdown — that manager owns the - * process signal handlers, so telemetry no longer registers its own. + * Idempotent: the SDK reference is cleared synchronously and concurrent or + * repeated calls await the same in-flight flush. Awaited by the core lifecycle + * manager during graceful shutdown — that manager owns the process signal + * handlers, so telemetry no longer registers its own. + * + * Survives re-`initialize()`. `shutdownPromise` is deliberately *not* cleared + * when the flush settles, and that is safe: the memo is only ever returned + * after being reassigned for whatever SDK is currently live, so a stale + * resolved promise can only be returned when there is no SDK to flush. The + * covering test asserts every SDK across repeated + * initialize/shutdown cycles is flushed. */ async shutdown(): Promise { if (this.sdk) { @@ -182,4 +189,16 @@ export class TelemetryManager { return this.shutdownPromise; } + + /** + * Drop the singleton so the next {@link getInstance} builds a fresh manager. + * + * Does not flush: callers `shutdown()` first, then reset — the order + * `LifecycleManager.close()` uses. + * + * @internal + */ + static reset(): void { + TelemetryManager.instance = undefined; + } } diff --git a/packages/appkit/src/telemetry/tests/telemetry-manager-reset.test.ts b/packages/appkit/src/telemetry/tests/telemetry-manager-reset.test.ts new file mode 100644 index 000000000..06e6a8e45 --- /dev/null +++ b/packages/appkit/src/telemetry/tests/telemetry-manager-reset.test.ts @@ -0,0 +1,111 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +/** + * `_initialize` builds no SDK without `OTEL_EXPORTER_OTLP_ENDPOINT`, so these set + * it and mock `NodeSDK` to make the shutdown path observable. + * + * The never-cleared `shutdownPromise` was suspected of skipping a re-initialized + * SDK's flush. It does not — the memo is reassigned whenever an SDK is live — and + * the first test pins that so a future "cleanup" cannot change it. + */ + +const { sdkShutdown, NodeSDKMock } = vi.hoisted(() => { + const sdkShutdown = vi.fn().mockResolvedValue(undefined); + const NodeSDKMock = vi.fn(() => ({ + start: vi.fn(), + shutdown: sdkShutdown, + })); + return { sdkShutdown, NodeSDKMock }; +}); + +vi.mock("@opentelemetry/sdk-node", () => ({ NodeSDK: NodeSDKMock })); +vi.mock("@opentelemetry/auto-instrumentations-node", () => ({ + getNodeAutoInstrumentations: vi.fn(() => []), +})); +vi.mock("@opentelemetry/exporter-trace-otlp-proto", () => ({ + OTLPTraceExporter: vi.fn(() => ({})), +})); +vi.mock("@opentelemetry/exporter-metrics-otlp-proto", () => ({ + OTLPMetricExporter: vi.fn(() => ({})), +})); +vi.mock("@opentelemetry/exporter-logs-otlp-proto", () => ({ + OTLPLogExporter: vi.fn(() => ({})), +})); +vi.mock("@opentelemetry/resources", async () => { + const actual = await vi.importActual< + typeof import("@opentelemetry/resources") + >("@opentelemetry/resources"); + return { ...actual, detectResources: vi.fn(() => actual.emptyResource()) }; +}); + +import { TelemetryManager } from "../telemetry-manager"; + +describe("TelemetryManager re-bootability", () => { + let originalEndpoint: string | undefined; + + beforeEach(() => { + originalEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "http://localhost:4318"; + vi.clearAllMocks(); + TelemetryManager.reset(); + }); + + afterEach(() => { + if (originalEndpoint === undefined) { + delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + } else { + process.env.OTEL_EXPORTER_OTLP_ENDPOINT = originalEndpoint; + } + TelemetryManager.reset(); + }); + + test("shutdown() twice across a re-initialize() flushes both SDKs", async () => { + TelemetryManager.initialize({}); + const manager = TelemetryManager.getInstance(); + expect(NodeSDKMock).toHaveBeenCalledTimes(1); + + await manager.shutdown(); + expect(sdkShutdown).toHaveBeenCalledTimes(1); + + // Re-initialize builds a *new* SDK, because shutdown() cleared `sdk`. + TelemetryManager.initialize({}); + expect(NodeSDKMock).toHaveBeenCalledTimes(2); + + await manager.shutdown(); + expect(sdkShutdown).toHaveBeenCalledTimes(2); + + // A third cycle, to pin the general property rather than one transition. + TelemetryManager.initialize({}); + await manager.shutdown(); + expect(NodeSDKMock).toHaveBeenCalledTimes(3); + expect(sdkShutdown).toHaveBeenCalledTimes(3); + }); + + test("concurrent shutdown() calls share one flush", async () => { + TelemetryManager.initialize({}); + const manager = TelemetryManager.getInstance(); + + await Promise.all([manager.shutdown(), manager.shutdown()]); + + // Clearing `sdk` synchronously is what makes this safe: the second caller + // finds no SDK and awaits the first caller's memo. + expect(sdkShutdown).toHaveBeenCalledTimes(1); + }); + + test("shutdown() with no SDK built resolves without flushing", async () => { + delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + TelemetryManager.initialize({}); + const manager = TelemetryManager.getInstance(); + + await expect(manager.shutdown()).resolves.toBeUndefined(); + expect(sdkShutdown).not.toHaveBeenCalled(); + }); + + test("reset() drops the singleton so the next getInstance() is fresh", () => { + const first = TelemetryManager.getInstance(); + TelemetryManager.reset(); + const second = TelemetryManager.getInstance(); + + expect(second).not.toBe(first); + }); +}); diff --git a/packages/appkit/src/testing/create-test-app.ts b/packages/appkit/src/testing/create-test-app.ts new file mode 100644 index 000000000..f9d972e63 --- /dev/null +++ b/packages/appkit/src/testing/create-test-app.ts @@ -0,0 +1,404 @@ +/** + * Boot a real AppKit app with no workspace, credentials, or network, then call it + * over real HTTP. + */ + +import type { Server } from "node:http"; + +import type { + CacheConfig, + PluginConstructor, + PluginData, + PluginMap, +} from "shared"; +import { vi } from "vitest"; + +import { InMemoryStorage } from "../cache/storage/memory"; +import { ServiceContext } from "../context/service-context"; +import { createApp } from "../core/appkit"; +import type { WorkspaceClient } from "../workspace-client"; +import type { OboOption } from "./fixtures"; +import { oboHeaders, setupDatabricksEnv } from "./fixtures"; +import type { CreateMockWorkspaceClientOptions } from "./mock-workspace-client"; +import { createMockWorkspaceClient } from "./mock-workspace-client"; +import { claimAppKitSingletons, releaseAppKitSingletons } from "./reset"; + +type Any = any; + +/** + * One baseline shared by every live harness app, reference-counted. + * + * A per-app snapshot does not compose: the second boot captures the first's + * mutations and whichever closes last re-applies them. Anchoring on the first + * boot and restoring on the last close makes the result order-independent. + */ +let envBaseline: NodeJS.ProcessEnv | undefined; +let liveHarnessApps = 0; + +/** Take the baseline on the first live app. */ +function acquireEnvBaseline(): void { + if (liveHarnessApps === 0) envBaseline = { ...process.env }; + liveHarnessApps += 1; +} + +/** Restore the baseline once no apps are left. */ +function releaseEnvBaseline(): void { + liveHarnessApps = Math.max(0, liveHarnessApps - 1); + if (liveHarnessApps > 0 || !envBaseline) return; + + const baseline = envBaseline; + envBaseline = undefined; + for (const key of Object.keys(process.env)) { + if (!(key in baseline)) delete process.env[key]; + } + Object.assign(process.env, baseline); +} + +/** Plugin descriptors, exactly as `createApp` takes them. */ +type Plugins = PluginData[]; + +/** Options for {@link createTestApp}. */ +export interface CreateTestAppOptions { + /** The plugins under test, as `createApp` takes them. */ + plugins?: T; + + /** Dotted-path responses for the built-in mock. Ignored when `client` is set. */ + responses?: CreateMockWorkspaceClientOptions["responses"]; + + /** + * Replaces the built-in mock. You then own `currentUser.me()` — boot reads + * `currentUser.id` and fails without it. + */ + client?: WorkspaceClient; + + /** Extra env for the boot, restored on `close()`; satisfies declared resources. */ + env?: Record; + + /** No socket; setup, validation, and teardown still run, request methods throw. */ + server?: false; + + /** + * Defaults to `"test"`. `"development"` is refused — it throws a `RangeError` + * in `get-port` on `port: 0`, boots Vite, and relaxes validation. + */ + nodeEnv?: string; + + /** Defaults to in-memory, which is what keeps boot offline. */ + cache?: CacheConfig; + + /** Teardown budget. Defaults to AppKit's programmatic budget. */ + closeTimeoutMs?: number; +} + +/** Per-request options for the {@link TestApp} HTTP methods. */ +export interface TestRequestOptions { + /** A non-string value is JSON-encoded with `content-type: application/json`. */ + body?: unknown; + /** Merged last, so they win over anything the harness sets. */ + headers?: Record; + /** Same convention as `createMockRequest({ obo })`. */ + obo?: OboOption; + /** Forwarded to `fetch`. */ + signal?: AbortSignal; +} + +/** A booted test app. */ +export interface TestApp { + /** + * Plugin exports by manifest name. Nested rather than spread because `get` and + * `delete` are plausible plugin names and would collide with the request methods. + */ + plugins: PluginMap; + /** The same object a handler resolves at runtime. */ + client: WorkspaceClient; + /** e.g. `http://127.0.0.1:54321`. Throws when `server: false`. */ + baseUrl: string; + /** The bound ephemeral port. Throws when `server: false`. */ + port: number; + /** The underlying HTTP server, or `undefined` with `server: false`. */ + server?: Server; + + /** Release the app and restore env. Idempotent. */ + close(): Promise; + [Symbol.asyncDispose](): Promise; + + get(path: string, options?: TestRequestOptions): Promise; + post(path: string, options?: TestRequestOptions): Promise; + put(path: string, options?: TestRequestOptions): Promise; + patch(path: string, options?: TestRequestOptions): Promise; + delete(path: string, options?: TestRequestOptions): Promise; +} + +/** + * Point `ServiceContext.createUserContext` at the harness's mock so an `obo` + * request does not construct a real SDK client from `DATABRICKS_HOST`. + * + * Mirrors the `createUserContextSpy` in `fixtures.ts`; returns its restore. + */ +function stubUserContext(client: WorkspaceClient): () => void { + const spy = vi + .spyOn(ServiceContext, "createUserContext") + .mockImplementation((token, userId, userName, userEmail) => { + if (!token) throw new Error("createTestApp: obo requires a token"); + const service = ServiceContext.get(); + return { + client, + userId, + userName, + userEmail, + tokenFingerprint: `test-${userId}`, + warehouseId: service.warehouseId, + workspaceId: service.workspaceId, + isUserContext: true, + }; + }); + return () => spy.mockRestore(); +} + +/** + * `start()` returns once `listen()` is invoked, before the bind completes, so + * `address()` is null until the `listening` event fires. + * + * @internal + */ +export async function getListeningPort(server: Server): Promise { + const addr = server.address(); + if (addr && typeof addr === "object" && typeof addr.port === "number") { + return addr.port; + } + await new Promise((resolve, reject) => { + server.once("listening", () => resolve()); + server.once("error", (err) => reject(err)); + }); + const ready = server.address(); + if (!ready || typeof ready !== "object") { + throw new Error("Server is listening but address() returned null"); + } + return ready.port; +} + +/** + * Boot a real app — real Express wiring, routes, and resource validation — with + * no workspace, credentials, or network. `createTestPluginContext` is cheaper + * when you only need to unit-test wiring. + * + * Does **not** validate config values against `manifest.config.schema`; no + * runtime validator exists for that. + * + * @example + * ```ts + * const app = await createTestApp({ plugins: [myPlugin()] }); + * try { + * const res = await app.post("/api/my-plugin/thing", { body: { q: 1 }, obo: true }); + * await expectStream(res).toEmit("status", "result"); + * } finally { + * await app.close(); + * } + * ``` + */ +export async function createTestApp( + options: CreateTestAppOptions = {}, +): Promise> { + const { + plugins = [] as unknown as T, + responses, + client: suppliedClient, + env = {}, + server: serverOption, + nodeEnv = "test", + cache, + closeTimeoutMs, + } = options; + + if (nodeEnv === "development") { + throw new Error( + 'createTestApp: nodeEnv "development" is not supported. Dev mode routes ' + + "the harness's ephemeral `port: 0` through get-port, which throws a " + + "RangeError, and it also boots a real Vite dev server, downgrades " + + "resource validation to a warning, and stops filtering dev-only " + + "plugins. Pin a port explicitly with your own server plugin if you " + + "need dev behaviour.", + ); + } + + // Wholesale rather than a whitelist: plugins read vars we cannot enumerate. + acquireEnvBaseline(); + + let app: Awaited> | undefined; + let restoreUserContext: (() => void) | undefined; + + try { + process.env.NODE_ENV = nodeEnv; + + // Redundant while NODE_ENV is pinned, but keeps the throw-on-missing-resource + // contract if that pin ever changes. No opt-out: the warning path is + // dev-only, and dev is refused. + process.env.APPKIT_STRICT_VALIDATION = "true"; + + // The workspace ID short-circuits getWorkspaceId's SCIM probe, which would + // otherwise show up as an apiClient.request call. + setupDatabricksEnv({ + DATABRICKS_WORKSPACE_ID: "test-workspace-id", + ...env, + }); + + claimAppKitSingletons(); + + // Boot runs ServiceContext.createContext for real, which reads + // currentUser.id — the mock's built-in default is what lets it through. + const client = suppliedClient ?? createMockWorkspaceClient({ responses }); + + // createApp({ client }) installs only the service-principal client. An `obo` + // request reaches ServiceContext.createUserContext, which builds a *real* + // client from process.env.DATABRICKS_HOST — so the user-scoped path is faked + // here too, or "no network" is false the moment a handler calls asUser. + restoreUserContext = stubUserContext(client); + + // createApp never auto-adds a server, so without this there is nothing to + // fetch. Lazily imported: the plugin runs dotenv.config() at module load, so + // a static import would mutate a consumer's env on import of this kit. + const hasServer = plugins.some((p) => p?.name === "server"); + if (serverOption === false && hasServer) { + // The plugin would still bind a socket while the handle denied one existed. + throw new Error( + "createTestApp: `server: false` conflicts with the server plugin in " + + "`plugins`. Drop one — omit `server: false` to use your plugin, or " + + "remove the plugin to boot without a socket.", + ); + } + const bootPlugins = [...plugins] as Plugins; + if (serverOption !== false && !hasServer) { + const { server: serverPlugin } = await import("../plugins/server"); + bootPlugins.push(serverPlugin({ port: 0, host: "127.0.0.1" })); + } + + // Both extras are load-bearing: without explicit storage the cache builds its + // own client and probes Lakebase over the network, and without the opt-out + // TelemetryReporter fires an apiClient.request on boot. + app = await createApp({ + plugins: bootPlugins as Any, + client, + cache: cache ?? { + storage: new InMemoryStorage({ enabled: true } as Any), + }, + disableInternalTelemetry: true, + }); + + const serverExports = (app as Any).server; + const httpServer: Server | undefined = + serverOption === false ? undefined : serverExports?.getServer?.(); + const port = httpServer ? await getListeningPort(httpServer) : undefined; + const baseUrl = port === undefined ? undefined : `http://127.0.0.1:${port}`; + + const bootedApp = app; + let closed: Promise | undefined; + + /** Memoized, so repeated calls are safe in nested `finally`s. */ + const close = () => { + closed ??= (async () => { + try { + await bootedApp.close( + closeTimeoutMs === undefined ? {} : { timeoutMs: closeTimeoutMs }, + ); + } finally { + // No release here: app.close() -> LifecycleManager.close() already + // drops this app's claim, once. Releasing twice would pull the + // singletons out from under a still-live sibling app. + restoreUserContext?.(); + releaseEnvBaseline(); + } + })(); + return closed; + }; + + const request = async ( + method: string, + path: string, + reqOptions: TestRequestOptions = {}, + ): Promise => { + if (baseUrl === undefined) { + throw new Error( + "createTestApp: no HTTP server was started (server: false), so " + + `${method} ${path} cannot be issued.`, + ); + } + + const headers: Record = {}; + if (reqOptions.obo) { + Object.assign(headers, oboHeaders(reqOptions.obo)); + } + + let body: string | undefined; + if (reqOptions.body !== undefined) { + if (typeof reqOptions.body === "string") { + body = reqOptions.body; + } else { + body = JSON.stringify(reqOptions.body); + headers["content-type"] = "application/json"; + } + } + + // Caller headers last, so an explicit content-type or identity wins. + // Lowercased first: `Headers` comma-joins case variants instead of + // replacing, so a mixed-case override would corrupt the value into + // "alice, bob" rather than win. + for (const [name, value] of Object.entries(reqOptions.headers ?? {})) { + headers[name.toLowerCase()] = value; + } + + return fetch(new URL(path, baseUrl), { + method, + headers, + body, + signal: reqOptions.signal, + }); + }; + + return { + plugins: bootedApp as unknown as PluginMap, + client, + get baseUrl() { + if (baseUrl === undefined) { + throw new Error( + "createTestApp: no HTTP server was started (server: false).", + ); + } + return baseUrl; + }, + get port() { + if (port === undefined) { + throw new Error( + "createTestApp: no HTTP server was started (server: false).", + ); + } + return port; + }, + server: httpServer, + close, + [Symbol.asyncDispose]: close, + get: (path, o) => request("GET", path, o), + post: (path, o) => request("POST", path, o), + put: (path, o) => request("PUT", path, o), + patch: (path, o) => request("PATCH", path, o), + delete: (path, o) => request("DELETE", path, o), + }; + } catch (err) { + // Teardown must run from the failure path too, or the boot leaks env + // mutations and singletons into every later test in the file. + if (app) { + // No release alongside this: close() drops the claim itself, and a second + // release would pull the singletons out from under a live sibling app. + try { + await app.close(); + } catch { + // The boot error is the interesting one; don't let teardown mask it. + } + } else { + // Nothing was booted, so nothing else will drop the claim taken above. + releaseAppKitSingletons(); + } + restoreUserContext?.(); + releaseEnvBaseline(); + throw err; + } +} diff --git a/packages/appkit/src/testing/create-test-plugin.ts b/packages/appkit/src/testing/create-test-plugin.ts new file mode 100644 index 000000000..b969e2799 --- /dev/null +++ b/packages/appkit/src/testing/create-test-plugin.ts @@ -0,0 +1,27 @@ +import type { PluginConstructor, PluginData } from "shared"; + +/** + * Instantiate a plugin from its `toPlugin()` factory for use with + * `createTestPluginContext`. + * + * Merge order mirrors `AppKit.createAndRegisterPlugin` — `DEFAULT_CONFIG`, then + * the factory's config, then the manifest `name` — so the instance matches what + * production builds. Reaching through the descriptor by hand + * (`new (genie({}).plugin)({})`) skips both. + */ +export function createTestPlugin< + TClass extends PluginConstructor, + TConfig, + TName extends string, +>( + factory: (config?: TConfig) => PluginData, + config?: TConfig, +): InstanceType { + const { plugin: PluginClass, config: factoryConfig, name } = factory(config); + + return new PluginClass({ + ...(PluginClass.DEFAULT_CONFIG ?? {}), + ...(factoryConfig ?? {}), + name, + }) as InstanceType; +} diff --git a/packages/appkit/src/testing/fixtures.ts b/packages/appkit/src/testing/fixtures.ts index f3663b430..4c6dd12c8 100644 --- a/packages/appkit/src/testing/fixtures.ts +++ b/packages/appkit/src/testing/fixtures.ts @@ -6,9 +6,10 @@ import { CacheManager } from "../cache"; import type { ServiceContextState } from "../context/service-context"; import { ServiceContext } from "../context/service-context"; import type { InstrumentConfig, ITelemetry } from "../telemetry/types"; +import { createMockWorkspaceClient } from "./mock-workspace-client"; // Test fixtures intentionally use loose shapes; `noExplicitAny` is disabled -// repo-wide (see biome.json), so a local alias keeps the intent readable. +// repo-wide (see .oxlintrc.json), so a local alias keeps the intent readable. type Any = any; /** @@ -121,8 +122,17 @@ export type OboOption = email?: string; }; -/** Build the forwarded identity headers an `obo` option implies. */ -function oboHeaders(obo: Exclude): Record { +/** + * Build the forwarded identity headers an `obo` option implies. + * + * Exported so `createTestApp`'s request methods use the same convention as + * `createMockRequest` rather than a second one. + * + * @internal + */ +export function oboHeaders( + obo: Exclude, +): Record { const opts = obo === true ? {} : obo; const headers: Record = { "x-forwarded-access-token": opts.token ?? "test-user-token", @@ -332,28 +342,6 @@ export interface TestContextOptions { workspaceId?: string; } -/** - * Creates a default mock WorkspaceClient for testing (SQL succeeds, warehouse - * RUNNING). - */ -export function createMockWorkspaceClient() { - return { - statementExecution: { - executeStatement: vi.fn().mockResolvedValue({ - status: { state: "SUCCEEDED" }, - result: { data: [] }, - }), - }, - // Analytics route now calls `warehouses.get` before issuing SQL to - // ensure the warehouse is RUNNING. Default to RUNNING so existing - // tests that only care about SQL behaviour aren't affected. - warehouses: { - get: vi.fn().mockResolvedValue({ state: "RUNNING" }), - start: vi.fn().mockResolvedValue(undefined), - }, - }; -} - /** * Builds a {@link ServiceContextState} value for testing without touching the * singleton. Internal building block for {@link mockServiceContext}, which @@ -534,39 +522,3 @@ export function createFailedSQLResponse(errorMessage: string) { statement_id: `stmt-${Date.now()}`, }; } - -/** - * A WorkspaceClient whose `executeStatement`/`getStatement` are bare `vi.fn()`s - * (no default resolution) so a test can script exactly what SQL returns. - * `warehouses.get` defaults to RUNNING. - */ -export function createConfigurableMockWorkspaceClient() { - const executeStatement = vi.fn(); - const getStatement = vi.fn(); - // Analytics route now calls `warehouses.get` before issuing SQL; default to - // RUNNING so callers that don't care about warehouse readiness don't have - // to wire it up. - const warehousesGet = vi.fn().mockResolvedValue({ state: "RUNNING" }); - const warehousesStart = vi.fn().mockResolvedValue(undefined); - - const client = { - statementExecution: { - executeStatement, - getStatement, - }, - warehouses: { - get: warehousesGet, - start: warehousesStart, - }, - }; - - return { - client, - mocks: { - executeStatement, - getStatement, - warehousesGet, - warehousesStart, - }, - }; -} diff --git a/packages/appkit/src/testing/index.ts b/packages/appkit/src/testing/index.ts index 8565e4d5e..1b305581a 100644 --- a/packages/appkit/src/testing/index.ts +++ b/packages/appkit/src/testing/index.ts @@ -9,9 +9,11 @@ * buffering, tool dispatch, timeout composition, user scoping — run under test * with no credentials. * - * Two entry points: + * Three entry points: + * - {@link createTestApp} — boot a real app with a faked data plane and call it + * over real HTTP. The recommended starting point. * - {@link createTestPluginContext} — build a real `PluginContext` with faked edges - * and attach it to a plugin. + * and attach it to a plugin, with no boot and no socket. * - {@link expectStream} — assert the ordered event types a stream emits. * * Plus the fixture helpers (`createMockRequest`, `mockServiceContext`, …) for @@ -41,6 +43,13 @@ // through this entry point — the class is otherwise reachable only via a deep // path (../core/plugin-context) that is not part of the package's exports map. export type { PluginContext } from "../core/plugin-context"; +export { + createTestApp, + type CreateTestAppOptions, + getListeningPort, + type TestApp, + type TestRequestOptions, +} from "./create-test-app"; export { type CapturedSSEResponse, type ExpectStreamOptions, @@ -51,13 +60,11 @@ export { type StreamSource, } from "./expect-stream"; export { - createConfigurableMockWorkspaceClient, createFailedSQLResponse, createMockRequest, createMockResponse, createMockRouter, createMockTelemetry, - createMockWorkspaceClient, createSuccessfulSQLResponse, mockServiceContext, type OboOption, @@ -68,6 +75,14 @@ export { type TestContextOptions, useServiceContextMock, } from "./fixtures"; +export { + createMockWorkspaceClient, + type CreateMockWorkspaceClientOptions, + getMockFn, + type MockWorkspaceClient, +} from "./mock-workspace-client"; +export { createTestPlugin } from "./create-test-plugin"; +export { resetAppKitSingletons } from "./reset"; export { createTestPluginContext, type FakeProvider, diff --git a/packages/appkit/src/testing/mock-workspace-client.ts b/packages/appkit/src/testing/mock-workspace-client.ts new file mode 100644 index 000000000..a427be8f0 --- /dev/null +++ b/packages/appkit/src/testing/mock-workspace-client.ts @@ -0,0 +1,262 @@ +/** + * A never-crash fake `WorkspaceClient`. Declared paths resolve their value; + * everything else resolves `undefined` instead of throwing. + */ + +import type { Mock } from "vitest"; +import { vi } from "vitest"; + +import type { WorkspaceClient } from "../workspace-client"; + +type Any = any; + +type LegacyClient = ReturnType; + +/** Options for {@link createMockWorkspaceClient}. */ +export interface CreateMockWorkspaceClientOptions { + /** + * Responses keyed by dotted path (`"jobs.getRun"`). A function value is called + * with the arguments, so a test can script behaviour or reject. + */ + responses?: Record; + + /** Seed `config`; `host` must stay a real string. */ + config?: Partial; + + /** Apply the canned defaults (SQL succeeds, warehouse RUNNING). Default true. */ + defaults?: boolean; +} + +export type MockWorkspaceClient = WorkspaceClient; + +/** + * Applied beneath caller-supplied `responses`. + * + * The first three must stay byte-identical to the old `fixtures.ts` values — 13 + * suites reach them implicitly via `mockServiceContext`. `currentUser.me` is + * required: `ServiceContext.createContext` reads `.id`, so `createApp({ client })` + * cannot boot without it. + */ +const DEFAULT_RESPONSES: Record = { + "statementExecution.executeStatement": { + status: { state: "SUCCEEDED" }, + result: { data: [] }, + }, + "warehouses.get": { state: "RUNNING" }, + "warehouses.start": undefined, + "currentUser.me": { + id: "test-service-user", + userName: "test-service-user", + }, +}; + +/** The seven generically-proxied services; `config`/`apiClient` are seeded below. */ +const FACADE_SERVICES = [ + "files", + "warehouses", + "genie", + "jobs", + "statementExecution", + "servingEndpoints", + "currentUser", +] as const; + +/** + * Answered with `undefined` rather than a minted mock. `then` is load-bearing: + * without it a service is thenable, so `await client.jobs` hangs. + */ +const PASSTHROUGH_DENY: ReadonlySet = new Set([ + "then", + "catch", + "finally", + "toJSON", + "inspect", + "constructor", + "$$typeof", + "asymmetricMatch", +]); + +/** + * Symbols and denied names short-circuit before minting; anything already on the + * target (seeded members, `Object.prototype`) wins. + * + * `ownKeys`/`getOwnPropertyDescriptor` stay at their defaults on purpose — + * reporting keys makes `util.inspect` probe each one, minting a mock per probe. + */ +function neverCrashGet(namespace: string, mint: (path: string) => Mock) { + return (target: Any, prop: Any): Any => { + if (typeof prop === "symbol") return Reflect.get(target, prop); + if (PASSTHROUGH_DENY.has(prop)) return undefined; + if (prop in target) return target[prop]; + return mint(`${namespace}.${String(prop)}`); + }; +} + +// In a WeakMap, not on the client: a stray own property would show up in +// util.inspect, toEqual, and key enumeration. +const clientFns = new WeakMap>(); + +/** + * @example + * ```ts + * const client = createMockWorkspaceClient({ + * responses: { "jobs.getRun": { state: "TERMINATED" } }, + * }); + * ``` + */ +export function createMockWorkspaceClient( + options: CreateMockWorkspaceClientOptions = {}, +): MockWorkspaceClient { + const { responses = {}, config = {}, defaults = true } = options; + + // Caller entries win over the canned defaults for the same path. + const merged: Record = defaults + ? { ...DEFAULT_RESPONSES, ...responses } + : { ...responses }; + + // Shared with the legacy view and getMockFn, so both see the same functions. + const fns = new Map(); + + /** Mint once per path, so call assertions see a stable reference. */ + function mint(path: string): Mock { + const cached = fns.get(path); + if (cached) return cached; + + const response = merged[path]; + const fn = vi.fn(); + if (typeof response === "function") fn.mockImplementation(response); + else fn.mockResolvedValue(response); + + fns.set(path, fn); + return fn; + } + + /** Memoized, so `client.jobs === client.jobs`. */ + const services = new Map(); + function service(namespace: string): Any { + const cached = services.get(namespace); + if (cached) return cached; + const proxy = new Proxy({}, { get: neverCrashGet(namespace, mint) }); + services.set(namespace, proxy); + return proxy; + } + + /** Pull `"config.*"` / `"apiClient.*"` entries out so they seed real values. */ + function seededOverrides(namespace: string): Record { + const prefix = `${namespace}.`; + const out: Record = {}; + for (const [key, value] of Object.entries(merged)) { + if (key.startsWith(prefix)) out[key.slice(prefix.length)] = value; + } + return out; + } + + // `host` is read as a string and throws if falsy, so it cannot be a mock. + const configTarget: Record = { + host: "https://test.databricks.com", + authenticate: vi.fn((headers?: Headers) => { + headers?.set?.("Authorization", "Bearer test-token"); + }), + ensureResolved: vi.fn().mockResolvedValue(undefined), + ...config, + ...seededOverrides("config"), + }; + + // userAgent() must be synchronous (a Promise stringifies to "[object Promise]" + // inside a Headers value); request resolves {} so destructuring works. + const apiClientTarget: Record = { + userAgent: vi.fn().mockReturnValue("appkit-test/1.0"), + request: vi.fn().mockResolvedValue({}), + }; + for (const [key, value] of Object.entries(seededOverrides("apiClient"))) { + const fn = typeof value === "function" ? vi.fn(value) : vi.fn(); + if (typeof value !== "function") fn.mockResolvedValue(value); + apiClientTarget[key] = fn; + fns.set(`apiClient.${key}`, fn); + } + for (const key of ["userAgent", "request"]) { + if (!fns.has(`apiClient.${key}`)) { + fns.set(`apiClient.${key}`, apiClientTarget[key] as Mock); + } + } + for (const [key, value] of Object.entries(configTarget)) { + if (typeof value === "function" && !fns.has(`config.${key}`)) { + fns.set(`config.${key}`, value as Mock); + } + } + + const configProxy = new Proxy(configTarget, { + get: neverCrashGet("config", mint), + }); + const apiClientProxy = new Proxy(apiClientTarget, { + get: neverCrashGet("apiClient", mint), + }); + + /** Memoized; routes facade names onto the same objects, others onto the floor. */ + let legacy: LegacyClient | undefined; + function toLegacyWorkspaceClient(): LegacyClient { + legacy ??= new Proxy( + {}, + { + get: (target: Any, prop: Any): Any => { + if (typeof prop === "symbol") return Reflect.get(target, prop); + if (PASSTHROUGH_DENY.has(prop)) return undefined; + if (prop === "config") return configProxy; + if (prop === "apiClient") return apiClientProxy; + if (prop === "toLegacyWorkspaceClient") { + return toLegacyWorkspaceClient; + } + return service(String(prop)); + }, + }, + ) as LegacyClient; + return legacy; + } + + const client: WorkspaceClient = { + ...(Object.fromEntries( + FACADE_SERVICES.map((name) => [name, service(name)]), + ) as Pick), + config: configProxy as WorkspaceClient["config"], + apiClient: apiClientProxy as WorkspaceClient["apiClient"], + toLegacyWorkspaceClient, + }; + + clientFns.set(client, fns); + return client; +} + +/** + * The typed assertion path onto a mocked method — facade accessors are SDK-typed, + * so `expect(client.jobs.getRun).toHaveBeenCalled()` does not typecheck. + * + * Minting is idempotent, so this can be called before the code under test runs. + * Throws for a non-function member such as `"config.host"`. + */ +export function getMockFn(client: MockWorkspaceClient, path: string): Mock { + const fns = clientFns.get(client); + if (!fns) { + throw new Error( + "getMockFn: not a createMockWorkspaceClient() client. Pass the client " + + "the builder returned, not a hand-rolled object.", + ); + } + + const cached = fns.get(path); + if (cached) return cached; + + const dot = path.indexOf("."); + const namespace = dot === -1 ? path : path.slice(0, dot); + const member = dot === -1 ? "" : path.slice(dot + 1); + const resolved = member + ? (client as Any)[namespace]?.[member] + : (client as Any)[namespace]; + + if (typeof resolved !== "function") { + throw new Error( + `getMockFn: "${path}" is not a mocked function (got ${typeof resolved}). ` + + "Members seeded with a real value, such as config.host, have no mock.", + ); + } + return resolved as Mock; +} diff --git a/packages/appkit/src/testing/reset.ts b/packages/appkit/src/testing/reset.ts new file mode 100644 index 000000000..2452b6095 --- /dev/null +++ b/packages/appkit/src/testing/reset.ts @@ -0,0 +1,33 @@ +import { + claimCoreSingletons, + dropCoreSingletons, + releaseCoreSingletons, +} from "../core/reset-singletons"; + +/** + * Drop the process-wide singletons `createApp()` initializes, ignoring how many + * apps are live. + * + * A pointer drop, not teardown — close first or the old app's pools and + * exporters leak. `app.close()` does both, so this is only for tests that + * hand-roll `createApp`. + */ +export function resetAppKitSingletons(): void { + dropCoreSingletons(); +} + +/** + * Claim the singletons for a booting app; resets only if it is the first. + * @internal + */ +export function claimAppKitSingletons(): void { + claimCoreSingletons(); +} + +/** + * Release one claim, dropping the singletons once no app holds them. + * @internal + */ +export function releaseAppKitSingletons(): void { + releaseCoreSingletons(); +} diff --git a/packages/appkit/src/testing/tests/create-test-app.test.ts b/packages/appkit/src/testing/tests/create-test-app.test.ts new file mode 100644 index 000000000..cc5aa60e6 --- /dev/null +++ b/packages/appkit/src/testing/tests/create-test-app.test.ts @@ -0,0 +1,704 @@ +import type { + IAppRequest, + IAppResponse, + IAppRouter, + PluginConstructor, + PluginData, + PluginManifest, +} from "shared"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; + +import { getWorkspaceClient } from "../../context"; +import { getUserContext } from "../../context/execution-context"; +import { Plugin, toPlugin } from "../../plugin"; +import type { WorkspaceClient } from "../../workspace-client"; +import type { CreateTestAppOptions, TestApp } from "../create-test-app"; +import { createTestApp } from "../create-test-app"; +import { expectStream } from "../expect-stream"; +import { getMockFn } from "../mock-workspace-client"; + +/** + * Coverage for the harness itself. Nothing here is mocked beyond the workspace + * client the harness installs: these boots bind real sockets and run the real + * Express stack, because that is the claim being tested. + */ + +/** Builds a manifest with the fields the loader validates. */ +function manifest( + name: string, + extra: Record = {}, +): PluginManifest { + return { + name, + displayName: name, + version: "0.0.0", + description: `${name} test plugin`, + resources: { required: [] }, + ...extra, + } as unknown as PluginManifest; +} + +/** + * One probe for both halves of the harness: boot/data-plane concerns and the + * HTTP layer. Routes go through `this.route()`, the way real plugins register + * them — that is what wraps handlers in forwardAsyncErrors, so a rejection + * reaches errorHandlerMiddleware instead of hanging the request. + */ +class ProbePlugin extends Plugin { + static manifest = manifest("probe"); + + /** The client this plugin resolved at request time. */ + seenClient: WorkspaceClient | undefined; + + injectRoutes(router: IAppRouter): void { + const r = ( + method: "get" | "post" | "put" | "patch" | "delete", + path: string, + handler: (req: IAppRequest, res: IAppResponse) => Promise, + ) => + this.route(router, { name: `${method}${path}`, method, path, handler }); + + r("get", "/ping", async (_req, res) => { + res.json({ pong: true }); + }); + + // A non-default status, to prove the handler's status propagates. + r("get", "/created", async (_req, res) => { + res.status(201).json({ ok: true, method: "GET" }); + }); + + r("get", "/from-client", async (_req, res) => { + this.seenClient = getWorkspaceClient(); + res.json({ + run: await this.seenClient.jobs.getRun({ run_id: 1 } as never), + }); + }); + + r("post", "/echo", async (req, res) => { + res.json({ + body: req.body, + contentType: req.headers["content-type"] ?? null, + }); + }); + + r("get", "/headers", async (req, res) => { + res.json({ + custom: req.headers["x-custom"] ?? null, + user: req.headers["x-forwarded-user"] ?? null, + token: req.headers["x-forwarded-access-token"] ?? null, + email: req.headers["x-forwarded-email"] ?? null, + }); + }); + + // The real asUser path, so the forwarded identity has to be genuine. + r("get", "/as-user", async (req, res) => { + const ex = this.asUser(req).exports() as { + whoami: () => { userId?: string }; + }; + res.json(ex.whoami()); + }); + + // Calls the client *inside* asUser, unlike /as-user which only reads userId. + r("get", "/as-user-client", async (req, res) => { + const ex = this.asUser(req).exports() as { + probeClient: () => Promise; + }; + res.json({ run: (await ex.probeClient()) ?? null }); + }); + + r("get", "/boom", async () => { + throw new Error("handler exploded"); + }); + + r("post", "/stream", async (_req, res) => { + res.setHeader("content-type", "text/event-stream"); + res.write(`event: status\ndata: ${JSON.stringify({ s: "start" })}\n\n`); + res.write(`event: result\ndata: ${JSON.stringify({ rows: [1] })}\n\n`); + res.end(); + }); + + for (const method of ["put", "patch"] as const) { + r(method, "/verb", async (req, res) => { + res.json({ m: method.toUpperCase(), b: req.body }); + }); + } + r("delete", "/verb", async (_req, res) => { + res.json({ m: "DELETE" }); + }); + } + + exports() { + return { + seenClient: () => this.seenClient, + whoami: () => ({ userId: getUserContext()?.userId }), + // Calls through the client so the harness's mock records it — a real + // OBO client would record nothing here. + probeClient: () => + getWorkspaceClient().jobs.getRun({ run_id: 42 } as never), + }; + } +} +const probe = toPlugin(ProbePlugin); + +/** Boot, run the body, always close. Collapses the try/finally every test needs. */ +async function withApp< + P extends PluginData[], +>( + options: CreateTestAppOptions

, + body: (app: TestApp

) => Promise, +): Promise { + const app = await createTestApp(options); + try { + await body(app); + } finally { + await app.close(); + } +} + +/** Declares a required env var, so resource validation has something to fail on. */ +class NeedsEnvPlugin extends Plugin { + static manifest = manifest("needsEnv", { + resources: { + required: [ + { + type: "sql_warehouse", + alias: "Harness Probe Warehouse", + resourceKey: "harness-probe", + description: "Exists only so validation has something to fail on", + permission: "CAN_USE", + fields: { + id: { + env: "MY_REQUIRED_SECRET", + description: "Stand-in for a required resource field", + }, + }, + }, + ], + optional: [], + }, + }); +} +const needsEnv = toPlugin(NeedsEnvPlugin); + +/** Fails during setup, to exercise the boot-failure teardown path. */ +class BadSetupPlugin extends Plugin { + static manifest = manifest("badSetup"); + async setup(): Promise { + throw new Error("setup went wrong"); + } +} +const badSetup = toPlugin(BadSetupPlugin); + +describe("createTestApp", () => { + test("boots with a single plugin and serves a real route", async () => { + await withApp({ plugins: [probe()] }, async (app) => { + expect(app.baseUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/); + expect(app.port).toBeGreaterThan(0); + + const res = await app.get("/api/probe/ping"); + expect(res.status).toBe(200); + await expect(res.json()).resolves.toEqual({ pong: true }); + }); + }); + + test("two apps in one file get different ephemeral ports", async () => { + const a = await createTestApp({ plugins: [probe()] }); + const b = await createTestApp({ plugins: [probe()] }); + try { + // No EADDRINUSE, which is what makes the harness parallel-safe and is why + // hardcoded test ports are worth removing. + expect(a.port).not.toBe(b.port); + await expect( + a.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + await expect( + b.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + } finally { + await a.close(); + await b.close(); + } + }); + + test("boots with no credentials in the environment", async () => { + const saved = { ...process.env }; + for (const key of Object.keys(process.env)) { + if (key.startsWith("DATABRICKS_")) delete process.env[key]; + } + try { + await withApp({ plugins: [probe()] }, async (app) => { + await expect( + app.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + }); + } finally { + process.env = saved; + } + }); + + test("the default mock client reaches the plugin instead of crashing", async () => { + await withApp({ plugins: [probe()] }, async (app) => { + const res = await app.get("/api/probe/from-client"); + expect(res.status).toBe(200); + // Undeclared path, so it resolves undefined rather than throwing — the + // never-crash floor, exercised through a real handler. + await expect(res.json()).resolves.toEqual({}); + }); + }); + + test("caller-supplied responses reach the plugin's client calls", async () => { + await withApp( + { + plugins: [probe()], + responses: { "jobs.getRun": { state: "TERMINATED" } }, + }, + async (app) => { + const res = await app.get("/api/probe/from-client"); + await expect(res.json()).resolves.toEqual({ + run: { state: "TERMINATED" }, + }); + expect(getMockFn(app.client, "jobs.getRun")).toHaveBeenCalledWith({ + run_id: 1, + }); + }, + ); + }); + + test("app.client is the same object a handler resolves", async () => { + await withApp({ plugins: [probe()] }, async (app) => { + await app.get("/api/probe/from-client"); + // Retires the "tribal seam knowledge" problem: no need to know that + // createApp({ client }) flows through ServiceContext to reach a handler. + expect(app.plugins.probe.seenClient()).toBe(app.client); + }); + }); + + test("apiClient.request has zero calls after boot", async () => { + await withApp({ plugins: [probe()] }, async (app) => { + // A canary for two hazards at once: DATABRICKS_WORKSPACE_ID must + // short-circuit the SCIM probe in getWorkspaceId, and internal telemetry + // must stay off. If either regresses, request assertions get polluted and + // this fails loudly. + expect(getMockFn(app.client, "apiClient.request")).toHaveBeenCalledTimes( + 0, + ); + }); + }); + + test("a caller-supplied server plugin is respected, and dedupes the injected one", async () => { + const { server: serverPlugin } = await import("../../plugins/server"); + await withApp( + { + plugins: [probe(), serverPlugin({ port: 0, host: "127.0.0.1" })], + }, + async (app) => { + expect(app.port).toBeGreaterThan(0); + await expect( + app.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + }, + ); + }); + + test("server: false together with a server plugin is refused", async () => { + const { server: serverPlugin } = await import("../../plugins/server"); + await expect( + createTestApp({ + plugins: [probe(), serverPlugin({ port: 0, host: "127.0.0.1" })], + server: false, + }), + ).rejects.toThrow(/conflicts with the server plugin/); + }); + + test("server: false boots without a socket and request methods explain why", async () => { + await withApp({ plugins: [probe()], server: false }, async (app) => { + expect(app.server).toBeUndefined(); + expect(() => app.baseUrl).toThrow(/no HTTP server/); + await expect(app.get("/api/probe/ping")).rejects.toThrow( + /no HTTP server/, + ); + }); + }); + + test("await using releases at scope exit", async () => { + let port: number | undefined; + { + await using app = await createTestApp({ plugins: [probe()] }); + port = app.port; + await expect( + app.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + } + await expect(fetch(`http://127.0.0.1:${port}/health`)).rejects.toThrow(); + }); + + describe("resource validation (the strict posture)", () => { + test("a missing required env var fails the boot", async () => { + delete process.env.MY_REQUIRED_SECRET; + await expect(createTestApp({ plugins: [needsEnv()] })).rejects.toThrow( + /MY_REQUIRED_SECRET/, + ); + }); + + test("supplying it through env makes the same boot pass", async () => { + await withApp( + { + plugins: [needsEnv(), probe()], + env: { MY_REQUIRED_SECRET: "s3cret" }, + }, + async (app) => { + await expect( + app.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + }, + ); + // Restored, not leaked into the next test. + expect(process.env.MY_REQUIRED_SECRET).toBeUndefined(); + }); + + test("validation always throws, because the harness pins NODE_ENV", async () => { + delete process.env.MY_REQUIRED_SECRET; + + // enforceValidation computes `shouldThrow = !isDevelopment || strict`, so + // pinning NODE_ENV away from "development" is what makes the throw + // unconditional. There is intentionally no option to soften this: the + // warning path exists only in dev mode, which the harness refuses. + await expect( + createTestApp({ plugins: [needsEnv()], nodeEnv: "production" }), + ).rejects.toThrow(/Missing required resources/); + await expect( + createTestApp({ plugins: [needsEnv()], nodeEnv: "test" }), + ).rejects.toThrow(/Missing required resources/); + }); + }); + + describe("environment hygiene", () => { + test("close() restores the snapshot, including pre-existing values", async () => { + process.env.DATABRICKS_HOST = "https://original.example.com"; + const before = { ...process.env }; + + const app = await createTestApp({ + plugins: [probe()], + env: { HARNESS_ADDED: "yes" }, + }); + // The harness overwrote DATABRICKS_HOST with its test default. + expect(process.env.DATABRICKS_HOST).not.toBe( + "https://original.example.com", + ); + await app.close(); + + // A pre-existing value is restored to *its* value, not the test default, + // and a key the harness added is deleted rather than left behind. + expect(process.env.DATABRICKS_HOST).toBe("https://original.example.com"); + expect(process.env.HARNESS_ADDED).toBeUndefined(); + expect(Object.keys(process.env).sort()).toEqual( + Object.keys(before).sort(), + ); + + delete process.env.DATABRICKS_HOST; + }); + + test("a boot failure still restores env and resets singletons", async () => { + const before = { ...process.env }; + + await expect( + createTestApp({ plugins: [badSetup()], env: { LEAKED: "no" } }), + ).rejects.toThrow(/setup went wrong/); + + // Teardown has to run from the setup-failure path, or every later test in + // the file inherits the mutated env. + expect(process.env.LEAKED).toBeUndefined(); + expect(Object.keys(process.env).sort()).toEqual( + Object.keys(before).sort(), + ); + + // And the next boot still works. + const app = await createTestApp({ plugins: [probe()] }); + await expect( + app.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + await app.close(); + }); + + test('nodeEnv: "development" is refused with an explanation', async () => { + // The get-port RangeError must never reach the user. + await expect( + createTestApp({ plugins: [probe()], nodeEnv: "development" }), + ).rejects.toThrow(/not supported/); + }); + + test("SIGTERM listener count is unchanged across boot and close", async () => { + const baseline = process.listenerCount("SIGTERM"); + const app = await createTestApp({ plugins: [probe()] }); + await app.close(); + // Guards the MaxListenersExceededWarning that shows up at ~6 un-closed + // boots in one file. + expect(process.listenerCount("SIGTERM")).toBe(baseline); + }); + + test("boot, close, boot again in one file", async () => { + const first = await createTestApp({ plugins: [probe()] }); + const firstPort = first.port; + await first.close(); + + const second = await createTestApp({ plugins: [probe()] }); + try { + expect(second.port).not.toBe(firstPort); + await expect( + second.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + } finally { + await second.close(); + } + }); + + test("overlapping boots restore env regardless of close order", async () => { + const before = { ...process.env }; + + // The second boot's view of "original" already contains the first boot's + // mutations. A per-app snapshot would let whichever closes last re-apply + // them, stranding harness keys and `A_ONLY` after both apps are gone. + const a = await createTestApp({ + plugins: [probe()], + env: { OVERLAP_A: "a" }, + }); + const b = await createTestApp({ + plugins: [probe()], + env: { OVERLAP_B: "b" }, + }); + + await a.close(); + await b.close(); + + const leaked = Object.keys(process.env).filter((k) => !(k in before)); + expect(leaked).toEqual([]); + expect(process.env.OVERLAP_A).toBeUndefined(); + expect(process.env.OVERLAP_B).toBeUndefined(); + expect(Object.keys(process.env).sort()).toEqual( + Object.keys(before).sort(), + ); + }); + + test("closing in reverse order also restores env", async () => { + const before = { ...process.env }; + const a = await createTestApp({ + plugins: [probe()], + env: { REV_A: "a" }, + }); + const b = await createTestApp({ + plugins: [probe()], + env: { REV_B: "b" }, + }); + + // Reverse of boot order — the outcome must not depend on it. + await b.close(); + await a.close(); + + expect(Object.keys(process.env).filter((k) => !(k in before))).toEqual( + [], + ); + }); + + test("close() is idempotent", async () => { + const app = await createTestApp({ plugins: [probe()] }); + await app.close(); + await expect(app.close()).resolves.toBeUndefined(); + }); + }); +}); + +describe("createTestApp HTTP layer", () => { + let app: TestApp<[ReturnType]>; + + beforeAll(async () => { + app = await createTestApp({ plugins: [probe()] }); + }); + + afterAll(async () => { + await app?.close(); + }); + + test("GET returns the plugin's JSON body and status", async () => { + const res = await app.get("/api/probe/created"); + expect(res.status).toBe(201); + await expect(res.json()).resolves.toEqual({ ok: true, method: "GET" }); + }); + + test("POST with an object body arrives JSON-parsed at the handler", async () => { + const res = await app.post("/api/probe/echo", { + body: { q: 1, nested: [2] }, + }); + + // Proves the real express.json() middleware ran, not a shortcut. + await expect(res.json()).resolves.toEqual({ + body: { q: 1, nested: [2] }, + contentType: "application/json", + }); + }); + + test("POST with a string body and explicit content-type passes through unmodified", async () => { + const res = await app.post("/api/probe/echo", { + body: "raw text, not JSON", + headers: { "content-type": "text/plain" }, + }); + + // express.json() ignores a non-JSON content-type, so the handler sees an + // empty body — the point is that the harness did not re-encode or override. + await expect(res.json()).resolves.toMatchObject({ + contentType: "text/plain", + }); + }); + + // All three hit /headers and differ only in what `obo`/`headers` should produce. + test.each([ + [ + "obo: true sets the forwarded identity", + { obo: true as const }, + { user: "test-user", token: "test-user-token" }, + ], + [ + "obo object overrides the identity", + { obo: { userId: "alice", email: "alice@example.com" } }, + { user: "alice", email: "alice@example.com" }, + ], + [ + "explicit headers win over what obo generated", + { + obo: true as const, + headers: { "x-custom": "hello", "x-forwarded-user": "override" }, + }, + { custom: "hello", user: "override", token: "test-user-token" }, + ], + [ + "a mixed-case override wins too, rather than comma-joining", + { obo: true as const, headers: { "X-Forwarded-User": "override" } }, + { user: "override", token: "test-user-token" }, + ], + ])("%s", async (_name, options, expected) => { + const res = await app.get("/api/probe/headers", options); + await expect(res.json()).resolves.toMatchObject(expected); + }); + + test("a handler using asUser resolves the forwarded test user", async () => { + const res = await app.get("/api/probe/as-user", { obo: { userId: "bob" } }); + // The real user-context path, driven entirely by the `obo` flag. + await expect(res.json()).resolves.toEqual({ userId: "bob" }); + }); + + test("an SSE route composes with expectStream directly", async () => { + // The dogfooding report's #1 friction, avoided by construction: the request + // methods return a native Response, which expectStream already accepts. + const res = await app.post("/api/probe/stream"); + await expectStream(res).toEmit("status", "result"); + }); + + test("a throwing handler produces the real error-middleware response", async () => { + const res = await app.get("/api/probe/boom"); + + // Handled by the real errorHandlerMiddleware rather than escaping as an + // unhandled rejection that would hang the request and fail the run. + expect(res.status).toBe(500); + + // The message is included because errorHandlerMiddleware redacts only when + // NODE_ENV === "production", and the harness pins "test". That is the + // useful behaviour for a test — an assertion can name the failure — but it + // does mean this response shape is the dev one, not what a deployed app + // returns to a client. + await expect(res.json()).resolves.toEqual({ error: "handler exploded" }); + }); + + test("an unmounted path is a 404", async () => { + const res = await app.get("/api/probe/nope"); + expect(res.status).toBe(404); + }); + + test("put, patch, and delete reach their handlers", async () => { + await expect( + app.put("/api/probe/verb", { body: { a: 1 } }).then((r) => r.json()), + ).resolves.toEqual({ m: "PUT", b: { a: 1 } }); + await expect( + app.patch("/api/probe/verb", { body: { a: 2 } }).then((r) => r.json()), + ).resolves.toEqual({ m: "PATCH", b: { a: 2 } }); + await expect( + app.delete("/api/probe/verb").then((r) => r.json()), + ).resolves.toEqual({ m: "DELETE" }); + }); + + test("a signal aborts an in-flight request", async () => { + const controller = new AbortController(); + controller.abort(); + await expect( + app.get("/api/probe/json", { signal: controller.signal }), + ).rejects.toThrow(); + }); + test("an obo request gets the mock client, not a real one", async () => { + await withApp( + { plugins: [probe()], responses: { "jobs.getRun": { via: "mock" } } }, + async (app) => { + const res = await app.get("/api/probe/as-user-client", { + obo: { userId: "carol" }, + }); + expect(res.status).toBe(200); + + // Asserting the host would not discriminate — a real client built from + // DATABRICKS_HOST carries the same string. What only the mock can do is + // record the call and return the declared response. + await expect(res.json()).resolves.toEqual({ run: { via: "mock" } }); + expect(getMockFn(app.client, "jobs.getRun")).toHaveBeenCalledWith({ + run_id: 42, + }); + }, + ); + }); + + describe("overlapping apps", () => { + test("booting a second app does not rebind the first's singletons", async () => { + const a = await createTestApp({ plugins: [probe()] }); + const b = await createTestApp({ plugins: [probe()] }); + try { + // Both must still resolve their own client through the real seam. Before + // the singletons were refcounted, B's boot reset and rebound A's. + await expect( + a.get("/api/probe/from-client").then((r) => r.status), + ).resolves.toBe(200); + await expect( + b.get("/api/probe/from-client").then((r) => r.status), + ).resolves.toBe(200); + } finally { + await a.close(); + await b.close(); + } + }); + + test("closing one app leaves the other's context intact", async () => { + const a = await createTestApp({ plugins: [probe()] }); + const b = await createTestApp({ plugins: [probe()] }); + try { + await a.close(); + // Previously A's close dropped the singletons, so this threw + // InitializationError from ServiceContext.get(). + await expect( + b.get("/api/probe/from-client").then((r) => r.status), + ).resolves.toBe(200); + } finally { + await b.close(); + } + }); + + test("a stale handle's second close cannot reset a newer app", async () => { + const first = await createTestApp({ plugins: [probe()] }); + await first.close(); + + const second = await createTestApp({ plugins: [probe()] }); + try { + // close() is memoized, so this is a no-op rather than a second release. + await first.close(); + await expect( + second.get("/api/probe/from-client").then((r) => r.status), + ).resolves.toBe(200); + } finally { + await second.close(); + } + }); + }); +}); diff --git a/packages/appkit/src/testing/tests/create-test-plugin.test.ts b/packages/appkit/src/testing/tests/create-test-plugin.test.ts new file mode 100644 index 000000000..e92731677 --- /dev/null +++ b/packages/appkit/src/testing/tests/create-test-plugin.test.ts @@ -0,0 +1,82 @@ +import type { BasePluginConfig, PluginManifest } from "shared"; +import { describe, expect, test } from "vitest"; + +import { Plugin, toPlugin } from "../../plugin"; +import { createTestPlugin } from "../create-test-plugin"; + +/** + * The behaviour that matters is the merge: an instance built by hand skips + * DEFAULT_CONFIG and forgets `name`, so a test against it can pass wrongly. + */ + +interface WidgetConfig extends BasePluginConfig { + size?: string; + colour?: string; +} + +class WidgetPlugin extends Plugin { + static manifest = { + name: "widget", + displayName: "Widget", + version: "0.0.0", + description: "config-merge probe", + resources: { required: [], optional: [] }, + } as unknown as PluginManifest; + + static DEFAULT_CONFIG = { size: "medium", colour: "blue" }; + + readonly received: WidgetConfig; + + constructor(config: WidgetConfig) { + super(config); + this.received = config; + } +} +// No cast: the class satisfies PluginConstructor, so the factory's config and +// instance types both infer — which is what lets createTestPlugin be typed. +const widget = toPlugin(WidgetPlugin); + +describe("createTestPlugin", () => { + test("returns an instance of the plugin class", () => { + const plugin = createTestPlugin(widget); + expect(plugin).toBeInstanceOf(WidgetPlugin); + }); + + test("applies DEFAULT_CONFIG", () => { + const plugin = createTestPlugin(widget); + // The hand-rolled `new (widget({}).plugin)({})` skips these entirely. + expect(plugin.received.size).toBe("medium"); + expect(plugin.received.colour).toBe("blue"); + }); + + test("explicit config wins over DEFAULT_CONFIG", () => { + const plugin = createTestPlugin(widget, { + size: "large", + }); + expect(plugin.received.size).toBe("large"); + // Unspecified keys still come from the defaults. + expect(plugin.received.colour).toBe("blue"); + }); + + test("sets the manifest name, which the hand-rolled form forgets", () => { + const plugin = createTestPlugin(widget); + expect(plugin.received.name).toBe("widget"); + expect(plugin.name).toBe("widget"); + }); + + test("a zero-argument call works", () => { + expect(() => createTestPlugin(widget)).not.toThrow(); + }); + + test("the merge order matches what registration produces", () => { + // Same order as AppKit.createAndRegisterPlugin: DEFAULT_CONFIG, then the + // factory's config, then `name`. A caller cannot override `name`, because + // the manifest owns it. + const plugin = createTestPlugin(widget, { + name: "not-this", + colour: "red", + }); + expect(plugin.received.name).toBe("widget"); + expect(plugin.received.colour).toBe("red"); + }); +}); diff --git a/packages/appkit/src/testing/tests/mock-workspace-client.test.ts b/packages/appkit/src/testing/tests/mock-workspace-client.test.ts new file mode 100644 index 000000000..6da9af93f --- /dev/null +++ b/packages/appkit/src/testing/tests/mock-workspace-client.test.ts @@ -0,0 +1,253 @@ +import { inspect } from "node:util"; + +import { describe, expect, test, vi } from "vitest"; + +import { ServiceContext } from "../../context/service-context"; +import { mockServiceContext } from "../fixtures"; +import { createMockWorkspaceClient, getMockFn } from "../mock-workspace-client"; + +const mk = createMockWorkspaceClient; +/** Service methods are SDK-typed, so calling an arbitrary one needs a cast. */ +const svc = (client: unknown, name: string) => + (client as Record unknown>>)[ + name + ]; + +const SUCCEEDED = { status: { state: "SUCCEEDED" }, result: { data: [] } }; +const TEST_USER = { id: "test-service-user", userName: "test-service-user" }; + +describe("createMockWorkspaceClient", () => { + describe("the never-crash floor", () => { + // Never-crash is the headline claim, so all nine are asserted, not sampled. + test.each([ + ["files", "listDirectory", undefined], + ["genie", "getMessage", undefined], + ["jobs", "getRun", undefined], + ["servingEndpoints", "get", undefined], + ["warehouses", "get", { state: "RUNNING" }], + ["warehouses", "start", undefined], + ["statementExecution", "executeStatement", SUCCEEDED], + ["currentUser", "me", TEST_USER], + ])("%s.%s resolves its default", async (service, method, expected) => { + const client = mk(); + expect(client[service as "jobs"]).toBeDefined(); + await expect(svc(client, service)[method]({})).resolves.toEqual(expected); + }); + + test("config and apiClient are reachable, and not mocks where it matters", () => { + const client = mk(); + // Both read directly by production code — a Promise or mock here breaks it. + expect(typeof client.config.host).toBe("string"); + expect(client.config.host).toBeTruthy(); + expect(typeof client.apiClient.userAgent()).toBe("string"); + }); + + test("apiClient.request is depth-2 and destructurable", async () => { + await expect(mk().apiClient.request({} as never)).resolves.toEqual({}); + const client = mk({ + responses: { "apiClient.request": { results: [] } }, + }); + await expect(client.apiClient.request({} as never)).resolves.toEqual({ + results: [], + }); + }); + }); + + describe("responses", () => { + test("a declared value resolves, and overrides a default", async () => { + const client = mk({ + responses: { + "jobs.getRun": { state: "TERMINATED" }, + "statementExecution.executeStatement": { status: { state: "MINE" } }, + }, + }); + await expect(client.jobs.getRun({} as never)).resolves.toEqual({ + state: "TERMINATED", + }); + await expect( + client.statementExecution.executeStatement({} as never), + ).resolves.toEqual({ status: { state: "MINE" } }); + }); + + test("a function receives the arguments, and its rejection propagates", async () => { + const fn = vi.fn().mockResolvedValue({ ok: true }); + await mk({ responses: { "jobs.getRun": fn } }).jobs.getRun({ + run_id: 456, + } as never); + expect(fn).toHaveBeenCalledWith({ run_id: 456 }); + + const err = new Error("boom"); + const rejecting = mk({ + responses: { "jobs.getRun": () => Promise.reject(err) }, + }); + await expect(rejecting.jobs.getRun({} as never)).rejects.toBe(err); + }); + + test("{ defaults: false } leaves the canned paths unresolved", async () => { + const client = mk({ defaults: false }); + await expect( + client.statementExecution.executeStatement({} as never), + ).resolves.toBeUndefined(); + }); + + test("the config option overrides defaults and adds members", () => { + const authenticate = vi.fn(); + const client = mk({ + config: { host: "https://custom.example.com", authenticate }, + }); + expect(client.config.host).toBe("https://custom.example.com"); + expect(client.config.authenticate).toBe(authenticate); + }); + + test('a "config.host" response stays a raw string, not a mock', () => { + expect( + mk({ responses: { "config.host": "https://a.b" } }).config.host, + ).toBe("https://a.b"); + }); + + test("config.authenticate stamps a header; ensureResolved resolves", async () => { + const client = mk(); + const headers = new Headers(); + // Asserting only "was called" would pass against a mock that does nothing. + await client.config.authenticate(headers); + expect(headers.get("Authorization")).toBe("Bearer test-token"); + await expect(client.config.ensureResolved()).resolves.toBeUndefined(); + }); + + test("an unknown member of a seeded namespace still hits the floor", () => { + expect( + typeof (mk().config as never as Record).nope, + ).toBe("function"); + }); + }); + + describe("memoization (call assertions depend on it)", () => { + test("methods, namespaces, and the legacy view share one identity", () => { + const client = mk(); + expect(client.jobs.getRun).toBe(client.jobs.getRun); + expect(client.jobs).toBe(client.jobs); + expect(client.toLegacyWorkspaceClient().jobs.getRun).toBe( + client.jobs.getRun, + ); + }); + + test("un-faceted legacy services also work", async () => { + const legacy = mk().toLegacyWorkspaceClient(); + await expect(svc(legacy, "clusters").list({})).resolves.toBeUndefined(); + }); + }); + + describe("footguns", () => { + test("a service is not thenable, so await does not hang", async () => { + const client = mk(); + expect((client.jobs as never as { then?: unknown }).then).toBeUndefined(); + await expect(Promise.resolve(client.jobs)).resolves.toBe(client.jobs); + }); + + test("formatting and structural equality neither throw nor recurse", () => { + const client = mk(); + // ownKeys stays default, so a service inspects as {} instead of minting a + // mock per probed property. + expect(inspect(client.jobs)).toBe("{}"); + expect(inspect(client.toLegacyWorkspaceClient())).toBe("{}"); + expect(inspect(client)).toContain("https://test.databricks.com"); + expect(() => JSON.stringify(client.config)).not.toThrow(); + expect(() => expect(client.jobs).toEqual({})).not.toThrow(); + + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + expect(() => console.log("%O", client)).not.toThrow(); + } finally { + log.mockRestore(); + } + }); + }); + + describe("getMockFn", () => { + test("mints before first use and stays stable after", async () => { + const client = mk(); + const getRun = getMockFn(client, "jobs.getRun"); + expect(getRun).toHaveBeenCalledTimes(0); + + await client.jobs.getRun({ run_id: 7 } as never); + expect(getRun).toBe(getMockFn(client, "jobs.getRun")); + expect(getRun).toHaveBeenCalledWith({ run_id: 7 }); + }); + + test("resolves seeded members and rejects non-function paths", () => { + const client = mk(); + expect(getMockFn(client, "apiClient.request")).toBe( + client.apiClient.request, + ); + expect(() => getMockFn(client, "config.host")).toThrow( + /not a mocked function/, + ); + expect(() => getMockFn({} as never, "jobs.getRun")).toThrow( + /not a createMockWorkspaceClient/, + ); + }); + }); + + describe("convergence with mockServiceContext (D4)", () => { + test("the historical canned defaults are byte-identical", async () => { + const client = mk(); + await expect( + client.statementExecution.executeStatement({} as never), + ).resolves.toEqual(SUCCEEDED); + await expect(client.warehouses.get({} as never)).resolves.toEqual({ + state: "RUNNING", + }); + await expect( + client.warehouses.start({} as never), + ).resolves.toBeUndefined(); + }); + + test("the service and user clients are both faked, and neither crashes", async () => { + const mock = mockServiceContext(); + try { + // Before convergence this threw "Cannot read properties of undefined". + await expect( + mock.serviceContext.client.jobs.getRun({} as never), + ).resolves.toBeUndefined(); + await expect( + mock.serviceContext.client.statementExecution.executeStatement( + {} as never, + ), + ).resolves.toMatchObject({ status: { state: "SUCCEEDED" } }); + + const user = ServiceContext.createUserContext("tok", "u-1", "alice"); + await expect( + user.client.jobs.getRun({} as never), + ).resolves.toBeUndefined(); + } finally { + mock.restore(); + } + }); + }); + + /** + * Enforced by `tsc --noEmit`, not at runtime: a `@ts-expect-error` that stops + * being an error fails the typecheck. + */ + describe("compile-time contract", () => { + test("unknown members and misspelled methods are compile errors", () => { + const client = mk(); + + // @ts-expect-error - `jbos` is not a facade member + expect(client.jbos).toBeUndefined(); + // @ts-expect-error - `getRunz` is not a jobs method + void client.jobs.getRunz; + // @ts-expect-error - `getMessagez` is not a genie method + void client.genie.getMessagez; + + // `host` is `string | undefined` in the SDK, so the honest claim is that it + // narrows to a string — not that it is non-optional. + const host = client.config.host; + expect(typeof host).toBe("string"); + + const getRun = getMockFn(client, "jobs.getRun"); + getRun.mockResolvedValue({ state: "TERMINATED" }); + expect(getRun.mock.calls).toEqual([]); + }); + }); +}); diff --git a/packages/appkit/src/testing/tests/published-surface.integration.test.ts b/packages/appkit/src/testing/tests/published-surface.integration.test.ts new file mode 100644 index 000000000..baa65998d --- /dev/null +++ b/packages/appkit/src/testing/tests/published-surface.integration.test.ts @@ -0,0 +1,90 @@ +import { + createTestApp, + expectStream, + getMockFn, +} from "@databricks/appkit/testing"; +import { describe, expect, test } from "vitest"; + +import { Plugin, toPlugin } from "../../plugin"; + +/** + * Acceptance test for the published surface: everything the test needs comes from + * `@databricks/appkit/testing` — no `@tools` shim, no deep imports. + * `Plugin`/`toPlugin` come from the main entry because they are how you *write* a + * plugin, not how you test one. + */ + +class WidgetPlugin extends Plugin { + static manifest = { + name: "widget", + displayName: "Widget", + version: "0.0.0", + description: "A plugin an external author might write", + resources: { required: [], optional: [] }, + } as never; + + injectRoutes(router: never): void { + this.route(router, { + name: "run", + method: "post", + path: "/run", + handler: async (req, res) => { + // The data plane, faked by the harness with no workspace in sight. + const { getWorkspaceClient } = await import("../../context"); + const run = await getWorkspaceClient().jobs.getRun({ + run_id: (req.body as { id: number }).id, + } as never); + res.json({ run }); + }, + }); + + this.route(router, { + name: "stream", + method: "post", + path: "/stream", + handler: async (_req, res) => { + res.setHeader("content-type", "text/event-stream"); + res.write(`event: status\ndata: ${JSON.stringify({ s: "go" })}\n\n`); + res.write(`event: result\ndata: ${JSON.stringify({ n: 1 })}\n\n`); + res.end(); + }, + }); + } +} +const widget = toPlugin(WidgetPlugin); + +describe("@databricks/appkit/testing as a standalone surface", () => { + test("boot, request, assert a stream, and close — public imports only", async () => { + const app = await createTestApp({ + plugins: [widget()], + responses: { "jobs.getRun": { state: "TERMINATED" } }, + }); + + try { + const res = await app.post("/api/widget/run", { body: { id: 42 } }); + expect(res.status).toBe(200); + await expect(res.json()).resolves.toEqual({ + run: { state: "TERMINATED" }, + }); + expect(getMockFn(app.client, "jobs.getRun")).toHaveBeenCalledWith({ + run_id: 42, + }); + + const stream = await app.post("/api/widget/stream"); + await expectStream(stream).toEmit("status", "result"); + } finally { + await app.close(); + } + }); + + test("await using works from the public entry too", async () => { + let port: number | undefined; + { + await using app = await createTestApp({ plugins: [widget()] }); + port = app.port; + const res = await app.post("/api/widget/run", { body: { id: 1 } }); + expect(res.status).toBe(200); + } + await expect(fetch(`http://127.0.0.1:${port}/health`)).rejects.toThrow(); + }); +}); diff --git a/packages/appkit/src/testing/tests/test-plugin-context.test.ts b/packages/appkit/src/testing/tests/test-plugin-context.test.ts index 60b30b917..d84a52937 100644 --- a/packages/appkit/src/testing/tests/test-plugin-context.test.ts +++ b/packages/appkit/src/testing/tests/test-plugin-context.test.ts @@ -4,6 +4,7 @@ import { describe, expect, test } from "vitest"; import { PluginContext } from "../../core/plugin-context"; import { Plugin } from "../../plugin"; import type { PluginManifest } from "../../registry"; +import { createMockRequest } from "../fixtures"; import { createTestPluginContext } from "../test-plugin-context"; // A minimal real plugin for exercising attach() end-to-end. @@ -40,11 +41,7 @@ function mockReq( "x-forwarded-user": "alice", }, ): express.Request { - return { - body: {}, - headers, - header: (name: string) => headers[name.toLowerCase()], - } as unknown as express.Request; + return createMockRequest({ headers }) as unknown as express.Request; } describe("createTestPluginContext — construction", () => { diff --git a/packages/appkit/tsconfig.json b/packages/appkit/tsconfig.json index 5265a6881..76212e07e 100644 --- a/packages/appkit/tsconfig.json +++ b/packages/appkit/tsconfig.json @@ -7,7 +7,9 @@ "@/*": ["src/*"], "@tools/*": ["../../tools/*"], "shared": ["../../packages/shared/src"], - "@databricks/lakebase": ["../../packages/lakebase/src"] + "@databricks/lakebase": ["../../packages/lakebase/src"], + "@databricks/appkit": ["src/index.ts"], + "@databricks/appkit/testing": ["src/testing/index.ts"] } }, "include": ["src/**/*"], diff --git a/packages/shared/src/plugin.ts b/packages/shared/src/plugin.ts index 15148895e..f04278187 100644 --- a/packages/shared/src/plugin.ts +++ b/packages/shared/src/plugin.ts @@ -264,6 +264,29 @@ export type PluginMap< >; }; +/** + * What `createApp()` returns: every plugin's exports keyed by manifest name, + * plus the app's own teardown handle. + * + * `close()` releases what AppKit acquired — sockets, timers, pools, cache, and + * telemetry — without terminating the process, so a host can embed AppKit and a + * test can boot more than once in a file. + * + * `Symbol.asyncDispose` is exposed alongside it because a plugin's manifest name + * can never be a symbol: `await using app = await createApp(...)` is safe even + * if a plugin were somehow named `close`. + */ +export type AppHandle< + U extends readonly PluginData[], +> = PluginMap & { + /** + * @param options.timeoutMs - Overall teardown budget. Defaults to AppKit's + * programmatic budget, which is shorter than the signal path's. + */ + close(options?: { timeoutMs?: number }): Promise; + [Symbol.asyncDispose](): Promise; +}; + /** Tuple of plugin class, config, and name. Created by `toPlugin()` and passed to `createApp()`. */ export type PluginData = { plugin: T; config: U; name: N }; /** Factory function type returned by `toPlugin()`. Accepts optional config and returns a PluginData tuple. */ diff --git a/template/server/example.test.ts b/template/server/example.test.ts index 9140c2e24..535f800fd 100644 --- a/template/server/example.test.ts +++ b/template/server/example.test.ts @@ -1,5 +1,5 @@ -import { Plugin, type PluginManifest } from '@databricks/appkit'; -import { expectStream, createTestPluginContext } from '@databricks/appkit/testing'; +import { Plugin, type PluginManifest, toPlugin } from '@databricks/appkit'; +import { createTestApp, createTestPluginContext, expectStream } from '@databricks/appkit/testing'; import { describe, expect, test } from 'vitest'; /** @@ -9,10 +9,13 @@ import { describe, expect, test } from 'vitest'; * network — so these tests run anywhere, including CI. Delete this file, or use * it as a starting point for testing your own plugins. * - * Two headline helpers are shown below: + * Three headline helpers are shown below: + * - `createTestApp({ plugins })` — boot a real app (real Express, real routes, + * real validation) on an ephemeral port and call it over HTTP. Start here for + * a plugin's end-to-end behaviour. Every boot needs `close()`. * - `createTestPluginContext()` — a real PluginContext with faked edges, attachable * to a plugin so its real code paths (routes, tool dispatch, user scoping) - * run under test. + * run under test. No boot, no socket — the fastest option for unit tests. * - `expectStream(...).toEmit(...)` — assert the ordered event types a * streaming handler emits. * @@ -43,8 +46,25 @@ class GreeterPlugin extends Plugin { yield { type: 'greeting_start', name }; yield { type: 'greeting_end', message: `Hello, ${name}!` }; } + + // A real HTTP route, so createTestApp has something to call. + injectRoutes(router: Parameters[0]) { + this.route(router, { + name: 'greet', + method: 'post', + path: '/greet', + handler: async (req, res) => { + const { name } = req.body as { name: string }; + res.json({ message: `Hello, ${name}!` }); + }, + }); + } } +// The factory form `createApp` (and `createTestApp`) take. `toPlugin` reads the +// plugin name from the static manifest. +const greeter = toPlugin(GreeterPlugin); + describe('testing kit example', () => { test('attaches a real PluginContext and records registered routes', async () => { const mock = createTestPluginContext(); @@ -61,4 +81,20 @@ describe('testing kit example', () => { await expectStream(plugin.greet('world')).toEmit('greeting_start', 'greeting_end'); }); + + test('boots a real app and calls the plugin over HTTP', async () => { + // No workspace, no credentials, no network. The harness fakes the whole + // Databricks data plane and binds an ephemeral port. + const app = await createTestApp({ plugins: [greeter()] }); + + try { + const res = await app.post('/api/greeter/greet', { body: { name: 'world' } }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ message: 'Hello, world!' }); + } finally { + // Required: releases the socket and restores process.env. + await app.close(); + } + }); }); diff --git a/tools/test-helpers.ts b/tools/test-helpers.ts index 5a88312da..6685e9401 100644 --- a/tools/test-helpers.ts +++ b/tools/test-helpers.ts @@ -5,13 +5,16 @@ * `@tools/test-helpers` importers keep working; new code (inside or outside * this repo) should import from `@databricks/appkit/testing` instead. * + * The integration suites have already moved to the public entry point, which is + * what verifies the published surface is self-sufficient. The remaining + * importers are unit suites, migrated opportunistically. + * * Note: `mockServiceContext` is now synchronous (the previous dynamic * `import()` became a static one to avoid a circular-init trap once packaged). * Existing `await mockServiceContext(...)` call sites are unaffected — awaiting * a non-promise is a no-op, and `Awaited>` unwraps identically. */ export { - createConfigurableMockWorkspaceClient, createFailedSQLResponse, createMockRequest, createMockResponse, @@ -22,9 +25,17 @@ export { createTestPluginContext, expectStream, mockServiceContext, + createTestApp, + type CreateTestAppOptions, + getListeningPort, + getMockFn, + type MockWorkspaceClient, parseSSEResponse, + resetAppKitSingletons, runWithRequestContext, setupDatabricksEnv, + type TestApp, type TestContextOptions, + type TestRequestOptions, useServiceContextMock, } from "../packages/appkit/src/testing";