@dbx-tools/dbx-model-catalog 0.2.0 → 0.3.1

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.
Files changed (54) hide show
  1. package/README.md +294 -57
  2. package/dist/_generated/channels.d.ts +4 -3
  3. package/dist/_generated/json-schema.d.ts +6527 -175
  4. package/dist/_generated/schemas.d.ts +154 -0
  5. package/dist/_generated/workspace-rules.d.ts +133 -0
  6. package/dist/browser.d.ts +34 -17
  7. package/dist/browser.js +1192 -149
  8. package/dist/catalog-index.d.ts +15 -2
  9. package/dist/chunk-engbh7tj.js +39 -0
  10. package/dist/chunk-gzjer0mc.js +1797 -0
  11. package/dist/chunk-pp7fw379.js +51 -0
  12. package/dist/chunk-pwssxaq0.js +39 -0
  13. package/dist/cli.js +9 -654
  14. package/dist/effective.d.ts +31 -0
  15. package/dist/index.d.ts +33 -16
  16. package/dist/index.js +60 -660
  17. package/dist/local-client.d.ts +16 -3
  18. package/dist/pynect.d.ts +6 -3
  19. package/dist/search.d.ts +7 -1
  20. package/dist/serving-endpoints.d.ts +15 -0
  21. package/dist/sources.d.ts +30 -0
  22. package/dist/types.d.ts +31 -3
  23. package/dist/validation.d.ts +15 -1
  24. package/dist/workspace-cache.d.ts +68 -0
  25. package/dist/workspace-client.d.ts +49 -0
  26. package/dist/workspace-connection.d.ts +67 -0
  27. package/dist/workspace-file-cache.d.ts +11 -0
  28. package/dist/workspace-identity.d.ts +27 -0
  29. package/dist/workspace-overlay.d.ts +71 -0
  30. package/package.json +5 -6
  31. package/src/_generated/channels.ts +5 -2
  32. package/src/_generated/json-schema.ts +4 -2
  33. package/src/_generated/schemas.ts +177 -0
  34. package/src/_generated/workspace-rules.ts +285 -0
  35. package/src/browser.ts +105 -54
  36. package/src/catalog-index.ts +46 -19
  37. package/src/cli.ts +8 -11
  38. package/src/effective.ts +200 -0
  39. package/src/identity.ts +3 -26
  40. package/src/index.ts +155 -82
  41. package/src/local-client.ts +94 -18
  42. package/src/pynect.ts +28 -65
  43. package/src/search.ts +48 -0
  44. package/src/serving-endpoints.ts +157 -0
  45. package/src/sources.ts +107 -0
  46. package/src/types.ts +32 -2
  47. package/src/validation.ts +33 -0
  48. package/src/workspace-cache.ts +234 -0
  49. package/src/workspace-client.ts +134 -0
  50. package/src/workspace-connection.ts +160 -0
  51. package/src/workspace-file-cache.ts +45 -0
  52. package/src/workspace-identity.ts +77 -0
  53. package/src/workspace-overlay.ts +200 -0
  54. package/dist/pynect.js +0 -557
