@dbx-tools/dbx-model-catalog 0.1.9 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +296 -55
- package/dist/_generated/channels.d.ts +4 -3
- package/dist/_generated/json-schema.d.ts +6527 -175
- package/dist/_generated/schemas.d.ts +154 -0
- package/dist/_generated/workspace-rules.d.ts +133 -0
- package/dist/browser.d.ts +34 -15
- package/dist/browser.js +1152 -9042
- package/dist/catalog-index.d.ts +15 -2
- package/dist/chunk-engbh7tj.js +39 -0
- package/dist/chunk-gzjer0mc.js +1797 -0
- package/dist/chunk-pp7fw379.js +51 -0
- package/dist/chunk-pwssxaq0.js +39 -0
- package/dist/cli.js +41 -9619
- package/dist/effective.d.ts +31 -0
- package/dist/index.d.ts +33 -16
- package/dist/index.js +60 -9630
- package/dist/local-client.d.ts +16 -3
- package/dist/pynect.d.ts +6 -3
- package/dist/search.d.ts +7 -1
- package/dist/serving-endpoints.d.ts +15 -0
- package/dist/sources.d.ts +30 -0
- package/dist/types.d.ts +31 -3
- package/dist/validation.d.ts +15 -1
- package/dist/workspace-cache.d.ts +68 -0
- package/dist/workspace-client.d.ts +49 -0
- package/dist/workspace-connection.d.ts +67 -0
- package/dist/workspace-file-cache.d.ts +11 -0
- package/dist/workspace-identity.d.ts +27 -0
- package/dist/workspace-overlay.d.ts +71 -0
- package/package.json +8 -12
- package/src/_generated/channels.ts +41 -0
- package/src/_generated/index.ts +6 -0
- package/src/_generated/json-schema.ts +5 -0
- package/src/_generated/published.ts +7 -0
- package/src/_generated/schemas.ts +585 -0
- package/src/_generated/workspace-rules.ts +285 -0
- package/src/browser.ts +115 -0
- package/src/catalog-index.ts +121 -0
- package/src/cli.ts +99 -0
- package/src/effective.ts +200 -0
- package/src/filter.ts +47 -0
- package/src/identity.ts +56 -0
- package/src/index.ts +187 -0
- package/src/local-client.ts +127 -0
- package/src/pynect.ts +31 -0
- package/src/search.ts +582 -0
- package/src/serving-endpoints.ts +157 -0
- package/src/sources.ts +107 -0
- package/src/types.ts +49 -0
- package/src/validation.ts +127 -0
- package/src/workspace-cache.ts +234 -0
- package/src/workspace-client.ts +134 -0
- package/src/workspace-connection.ts +160 -0
- package/src/workspace-file-cache.ts +45 -0
- package/src/workspace-identity.ts +77 -0
- package/src/workspace-overlay.ts +200 -0
- package/dist/browser.js.map +0 -38
- package/dist/catalog.json +0 -1
- package/dist/cli.js.map +0 -40
- package/dist/index.js.map +0 -39
- package/dist/pynect.js +0 -553
- package/dist/pynect.js.map +0 -15
- package/dist/search-index.json +0 -1
- package/dist/snapshot.d.ts +0 -7
- package/dist/snapshot.js +0 -9515
- package/dist/snapshot.js.map +0 -36
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type BrowserModelServingClientOption,
|
|
3
|
+
type ModelServingConnector,
|
|
4
|
+
type ModelServingConnectorOptions,
|
|
5
|
+
type RawServingEndpointsListing,
|
|
6
|
+
collectPages,
|
|
7
|
+
connectBrowserModelServing,
|
|
8
|
+
requesterSnapshot,
|
|
9
|
+
} from "./workspace-connection.js";
|
|
10
|
+
import { resolveWorkspaceIdentity } from "./workspace-identity.js";
|
|
11
|
+
|
|
12
|
+
/** Request accepted by the Databricks SDK `ApiClient.request` for a raw-JSON GET. */
|
|
13
|
+
export interface WorkspaceClientRequest {
|
|
14
|
+
path: string;
|
|
15
|
+
method: "GET";
|
|
16
|
+
headers: Headers;
|
|
17
|
+
raw: false;
|
|
18
|
+
query?: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The `@databricks/sdk-experimental` `WorkspaceClient` surface the catalog uses. The SDK client
|
|
23
|
+
* stays the only authentication owner; the catalog never constructs one or resolves profiles.
|
|
24
|
+
*/
|
|
25
|
+
export interface WorkspaceClientLike {
|
|
26
|
+
readonly config: {
|
|
27
|
+
getHost(): Promise<URL>;
|
|
28
|
+
authenticate(headers: Headers): Promise<void>;
|
|
29
|
+
};
|
|
30
|
+
readonly apiClient: {
|
|
31
|
+
request(options: WorkspaceClientRequest): Promise<unknown>;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The `@databricks/sdk-modelserving/v1` `ModelServingClient` surface the catalog uses. Its host,
|
|
37
|
+
* configuration, and credentials are private and it has no current-user lookup, so overlays from
|
|
38
|
+
* it stay in session memory.
|
|
39
|
+
*/
|
|
40
|
+
export interface ModelServingSdkClientLike {
|
|
41
|
+
listInferenceEndpoints(
|
|
42
|
+
request: { readonly pageToken?: string },
|
|
43
|
+
options?: unknown,
|
|
44
|
+
): Promise<{ readonly endpoints?: readonly object[] | undefined; readonly nextPageToken?: string | undefined }>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The Node `modelServingClient` option: an existing `@databricks/sdk-experimental` `WorkspaceClient`
|
|
49
|
+
* or `@databricks/sdk-modelserving` `ModelServingClient` (reusing its authentication), a
|
|
50
|
+
* `{ host, headers }` connection, or a sync or async function returning one.
|
|
51
|
+
*/
|
|
52
|
+
export type ModelServingClientOption =
|
|
53
|
+
| WorkspaceClientLike
|
|
54
|
+
| ModelServingSdkClientLike
|
|
55
|
+
| BrowserModelServingClientOption;
|
|
56
|
+
|
|
57
|
+
const NODE_MODEL_SERVING_FORMS =
|
|
58
|
+
"a @databricks/sdk-experimental WorkspaceClient, a @databricks/sdk-modelserving ModelServingClient, "
|
|
59
|
+
+ "a { host, headers } connection, or a function returning one";
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Normalize a Node `modelServingClient` option once. A `WorkspaceClient` lends its host,
|
|
63
|
+
* authentication, and transport (including SCIM `Me`); a modular `ModelServingClient` lists
|
|
64
|
+
* through `listInferenceEndpoints` and, exposing no host or principal, stays session-only.
|
|
65
|
+
*/
|
|
66
|
+
export function connectModelServing(
|
|
67
|
+
source: ModelServingClientOption,
|
|
68
|
+
options: ModelServingConnectorOptions = {},
|
|
69
|
+
): ModelServingConnector {
|
|
70
|
+
if (isWorkspaceClient(source)) return workspaceClientConnector(source);
|
|
71
|
+
if (isModelServingSdkClient(source)) {
|
|
72
|
+
return {
|
|
73
|
+
kind: "model_serving_client",
|
|
74
|
+
snapshot: async () => ({
|
|
75
|
+
listServingEndpoints: () => listInferenceEndpoints(source),
|
|
76
|
+
principal: async () => undefined,
|
|
77
|
+
}),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
return connectBrowserModelServing(source as BrowserModelServingClientOption, options, NODE_MODEL_SERVING_FORMS);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function workspaceClientConnector(client: WorkspaceClientLike): ModelServingConnector {
|
|
84
|
+
return {
|
|
85
|
+
kind: "workspace_client",
|
|
86
|
+
snapshot: async () => {
|
|
87
|
+
const headers = new Headers();
|
|
88
|
+
await client.config.authenticate(headers);
|
|
89
|
+
const host = (await client.config.getHost()).toString();
|
|
90
|
+
return requesterSnapshot(resolveWorkspaceIdentity(host, headers), (path, query) =>
|
|
91
|
+
client.apiClient.request({
|
|
92
|
+
path,
|
|
93
|
+
method: "GET",
|
|
94
|
+
headers: new Headers({ accept: "application/json" }),
|
|
95
|
+
raw: false,
|
|
96
|
+
...(query === undefined ? {} : { query: { ...query } }),
|
|
97
|
+
}));
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Deep-convert SDK output to wire JSON: camelCase keys to snake_case, `bigint` to number, `undefined` members dropped. */
|
|
103
|
+
export function toServingEndpointsWire(value: unknown): unknown {
|
|
104
|
+
if (typeof value === "bigint") return Number(value);
|
|
105
|
+
if (Array.isArray(value)) return value.map(toServingEndpointsWire);
|
|
106
|
+
if (!value || typeof value !== "object") return value;
|
|
107
|
+
const prototype = Object.getPrototypeOf(value);
|
|
108
|
+
if (prototype !== Object.prototype && prototype !== null) return value;
|
|
109
|
+
return Object.fromEntries(
|
|
110
|
+
Object.entries(value)
|
|
111
|
+
.filter(([, item]) => item !== undefined)
|
|
112
|
+
.map(([key, item]) => [key.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`), toServingEndpointsWire(item)]),
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function listInferenceEndpoints(client: ModelServingSdkClientLike): Promise<RawServingEndpointsListing> {
|
|
117
|
+
return collectPages(async pageToken => {
|
|
118
|
+
const page = await client.listInferenceEndpoints(pageToken === undefined ? {} : { pageToken });
|
|
119
|
+
return { endpoints: (page.endpoints ?? []).map(toServingEndpointsWire), next: page.nextPageToken };
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function isWorkspaceClient(source: unknown): source is WorkspaceClientLike {
|
|
124
|
+
const candidate = source as Partial<WorkspaceClientLike> | null | undefined;
|
|
125
|
+
return typeof candidate === "object" && candidate !== null
|
|
126
|
+
&& typeof candidate.apiClient?.request === "function"
|
|
127
|
+
&& typeof candidate.config?.authenticate === "function"
|
|
128
|
+
&& typeof candidate.config.getHost === "function";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function isModelServingSdkClient(source: unknown): source is ModelServingSdkClientLike {
|
|
132
|
+
return typeof source === "object" && source !== null
|
|
133
|
+
&& typeof (source as Partial<ModelServingSdkClientLike>).listInferenceEndpoints === "function";
|
|
134
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type WorkspaceHeaders,
|
|
3
|
+
type WorkspaceIdentity,
|
|
4
|
+
WorkspaceConnectionError,
|
|
5
|
+
parseWorkspaceUrl,
|
|
6
|
+
principalIdentity,
|
|
7
|
+
resolveWorkspaceIdentity,
|
|
8
|
+
} from "./workspace-identity.js";
|
|
9
|
+
import { WORKSPACE_OVERLAY_RULES } from "./_generated/workspace-rules.js";
|
|
10
|
+
|
|
11
|
+
export const SERVING_ENDPOINTS_PATH: string = WORKSPACE_OVERLAY_RULES.serving_endpoints_path;
|
|
12
|
+
export const CURRENT_USER_PATH: string = WORKSPACE_OVERLAY_RULES.principal.path;
|
|
13
|
+
|
|
14
|
+
/** Workspace host (bare host or workspace URL) and the headers sent on its API requests. */
|
|
15
|
+
export interface ModelServingConnection {
|
|
16
|
+
readonly host: string;
|
|
17
|
+
readonly headers?: WorkspaceHeaders;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Called before every refresh so refreshed credentials or targets take effect. */
|
|
21
|
+
export type ModelServingConnectionGenerator = () => ModelServingConnection | Promise<ModelServingConnection>;
|
|
22
|
+
|
|
23
|
+
/** `modelServingClient` forms the browser-safe entry point accepts: a connection value or a connection generator. */
|
|
24
|
+
export type BrowserModelServingClientOption = ModelServingConnection | ModelServingConnectionGenerator;
|
|
25
|
+
|
|
26
|
+
/** Raw, unvalidated snake_case `GET /api/2.0/serving-endpoints` listing with all pages concatenated. */
|
|
27
|
+
export interface RawServingEndpointsListing {
|
|
28
|
+
readonly endpoints: unknown[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* One refresh attempt, resolved once (a generator is called once): the workspace identity plus the
|
|
33
|
+
* Serving Endpoints and principal lookups bound to that host and those credentials.
|
|
34
|
+
*/
|
|
35
|
+
export interface ModelServingSnapshot {
|
|
36
|
+
/** Workspace cache identity; absent when the source exposes no host. */
|
|
37
|
+
readonly workspace?: WorkspaceIdentity;
|
|
38
|
+
/** Every Serving Endpoints page in the snake_case wire shape. */
|
|
39
|
+
listServingEndpoints(): Promise<RawServingEndpointsListing>;
|
|
40
|
+
/** Non-secret principal identity (SCIM `Me` id, else userName); `undefined` when unavailable. */
|
|
41
|
+
principal(): Promise<string | undefined>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Which `modelServingClient` form a connector was normalized from. */
|
|
45
|
+
export type ModelServingConnectorKind = "workspace_client" | "model_serving_client" | "connection" | "generator";
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Internal normalization of one `modelServingClient` option. Not exported from the entry points:
|
|
49
|
+
* catalog clients build it once and take one snapshot per refresh attempt.
|
|
50
|
+
*/
|
|
51
|
+
export interface ModelServingConnector {
|
|
52
|
+
readonly kind: ModelServingConnectorKind;
|
|
53
|
+
/** Resolve the workspace and transport for one refresh attempt. */
|
|
54
|
+
snapshot(): Promise<ModelServingSnapshot>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ModelServingConnectorOptions {
|
|
58
|
+
/** Transport for connection and generator requests. Defaults to `globalThis.fetch`. */
|
|
59
|
+
fetch?: typeof globalThis.fetch | undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Raised when a workspace request returns a non-success status. */
|
|
63
|
+
export class WorkspaceRequestError extends Error {
|
|
64
|
+
override readonly name = "WorkspaceRequestError";
|
|
65
|
+
constructor(
|
|
66
|
+
readonly path: string,
|
|
67
|
+
readonly status: number,
|
|
68
|
+
) {
|
|
69
|
+
super(`Workspace request ${path} failed with ${status}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Raw-JSON GET for a workspace REST path. */
|
|
74
|
+
export type WorkspaceGet = (path: string, query?: Readonly<Record<string, string>>) => Promise<unknown>;
|
|
75
|
+
|
|
76
|
+
/** Supported forms the browser-safe entry point names in its unsupported-value error. */
|
|
77
|
+
export const BROWSER_MODEL_SERVING_FORMS = "a { host, headers } connection or a function returning one";
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Normalize a browser-safe `modelServingClient`: a static connection (a missing or invalid host
|
|
81
|
+
* fails here, before any request) or a generator (a returned value without a host fails that
|
|
82
|
+
* refresh). Anything else fails with an error naming `supportedForms`.
|
|
83
|
+
*/
|
|
84
|
+
export function connectBrowserModelServing(
|
|
85
|
+
source: BrowserModelServingClientOption,
|
|
86
|
+
options: ModelServingConnectorOptions = {},
|
|
87
|
+
supportedForms: string = BROWSER_MODEL_SERVING_FORMS,
|
|
88
|
+
): ModelServingConnector {
|
|
89
|
+
if (typeof source === "function") {
|
|
90
|
+
return {
|
|
91
|
+
kind: "generator",
|
|
92
|
+
snapshot: async () =>
|
|
93
|
+
restSnapshot(
|
|
94
|
+
validateConnection(await source(), "Model serving connection generator returned no host"),
|
|
95
|
+
options.fetch,
|
|
96
|
+
),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
if (source && typeof source === "object" && ("host" in source || "headers" in source)) {
|
|
100
|
+
const resolved = validateConnection(source, "Model serving connection requires a host");
|
|
101
|
+
return { kind: "connection", snapshot: async () => restSnapshot(resolved, options.fetch) };
|
|
102
|
+
}
|
|
103
|
+
throw new WorkspaceConnectionError(`Unsupported modelServingClient; expected ${supportedForms}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Snapshot over a raw-JSON GET transport: paged Serving Endpoints and SCIM `Me`. */
|
|
107
|
+
export function requesterSnapshot(workspace: WorkspaceIdentity | undefined, get: WorkspaceGet): ModelServingSnapshot {
|
|
108
|
+
return {
|
|
109
|
+
...(workspace === undefined ? {} : { workspace }),
|
|
110
|
+
listServingEndpoints: () =>
|
|
111
|
+
collectPages(async pageToken => {
|
|
112
|
+
const page = await get(SERVING_ENDPOINTS_PATH, pageToken === undefined ? undefined : { page_token: pageToken });
|
|
113
|
+
if (!page || typeof page !== "object") throw new TypeError("Serving Endpoints response is not a JSON object");
|
|
114
|
+
const { endpoints, next_page_token: next } = page as Record<string, unknown>;
|
|
115
|
+
return { endpoints: Array.isArray(endpoints) ? endpoints : [], next };
|
|
116
|
+
}),
|
|
117
|
+
principal: async () => principalIdentity(await get(CURRENT_USER_PATH)),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Concatenate every page, following a non-empty page token until it is absent or repeats. */
|
|
122
|
+
export async function collectPages(
|
|
123
|
+
page: (pageToken: string | undefined) => Promise<{ endpoints: readonly unknown[]; next: unknown }>,
|
|
124
|
+
): Promise<RawServingEndpointsListing> {
|
|
125
|
+
const endpoints: unknown[] = [];
|
|
126
|
+
const seen = new Set<string>();
|
|
127
|
+
let pageToken: string | undefined;
|
|
128
|
+
do {
|
|
129
|
+
const { endpoints: items, next } = await page(pageToken);
|
|
130
|
+
endpoints.push(...items);
|
|
131
|
+
pageToken = typeof next === "string" && next && !seen.has(next) ? next : undefined;
|
|
132
|
+
if (pageToken) seen.add(pageToken);
|
|
133
|
+
} while (pageToken);
|
|
134
|
+
return { endpoints };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
interface ResolvedConnection {
|
|
138
|
+
readonly host: string;
|
|
139
|
+
readonly headers: Headers;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function restSnapshot({ host, headers }: ResolvedConnection, fetcher?: typeof globalThis.fetch): ModelServingSnapshot {
|
|
143
|
+
const origin = parseWorkspaceUrl(host).origin;
|
|
144
|
+
return requesterSnapshot(resolveWorkspaceIdentity(host, headers), async (path, query) => {
|
|
145
|
+
const url = new URL(path, origin);
|
|
146
|
+
for (const [name, value] of Object.entries(query ?? {})) url.searchParams.set(name, value);
|
|
147
|
+
const requestHeaders = new Headers(headers);
|
|
148
|
+
if (!requestHeaders.has("accept")) requestHeaders.set("accept", "application/json");
|
|
149
|
+
const response = await (fetcher ?? globalThis.fetch)(url, { headers: requestHeaders });
|
|
150
|
+
if (!response.ok) throw new WorkspaceRequestError(path, response.status);
|
|
151
|
+
return response.json();
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function validateConnection(value: ModelServingConnection | undefined, message: string): ResolvedConnection {
|
|
156
|
+
const host = value && typeof value === "object" && typeof value.host === "string" ? value.host.trim() : "";
|
|
157
|
+
if (!host) throw new WorkspaceConnectionError(message);
|
|
158
|
+
parseWorkspaceUrl(host);
|
|
159
|
+
return { host, headers: new Headers(value?.headers) };
|
|
160
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { join, resolve } from "node:path";
|
|
2
|
+
import envPaths from "env-paths";
|
|
3
|
+
import { KeyvFile } from "keyv-file";
|
|
4
|
+
import {
|
|
5
|
+
type WorkspaceCacheStore,
|
|
6
|
+
type WorkspaceCatalogCache,
|
|
7
|
+
type WorkspaceCatalogCacheOptions,
|
|
8
|
+
createWorkspaceCatalogCache,
|
|
9
|
+
} from "./workspace-cache.js";
|
|
10
|
+
|
|
11
|
+
export interface FileWorkspaceCacheStoreOptions {
|
|
12
|
+
/** Cache file. Defaults to `workspace-catalog.json` in the user cache directory for this package. */
|
|
13
|
+
filename?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const fileStores = new Map<string, WorkspaceCacheStore>();
|
|
17
|
+
|
|
18
|
+
/** Default persistent cache file under the platform user cache directory. */
|
|
19
|
+
export function defaultWorkspaceCacheFile(): string {
|
|
20
|
+
return join(envPaths("dbx-model-catalog", { suffix: "" }).cache, "workspace-catalog.json");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Process-shared `keyv-file` store, one per file, so all caches on a file coalesce together. */
|
|
24
|
+
export function createFileWorkspaceCacheStore(
|
|
25
|
+
options: FileWorkspaceCacheStoreOptions = {},
|
|
26
|
+
): WorkspaceCacheStore {
|
|
27
|
+
const filename = resolve(options.filename ?? defaultWorkspaceCacheFile());
|
|
28
|
+
let store = fileStores.get(filename);
|
|
29
|
+
if (!store) {
|
|
30
|
+
store = new KeyvFile({ filename, writeDelay: 50 });
|
|
31
|
+
fileStores.set(filename, store);
|
|
32
|
+
}
|
|
33
|
+
return store;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Workspace cache persisted to a file for principal-scoped keys; session-only keys stay in memory. */
|
|
37
|
+
export function createPersistentWorkspaceCatalogCache<T>(
|
|
38
|
+
options: Omit<WorkspaceCatalogCacheOptions, "store"> & FileWorkspaceCacheStoreOptions = {},
|
|
39
|
+
): WorkspaceCatalogCache<T> {
|
|
40
|
+
const { filename, ...cacheOptions } = options;
|
|
41
|
+
return createWorkspaceCatalogCache<T>({
|
|
42
|
+
...cacheOptions,
|
|
43
|
+
store: createFileWorkspaceCacheStore(filename === undefined ? {} : { filename }),
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { WORKSPACE_OVERLAY_RULES } from "./_generated/workspace-rules.js";
|
|
2
|
+
|
|
3
|
+
const RULES = WORKSPACE_OVERLAY_RULES.workspace_identity;
|
|
4
|
+
const HOST_PATTERNS = RULES.host_patterns.map(pattern => new RegExp(pattern));
|
|
5
|
+
const SCHEME = /^[a-z][a-z\d+.-]*:\/\//i;
|
|
6
|
+
|
|
7
|
+
/** Headers accepted by a model serving connection: a `Headers`, a record, or name/value pairs. */
|
|
8
|
+
export type WorkspaceHeaders = ConstructorParameters<typeof Headers>[0];
|
|
9
|
+
|
|
10
|
+
/** Raised for invalid or ambiguous workspace connection input. */
|
|
11
|
+
export class WorkspaceConnectionError extends TypeError {
|
|
12
|
+
override readonly name = "WorkspaceConnectionError";
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Non-secret workspace cache identity: a workspace ID from headers, host, or URL query, or
|
|
17
|
+
* otherwise the normalized host plus any non-root path.
|
|
18
|
+
*/
|
|
19
|
+
export interface WorkspaceIdentity {
|
|
20
|
+
readonly kind: "workspace_id" | "host";
|
|
21
|
+
readonly value: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Parse a bare host (`adb-1.2.azuredatabricks.net`) or a full workspace URL. */
|
|
25
|
+
export function parseWorkspaceUrl(host: string): URL {
|
|
26
|
+
const trimmed = typeof host === "string" ? host.trim() : "";
|
|
27
|
+
if (!trimmed) throw new WorkspaceConnectionError("Workspace host is required");
|
|
28
|
+
try {
|
|
29
|
+
return new URL(SCHEME.test(trimmed) ? trimmed : `https://${trimmed}`);
|
|
30
|
+
} catch {
|
|
31
|
+
throw new WorkspaceConnectionError(`Workspace host is not a valid host or URL: ${trimmed}`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Lowercase hostname, any explicit port, and any non-root path, without scheme, query, or trailing slash. */
|
|
36
|
+
export function normalizeWorkspaceHost(host: string): string {
|
|
37
|
+
const url = parseWorkspaceUrl(host);
|
|
38
|
+
return `${url.hostname.toLowerCase()}${url.port ? `:${url.port}` : ""}${url.pathname.replace(/\/+$/, "")}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The shared string form used in `WorkspaceRefresh.workspace`: `id:<workspace id>` or `host:<host[/path]>`. */
|
|
42
|
+
export function formatWorkspaceIdentity(identity: WorkspaceIdentity): string {
|
|
43
|
+
return `${identity.kind === "workspace_id" ? "id" : "host"}:${identity.value}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Resolve the workspace cache identity using the shared `workspace_identity` rules:
|
|
48
|
+
* a matching header, then a host pattern or query parameter, then the normalized host.
|
|
49
|
+
*/
|
|
50
|
+
export function resolveWorkspaceIdentity(host: string, headers?: WorkspaceHeaders): WorkspaceIdentity {
|
|
51
|
+
const url = parseWorkspaceUrl(host);
|
|
52
|
+
const resolvedHeaders = new Headers(headers);
|
|
53
|
+
for (const name of RULES.header_names) {
|
|
54
|
+
const value = resolvedHeaders.get(name)?.trim();
|
|
55
|
+
if (value) return { kind: "workspace_id", value };
|
|
56
|
+
}
|
|
57
|
+
const hostname = url.hostname.toLowerCase();
|
|
58
|
+
for (const pattern of HOST_PATTERNS) {
|
|
59
|
+
const value = pattern.exec(hostname)?.[1];
|
|
60
|
+
if (value) return { kind: "workspace_id", value };
|
|
61
|
+
}
|
|
62
|
+
for (const name of RULES.query_parameters) {
|
|
63
|
+
const value = url.searchParams.get(name)?.trim();
|
|
64
|
+
if (value) return { kind: "workspace_id", value };
|
|
65
|
+
}
|
|
66
|
+
return { kind: "host", value: normalizeWorkspaceHost(host) };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Non-secret principal identity (`id`, else `userName`) from a SCIM `Me` response. */
|
|
70
|
+
export function principalIdentity(user: unknown): string | undefined {
|
|
71
|
+
if (!user || typeof user !== "object") return undefined;
|
|
72
|
+
for (const field of ["id", "userName"] as const) {
|
|
73
|
+
const value = (user as Record<string, unknown>)[field];
|
|
74
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
75
|
+
}
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import type { WorkspaceRefresh } from "./_generated/schemas.js";
|
|
2
|
+
import { EFFECTIVE_CATALOG_CONTRACT_VERSION } from "./effective.js";
|
|
3
|
+
import { normalizeServingEndpoints, type WorkspaceEndpoint } from "./serving-endpoints.js";
|
|
4
|
+
import {
|
|
5
|
+
DEFAULT_WORKSPACE_REFRESH_AFTER_MS,
|
|
6
|
+
DEFAULT_WORKSPACE_STALE_ON_ERROR_MS,
|
|
7
|
+
type WorkspaceCacheKey,
|
|
8
|
+
type WorkspaceCacheResult,
|
|
9
|
+
type WorkspaceCacheStore,
|
|
10
|
+
type WorkspaceCatalogCache,
|
|
11
|
+
createWorkspaceCatalogCache,
|
|
12
|
+
workspaceCacheKey,
|
|
13
|
+
} from "./workspace-cache.js";
|
|
14
|
+
import type { ModelServingConnector, ModelServingSnapshot } from "./workspace-connection.js";
|
|
15
|
+
import { formatWorkspaceIdentity } from "./workspace-identity.js";
|
|
16
|
+
|
|
17
|
+
/** Cached overlay payload: the normalized endpoint inventory only, never headers or principals. */
|
|
18
|
+
export interface CachedWorkspaceOverlay {
|
|
19
|
+
readonly endpoints: WorkspaceEndpoint[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Workspace overlay refresh and persistence settings. */
|
|
23
|
+
export interface WorkspaceCacheOptions {
|
|
24
|
+
/** Minimum time between refresh attempts. Defaults to five minutes. */
|
|
25
|
+
refreshAfterMs?: number;
|
|
26
|
+
/** Maximum age of an overlay served after a failed refresh. Defaults to seven days. */
|
|
27
|
+
staleOnErrorMs?: number;
|
|
28
|
+
/** Keyv-compatible store for principal-scoped overlays. Defaults to process memory. */
|
|
29
|
+
store?: WorkspaceCacheStore;
|
|
30
|
+
/** Whether `store` keeps entries across processes; reported as `WorkspaceRefresh.persistent`. */
|
|
31
|
+
persistent?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* A prepared overlay cache, such as `createPersistentWorkspaceCatalogCache()`; replaces the cache
|
|
34
|
+
* built from `store`, `refreshAfterMs`, and `staleOnErrorMs`.
|
|
35
|
+
*/
|
|
36
|
+
cache?: WorkspaceCatalogCache<CachedWorkspaceOverlay>;
|
|
37
|
+
now?: () => number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The served endpoints (absent when enrichment is unavailable) and their refresh state. */
|
|
41
|
+
export interface WorkspaceOverlayState {
|
|
42
|
+
readonly endpoints?: readonly WorkspaceEndpoint[];
|
|
43
|
+
readonly refresh: WorkspaceRefresh;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface Entry {
|
|
47
|
+
readonly endpoints: WorkspaceEndpoint[];
|
|
48
|
+
readonly writtenAt: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* One client's workspace overlay: refresh schedule, cache use, and failure state.
|
|
53
|
+
*
|
|
54
|
+
* A refresh is attempted when none was attempted within the refresh interval, or on
|
|
55
|
+
* `load({ force: true })`. Each attempt takes one connector snapshot (a generator is called once) and
|
|
56
|
+
* uses it for both the principal and Serving Endpoints requests. When the connection exposes no
|
|
57
|
+
* workspace host or principal the overlay stays in session memory. A fresh cache entry
|
|
58
|
+
* written by another client is reused; otherwise the inventory is fetched, coalesced per cache key.
|
|
59
|
+
* A failed refresh serves the newest entry at most `staleOnErrorMs` old as `stale`, or reports the
|
|
60
|
+
* workspace `unavailable` with no endpoints. Failures are reported in the state, never thrown.
|
|
61
|
+
* Internal: catalog clients build it from their `modelServingClient` option.
|
|
62
|
+
*/
|
|
63
|
+
export class WorkspaceOverlaySession {
|
|
64
|
+
private readonly cache: WorkspaceCatalogCache<CachedWorkspaceOverlay>;
|
|
65
|
+
private readonly now: () => number;
|
|
66
|
+
private readonly persistent: boolean;
|
|
67
|
+
private readonly refreshAfterMs: number;
|
|
68
|
+
private readonly staleOnErrorMs: number;
|
|
69
|
+
private attemptedAt: number | undefined;
|
|
70
|
+
private entry: Entry | undefined;
|
|
71
|
+
private inflight: Promise<WorkspaceOverlayState> | undefined;
|
|
72
|
+
private key: WorkspaceCacheKey | undefined;
|
|
73
|
+
private state: WorkspaceOverlayState | undefined;
|
|
74
|
+
private workspace: string | undefined;
|
|
75
|
+
|
|
76
|
+
constructor(
|
|
77
|
+
private readonly modelServing: ModelServingConnector,
|
|
78
|
+
options: WorkspaceCacheOptions = {},
|
|
79
|
+
) {
|
|
80
|
+
this.now = options.now ?? Date.now;
|
|
81
|
+
this.refreshAfterMs = options.refreshAfterMs ?? DEFAULT_WORKSPACE_REFRESH_AFTER_MS;
|
|
82
|
+
this.staleOnErrorMs = options.staleOnErrorMs ?? DEFAULT_WORKSPACE_STALE_ON_ERROR_MS;
|
|
83
|
+
this.persistent = options.persistent ?? false;
|
|
84
|
+
this.cache = options.cache ?? createWorkspaceCatalogCache<CachedWorkspaceOverlay>({
|
|
85
|
+
refreshAfterMs: this.refreshAfterMs,
|
|
86
|
+
staleOnErrorMs: this.staleOnErrorMs,
|
|
87
|
+
now: this.now,
|
|
88
|
+
...(options.store === undefined ? {} : { store: options.store }),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Return the current overlay, refreshing it when due (or when `force` is set). */
|
|
93
|
+
load(options: { force?: boolean } = {}): Promise<WorkspaceOverlayState> {
|
|
94
|
+
if (this.inflight) return this.inflight;
|
|
95
|
+
const now = this.now();
|
|
96
|
+
if (
|
|
97
|
+
!options.force && this.state && this.attemptedAt !== undefined
|
|
98
|
+
&& now - this.attemptedAt < this.refreshAfterMs
|
|
99
|
+
) {
|
|
100
|
+
return Promise.resolve(this.state);
|
|
101
|
+
}
|
|
102
|
+
const attempt = this.attempt(Boolean(options.force), now)
|
|
103
|
+
.catch(error => this.failed(error, now, this.workspace));
|
|
104
|
+
this.inflight = attempt.finally(() => {
|
|
105
|
+
this.inflight = undefined;
|
|
106
|
+
});
|
|
107
|
+
return this.inflight;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Forget this session's overlay and delete its cache entry, or every entry when `all`. */
|
|
111
|
+
async evict(options: { all?: boolean } = {}): Promise<void> {
|
|
112
|
+
await this.inflight;
|
|
113
|
+
if (options.all) await this.cache.clear();
|
|
114
|
+
else if (this.key) await this.cache.evict(this.key);
|
|
115
|
+
this.attemptedAt = this.entry = this.key = this.state = undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Wait for the in-flight attempt and any background cache refreshes. */
|
|
119
|
+
async settle(): Promise<void> {
|
|
120
|
+
await this.inflight;
|
|
121
|
+
await this.cache.settle();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private async attempt(force: boolean, now: number): Promise<WorkspaceOverlayState> {
|
|
125
|
+
this.attemptedAt = now;
|
|
126
|
+
let snapshot: ModelServingSnapshot;
|
|
127
|
+
try {
|
|
128
|
+
snapshot = await this.modelServing.snapshot();
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return this.failed(error, now, this.workspace);
|
|
131
|
+
}
|
|
132
|
+
const scoped = snapshot;
|
|
133
|
+
const workspace = scoped.workspace && formatWorkspaceIdentity(scoped.workspace);
|
|
134
|
+
const principal = await Promise.resolve().then(() => scoped.principal()).catch(() => undefined);
|
|
135
|
+
const key = await workspaceCacheKey({
|
|
136
|
+
workspace: scoped.workspace,
|
|
137
|
+
contractVersion: EFFECTIVE_CATALOG_CONTRACT_VERSION,
|
|
138
|
+
principal,
|
|
139
|
+
});
|
|
140
|
+
if (workspace !== this.workspace || key.id !== this.key?.id) this.entry = undefined;
|
|
141
|
+
this.workspace = workspace;
|
|
142
|
+
this.key = key;
|
|
143
|
+
const loader = async (): Promise<CachedWorkspaceOverlay> => ({
|
|
144
|
+
endpoints: normalizeServingEndpoints(await scoped.listServingEndpoints()),
|
|
145
|
+
});
|
|
146
|
+
try {
|
|
147
|
+
let result = force ? await this.cache.refresh(key, loader) : await this.cache.get(key, loader);
|
|
148
|
+
// An entry past the refresh interval is refreshed now; the cache coalesces the request.
|
|
149
|
+
if (result.status !== "fresh") result = await this.cache.refresh(key, loader);
|
|
150
|
+
return this.succeeded(result, now);
|
|
151
|
+
} catch (error) {
|
|
152
|
+
return this.failed(error, now, workspace);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private succeeded(result: WorkspaceCacheResult<CachedWorkspaceOverlay>, now: number): WorkspaceOverlayState {
|
|
157
|
+
this.entry = { endpoints: result.value.endpoints, writtenAt: result.writtenAt };
|
|
158
|
+
const stale = result.status === "stale";
|
|
159
|
+
return this.serve(this.entry, now, {
|
|
160
|
+
status: stale ? "stale" : "current",
|
|
161
|
+
persistent: this.persistent && result.shared,
|
|
162
|
+
...(stale ? { error: describeError(result.error) } : {}),
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private failed(error: unknown, now: number, workspace: string | undefined): WorkspaceOverlayState {
|
|
167
|
+
const fallback = this.entry && now - this.entry.writtenAt <= this.staleOnErrorMs ? this.entry : undefined;
|
|
168
|
+
this.entry = fallback;
|
|
169
|
+
this.workspace = workspace;
|
|
170
|
+
return this.serve(fallback, now, {
|
|
171
|
+
status: fallback ? "stale" : "unavailable",
|
|
172
|
+
persistent: Boolean(fallback) && this.persistent && Boolean(this.key?.shared),
|
|
173
|
+
error: describeError(error),
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private serve(
|
|
178
|
+
entry: Entry | undefined,
|
|
179
|
+
now: number,
|
|
180
|
+
refresh: Pick<WorkspaceRefresh, "status" | "persistent" | "error">,
|
|
181
|
+
): WorkspaceOverlayState {
|
|
182
|
+
this.state = {
|
|
183
|
+
...(entry && refresh.status !== "unavailable" ? { endpoints: entry.endpoints } : {}),
|
|
184
|
+
refresh: {
|
|
185
|
+
status: refresh.status,
|
|
186
|
+
...(this.workspace === undefined ? {} : { workspace: this.workspace }),
|
|
187
|
+
persistent: refresh.persistent ?? false,
|
|
188
|
+
...(entry ? { refreshed_at: new Date(entry.writtenAt).toISOString() } : {}),
|
|
189
|
+
attempted_at: new Date(now).toISOString(),
|
|
190
|
+
...(entry ? { age_seconds: Math.max(0, (now - entry.writtenAt) / 1000) } : {}),
|
|
191
|
+
...(refresh.error ? { error: refresh.error } : {}),
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
return this.state;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function describeError(error: unknown): string {
|
|
199
|
+
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
200
|
+
}
|