-
Notifications
You must be signed in to change notification settings - Fork 9
feat: add Model Serving connector and plugin #239
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pkosiec
wants to merge
4
commits into
main
Choose a base branch
from
pkosiec/serving-1-core
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
53f7399
feat: add Model Serving connector and plugin
pkosiec cab05df
fix: pass abort signal to serving connector in stream handler
pkosiec 97d645f
fix: address PR review feedback for serving connector and plugin
pkosiec 2080612
fix: only cancel stream reader on abort to prevent double-close
pkosiec File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| # Interface: EndpointConfig | ||
|
|
||
| ## Properties | ||
|
|
||
| ### env | ||
|
|
||
| ```ts | ||
| env: string; | ||
| ``` | ||
|
|
||
| Environment variable holding the endpoint name. | ||
|
|
||
| *** | ||
|
|
||
| ### servedModel? | ||
|
|
||
| ```ts | ||
| optional servedModel: string; | ||
| ``` | ||
|
|
||
| Target a specific served model (bypasses traffic routing). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| # Interface: ServingEndpointEntry | ||
|
|
||
| Shape of a single registry entry. | ||
|
|
||
| ## Properties | ||
|
|
||
| ### chunk | ||
|
|
||
| ```ts | ||
| chunk: unknown; | ||
| ``` | ||
|
|
||
| *** | ||
|
|
||
| ### request | ||
|
|
||
| ```ts | ||
| request: Record<string, unknown>; | ||
| ``` | ||
|
|
||
| *** | ||
|
|
||
| ### response | ||
|
|
||
| ```ts | ||
| response: unknown; | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| # Interface: ServingEndpointRegistry | ||
|
|
||
| Registry interface for serving endpoint type generation. | ||
| Empty by default — augmented by the Vite type generator's `.d.ts` output via module augmentation. | ||
| When populated, provides autocomplete for alias names and typed request/response/chunk per endpoint. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # Type Alias: ServingFactory | ||
|
|
||
| ```ts | ||
| type ServingFactory = keyof ServingEndpointRegistry extends never ? (alias?: string) => ServingEndpointMethods : <K>(alias: K) => ServingEndpointMethods<ServingEndpointRegistry[K]["request"], ServingEndpointRegistry[K]["response"], ServingEndpointRegistry[K]["chunk"]>; | ||
| ``` | ||
|
|
||
| Factory function returned by `AppKit.serving`. | ||
|
|
||
| This is a conditional type that adapts based on whether `ServingEndpointRegistry` | ||
| has been populated via module augmentation (generated by `appKitServingTypesPlugin()`): | ||
|
|
||
| - **Registry empty (default):** `(alias?: string) => ServingEndpointMethods` — | ||
| accepts any alias string with untyped request/response/chunk. | ||
| - **Registry populated:** `<K>(alias: K) => ServingEndpointMethods<...>` — | ||
| restricts `alias` to known endpoint keys and infers typed request/response/chunk | ||
| from the registry entry. | ||
|
|
||
| Run `appKitServingTypesPlugin()` in your Vite config to generate the registry | ||
| augmentation and enable full type safety. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| import type { serving } from "@databricks/sdk-experimental"; | ||
| import { ApiError, type WorkspaceClient } from "@databricks/sdk-experimental"; | ||
| import { createLogger } from "../../logging/logger"; | ||
| import type { ServingStreamOptions } from "./types"; | ||
|
|
||
| const logger = createLogger("connectors:serving"); | ||
|
|
||
| /** | ||
| * Maps upstream Databricks error status codes to appropriate proxy responses. | ||
| * Used for raw API responses where the SDK doesn't handle errors automatically. | ||
| */ | ||
| function mapUpstreamError(status: number, body: string): ApiError { | ||
| const safeMessage = body.length > 500 ? `${body.slice(0, 500)}...` : body; | ||
|
|
||
| let parsed: { message?: string; error?: string } = {}; | ||
| try { | ||
| parsed = JSON.parse(body); | ||
| } catch { | ||
| // body is not JSON | ||
| } | ||
|
|
||
| const message = parsed.message || parsed.error || safeMessage; | ||
|
|
||
| switch (true) { | ||
| case status === 400: | ||
| return new ApiError(message, "BAD_REQUEST", 400, undefined, []); | ||
| case status === 401 || status === 403: | ||
| logger.warn("Authentication failure from serving endpoint: %s", message); | ||
| return new ApiError(message, "AUTH_FAILURE", status, undefined, []); | ||
| case status === 404: | ||
| return new ApiError(message, "NOT_FOUND", 404, undefined, []); | ||
| case status === 429: | ||
| return new ApiError(message, "RATE_LIMITED", 429, undefined, []); | ||
| case status === 503: | ||
| return new ApiError( | ||
| "Endpoint loading, retry shortly", | ||
| "SERVICE_UNAVAILABLE", | ||
| 503, | ||
| undefined, | ||
| [], | ||
| ); | ||
| case status >= 500: | ||
| return new ApiError(message, "BAD_GATEWAY", 502, undefined, []); | ||
| default: | ||
| return new ApiError(message, "UNKNOWN", status, undefined, []); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Invokes a serving endpoint using the SDK's high-level query API. | ||
| * Returns a typed QueryEndpointResponse. | ||
| */ | ||
| export async function invoke( | ||
| client: WorkspaceClient, | ||
| endpointName: string, | ||
| body: Record<string, unknown>, | ||
| ): Promise<serving.QueryEndpointResponse> { | ||
| // Strip `stream` from the body — the connector controls this | ||
| const { stream: _stream, ...cleanBody } = body; | ||
|
|
||
| logger.debug("Invoking endpoint %s", endpointName); | ||
|
|
||
| return client.servingEndpoints.query({ | ||
| name: endpointName, | ||
| ...cleanBody, | ||
| } as serving.QueryEndpointInput); | ||
| } | ||
|
|
||
| /** | ||
| * Invokes a serving endpoint with streaming enabled. | ||
| * Yields parsed JSON chunks from the SSE response. | ||
| * | ||
| * Uses the SDK's low-level `apiClient.request({ raw: true })` because | ||
| * the high-level `servingEndpoints.query()` returns `Promise<QueryEndpointResponse>` | ||
| * and does not support SSE streaming. | ||
| */ | ||
| export async function* stream( | ||
| client: WorkspaceClient, | ||
| endpointName: string, | ||
| body: Record<string, unknown>, | ||
| options?: ServingStreamOptions, | ||
| ): AsyncGenerator<unknown> { | ||
| // Strip any user-provided `stream` and inject `stream: true` | ||
| const { stream: _stream, ...cleanBody } = body; | ||
|
|
||
| logger.debug("Streaming from endpoint %s", endpointName); | ||
|
|
||
| const response = (await client.apiClient.request({ | ||
| path: `/serving-endpoints/${encodeURIComponent(endpointName)}/invocations`, | ||
| method: "POST", | ||
| headers: new Headers({ | ||
| "Content-Type": "application/json", | ||
| Accept: "text/event-stream", | ||
| }), | ||
| payload: { ...cleanBody, stream: true }, | ||
| raw: true, | ||
| })) as { contents: ReadableStream<Uint8Array> }; | ||
|
|
||
| if (!response.contents) { | ||
| throw new Error("Response body is null — streaming not supported"); | ||
| } | ||
|
|
||
| const reader = response.contents.getReader(); | ||
| const decoder = new TextDecoder(); | ||
| let buffer = ""; | ||
| const MAX_BUFFER_SIZE = 1024 * 1024; // 1 MB | ||
|
|
||
| try { | ||
| while (true) { | ||
| if (options?.signal?.aborted) break; | ||
|
|
||
| const { done, value } = await reader.read(); | ||
| if (done) break; | ||
|
|
||
| buffer += decoder.decode(value, { stream: true }); | ||
|
|
||
| if (buffer.length > MAX_BUFFER_SIZE) { | ||
| throw new Error( | ||
| `Stream buffer exceeded ${MAX_BUFFER_SIZE} bytes — possible non-SSE response`, | ||
| ); | ||
| } | ||
|
|
||
| // Process complete lines from the buffer | ||
| const lines = buffer.split("\n"); | ||
| // Keep the last (potentially incomplete) line in the buffer | ||
| buffer = lines.pop() ?? ""; | ||
|
|
||
| for (const line of lines) { | ||
| const trimmed = line.trim(); | ||
| // Per SSE spec: empty lines are event delimiters, | ||
| // lines starting with ":" are comments (often used as heartbeats). | ||
| if (!trimmed || trimmed.startsWith(":")) continue; | ||
| if (trimmed === "data: [DONE]") return; | ||
|
|
||
| if (trimmed.startsWith("data: ")) { | ||
| const jsonStr = trimmed.slice(6); | ||
| try { | ||
| yield JSON.parse(jsonStr); | ||
| } catch { | ||
| logger.warn("Failed to parse streaming chunk: %s", jsonStr); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Process any remaining data in the buffer | ||
| if (buffer.trim() && !options?.signal?.aborted) { | ||
| const trimmed = buffer.trim(); | ||
| if (trimmed.startsWith("data: ") && trimmed !== "data: [DONE]") { | ||
| try { | ||
| yield JSON.parse(trimmed.slice(6)); | ||
| } catch { | ||
| logger.warn("Failed to parse final streaming chunk: %s", trimmed); | ||
| } | ||
| } | ||
| } | ||
| } finally { | ||
| if (options?.signal?.aborted) { | ||
| reader.cancel().catch(() => {}); | ||
| } | ||
| reader.releaseLock(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.