diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc0fb6272..379d83951 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -213,6 +213,16 @@ jobs: working-directory: pr-template run: npm install + # The scaffold's own vitest suite, run against the tarballs built above + # rather than the published versions template/package.json pins. This is + # the only CI check that exercises the template's example test, and the + # only one that consumes @databricks/appkit/testing the way a customer + # does — through a real npm install of a packed tarball. Before the zip, + # so a broken example fails the build instead of shipping. + - name: Run the template's own tests + working-directory: pr-template + run: npm test + # npm install above runs under the JFrog .npmrc (setup-jfrog-npm), which # bakes internal registry URLs into the regenerated lock. Rewrite them back # to public npm and fail-closed if any non-public registry remains, so the diff --git a/.gitignore b/.gitignore index 835aa9ef3..a623d8837 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,10 @@ tmp node_modules .env +# Staging dir and zip produced by tools/prepare-template-artifact.ts +pr-template +appkit-template-*.zip + coverage *.tsbuildinfo diff --git a/docs/docs/api/appkit/Function.createApp.md b/docs/docs/api/appkit/Function.createApp.md index bc656537d..b7cd2fc3a 100644 --- a/docs/docs/api/appkit/Function.createApp.md +++ b/docs/docs/api/appkit/Function.createApp.md @@ -29,15 +29,15 @@ 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. | +| `config.plugins?` | `T` | - | +| `config.telemetry?` | [`TelemetryConfig`](Interface.TelemetryConfig.md) | - | ## Returns diff --git a/docs/docs/plugins/testing.md b/docs/docs/plugins/testing.md index 30fc66642..ca02a5aba 100644 --- a/docs/docs/plugins/testing.md +++ b/docs/docs/plugins/testing.md @@ -1,26 +1,151 @@ --- -sidebar_position: 8 +sidebar_position: 10 --- # Testing -AppKit ships a testing kit at `@databricks/appkit/testing` so you can test a plugin — including its cross-plugin tool calls and streaming responses — without a live Databricks workspace, credentials, or network access. That makes plugin tests fast and lets them run in CI, where no workspace is available. +AppKit ships a testing kit at `@databricks/appkit/testing` so you can test a plugin, including its cross-plugin tool calls and streaming responses, without a live Databricks workspace, credentials, or network access. Plugin tests stay fast and run in CI, where no workspace is available. ## Goal -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. +Exercise a plugin's real code paths against a real `PluginContext` with only its outer edges faked. That covers route registration, cross-plugin tool dispatch, user-scoped (on-behalf-of) execution, and per-call timeouts. 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, with the real Express wiring, routes, and resource validation, then 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 behavior 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 behavior or reject to test an error path. `responses` configures the built-in mock, so passing it alongside your own `client` is rejected rather than silently ignored — configure the responses on that client instead. Any path you **don't** declare resolves `undefined` rather than crashing — see [Mocking Databricks services](#mocking-databricks-services) for the trade-off it makes. + +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. + +With one app open, `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 { getMock } from "@databricks/appkit/testing"; + +expect(getMock(app.client, "jobs.getRun")).toHaveBeenCalledWith({ run_id: 42 }); +``` + +`getMock` 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, so **every boot needs a `close()`**. It 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. + +Prefer `await using`, which closes the app at scope exit even if the test throws: + +```ts +await using app = await createTestApp({ plugins: [myPlugin()] }); +// released at scope exit +``` + +`try/finally` works too, and is what you need if the app has to outlive a block: + +```ts +const app = await createTestApp({ plugins: [myPlugin()] }); +try { + // ... +} finally { + await app.close(); +} +``` + +Miss the close and the app stays live — socket bound, singletons and `process.env` not restored — so the next `createTestApp` is refused (one app at a time). + +### 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. + ## `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: +`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: | Edge | How it's faked | | --- | --- | @@ -58,6 +183,8 @@ await mock.attach(plugin); Instantiate the plugin **class** directly (`new MyAgentPlugin(...)`). The `analytics()` / `agents()` factories you pass to `createApp` return a descriptor for the app to construct — for a unit test you want the instance. +The workspace client and the on-behalf-of stub are process-wide too, not per app: `ServiceContext` holds one client, and the `createUserContext` fake is a single spy. Because of that, **`createTestApp` allows one open app at a time** and throws if you boot a second before closing the first — with two open, the second one's `client` and `responses` would not reach the handlers, and closing either would remove the shared OBO fake from the other. Vitest isolates test *files* in separate workers, so this only constrains apps within a single file. One consequence worth knowing: a `describe` that holds an app open in `beforeAll` cannot contain a test that boots its own. + The cache `attach()` seeds is a process-wide singleton: `CacheManager` is initialized once per test process and reused. Vitest isolates test *files* in separate workers, so caches never leak across files, but tests **within one file** share it. If a test populates the cache and a later test in the same file must not see it, clear it between tests with `resetTestCache()`: ```ts @@ -96,7 +223,7 @@ expect(mock.telemetry.getTracer().startActiveSpan).toHaveBeenCalled(); `mock.telemetry` is injected into the `PluginContext`, so it captures the spans the *context* opens (notably `executeTool`). It is **not** the plugin's own telemetry: `attachContext` rebuilds `this.telemetry` from the real `TelemetryManager`, so spans a plugin opens internally do not land on `mock.telemetry`. -`RecordedToolCall.asUser` is the high-value signal for cross-plugin calls: because the fake `asUser` enforces the same token precondition as the real `Plugin.asUser`, a dispatch that records `asUser: true` (with `userId` set) genuinely resolved the caller's user scope, and a request missing `x-forwarded-access-token` **rejects** instead — the OBO distinction that silent `{ executeTool }` stubs cannot verify. Assert both directions: a well-formed request records the expected `userId`, and a token-less one throws. +`RecordedToolCall.asUser` is the field to assert for cross-plugin calls: because the fake `asUser` enforces the same token precondition as the real `Plugin.asUser`, a dispatch that records `asUser: true` (with `userId` set) genuinely resolved the caller's user scope, and a request missing `x-forwarded-access-token` **rejects** instead — the OBO distinction that silent `{ executeTool }` stubs cannot verify. Assert both directions: a well-formed request records the expected `userId`, and a token-less one throws. The fake replicates `asUser`'s **token precondition**, not its internal dev-mode telemetry marker: in `NODE_ENV=development` the real `Plugin.asUser` skips impersonation and sets an OTel `isDevOboFallback()` flag, which the fake does not reproduce. Assert OBO through the recorded `asUser`/`userId` fields rather than `isDevOboFallback()`. @@ -131,7 +258,7 @@ await plugin._handleStream(createMockRequest({ obo: true }), res); await expectStream(res).toEmit("status", "result"); ``` -`expectStream(res)` and `expectStream(res.sseResponse())` are equivalent — the latter hands you the raw `Response` if you want it. Do **not** pass the SSE body as a string: a string is an iterable of characters, so `expectStream` rejects it with a pointer to `sseResponse()` rather than emitting one "event" per character. +`expectStream(res)` and `expectStream(res.sseResponse())` are equivalent; the latter hands you the raw `Response` if you want it. Do **not** pass the SSE body as a string: a string is an iterable of characters, so `expectStream` rejects it with a pointer to `sseResponse()` rather than emitting one "event" per character. `toEmit` checks that the expected types appear **in order** but tolerates other events before, between, or after them — which is what you want for streams that interleave bookkeeping events like heartbeats or metadata. Use `toEmitExactly` when the stream's shape is fully determined. @@ -143,6 +270,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, handling routes, tool dispatch, and user scoping; `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 +291,70 @@ 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. +The kit uses both words deliberately: a **mock** records calls so you can assert on them (`createMockWorkspaceClient`, `mockServiceContext`), while a **fake** stands in and simply works (`FakeProvider`, `FakeToolResponse`). + +- `createTestPlugin(factory, config?)` — instantiate a plugin from its factory with the same config merge AppKit applies. See [Full example](#full-example). +- `getListeningPort(server)` — wait for a server to finish binding and return the port it landed on. `createTestApp` does this for you; reach for it when you start a server yourself with `port: 0`. + +## 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, getMock } 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 the 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 Undeclared methods return undefined +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. + +Pass `strict: true` to turn that silence into a failure: a call to a path with no declared response throws instead of resolving `undefined`, naming the path. The canned defaults still count as declared, so a harness boot works unchanged. + +```ts +const app = await createTestApp({ plugins: [myPlugin()], strict: true }); +// a handler calling an undeclared path now fails the request +``` + +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: 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 deliberate: 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 8fa4174c8..0cc301c72 100644 --- a/docs/static/appkit-ui/styles.gen.css +++ b/docs/static/appkit-ui/styles.gen.css @@ -401,6 +401,9 @@ .\!m-0 { margin: calc(var(--spacing) * 0) !important; } + .m-1 { + margin: calc(var(--spacing) * 1); + } .-mx-1 { margin-inline: calc(var(--spacing) * -1); } @@ -717,6 +720,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..486bd8133 100644 --- a/packages/appkit/src/cache/index.ts +++ b/packages/appkit/src/cache/index.ts @@ -128,6 +128,10 @@ export class CacheManager { if (!CacheManager.initPromise) { CacheManager.initPromise = CacheManager.create(userConfig).then( (instance) => { + // Publishes unconditionally: safe only because every getInstance() is + // awaited before any reset(), so a reset() can never land mid-init and + // this can never publish over it. A future unawaited-init caller would + // reintroduce that stale-publish race (the removed `generation` guard). CacheManager.instance = instance; return instance; }, @@ -557,6 +561,20 @@ 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; + } + /** * 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..a8804f0bb --- /dev/null +++ b/packages/appkit/src/cache/tests/cache-manager-reset.test.ts @@ -0,0 +1,100 @@ +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("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 f5f4f2725..42227b992 100644 --- a/packages/appkit/src/core/appkit.ts +++ b/packages/appkit/src/core/appkit.ts @@ -27,10 +27,20 @@ import { isToolProvider, PluginContext } from "./plugin-context"; const logger = createLogger("appkit"); +/** + * Internal teardown entry for the test harness (see `createTestApp`). + * Symbol-keyed so it cannot collide with — or be shadowed by — a plugin + * manifest name, and so it stays off the public `PluginMap` surface. + * @internal + */ +export const disposeApp = Symbol("appkit.internal.dispose"); + export class AppKit { #pluginInstances: Record = {}; #setupPromises: Promise[] = []; #context: PluginContext; + /** Owns the shutdown sequence; assigned once every plugin has started. */ + #lifecycle: LifecycleManager | undefined; private constructor(config: { plugins: TPlugins }) { const { plugins, ...globalConfig } = config; @@ -190,6 +200,13 @@ export class AppKit { client?: WorkspaceClient; onPluginsReady?: (appkit: PluginMap) => void | Promise; disableInternalTelemetry?: boolean; + /** + * Skip installing the SIGTERM/SIGINT handlers. Internal, and not exposed + * on {@link createApp}: only the test harness sets it, because it boots + * repeatedly in one process and manages its own teardown, so + * accumulating signal handlers would be a leak. + */ + installSignalHandlers?: boolean; } = {}, ): Promise> { // Initialize core services @@ -231,11 +248,11 @@ export class AppKit { await instance.#context.emitLifecycle("setup:complete"); - const handle = instance as unknown as PluginMap; + const app = instance as unknown as PluginMap; if (config.onPluginsReady) { logger.debug("Running onPluginsReady hook"); - await config.onPluginsReady(handle); + await config.onPluginsReady(app); logger.debug("onPluginsReady hook completed"); } @@ -252,9 +269,24 @@ 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); + if (config.installSignalHandlers !== false) { + instance.#lifecycle.installSignalHandlers(); + } + + return app; + } - return handle; + /** + * Internal teardown entry point for the test harness: delegates to the + * lifecycle's non-exiting `shutdown({ exit: false })` (the phases are + * canonical there). Not public API — AppKit does not support re-booting or + * embedding, so real apps tear down only through the signal path. The harness + * drops the core singletons and restores env after this resolves. + * @internal + */ + async [disposeApp](): Promise { + await this.#lifecycle?.shutdown({ exit: false }); } private static bootstrapInternalTelemetry(): void { @@ -388,6 +420,7 @@ export async function createApp< telemetry?: TelemetryConfig; cache?: CacheConfig; client?: WorkspaceClient; + /** Runs after plugin setup but **before** the server starts. */ onPluginsReady?: (appkit: PluginMap) => void | Promise; disableInternalTelemetry?: boolean; } = {}, diff --git a/packages/appkit/src/core/lifecycle-manager.ts b/packages/appkit/src/core/lifecycle-manager.ts index 84dcb4a9e..cfe4147b6 100644 --- a/packages/appkit/src/core/lifecycle-manager.ts +++ b/packages/appkit/src/core/lifecycle-manager.ts @@ -46,34 +46,31 @@ export class LifecycleManager { private static readonly PHASE_SHUTDOWN_TIMEOUT_MS = 2_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 the + * harness path (`{ exit: false }`), 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"; constructor(private readonly context: PluginContext) {} /** - * 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}. + * Install the SIGTERM/SIGINT handlers that trigger {@link shutdown}. Never + * removed: the signal path exits the process, and the harness opts out of + * installing them, so nothing accumulates across boots. */ installSignalHandlers(): void { - process.once("SIGTERM", () => this.shutdown()); - process.once("SIGINT", () => this.shutdown()); + process.once("SIGTERM", () => void this.shutdown()); + process.once("SIGINT", () => void this.shutdown()); } /** - * Run the graceful-shutdown sequence and exit the process. + * Run the graceful-shutdown sequence. Exits the process unless + * `exit: false` — the flag the test harness passes so it can tear a booted + * app down between tests without killing the vitest process. * * Phases: * 1. stop the internal-telemetry reporter @@ -83,25 +80,28 @@ export class LifecycleManager { * 4. emit the `"shutdown"` lifecycle event, bounded * 5. close the cache storage and flush telemetry concurrently, each bounded * + * Every phase is individually bounded, so the sequence always completes — + * `{ exit: false }` therefore needs no outer timeout and an `afterEach` + * cannot hang on it. A second call joins the first teardown. + * * 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. */ - 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; + async shutdown(options: { exit?: boolean } = {}): Promise { + const exit = options.exit ?? true; - logger.info("Starting graceful shutdown..."); - - let exitCode = 0; + if (!exit) { + // Harness path: no backstop, no process.exit. The phases are internally + // bounded, and this is fully awaited before the harness drops the + // singletons — so phase 5 always acts on this app's own cache/telemetry. + await this.runPhasesOnce(); + return; + } - // 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. Belt-and-suspenders over the per-phase budgets. 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 +110,28 @@ 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.runPhasesOnce(); + + clearTimeout(forceExitTimer); + process.exit(exitCode); + } + + /** No `await` between read and assign — that gap is the re-entrancy window. */ + private runPhasesOnce(): 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..."); + + let exitCode = 0; + try { const plugins = Array.from(this.context.getPlugins().values()); @@ -184,17 +199,16 @@ export class LifecycleManager { exitCode = 1; } - clearTimeout(forceExitTimer); - process.exit(exitCode); + return exitCode; } - /** Close the cache storage, bounded and error-isolated. */ + /** Bounded and error-isolated. Reads the cache manager at phase-5 time. */ private async closeCacheStorage(): Promise { - let cache: CacheManager; + let cache: CacheManager | undefined; try { cache = CacheManager.getInstanceSync(); } catch { - // Cache was never initialized — nothing to close. + // Never initialized — nothing to close. return; } try { @@ -208,11 +222,19 @@ export class LifecycleManager { } } - /** Flush and shut down the telemetry SDK, bounded and error-isolated. */ + /** Bounded and error-isolated. Reads the telemetry manager at phase-5 time. */ private async flushTelemetry(): Promise { + let telemetry: TelemetryManager | undefined; + try { + telemetry = TelemetryManager.getInstance(); + } catch { + // Unavailable or mocked away — nothing to flush. + return; + } + 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/tests/lifecycle-manager.test.ts b/packages/appkit/src/core/tests/lifecycle-manager.test.ts index 121e7eb5c..461881910 100644 --- a/packages/appkit/src/core/tests/lifecycle-manager.test.ts +++ b/packages/appkit/src/core/tests/lifecycle-manager.test.ts @@ -380,5 +380,206 @@ describe("LifecycleManager", () => { expect(signals).toContain("SIGINT"); onceSpy.mockRestore(); }); + + test("a manager that never installs them adds no listener", () => { + // The harness boots this way (installSignalHandlers: false), so repeated + // boots in one process must not accumulate handlers — there is no removal + // path any more. + const termBaseline = process.listenerCount("SIGTERM"); + const intBaseline = process.listenerCount("SIGINT"); + + new LifecycleManager(contextWithPlugins({})); + + expect(process.listenerCount("SIGTERM")).toBe(termBaseline); + expect(process.listenerCount("SIGINT")).toBe(intBaseline); + }); + }); + + describe("shutdown({ exit: false }) (the harness 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.shutdown({ exit: false }); + + expect(stop).toHaveBeenCalledTimes(1); + expect(abortActiveOperations).toHaveBeenCalledTimes(1); + expect(shutdown).toHaveBeenCalledTimes(1); + expect(emit).toHaveBeenCalledWith("shutdown"); + expect(cacheClose).toHaveBeenCalledTimes(1); + expect(telemetryShutdown).toHaveBeenCalledTimes(1); + + // shutdown({ exit: false }) never exits — that is the whole point of the + // harness path. (Dropping the core singletons is the harness's job, not + // the manager's.) + expect(exitSpy).not.toHaveBeenCalled(); + }); + + 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 + .shutdown({ exit: false }) + .then(() => observed.push(`first:${teardownFinished}`)); + const second = manager + .shutdown({ exit: false }) + .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 a harness shutdown 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.shutdown({ exit: false }); + // The signal path after a harness shutdown: teardown is memoized, so the + // phases do not run twice even though the exiting shutdown() is callable. + await manager.shutdown(); + + expect(shutdown).toHaveBeenCalledTimes(1); + }); + + test("a harness shutdown after a signal-initiated teardown awaits the in-flight one", async () => { + let releaseShutdown: (() => void) | undefined; + // Sentinel rather than a tick count: the harness shutdown joins the + // memoized teardown, 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 harnessSawFinishedTeardown: boolean | undefined; + const harnessPath = manager.shutdown({ exit: false }).then(() => { + harnessSawFinishedTeardown = teardownFinished; + }); + + // A full macrotask turn, so a harness shutdown that resolved early would. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(harnessSawFinishedTeardown).toBeUndefined(); + + releaseShutdown?.(); + await Promise.all([signalPath, harnessPath]); + + expect(shutdown).toHaveBeenCalledTimes(1); + // It joined the in-flight teardown rather than resolving alongside it. + expect(harnessSawFinishedTeardown).toBe(true); + // The signal wanted the process dead, and still gets it. + expect(exitSpy).toHaveBeenCalledWith(0); + }); + + test("a rejecting plugin shutdown() is isolated and the harness shutdown 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.shutdown({ exit: false })).resolves.toBeUndefined(); + expect(mockLoggerError).toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + }); + + test("the harness path is bounded by the internal per-plugin timeout, not an outer one", async () => { + vi.useFakeTimers(); + // Never resolves on its own: the only bound is now the internal + // PLUGIN_SHUTDOWN_TIMEOUT_MS (10s) — the same one the signal path uses — + // since the harness path has no outer budget of its own any more. + const hanging = vi.fn(() => new Promise(() => {})); + const ctx = contextWithPlugins({ + stuck: { name: "stuck", shutdown: hanging } as never, + }); + const manager = new LifecycleManager(ctx); + + const done = manager.shutdown({ exit: false }); + await vi.advanceTimersByTimeAsync(10_000); + await expect(done).resolves.toBeUndefined(); + + expect(hanging).toHaveBeenCalledTimes(1); + expect( + mockLoggerError.mock.calls.some( + (c) => + String(c[0]).includes("Error shutting down plugin") && + c[1] === "stuck" && + String(c[2]).includes("timed out"), + ), + ).toBe(true); + // The harness path never exits, even when a phase times out internally. + expect(exitSpy).not.toHaveBeenCalled(); + }); }); }); 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 92c44a90a..0fe6fa67c 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 @@ -9,7 +9,7 @@ import { CacheManager } from "../../../cache"; import { resolveSkillCatalog } from "../../../core/agent/skills/resolve-catalog"; import type { SkillDefinition } from "../../../core/agent/skills/types"; import type { ResolvedToolEntry } from "../../../core/agent/types"; -import { createTestPluginContext } from "../../../testing"; +import { createMockRequest, createTestPluginContext } from "../../../testing"; import { AgentsPlugin } from "../agents"; import { dispatchToolCall, @@ -49,25 +49,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 0eed1f884..db60da0cd 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({}); (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("POST /invocations — tool failures surfaced", () => { 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..c69a82e83 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, + getMock, 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 = getMock( + app.client, + "statementExecution.executeStatement", + ); + getStatement = getMock(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..8933d9eed 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, getMock } = + await import("../../../testing/mock-workspace-client"); + + const mockClient = createMockWorkspaceClient(); + + // Facade accessors are typed against the legacy SDK, so `.mockResolvedValue` + // on them would not typecheck. `getMock` is the typed handle; it mints + // idempotently, so these are the very functions the plugin will call. + const jobsApi = { + runNow: getMock(mockClient, "jobs.runNow"), + submit: getMock(mockClient, "jobs.submit"), + getRun: getMock(mockClient, "jobs.getRun"), + getRunOutput: getMock(mockClient, "jobs.getRunOutput"), + cancelRun: getMock(mockClient, "jobs.cancelRun"), + listRuns: getMock(mockClient, "jobs.listRuns"), + get: getMock(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 3d3815610..a2b3c9d5f 100644 --- a/packages/appkit/src/telemetry/telemetry-manager.ts +++ b/packages/appkit/src/telemetry/telemetry-manager.ts @@ -281,6 +281,12 @@ export class TelemetryManager { * 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 reassigned + * for whatever providers are currently live, so a stale resolved promise can + * only be returned when there is nothing to flush. The covering test asserts + * every provider set across repeated initialize/shutdown cycles is flushed. */ async shutdown(): Promise { const providers = [ @@ -308,4 +314,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.shutdown()` 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..97b10e33f --- /dev/null +++ b/packages/appkit/src/telemetry/tests/telemetry-manager-reset.test.ts @@ -0,0 +1,184 @@ +import { context, metrics, trace } from "@opentelemetry/api"; +import { logs } from "@opentelemetry/api-logs"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +/** + * Telemetry now builds three providers — the meter and logger in `initialize()`, + * the tracer in `start()` — instead of a single `NodeSDK`. These mock the three + * provider constructors so the shutdown/flush path is observable, and set an OTLP + * endpoint so `initialize()` actually builds the meter/logger providers. + * + * The never-cleared `shutdownPromise` was suspected of skipping a re-booted + * provider set's flush. It does not — the memo is reassigned whenever providers + * are live. Re-boot goes through `reset()` (what `dropCoreSingletons()` does + * between harness boots), because `initialize()`/`start()` are idempotent within + * one manager: they guard on `resource`/`started`, which `shutdown()` deliberately + * does not clear. A bare re-`initialize()` after `shutdown()` is therefore a no-op. + */ + +const { + meterProviderShutdown, + loggerProviderShutdown, + tracerProviderShutdown, + MeterProviderMock, + LoggerProviderMock, + NodeTracerProviderMock, +} = vi.hoisted(() => { + const meterProviderShutdown = vi.fn().mockResolvedValue(undefined); + const loggerProviderShutdown = vi.fn().mockResolvedValue(undefined); + const tracerProviderShutdown = vi.fn().mockResolvedValue(undefined); + return { + meterProviderShutdown, + loggerProviderShutdown, + tracerProviderShutdown, + MeterProviderMock: vi.fn(() => ({ shutdown: meterProviderShutdown })), + LoggerProviderMock: vi.fn(() => ({ shutdown: loggerProviderShutdown })), + NodeTracerProviderMock: vi.fn(() => ({ + register: vi.fn(), + shutdown: tracerProviderShutdown, + })), + }; +}); + +vi.mock("@opentelemetry/sdk-metrics", () => ({ + MeterProvider: MeterProviderMock, + PeriodicExportingMetricReader: vi.fn(() => ({})), +})); +vi.mock("@opentelemetry/sdk-logs", () => ({ + LoggerProvider: LoggerProviderMock, + BatchLogRecordProcessor: vi.fn(() => ({})), +})); +vi.mock("@opentelemetry/sdk-trace-node", () => ({ + NodeTracerProvider: NodeTracerProviderMock, +})); +// Keep the real module (AppKitSampler needs SamplingDecision); only stub the +// span processor so no real exporter/timer is wired up. +vi.mock("@opentelemetry/sdk-trace-base", async () => { + const actual = await vi.importActual< + typeof import("@opentelemetry/sdk-trace-base") + >("@opentelemetry/sdk-trace-base"); + return { ...actual, BatchSpanProcessor: vi.fn(() => ({})) }; +}); +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.resourceFromAttributes({})), + }; +}); + +import { TelemetryManager } from "../telemetry-manager"; + +/** Reset the singleton and clear any globals a prior boot registered. */ +function resetTelemetry(): void { + TelemetryManager.reset(); + metrics.disable(); + logs.disable(); + trace.disable(); + context.disable(); +} + +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(); + resetTelemetry(); + }); + + afterEach(() => { + if (originalEndpoint === undefined) { + delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + } else { + process.env.OTEL_EXPORTER_OTLP_ENDPOINT = originalEndpoint; + } + resetTelemetry(); + }); + + test("a reset() between boots rebuilds and re-flushes every provider", async () => { + // Boot 1: initialize() builds the meter + logger providers, start() the tracer. + TelemetryManager.initialize({}); + TelemetryManager.start(); + expect(MeterProviderMock).toHaveBeenCalledTimes(1); + expect(LoggerProviderMock).toHaveBeenCalledTimes(1); + expect(NodeTracerProviderMock).toHaveBeenCalledTimes(1); + + await TelemetryManager.getInstance().shutdown(); + expect(meterProviderShutdown).toHaveBeenCalledTimes(1); + expect(loggerProviderShutdown).toHaveBeenCalledTimes(1); + expect(tracerProviderShutdown).toHaveBeenCalledTimes(1); + + // Re-boot the way the harness does — reset() (dropCoreSingletons) then boot. + // A bare re-initialize() would be a no-op here (see the file header). + resetTelemetry(); + + TelemetryManager.initialize({}); + TelemetryManager.start(); + expect(MeterProviderMock).toHaveBeenCalledTimes(2); + expect(NodeTracerProviderMock).toHaveBeenCalledTimes(2); + + await TelemetryManager.getInstance().shutdown(); + expect(meterProviderShutdown).toHaveBeenCalledTimes(2); + expect(loggerProviderShutdown).toHaveBeenCalledTimes(2); + expect(tracerProviderShutdown).toHaveBeenCalledTimes(2); + + // A third cycle, to pin the general property rather than one transition. + resetTelemetry(); + TelemetryManager.initialize({}); + TelemetryManager.start(); + await TelemetryManager.getInstance().shutdown(); + expect(MeterProviderMock).toHaveBeenCalledTimes(3); + expect(meterProviderShutdown).toHaveBeenCalledTimes(3); + expect(tracerProviderShutdown).toHaveBeenCalledTimes(3); + }); + + test("concurrent shutdown() calls share one flush", async () => { + TelemetryManager.initialize({}); + TelemetryManager.start(); + const manager = TelemetryManager.getInstance(); + + await Promise.all([manager.shutdown(), manager.shutdown()]); + + // Clearing the provider refs synchronously is what makes this safe: the + // second caller finds no providers and awaits the first caller's memo. + expect(meterProviderShutdown).toHaveBeenCalledTimes(1); + expect(loggerProviderShutdown).toHaveBeenCalledTimes(1); + expect(tracerProviderShutdown).toHaveBeenCalledTimes(1); + }); + + test("shutdown() with no providers built resolves without flushing", async () => { + delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + TelemetryManager.initialize({}); + TelemetryManager.start(); + const manager = TelemetryManager.getInstance(); + + await expect(manager.shutdown()).resolves.toBeUndefined(); + expect(meterProviderShutdown).not.toHaveBeenCalled(); + expect(loggerProviderShutdown).not.toHaveBeenCalled(); + expect(tracerProviderShutdown).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..159646980 --- /dev/null +++ b/packages/appkit/src/testing/create-test-app.ts @@ -0,0 +1,436 @@ +/** + * 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 { AppKit, disposeApp } from "../core/appkit"; +import type { WorkspaceClient } from "../workspace-client"; +import type { OboOption } from "./fixtures"; +import { fakeUserContext, oboHeaders, setupDatabricksEnv } from "./fixtures"; +import type { CreateMockWorkspaceClientOptions } from "./mock-workspace-client"; +import { createMockWorkspaceClient } from "./mock-workspace-client"; +import { dropCoreSingletons } from "./reset-singletons"; + +// Loose shapes are intentional here; `noExplicitAny` is off repo-wide (see +// .oxlintrc.json), so a local alias keeps the intent readable. +type Any = any; + +/** + * The env snapshot to restore on close, and whether an app currently holds it. + * + * One live app at a time (see the guard in `createTestApp`), so a flag suffices. + */ +let envBaseline: NodeJS.ProcessEnv | undefined; +let harnessAppLive = false; + +/** Take the baseline on boot. */ +function acquireEnvBaseline(): void { + envBaseline = { ...process.env }; + harnessAppLive = true; +} + +/** Restore the baseline on close. */ +function releaseEnvBaseline(): void { + harnessAppLive = false; + if (!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. Refused when `client` is set. */ + responses?: CreateMockWorkspaceClientOptions["responses"]; + + /** + * Make the built-in mock throw when a path with no declared response is + * called, rather than resolving `undefined`. Refused when `client` is set — + * configure it on your own client instead. + */ + strict?: CreateMockWorkspaceClientOptions["strict"]; + + /** + * 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. + * + * Beyond refusing `development`, this decides error-response redaction: + * `errorHandlerMiddleware` returns the real message unless `NODE_ENV` is + * `production`, where a 5xx becomes `"Server error"`. Pass `"production"` to + * assert what a deployed app actually returns to a client. + */ + nodeEnv?: string; + + /** Defaults to in-memory, which is what keeps boot offline. */ + cache?: CacheConfig; +} + +/** 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) => + fakeUserContext(client, ServiceContext.get())( + token, + userId, + userName, + userEmail, + ), + ); + return () => spy.mockRestore(); +} + +/** + * Wait for a server to finish binding and return the port it landed on. + * + * Needed with `port: 0`: `start()` returns once `listen()` is invoked, before + * the bind completes, so `address()` is null until the `listening` event fires. + * `createTestApp` does this for you — reach for it when hand-rolling a server. + */ +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, + strict, + client: suppliedClient, + env = {}, + server: serverOption, + nodeEnv = "test", + cache, + } = 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.", + ); + } + + // Refused rather than half-supported: AppKit's workspace client, cache and + // on-behalf-of fake are process-wide, so a second live app cannot own its + // own. Checked before any mutation, so a refused boot leaves the live app + // untouched. + if (harnessAppLive) { + throw new Error( + "createTestApp: a harness app is already open. AppKit's workspace " + + "client, cache, and on-behalf-of fake are process-wide, so a second " + + "app would not receive its own `client`/`responses`, and closing " + + "either would un-fake the other's on-behalf-of path. Close the first " + + "app before booting another — `await using`, or try/finally.", + ); + } + + // Wholesale rather than a whitelist: plugins read vars we cannot enumerate. + acquireEnvBaseline(); + + let app: Awaited> | undefined; + let restoreUserContext: (() => void) | undefined; + + // Runs the booted plugins' shutdown() hooks and closes the server it started; + // the harness owns dropping the singletons and restoring env. The `as Any` is + // the one escape hatch the symbol-keyed teardown forces on the harness. + const disposeBooted = (a: unknown): Promise => (a as Any)[disposeApp](); + + 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, + }); + + dropCoreSingletons(); + + // `responses` only seeds the built-in mock, so alongside a caller-supplied + // client it would silently do nothing. Refuse instead, matching the + // `server: false` conflict below. + if (suppliedClient && (responses !== undefined || strict !== undefined)) { + throw new Error( + "createTestApp: `responses` and `strict` configure the built-in mock " + + "client, so they do nothing when you also pass `client`. Drop them " + + "and configure your own client instead.", + ); + } + + // 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, strict }); + + // 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 required to stay offline: without explicit storage the + // cache builds its own client and probes Lakebase, and without the opt-out + // TelemetryReporter fires an apiClient.request on boot. + app = await AppKit._createApp({ + plugins: bootPlugins as Any, + client, + cache: cache ?? { + storage: new InMemoryStorage({ enabled: true } as Any), + }, + disableInternalTelemetry: true, + // The harness boots repeatedly in one process and runs its own teardown, + // so it must not accumulate SIGTERM/SIGINT handlers across boots. + installSignalHandlers: false, + }); + + 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 disposeBooted(bootedApp); + } finally { + dropCoreSingletons(); + 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) { + try { + await disposeBooted(app); + } catch { + // The boot error is the interesting one; don't let teardown mask it. + } + } + // dispose() no longer drops the singletons, and a failure before boot may + // have left a partial init — drop unconditionally either way. + dropCoreSingletons(); + 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..13f79b5d7 100644 --- a/packages/appkit/src/testing/fixtures.ts +++ b/packages/appkit/src/testing/fixtures.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; + import type { Span, SpanOptions } from "@opentelemetry/api"; import type { IAppRouter } from "shared"; import { afterEach, beforeEach, vi } from "vitest"; @@ -5,10 +7,12 @@ import { afterEach, beforeEach, vi } from "vitest"; import { CacheManager } from "../cache"; import type { ServiceContextState } from "../context/service-context"; import { ServiceContext } from "../context/service-context"; +import { AuthenticationError } from "../errors"; 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 +125,60 @@ export type OboOption = email?: string; }; -/** Build the forwarded identity headers an `obo` option implies. */ -function oboHeaders(obo: Exclude): Record { +/** + * The one fake of `ServiceContext.createUserContext` this kit uses, shared by + * `mockServiceContext` and `createTestApp`. + * + * Shared rather than duplicated because the two used to disagree, and neither + * matched production: a missing token went unrejected and `tokenFingerprint` + * was absent, which silently disables Lakebase pool rotation — `pool-manager` + * treats a missing fingerprint as "not stale", so the drain-and-recreate branch + * could never run under a fake. + * + * @internal + */ +export function fakeUserContext( + client: Any, + ids: { warehouseId?: Any; workspaceId: Any }, +) { + return ( + token: string, + userId: string, + userName?: string, + userEmail?: string, + ): Any => { + // Same rejection as production, so a path that forgets to forward the token + // fails here instead of only in a deployed app. + if (!token) throw AuthenticationError.missingToken("user token"); + return { + client, + userId, + userName, + userEmail, + // Derived from the token exactly as production does. Keyed on the user it + // would be constant across tokens, and rotation compares this value. + tokenFingerprint: createHash("sha256") + .update(token) + .digest("hex") + .slice(0, 16), + warehouseId: ids.warehouseId, + workspaceId: ids.workspaceId, + isUserContext: true, + }; + }; +} + +/** + * 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 +388,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 @@ -396,17 +430,12 @@ export function mockServiceContext(options: TestContextOptions = {}) { const createUserContextSpy = vi .spyOn(ServiceContext, "createUserContext") - .mockImplementation((_token: string, userId: string, userName?: string) => { - return { - client: (options.userDatabricksClient || - createMockWorkspaceClient()) as Any, - userId, - userName, - warehouseId: serviceContext.warehouseId, - workspaceId: serviceContext.workspaceId, - isUserContext: true, - }; - }); + .mockImplementation( + fakeUserContext( + options.userDatabricksClient || createMockWorkspaceClient(), + serviceContext, + ), + ); return { serviceContext, @@ -534,39 +563,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..797ce6935 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,13 @@ export { type TestContextOptions, useServiceContextMock, } from "./fixtures"; +export { + createMockWorkspaceClient, + type CreateMockWorkspaceClientOptions, + getMock, + type MockWorkspaceClient, +} from "./mock-workspace-client"; +export { createTestPlugin } from "./create-test-plugin"; 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..7b9298379 --- /dev/null +++ b/packages/appkit/src/testing/mock-workspace-client.ts @@ -0,0 +1,319 @@ +/** + * 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"; + +// Loose shapes are intentional here; `noExplicitAny` is off repo-wide (see +// .oxlintrc.json), so a local alias keeps the intent readable. +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; + /** + * Throw when a path with no declared response is *called*, instead of + * resolving `undefined`. + * + * Off by default: the never-crash floor is what lets a plugin touch services + * a test does not care about. Turn it on when a silently `undefined` return + * would let the test pass for the wrong reason. + */ + strict?: boolean; + + /** 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`. + * + * `statementExecution.executeStatement`, `warehouses.get` and `warehouses.start` + * must stay byte-identical to the old `fixtures.ts` values — suites reach them + * implicitly through `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", + }, +}; + +/** Generically proxied; `config`/`apiClient` are seeded below instead. */ +const FACADE_SERVICES = [ + "files", + "warehouses", + "genie", + "jobs", + "statementExecution", + "servingEndpoints", + "currentUser", +] as const; + +/** + * Answered with `undefined` rather than a minted mock. `then` must stay listed: + * 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", +]); + +/** `apiClient` members read synchronously; a seeded value must not be resolved. */ +const SYNC_API_CLIENT_MEMBERS: ReadonlySet = new Set(["userAgent"]); + +/** Distinguishes "no passthrough rule applied" from a rule answering `undefined`. */ +const NOT_PASSTHROUGH = Symbol("not-passthrough"); + +/** + * The passthrough rules every trap in this file shares: symbols delegate to the + * target, denied names answer `undefined`, and anything already on the target + * (seeded members, `Object.prototype`) wins over minting. + * + * Shared rather than copied so a key added to {@link PASSTHROUGH_DENY} cannot + * cover one trap and miss another. + */ +function passthroughFor(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 NOT_PASSTHROUGH; +} + +/** + * `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 => { + const passthrough = passthroughFor(target, prop); + if (passthrough !== NOT_PASSTHROUGH) return passthrough; + 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, + strict = false, + } = 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 getMock, 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 if (strict && !(path in merged)) { + // Thrown on call, never on mint: `getMock` mints to hand back a handle + // before the code under test runs, and that must not blow up. + fn.mockImplementation(() => { + throw new Error( + `createMockWorkspaceClient: "${path}" was called with no declared ` + + "response and `strict: true` is set. Add it to `responses`, or drop " + + "`strict` to have undeclared paths resolve undefined.", + ); + }); + } 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") { + // Match the member's own shape. `userAgent()` is read straight into a + // Headers value, so resolving a seed would put "[object Promise]" there — + // the failure the synchronous default exists to avoid. Seed a function to + // decide for yourself. + if (SYNC_API_CLIENT_MEMBERS.has(key)) fn.mockReturnValue(value); + else 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 => { + // Same passthrough rules as `neverCrashGet` — shared, not copied, so a + // key added to PASSTHROUGH_DENY cannot cover one trap and miss this + // one (miss `then` here and `await client` hangs again). + const passthrough = passthroughFor(target, prop); + if (passthrough !== NOT_PASSTHROUGH) return passthrough; + 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 getMock(client: MockWorkspaceClient, path: string): Mock { + const fns = clientFns.get(client); + if (!fns) { + throw new Error( + "getMock: 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( + `getMock: "${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-singletons.ts b/packages/appkit/src/testing/reset-singletons.ts new file mode 100644 index 000000000..834e712d4 --- /dev/null +++ b/packages/appkit/src/testing/reset-singletons.ts @@ -0,0 +1,35 @@ +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("testing"); + +/** + * Drop the process-wide singletons `AppKit._createApp` initializes — called by + * the harness on boot to clear a previous test's leakage, and on teardown. + * + * Kit-owned: the only caller is the test harness, so it lives here rather than + * in core. A pointer drop, not teardown — close the app first (the harness runs + * the shutdown phases before this) or the old app's storage and exporters leak. + * A caller that drops then reads `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/testing/tests/create-test-app.test.ts b/packages/appkit/src/testing/tests/create-test-app.test.ts new file mode 100644 index 000000000..994f950c9 --- /dev/null +++ b/packages/appkit/src/testing/tests/create-test-app.test.ts @@ -0,0 +1,849 @@ +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 { ServiceContext } from "../../context/service-context"; +import { AuthenticationError } from "../../errors"; +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 { createMockWorkspaceClient, getMock } 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; + + /** Incremented when harness teardown runs this plugin's shutdown() hook. */ + shutdownCalls = 0; + + async shutdown(): Promise { + this.shutdownCalls += 1; + } + + 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, + shutdownCalls: () => this.shutdownCalls, + 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); + +/** + * Boots cleanly, then throws when the harness asks for the socket — the only way + * to reach the failure path *after* `createApp` has already returned an app. + * Named `server` so the harness uses it instead of adding the real one. + */ +class LateFailurePlugin extends Plugin { + static manifest = manifest("server"); + exports() { + return { + getServer: () => { + throw new Error("getServer exploded"); + }, + }; + } +} +const lateFailure = toPlugin(LateFailurePlugin); + +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("sequential apps in one file each bind their own ephemeral port", async () => { + // No EADDRINUSE and no hardcoded port, which is why fixed test ports are + // worth removing. Not asserting the two ports differ: the kernel may hand + // back the port just released, so that would flake. + for (const _ of [1, 2]) { + const app = await createTestApp({ plugins: [probe()] }); + try { + expect(app.port).toBeGreaterThan(0); + await expect( + app.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + } finally { + await app.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(getMock(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(getMock(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(); + }); + + test("close runs a booted plugin's shutdown() hook and releases the socket", async () => { + // The path this PR rewired (close() -> disposeApp -> dispose()): a *real* + // registered plugin's shutdown() must fire through the boot->teardown wiring, + // and the server socket must actually be released — not just re-port-picked + // on the next boot. The lifecycle unit test covers this against a mocked + // context; this asserts the composed integration path end to end. + const app = await createTestApp({ plugins: [probe()] }); + const port = app.port; + await expect( + app.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + + await app.close(); + + expect(app.plugins.probe.shutdownCalls()).toBe(1); + 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("a failure after createApp still tears the built app down", async () => { + // The other boot-failure test throws inside createApp, so `app` is never + // assigned and only the "nothing was built" branch runs. This one gets a + // live app first, exercising the branch that has to close it. + const before = { ...process.env }; + + await expect( + createTestApp({ plugins: [lateFailure()], env: { LEAKED: "no" } }), + ).rejects.toThrow(/getServer exploded/); + + expect(process.env.LEAKED).toBeUndefined(); + expect(Object.keys(process.env).sort()).toEqual( + Object.keys(before).sort(), + ); + + // The failed app's singletons have to be dropped too, or this boot + // reuses its half-closed ones. + const app = await createTestApp({ plugins: [probe()] }); + try { + await expect( + app.get("/api/probe/ping").then((r) => r.status), + ).resolves.toBe(200); + } finally { + await app.close(); + } + }); + + test("the obo token fingerprint tracks the token, matching production", async () => { + // Lakebase rotates its pool when this value changes (pool-manager compares + // it), so a fingerprint keyed on the user would be constant across tokens + // and rotation could never fire under the harness. + await using app = await createTestApp({ plugins: [probe()] }); + void app; + + // While a harness app is live, createUserContext *is* the stub. + const fingerprint = (token: string) => + ServiceContext.createUserContext(token, "same").tokenFingerprint; + + expect(fingerprint("tok-a")).toBe(fingerprint("tok-a")); + expect(fingerprint("tok-a")).not.toBe(fingerprint("tok-b")); + // A sha256 prefix, not a label derived from the user. + expect(fingerprint("tok-a")).toMatch(/^[0-9a-f]{16}$/); + expect(fingerprint("tok-a")).not.toContain("same"); + }); + + test("an obo request with no token is refused, as in production", async () => { + await using app = await createTestApp({ plugins: [probe()] }); + void app; + // The same error class production throws, not just a similar message — + // a handler that catches AuthenticationError must behave identically here. + expect(() => ServiceContext.createUserContext("", "nobody")).toThrow( + AuthenticationError, + ); + }); + + test("strict makes an undeclared data-plane call fail the request", async () => { + // Without strict the handler gets `undefined` and the route still 200s, + // so a forgotten response passes for the wrong reason. + await using app = await createTestApp({ + plugins: [probe()], + strict: true, + }); + const res = await app.get("/api/probe/from-client"); + expect(res.status).toBe(500); + await expect(res.text()).resolves.toMatch(/no declared response/); + }); + + test("passing both client and responses is refused, not silently ignored", async () => { + // `responses` only seeds the built-in mock, so with a supplied client it + // used to do nothing at all — the caller's seeded values never took effect + // and nothing said so. + await expect( + createTestApp({ + plugins: [probe()], + client: createMockWorkspaceClient(), + responses: { "jobs.getRun": { state: "IGNORED" } }, + }), + ).rejects.toThrow(/do nothing when you also pass `client`/); + }); + + 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("repeated boot/close cycles leave no env residue", async () => { + const before = { ...process.env }; + + // Overlapping boots are refused, so each snapshot starts from an already + // restored env and the old "whichever closes last wins" hazard cannot + // arise. What still has to hold is that a cycle leaves nothing behind. + for (const [key, value] of [ + ["CYCLE_A", "a"], + ["CYCLE_B", "b"], + ] as const) { + const app = await createTestApp({ + plugins: [probe()], + env: { [key]: value }, + }); + expect(process.env[key]).toBe(value); + await app.close(); + expect(process.env[key]).toBeUndefined(); + } + + const leaked = Object.keys(process.env).filter((k) => !(k in before)); + expect(leaked).toEqual([]); + expect(Object.keys(process.env).sort()).toEqual( + Object.keys(before).sort(), + ); + }); + + 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(); + }); +}); + +describe("createTestApp — one app at a time", () => { + // Top level on purpose: these boot their own apps, so they cannot live + // inside a describe that holds one open in beforeAll. + 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(getMock(app.client, "jobs.getRun")).toHaveBeenCalledWith({ + run_id: 42, + }); + }, + ); + }); + + test("refuses a second app while one is open", async () => { + const a = await createTestApp({ plugins: [probe()] }); + try { + await expect(createTestApp({ plugins: [probe()] })).rejects.toThrow( + /a harness app is already open/, + ); + } finally { + await a.close(); + } + }); + + test("a refused boot leaves the open app fully working", async () => { + // The guard runs before any mutation, so the refusal must not disturb the + // live app's env baseline, singletons, or on-behalf-of fake. Without that + // ordering the first app would be collateral damage of someone else's bug. + const a = await createTestApp({ + plugins: [probe()], + responses: { "jobs.getRun": { via: "mock" } }, + }); + try { + await expect(createTestApp({ plugins: [probe()] })).rejects.toThrow(); + + await expect( + a.get("/api/probe/from-client").then((r) => r.status), + ).resolves.toBe(200); + + // /as-user-client calls the client *inside* asUser, so it is the one + // route that notices a disturbed on-behalf-of fake. Asserting the + // declared response discriminates: a real client cannot invent it. + const oboRes = await a.get("/api/probe/as-user-client", { + obo: { userId: "u@example.com" }, + }); + expect(oboRes.status).toBe(200); + await expect(oboRes.json()).resolves.toEqual({ run: { via: "mock" } }); + expect(getMock(a.client, "jobs.getRun")).toHaveBeenCalledWith({ + run_id: 42, + }); + } finally { + await a.close(); + } + }); + + test("a refused boot does not strand the env baseline", async () => { + const before = { ...process.env }; + const a = await createTestApp({ plugins: [probe()] }); + await expect(createTestApp({ plugins: [probe()] })).rejects.toThrow(); + await a.close(); + + // The refused boot must leave harnessAppLive and the saved baseline alone, + // or a's close would not restore the env. + expect(process.env.NODE_ENV).toBe(before.NODE_ENV); + expect(process.env.DATABRICKS_WORKSPACE_ID).toBe( + before.DATABRICKS_WORKSPACE_ID, + ); + }); + + test("a new app boots cleanly once the previous one closed", async () => { + const a = await createTestApp({ plugins: [probe()] }); + await expect( + a.get("/api/probe/from-client").then((r) => r.status), + ).resolves.toBe(200); + await a.close(); + + // The singletons A dropped on close must be rebuilt for B, not inherited. + const b = await createTestApp({ plugins: [probe()] }); + try { + 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 stale call is a no-op — not a drop that + // would reset second's singletons. + 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/fixtures.test.ts b/packages/appkit/src/testing/tests/fixtures.test.ts index 39fc2fef1..599fb8151 100644 --- a/packages/appkit/src/testing/tests/fixtures.test.ts +++ b/packages/appkit/src/testing/tests/fixtures.test.ts @@ -3,8 +3,10 @@ import { afterEach, describe, expect, test, vi } from "vitest"; import { CacheManager } from "../../cache"; import { InMemoryStorage } from "../../cache/storage"; import { ServiceContext } from "../../context"; +import { AuthenticationError } from "../../errors"; import { createMockRequest, + mockServiceContext, resetTestCache, useServiceContextMock, } from "../fixtures"; @@ -102,6 +104,50 @@ describe("resetTestCache", () => { }); }); +describe("mockServiceContext — user context matches production", () => { + test("the fingerprint is derived from the token, not the user", () => { + // Lakebase rotates its pool by comparing this. A user-keyed value would be + // constant across tokens, so `pool-manager` would never see a change and the + // drain-and-recreate branch could never run under this fake. + const mock = mockServiceContext(); + try { + const fp = (token: string) => + ServiceContext.createUserContext(token, "same").tokenFingerprint; + expect(fp("tok-a")).toBe(fp("tok-a")); + expect(fp("tok-a")).not.toBe(fp("tok-b")); + expect(fp("tok-a")).toMatch(/^[0-9a-f]{16}$/); + } finally { + mock.restore(); + } + }); + + test("a missing token is refused, with production's error class", () => { + const mock = mockServiceContext(); + try { + expect(() => ServiceContext.createUserContext("", "nobody")).toThrow( + AuthenticationError, + ); + } finally { + mock.restore(); + } + }); + + test("userEmail is carried through", () => { + const mock = mockServiceContext(); + try { + const ctx = ServiceContext.createUserContext( + "tok", + "u-1", + "Alice", + "alice@example.com", + ); + expect(ctx.userEmail).toBe("alice@example.com"); + } finally { + mock.restore(); + } + }); +}); + describe("useServiceContextMock", () => { const ctx = useServiceContextMock({ warehouseId: "wh-1" }); 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..a2cbeda1a --- /dev/null +++ b/packages/appkit/src/testing/tests/mock-workspace-client.test.ts @@ -0,0 +1,307 @@ +import { inspect } from "node:util"; + +import { describe, expect, test, vi } from "vitest"; + +import { ServiceContext } from "../../context/service-context"; +import { mockServiceContext } from "../fixtures"; +import { createMockWorkspaceClient, getMock } 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("a seeded userAgent stays synchronous, not a Promise", async () => { + // Resolving it would put "[object Promise]" into a Headers value. + const client = mk({ responses: { "apiClient.userAgent": "custom/9" } }); + expect(client.apiClient.userAgent()).toBe("custom/9"); + const headers = new Headers(); + headers.set("user-agent", client.apiClient.userAgent()); + expect(headers.get("user-agent")).toBe("custom/9"); + // `request` is genuinely async, so its seeds still resolve. + await expect( + mk({ responses: { "apiClient.request": { ok: 1 } } }).apiClient.request( + {} as never, + ), + ).resolves.toEqual({ ok: 1 }); + }); + + 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("strict", () => { + test("an undeclared call throws, naming the path", async () => { + const client = mk({ strict: true, responses: { "jobs.getRun": {} } }); + await expect(client.jobs.getRun({} as never)).resolves.toEqual({}); + expect(() => client.jobs.cancelRun({} as never)).toThrow( + /"jobs.cancelRun" was called with no declared response/, + ); + }); + + test("it throws on call, not on mint, so getMock still hands back a handle", () => { + // Grabbing the handle before the code under test runs is the normal + // pattern; minting must not be what explodes. + const client = mk({ strict: true }); + const fn = getMock(client, "jobs.cancelRun"); + expect(fn).toHaveBeenCalledTimes(0); + expect(() => fn({} as never)).toThrow(/no declared response/); + }); + + test("the canned defaults still count as declared", async () => { + // Otherwise `strict` would break every harness boot, which reads + // currentUser.me through this client. + const client = mk({ strict: true }); + await expect(client.currentUser.me({} as never)).resolves.toMatchObject({ + id: "test-service-user", + }); + }); + + test("with defaults: false even the canned paths are undeclared", async () => { + const client = mk({ strict: true, defaults: false }); + expect(() => client.currentUser.me({} as never)).toThrow( + /no declared response/, + ); + }); + + test("off by default — an undeclared call still resolves undefined", async () => { + await expect(mk().jobs.cancelRun({} as never)).resolves.toBeUndefined(); + }); + }); + + describe("getMock", () => { + test("mints before first use and stays stable after", async () => { + const client = mk(); + const getRun = getMock(client, "jobs.getRun"); + expect(getRun).toHaveBeenCalledTimes(0); + + await client.jobs.getRun({ run_id: 7 } as never); + expect(getRun).toBe(getMock(client, "jobs.getRun")); + expect(getRun).toHaveBeenCalledWith({ run_id: 7 }); + }); + + test("resolves seeded members and rejects non-function paths", () => { + const client = mk(); + expect(getMock(client, "apiClient.request")).toBe( + client.apiClient.request, + ); + expect(() => getMock(client, "config.host")).toThrow( + /not a mocked function/, + ); + expect(() => getMock({} 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 = getMock(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..536099425 --- /dev/null +++ b/packages/appkit/src/testing/tests/published-surface.integration.test.ts @@ -0,0 +1,153 @@ +import * as testing from "@databricks/appkit/testing"; +import { + createMockRequest, + createTestApp, + createTestPluginContext, + expectStream, + getMock, +} 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("every documented export is reachable from the entry", () => { + // Importing a few symbols proves the entry resolves, not that the surface is + // intact — everything else could be dropped from the barrel and this file + // would still pass. `tsc` would catch it via other suites, but this test + // claims to guard the surface, so it should. + const expected = [ + "createTestApp", + "createTestPlugin", + "createTestPluginContext", + "createMockWorkspaceClient", + "getMock", + "getListeningPort", + "expectStream", + "mockServiceContext", + "createMockRequest", + "createMockResponse", + "createMockRouter", + "createMockTelemetry", + "createSuccessfulSQLResponse", + "createFailedSQLResponse", + "parseSSEResponse", + "resetTestCache", + "runWithRequestContext", + "setupDatabricksEnv", + "useServiceContextMock", + ]; + const missing = expected.filter( + (name) => + typeof (testing as Record)[name] !== "function", + ); + expect(missing).toEqual([]); + }); + + test("createTestPluginContext runs its real dispatch through the entry", async () => { + // The name check above only proves the barrel exports *something*. This + // drives the context's real tool registry and on-behalf-of path, so a + // hollowed-out export fails here instead of shipping. + const mock = createTestPluginContext({ + widget: { lookup: (args) => ({ echoed: args }) }, + }); + + const req = createMockRequest({ obo: { userId: "analyst@example.com" } }); + const result = await mock.ctx.executeTool( + req as never, + "widget", + "lookup", + { + id: 7, + }, + ); + + expect(result).toEqual({ echoed: { id: 7 } }); + expect(mock.toolCalls[0]).toMatchObject({ + plugin: "widget", + tool: "lookup", + asUser: true, + userId: "analyst@example.com", + }); + }); + + 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(getMock(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/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..b09c58524 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,