@@ -0,0 +1,234 @@
1
+ import { WORKSPACE_OVERLAY_RULES } from "./_generated/workspace-rules.js";
2
+ import type { WorkspaceIdentity } from "./workspace-identity.js";
3
+
4
+ /** Five minutes, from the shared `cache.refresh_interval_seconds` rule. */
5
+ export const DEFAULT_WORKSPACE_REFRESH_AFTER_MS: number =
6
+ WORKSPACE_OVERLAY_RULES.cache.refresh_interval_seconds * 1000;
7
+ /** Seven days, from the shared `cache.stale_ttl_seconds` rule. */
8
+ export const DEFAULT_WORKSPACE_STALE_ON_ERROR_MS: number =
9
+ WORKSPACE_OVERLAY_RULES.cache.stale_ttl_seconds * 1000;
10
+
11
+ /** Keyv-store-compatible persistence (for example `keyv-file`'s `KeyvFile`). `ttl` is milliseconds. */
12
+ export interface WorkspaceCacheStore {
13
+ get(key: string): Promise<unknown>;
14
+ set(key: string, value: unknown, ttl?: number): Promise<unknown>;
15
+ delete(key: string): Promise<boolean>;
16
+ clear(): Promise<unknown>;
17
+ }
18
+
19
+ /**
20
+ * Cache key for one workspace, contract version, and principal. `shared` is false when no
21
+ * principal identity is available; such entries stay in the cache instance's session memory.
22
+ */
23
+ export interface WorkspaceCacheKey {
24
+ readonly id: string;
25
+ readonly shared: boolean;
26
+ }
27
+
28
+ export interface WorkspaceCacheKeyInput {
29
+ /** Workspace identity; absent when the source exposes no host, which keeps the key session-only. */
30
+ readonly workspace?: WorkspaceIdentity | undefined;
31
+ readonly contractVersion: string | number;
32
+ /** Non-secret principal identity, such as the SCIM `Me` id. Stored only as a SHA-256 hash. */
33
+ readonly principal?: string | undefined;
34
+ }
35
+
36
+ export interface WorkspaceCatalogCacheOptions {
37
+ /** Shared store for keys with a principal. Defaults to process-wide memory. */
38
+ store?: WorkspaceCacheStore;
39
+ /** Age after which a hit is returned while one background refresh runs. Defaults to 5 minutes. */
40
+ refreshAfterMs?: number;
41
+ /** Maximum age of an entry served while refreshing or after a refresh error. Defaults to 7 days. */
42
+ staleOnErrorMs?: number;
43
+ now?: () => number;
44
+ }
45
+
46
+ /** `fresh`: within the refresh interval; `refreshing`: served while a refresh runs; `stale`: the last refresh failed. */
47
+ export type WorkspaceCacheStatus = "fresh" | "refreshing" | "stale";
48
+
49
+ export interface WorkspaceCacheResult<T> {
50
+ readonly value: T;
51
+ readonly status: WorkspaceCacheStatus;
52
+ readonly writtenAt: number;
53
+ readonly ageMs: number;
54
+ readonly shared: boolean;
55
+ /** The most recent refresh error when `status` is `stale`. */
56
+ readonly error?: unknown;
57
+ }
58
+
59
+ export interface WorkspaceCatalogCache<T> {
60
+ /** Return a cached value, refreshing in the background after the refresh interval, or load it. */
61
+ get(key: WorkspaceCacheKey, load: () => Promise<T>): Promise<WorkspaceCacheResult<T>>;
62
+ /** Reload now, returning a bounded stale entry with its error if the load fails. */
63
+ refresh(key: WorkspaceCacheKey, load: () => Promise<T>): Promise<WorkspaceCacheResult<T>>;
64
+ /** Remove only the matching workspace and principal entry. */
65
+ evict(key: WorkspaceCacheKey): Promise<boolean>;
66
+ /** Remove every entry in the shared store and this instance's session memory. */
67
+ clear(): Promise<void>;
68
+ /** Wait for background refreshes started by this instance. */
69
+ settle(): Promise<void>;
70
+ }
71
+
72
+ interface Entry<T> {
73
+ readonly value: T;
74
+ readonly writtenAt: number;
75
+ }
76
+
77
+ interface StoreState {
78
+ readonly inflight: Map<string, Promise<Entry<unknown>>>;
79
+ readonly failures: Map<string, { readonly error: unknown; readonly at: number }>;
80
+ }
81
+
82
+ const sharedMemoryStore = createMemoryWorkspaceCacheStore();
83
+ const storeStates = new WeakMap<WorkspaceCacheStore, StoreState>();
84
+
85
+ /**
86
+ * Build a key from workspace identity, contract version, and SHA-256 of the principal identity.
87
+ * The key is shared only when both the workspace and the principal are known.
88
+ */
89
+ export async function workspaceCacheKey(input: WorkspaceCacheKeyInput): Promise<WorkspaceCacheKey> {
90
+ const principal = input.workspace ? input.principal?.trim() : undefined;
91
+ const scope = principal ? await sha256(principal) : "session";
92
+ const workspace = input.workspace
93
+ ? `${input.workspace.kind}:${encodeURIComponent(input.workspace.value)}`
94
+ : "unknown";
95
+ return {
96
+ id: `workspace-catalog/v${input.contractVersion}/${workspace}/${scope}`,
97
+ shared: Boolean(principal),
98
+ };
99
+ }
100
+
101
+ /** In-memory store with millisecond TTLs. */
102
+ export function createMemoryWorkspaceCacheStore(now: () => number = Date.now): WorkspaceCacheStore {
103
+ const entries = new Map<string, { value: unknown; expires?: number }>();
104
+ return {
105
+ async get(key) {
106
+ const entry = entries.get(key);
107
+ if (entry?.expires !== undefined && entry.expires <= now()) entries.delete(key);
108
+ return entries.get(key)?.value;
109
+ },
110
+ async set(key, value, ttl) {
111
+ entries.set(key, ttl ? { value, expires: now() + ttl } : { value });
112
+ return true;
113
+ },
114
+ async delete(key) {
115
+ return entries.delete(key);
116
+ },
117
+ async clear() {
118
+ entries.clear();
119
+ },
120
+ };
121
+ }
122
+
123
+ /** Workspace-scoped cache with refresh-after-write, in-flight coalescing, and bounded stale-on-error. */
124
+ export function createWorkspaceCatalogCache<T>(
125
+ options: WorkspaceCatalogCacheOptions = {},
126
+ ): WorkspaceCatalogCache<T> {
127
+ const now = options.now ?? Date.now;
128
+ const refreshAfterMs = options.refreshAfterMs ?? DEFAULT_WORKSPACE_REFRESH_AFTER_MS;
129
+ const staleOnErrorMs = options.staleOnErrorMs ?? DEFAULT_WORKSPACE_STALE_ON_ERROR_MS;
130
+ const shared = options.store ?? sharedMemoryStore;
131
+ const session = createMemoryWorkspaceCacheStore(now);
132
+ const background = new Set<Promise<unknown>>();
133
+
134
+ const storeFor = (key: WorkspaceCacheKey) => (key.shared ? shared : session);
135
+
136
+ const read = async (key: WorkspaceCacheKey): Promise<Entry<T> | undefined> => {
137
+ const entry = (await storeFor(key).get(key.id)) as Entry<T> | undefined;
138
+ if (!entry || typeof entry.writtenAt !== "number") return undefined;
139
+ return now() - entry.writtenAt < staleOnErrorMs ? entry : undefined;
140
+ };
141
+
142
+ const load = (key: WorkspaceCacheKey, loader: () => Promise<T>): Promise<Entry<T>> => {
143
+ const store = storeFor(key);
144
+ const state = stateFor(store);
145
+ const existing = state.inflight.get(key.id);
146
+ if (existing) return existing as Promise<Entry<T>>;
147
+ const pending = (async () => {
148
+ try {
149
+ const entry: Entry<T> = { value: await loader(), writtenAt: now() };
150
+ await store.set(key.id, entry, staleOnErrorMs);
151
+ state.failures.delete(key.id);
152
+ return entry;
153
+ } catch (error) {
154
+ state.failures.set(key.id, { error, at: now() });
155
+ throw error;
156
+ } finally {
157
+ state.inflight.delete(key.id);
158
+ }
159
+ })();
160
+ state.inflight.set(key.id, pending);
161
+ return pending;
162
+ };
163
+
164
+ const result = (
165
+ key: WorkspaceCacheKey,
166
+ entry: Entry<T>,
167
+ status: WorkspaceCacheStatus,
168
+ error?: unknown,
169
+ ): WorkspaceCacheResult<T> => ({
170
+ value: entry.value,
171
+ status,
172
+ writtenAt: entry.writtenAt,
173
+ ageMs: Math.max(0, now() - entry.writtenAt),
174
+ shared: key.shared,
175
+ ...(status === "stale" ? { error } : {}),
176
+ });
177
+
178
+ return {
179
+ async get(key, loader) {
180
+ const entry = await read(key);
181
+ if (!entry) return result(key, await load(key, loader), "fresh");
182
+ if (now() - entry.writtenAt < refreshAfterMs) return result(key, entry, "fresh");
183
+ const failure = stateFor(storeFor(key)).failures.get(key.id);
184
+ const failed = failure !== undefined && failure.at >= entry.writtenAt;
185
+ // After a failed refresh, retry at most once per refresh interval.
186
+ if (!failed || now() - failure.at >= refreshAfterMs) {
187
+ const refresh = load(key, loader).catch(() => undefined);
188
+ background.add(refresh);
189
+ void refresh.finally(() => background.delete(refresh));
190
+ }
191
+ return failed ? result(key, entry, "stale", failure.error) : result(key, entry, "refreshing");
192
+ },
193
+
194
+ async refresh(key, loader) {
195
+ try {
196
+ return result(key, await load(key, loader), "fresh");
197
+ } catch (error) {
198
+ const entry = await read(key);
199
+ if (!entry) throw error;
200
+ return result(key, entry, "stale", error);
201
+ }
202
+ },
203
+
204
+ async evict(key) {
205
+ const store = storeFor(key);
206
+ stateFor(store).failures.delete(key.id);
207
+ return store.delete(key.id);
208
+ },
209
+
210
+ async clear() {
211
+ stateFor(shared).failures.clear();
212
+ stateFor(session).failures.clear();
213
+ await Promise.all([shared.clear(), session.clear()]);
214
+ },
215
+
216
+ async settle() {
217
+ while (background.size > 0) await Promise.all([...background]);
218
+ },
219
+ };
220
+ }
221
+
222
+ function stateFor(store: WorkspaceCacheStore): StoreState {
223
+ let state = storeStates.get(store);
224
+ if (!state) {
225
+ state = { inflight: new Map(), failures: new Map() };
226
+ storeStates.set(store, state);
227
+ }
228
+ return state;
229
+ }
230
+
231
+ async function sha256(value: string): Promise<string> {
232
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
233
+ return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("");
234
+ }
@@ -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
+ }