@milaboratories/pl-model-middle-layer 1.30.3 → 1.30.5
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/dist/block_meta/block_description.d.ts +10 -10
- package/dist/pframe/internal_api/http_helpers.cjs.map +1 -1
- package/dist/pframe/internal_api/http_helpers.d.ts +71 -2
- package/dist/pframe/internal_api/http_helpers.d.ts.map +1 -1
- package/dist/pframe/internal_api/http_helpers.js.map +1 -1
- package/dist/pframe/internal_api/index.d.ts +2 -2
- package/package.json +4 -4
- package/src/pframe/internal_api/http_helpers.ts +91 -2
|
@@ -659,6 +659,14 @@ declare const BlockPackDescriptionFromPackageJsonRaw: z.ZodObject<{
|
|
|
659
659
|
requiredCapabilities: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
660
660
|
}, ZodTypeAny, "passthrough">>;
|
|
661
661
|
}, "strip", ZodTypeAny, {
|
|
662
|
+
components: {
|
|
663
|
+
workflow: WorkflowV1<string> | {
|
|
664
|
+
type: "workflow-v1";
|
|
665
|
+
main: string;
|
|
666
|
+
};
|
|
667
|
+
model: string;
|
|
668
|
+
ui: string;
|
|
669
|
+
};
|
|
662
670
|
meta: {
|
|
663
671
|
organization: {
|
|
664
672
|
name: string;
|
|
@@ -722,15 +730,15 @@ declare const BlockPackDescriptionFromPackageJsonRaw: z.ZodObject<{
|
|
|
722
730
|
} & {
|
|
723
731
|
[k: string]: unknown;
|
|
724
732
|
};
|
|
733
|
+
}, {
|
|
725
734
|
components: {
|
|
726
|
-
workflow:
|
|
735
|
+
workflow: string | {
|
|
727
736
|
type: "workflow-v1";
|
|
728
737
|
main: string;
|
|
729
738
|
};
|
|
730
739
|
model: string;
|
|
731
740
|
ui: string;
|
|
732
741
|
};
|
|
733
|
-
}, {
|
|
734
742
|
meta: {
|
|
735
743
|
organization: {
|
|
736
744
|
name: string;
|
|
@@ -794,14 +802,6 @@ declare const BlockPackDescriptionFromPackageJsonRaw: z.ZodObject<{
|
|
|
794
802
|
} & {
|
|
795
803
|
[k: string]: unknown;
|
|
796
804
|
};
|
|
797
|
-
components: {
|
|
798
|
-
workflow: string | {
|
|
799
|
-
type: "workflow-v1";
|
|
800
|
-
main: string;
|
|
801
|
-
};
|
|
802
|
-
model: string;
|
|
803
|
-
ui: string;
|
|
804
|
-
};
|
|
805
805
|
}>;
|
|
806
806
|
declare const FeatureFlags: z.ZodEffects<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodBoolean, z.ZodNumber]>>, BlockCodeKnownFeatureFlags, Record<string, number | boolean>>;
|
|
807
807
|
declare function CreateBlockPackDescriptionSchema<Components extends ZodTypeAny, Meta extends ZodTypeAny>(components: Components, meta: Meta): z.ZodObject<{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http_helpers.cjs","names":[],"sources":["../../../src/pframe/internal_api/http_helpers.ts"],"sourcesContent":["import type { Readable } from \"node:stream\";\nimport type { RequestListener } from \"node:http\";\nimport type { Branded, Base64Encoded } from \"@milaboratories/pl-model-common\";\nimport type { Logger } from \"./common\";\n\n/** Parquet file extension */\nexport const ParquetExtension = \".parquet\" as const;\n\n/** Parquet file name */\nexport type ParquetFileName = Branded<`${string}.parquet`, \"PFrameInternal.ParquetFileName\">;\n\nexport type FileRange = {\n /** Start byte position (inclusive) */\n start: number;\n /** End byte position (inclusive) */\n end: number;\n};\n\n/** HTTP range as of RFC 9110 <https://datatracker.ietf.org/doc/html/rfc9110#name-range> */\nexport type HttpRange =\n | {\n /**\n * Get file content in the specified byte range\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=0-1023\n * ```\n */\n type: \"bounded\";\n /** Start byte position (inclusive) */\n start: number;\n /** End byte position (inclusive) */\n end: number;\n }\n | {\n /**\n * Get byte range starting from the specified offset\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=1024-\n * ```\n */\n type: \"offset\";\n /** Start byte position (inclusive) */\n offset: number;\n }\n | {\n /**\n * Get byte range starting from the specified suffix\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=-1024\n * ```\n */\n type: \"suffix\";\n /** End byte position (inclusive) */\n suffix: number;\n };\n\n/** HTTP method passed to object store */\nexport type HttpMethod = \"GET\" | \"HEAD\";\n\n/** HTTP response from object store */\nexport type ObjectStoreResponse =\n | {\n /**\n * Will be translated to 500 Internal Server Error by the handler\n * or 408 Request Timeout if the request was aborted\n */\n type: \"InternalError\";\n }\n | {\n /** Will be translated to 404 Not Found by the handler */\n type: \"NotFound\";\n }\n | {\n /** Will be translated to 416 Range Not Satisfiable by the handler */\n type: \"RangeNotSatisfiable\";\n /** Total file size in bytes */\n size: number;\n }\n | {\n /** Will be translated to 200 OK or 206 Partial Content by the handler */\n type: \"Ok\";\n /** Total file size in bytes */\n size: number;\n /** File range translated from HTTP range */\n range: FileRange;\n /** Stream of file content, undefined for HEAD requests */\n data?: Readable;\n };\n\n/** Common options for object store creation */\nexport interface ObjectStoreOptions {\n /** Logger instance, no logging is performed when not provided */\n logger?: Logger;\n}\n\n/** Options for file system object store creation */\nexport interface FsStoreOptions extends ObjectStoreOptions {\n /** Local directory to serve files from */\n rootDir: string;\n}\n\nexport interface ObjectStore {\n /**\n * Proxy HTTP(S) request for parquet file to object store.\n * Callback promise resolves when stream is closed by handler @see HttpHelpers.createRequestHandler\n * Callback API is used so that ObjectStore can limit the number of concurrent requests.\n */\n request(\n filename: ParquetFileName,\n params: {\n method: HttpMethod;\n range?: HttpRange;\n signal: AbortSignal;\n callback: (response: ObjectStoreResponse) => Promise<void>;\n },\n ): void;\n}\n\n/** File system abstraction for request handler factory, @see HttpHelpers.createRequestHandler */\nexport abstract class BaseObjectStore implements ObjectStore {\n protected readonly logger: Logger;\n\n constructor(options: ObjectStoreOptions) {\n this.logger = options.logger ?? (() => {});\n }\n\n /** Translate HTTP range to file range, @returns null if the range is not satisfiable */\n protected translate(fileSize: number, range?: HttpRange): FileRange | null {\n if (!range) return { start: 0, end: fileSize - 1 };\n switch (range.type) {\n case \"bounded\":\n if (range.end >= fileSize) return null;\n return { start: range.start, end: range.end };\n case \"offset\":\n if (range.offset >= fileSize) return null;\n return { start: range.offset, end: fileSize - 1 };\n case \"suffix\":\n if (range.suffix > fileSize) return null;\n return { start: fileSize - range.suffix, end: fileSize - 1 };\n }\n }\n\n /**\n * Proxy HTTP(S) request for parquet file to object store.\n * Callback promise resolves when stream is closed by handler @see HttpHelpers.createRequestHandler\n * Callback API is used so that ObjectStore can limit the number of concurrent requests.\n */\n abstract request(\n filename: ParquetFileName,\n params: {\n method: HttpMethod;\n range?: HttpRange;\n signal: AbortSignal;\n callback: (response: ObjectStoreResponse) => Promise<void>;\n },\n ): Promise<void>;\n}\n\n/** Object store base URL in format accepted by Apache DataFusion and DuckDB */\nexport type ObjectStoreUrl = Branded<string, \"PFrameInternal.ObjectStoreUrl\">;\n\n/** HTTP(S) request handler creation options */\nexport type RequestHandlerOptions = {\n /** Object store to serve files from, @see HttpHelpers.createFsStore */\n store: ObjectStore;\n /** Here will go caching options... */\n};\n\n/** Server configuration options */\nexport type HttpServerOptions = {\n /** HTTP(S) request handler function, @see HttpHelpers.createRequestHandler */\n handler: RequestListener;\n /** Port to bind to, @default 0 for auto-assignment */\n port?: number;\n /** Do not apply authorization middleware to @param handler */\n noAuth?: true;\n /** Downgrade default HTTPS server to plain HTTP, @warning use only for testing */\n noHttps?: true;\n};\n\n/**\n * Long unique opaque string for use in Bearer authorization header\n *\n * @example\n * ```ts\n * request.setHeader('Authorization', `Bearer ${authToken}`);\n * ```\n */\nexport type HttpAuthorizationToken = Branded<string, \"PFrameInternal.HttpAuthorizationToken\">;\n\n/**\n * TLS certificate in PEM format\n *\n * @example\n * ```txt\n * -----BEGIN CERTIFICATE-----\n * MIIC2zCCAcOgAwIBAgIJaVW7...\n * ...\n * ...Yf9CRK8fgnukKM7TJ\n * -----END CERTIFICATE-----\n * ```\n */\nexport type PemCertificate = Branded<string, \"PFrameInternal.PemCertificate\">;\n\n/** HTTP(S) server connection settings, {@link HttpHelpers.createHttpServer} */\nexport type HttpServerInfo = {\n /** URL of the HTTP(S) server formatted as `http{s}://<host>:<port>/` */\n url: ObjectStoreUrl;\n /** Authorization token for Bearer scheme, undefined when @see HttpServerOptions.noAuth flag is set */\n authToken?: HttpAuthorizationToken;\n /** Encoded CA certificate of HTTPS server, undefined when @see HttpServerOptions.noHttps flag is set */\n encodedCaCert?: Base64Encoded<PemCertificate>;\n};\n\n/** HTTP(S) server information and controls, @see HttpHelpers.createHttpServer */\nexport interface HttpServer {\n /** Server configuration information for initiating connections from clients */\n get info(): HttpServerInfo;\n /** Promise that resolves when the server is stopped */\n get stopped(): Promise<void>;\n /** Request server stop, returns the same promise as @see HttpServer.stopped */\n stop(): Promise<void>;\n}\n\n/** List of HTTP(S) related helper functions exposed by PFrame module */\nexport interface HttpHelpers {\n /**\n * Create an object store for serving files from a local directory.\n * Rejects if the provided path does not exist or is not a directory.\n */\n createFsStore(options: FsStoreOptions): Promise<ObjectStore>;\n\n /**\n * Create an HTTP request handler for serving files from an object store.\n * Accepts only paths of the form `/<filename>.parquet`, returns 410 otherwise.\n * Assumes that files are immutable (and sets cache headers accordingly).\n */\n createRequestHandler(options: RequestHandlerOptions): RequestListener;\n\n /**\n * Serve HTTP(S) requests using the provided handler on localhost port.\n * @returns promise that resolves when the server has stopped.\n *\n * @example\n * ```ts\n * const rootDir = '/path/to/directory/with/parquet/files';\n *\n * let store = await HttpHelpers.createFsStore({ rootDir }).catch((err: unknown) => {\n * throw new Error(`Failed to create file store for ${rootDir} - ${ensureError(err)}`);\n * });\n *\n * const server = await HttpHelpers.createHttpServer({\n * handler: HttpHelpers.createRequestHandler({ store }),\n * }).catch((err: unknown) => {\n * throw new Error(`Failed to start HTTPS server - ${ensureError(err)}`);\n * });\n *\n * const { url, authToken, encodedCaCert } = server.info;\n *\n * await server.stop();\n * ```\n */\n createHttpServer(options: HttpServerOptions): Promise<HttpServer>;\n}\n"],"mappings":";;AAMA,MAAa,mBAAmB;;AA0HhC,IAAsB,kBAAtB,MAA6D;CAC3D;CAEA,YAAY,SAA6B;AACvC,OAAK,SAAS,QAAQ,iBAAiB;;;CAIzC,UAAoB,UAAkB,OAAqC;AACzE,MAAI,CAAC,MAAO,QAAO;GAAE,OAAO;GAAG,KAAK,WAAW;GAAG;AAClD,UAAQ,MAAM,MAAd;GACE,KAAK;AACH,QAAI,MAAM,OAAO,SAAU,QAAO;AAClC,WAAO;KAAE,OAAO,MAAM;KAAO,KAAK,MAAM;KAAK;GAC/C,KAAK;AACH,QAAI,MAAM,UAAU,SAAU,QAAO;AACrC,WAAO;KAAE,OAAO,MAAM;KAAQ,KAAK,WAAW;KAAG;GACnD,KAAK;AACH,QAAI,MAAM,SAAS,SAAU,QAAO;AACpC,WAAO;KAAE,OAAO,WAAW,MAAM;KAAQ,KAAK,WAAW;KAAG"}
|
|
1
|
+
{"version":3,"file":"http_helpers.cjs","names":[],"sources":["../../../src/pframe/internal_api/http_helpers.ts"],"sourcesContent":["import type { Readable } from \"node:stream\";\nimport type { RequestListener } from \"node:http\";\nimport type { Branded, Base64Encoded } from \"@milaboratories/pl-model-common\";\nimport type { Logger } from \"./common\";\n\n/** Parquet file extension */\nexport const ParquetExtension = \".parquet\" as const;\n\n/** Parquet file name */\nexport type ParquetFileName = Branded<`${string}.parquet`, \"PFrameInternal.ParquetFileName\">;\n\nexport type FileRange = {\n /** Start byte position (inclusive) */\n start: number;\n /** End byte position (inclusive) */\n end: number;\n};\n\n/** HTTP range as of RFC 9110 <https://datatracker.ietf.org/doc/html/rfc9110#name-range> */\nexport type HttpRange =\n | {\n /**\n * Get file content in the specified byte range\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=0-1023\n * ```\n */\n type: \"bounded\";\n /** Start byte position (inclusive) */\n start: number;\n /** End byte position (inclusive) */\n end: number;\n }\n | {\n /**\n * Get byte range starting from the specified offset\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=1024-\n * ```\n */\n type: \"offset\";\n /** Start byte position (inclusive) */\n offset: number;\n }\n | {\n /**\n * Get byte range starting from the specified suffix\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=-1024\n * ```\n */\n type: \"suffix\";\n /** End byte position (inclusive) */\n suffix: number;\n };\n\n/** HTTP method passed to object store */\nexport type HttpMethod = \"GET\" | \"HEAD\";\n\n/** HTTP response from object store */\nexport type ObjectStoreResponse =\n | {\n /**\n * Will be translated to 500 Internal Server Error by the handler\n * or 408 Request Timeout if the request was aborted\n */\n type: \"InternalError\";\n }\n | {\n /** Will be translated to 404 Not Found by the handler */\n type: \"NotFound\";\n }\n | {\n /** Will be translated to 416 Range Not Satisfiable by the handler */\n type: \"RangeNotSatisfiable\";\n /** Total file size in bytes */\n size: number;\n }\n | {\n /** Will be translated to 200 OK or 206 Partial Content by the handler */\n type: \"Ok\";\n /** Total file size in bytes */\n size: number;\n /** File range translated from HTTP range */\n range: FileRange;\n /** Stream of file content, undefined for HEAD requests */\n data?: Readable;\n };\n\n/** Common options for object store creation */\nexport interface ObjectStoreOptions {\n /** Logger instance, no logging is performed when not provided */\n logger?: Logger;\n}\n\n/** Options for file system object store creation */\nexport interface FsStoreOptions extends ObjectStoreOptions {\n /** Local directory to serve files from */\n rootDir: string;\n}\n\nexport interface ObjectStore {\n /**\n * Proxy HTTP(S) request for parquet file to object store.\n * Callback promise resolves when stream is closed by handler @see HttpHelpers.createRequestHandler\n * Callback API is used so that ObjectStore can limit the number of concurrent requests.\n */\n request(\n filename: ParquetFileName,\n params: {\n method: HttpMethod;\n range?: HttpRange;\n signal: AbortSignal;\n callback: (response: ObjectStoreResponse) => Promise<void>;\n },\n ): void;\n}\n\n/** File system abstraction for request handler factory, @see HttpHelpers.createRequestHandler */\nexport abstract class BaseObjectStore implements ObjectStore {\n protected readonly logger: Logger;\n\n constructor(options: ObjectStoreOptions) {\n this.logger = options.logger ?? (() => {});\n }\n\n /** Translate HTTP range to file range, @returns null if the range is not satisfiable */\n protected translate(fileSize: number, range?: HttpRange): FileRange | null {\n if (!range) return { start: 0, end: fileSize - 1 };\n switch (range.type) {\n case \"bounded\":\n if (range.end >= fileSize) return null;\n return { start: range.start, end: range.end };\n case \"offset\":\n if (range.offset >= fileSize) return null;\n return { start: range.offset, end: fileSize - 1 };\n case \"suffix\":\n if (range.suffix > fileSize) return null;\n return { start: fileSize - range.suffix, end: fileSize - 1 };\n }\n }\n\n /**\n * Proxy HTTP(S) request for parquet file to object store.\n * Callback promise resolves when stream is closed by handler @see HttpHelpers.createRequestHandler\n * Callback API is used so that ObjectStore can limit the number of concurrent requests.\n */\n abstract request(\n filename: ParquetFileName,\n params: {\n method: HttpMethod;\n range?: HttpRange;\n signal: AbortSignal;\n callback: (response: ObjectStoreResponse) => Promise<void>;\n },\n ): Promise<void>;\n}\n\n/** Configuration for {@link HttpHelpers.createCachingObjectStore} */\nexport type CacheConfig = {\n /** Filesystem path where the cache persists its data */\n cachePath: string;\n /** Hard total size budget in bytes; the cache self-stabilizes near this size */\n maxSizeBytes: number;\n /**\n * Max share of the budget a single file may occupy (0..1); when a file exceeds it, that\n * file's oldest ranges are evicted first. Stops one large scan from flushing the working set.\n */\n admissionFraction: number;\n /** Upper bound on previously-evicted (ghost) files remembered to guide readmission; resident files are already byte-bounded */\n maxFilesTracked: number;\n};\n\n/**\n * Cumulative cache event counters. Surfaced both as lifetime totals (persisted across restarts)\n * and as a per-process session view, @see CacheMetrics.\n */\nexport type CacheCounters = {\n /** Requests fully served from cache */\n hits: number;\n /** Requests that fell through to upstream */\n misses: number;\n /** Bytes served from cache */\n bytesServed: number;\n /** Bytes downloaded from upstream on misses */\n bytesFetched: number;\n /** Bytes evicted to keep the cache within its total size budget, @see CacheConfig.maxSizeBytes */\n bytesEvictedByBudget: number;\n /** Bytes evicted because a single file exceeded its allowed share of the budget, @see CacheConfig.admissionFraction */\n bytesEvictedByFileCap: number;\n /** Files promoted on observed reuse, so they are retained longer than first-time entries */\n promotions: number;\n /** Previously evicted files that were re-requested and readmitted */\n ghostReadmissions: number;\n};\n\n/** Snapshot of cache state and counters, @see CachingObjectStore.getMetrics */\nexport type CacheMetrics = {\n /** Current resident bytes */\n sizeBytes: number;\n /** Number of files with resident (cached) bytes */\n residentFiles: number;\n /** Number of previously-evicted (ghost) files remembered, <= @see CacheConfig.maxFilesTracked */\n ghostFiles: number;\n /** Counters cumulative across all sessions (persisted) */\n lifetime: CacheCounters;\n /** The same counters scoped to the current process */\n session: CacheCounters;\n};\n\n/**\n * Options for caching object store creation, @see HttpHelpers.createCachingObjectStore.\n * Standalone (not extending {@link ObjectStoreOptions}): a caching store is a decorator over\n * `upstream`, so source-store options do not apply to it.\n */\nexport interface CachingObjectStoreOptions {\n /** Upstream store consulted on cache misses */\n upstream: ObjectStore;\n /** Cache configuration */\n config: CacheConfig;\n /** Logger instance, no logging is performed when not provided */\n logger?: Logger;\n}\n\n/**\n * An {@link ObjectStore} that serves byte ranges from a persistent local cache, fetching misses\n * from an upstream store. This is the single handle for the cache: pass it as\n * {@link RequestHandlerOptions.store}, read {@link CachingObjectStore.getMetrics}, and dispose it\n * to release the cache, @see HttpHelpers.createCachingObjectStore.\n */\nexport interface CachingObjectStore extends ObjectStore, AsyncDisposable {\n /** Instantaneous cache state plus lifetime/session counters */\n getMetrics(): CacheMetrics;\n /** Drop all cached data and zero the counters (test/benchmark use) */\n reset(): Promise<void>;\n}\n\n/** Object store base URL in format accepted by Apache DataFusion and DuckDB */\nexport type ObjectStoreUrl = Branded<string, \"PFrameInternal.ObjectStoreUrl\">;\n\n/** HTTP(S) request handler creation options */\nexport type RequestHandlerOptions = {\n /**\n * Object store to serve files from. Compose caching by wrapping the upstream store with\n * {@link HttpHelpers.createCachingObjectStore} and passing the result here,\n * @see HttpHelpers.createFsStore\n */\n store: ObjectStore;\n};\n\n/** Server configuration options */\nexport type HttpServerOptions = {\n /** HTTP(S) request handler function, @see HttpHelpers.createRequestHandler */\n handler: RequestListener;\n /** Port to bind to, @default 0 for auto-assignment */\n port?: number;\n /** Do not apply authorization middleware to @param handler */\n noAuth?: true;\n /** Downgrade default HTTPS server to plain HTTP, @warning use only for testing */\n noHttps?: true;\n};\n\n/**\n * Long unique opaque string for use in Bearer authorization header\n *\n * @example\n * ```ts\n * request.setHeader('Authorization', `Bearer ${authToken}`);\n * ```\n */\nexport type HttpAuthorizationToken = Branded<string, \"PFrameInternal.HttpAuthorizationToken\">;\n\n/**\n * TLS certificate in PEM format\n *\n * @example\n * ```txt\n * -----BEGIN CERTIFICATE-----\n * MIIC2zCCAcOgAwIBAgIJaVW7...\n * ...\n * ...Yf9CRK8fgnukKM7TJ\n * -----END CERTIFICATE-----\n * ```\n */\nexport type PemCertificate = Branded<string, \"PFrameInternal.PemCertificate\">;\n\n/** HTTP(S) server connection settings, {@link HttpHelpers.createHttpServer} */\nexport type HttpServerInfo = {\n /** URL of the HTTP(S) server formatted as `http{s}://<host>:<port>/` */\n url: ObjectStoreUrl;\n /** Authorization token for Bearer scheme, undefined when @see HttpServerOptions.noAuth flag is set */\n authToken?: HttpAuthorizationToken;\n /** Encoded CA certificate of HTTPS server, undefined when @see HttpServerOptions.noHttps flag is set */\n encodedCaCert?: Base64Encoded<PemCertificate>;\n};\n\n/** HTTP(S) server information and controls, @see HttpHelpers.createHttpServer */\nexport interface HttpServer {\n /** Server configuration information for initiating connections from clients */\n get info(): HttpServerInfo;\n /** Promise that resolves when the server is stopped */\n get stopped(): Promise<void>;\n /** Request server stop, returns the same promise as @see HttpServer.stopped */\n stop(): Promise<void>;\n}\n\n/** List of HTTP(S) related helper functions exposed by PFrame module */\nexport interface HttpHelpers {\n /**\n * Create an object store for serving files from a local directory.\n * Rejects if the provided path does not exist or is not a directory.\n */\n createFsStore(options: FsStoreOptions): Promise<ObjectStore>;\n\n /**\n * Wrap an upstream object store in a persistent byte-range cache backed by SQLite.\n * The returned store is itself an {@link ObjectStore} (pass it to {@link createRequestHandler})\n * and additionally exposes metrics and reset. Dispose it to close the cache database.\n */\n createCachingObjectStore(options: CachingObjectStoreOptions): Promise<CachingObjectStore>;\n\n /**\n * Create an HTTP request handler for serving files from an object store.\n * Accepts only paths of the form `/<filename>.parquet`, returns 410 otherwise.\n * Assumes that files are immutable (and sets cache headers accordingly).\n */\n createRequestHandler(options: RequestHandlerOptions): RequestListener;\n\n /**\n * Serve HTTP(S) requests using the provided handler on localhost port.\n * @returns promise that resolves when the server has stopped.\n *\n * @example\n * ```ts\n * const rootDir = '/path/to/directory/with/parquet/files';\n *\n * let store = await HttpHelpers.createFsStore({ rootDir }).catch((err: unknown) => {\n * throw new Error(`Failed to create file store for ${rootDir} - ${ensureError(err)}`);\n * });\n *\n * const server = await HttpHelpers.createHttpServer({\n * handler: HttpHelpers.createRequestHandler({ store }),\n * }).catch((err: unknown) => {\n * throw new Error(`Failed to start HTTPS server - ${ensureError(err)}`);\n * });\n *\n * const { url, authToken, encodedCaCert } = server.info;\n *\n * await server.stop();\n * ```\n */\n createHttpServer(options: HttpServerOptions): Promise<HttpServer>;\n}\n"],"mappings":";;AAMA,MAAa,mBAAmB;;AA0HhC,IAAsB,kBAAtB,MAA6D;CAC3D;CAEA,YAAY,SAA6B;AACvC,OAAK,SAAS,QAAQ,iBAAiB;;;CAIzC,UAAoB,UAAkB,OAAqC;AACzE,MAAI,CAAC,MAAO,QAAO;GAAE,OAAO;GAAG,KAAK,WAAW;GAAG;AAClD,UAAQ,MAAM,MAAd;GACE,KAAK;AACH,QAAI,MAAM,OAAO,SAAU,QAAO;AAClC,WAAO;KAAE,OAAO,MAAM;KAAO,KAAK,MAAM;KAAK;GAC/C,KAAK;AACH,QAAI,MAAM,UAAU,SAAU,QAAO;AACrC,WAAO;KAAE,OAAO,MAAM;KAAQ,KAAK,WAAW;KAAG;GACnD,KAAK;AACH,QAAI,MAAM,SAAS,SAAU,QAAO;AACpC,WAAO;KAAE,OAAO,WAAW,MAAM;KAAQ,KAAK,WAAW;KAAG"}
|
|
@@ -112,11 +112,74 @@ declare abstract class BaseObjectStore implements ObjectStore {
|
|
|
112
112
|
callback: (response: ObjectStoreResponse) => Promise<void>;
|
|
113
113
|
}): Promise<void>;
|
|
114
114
|
}
|
|
115
|
+
/** Configuration for {@link HttpHelpers.createCachingObjectStore} */
|
|
116
|
+
type CacheConfig = {
|
|
117
|
+
/** Filesystem path where the cache persists its data */cachePath: string; /** Hard total size budget in bytes; the cache self-stabilizes near this size */
|
|
118
|
+
maxSizeBytes: number;
|
|
119
|
+
/**
|
|
120
|
+
* Max share of the budget a single file may occupy (0..1); when a file exceeds it, that
|
|
121
|
+
* file's oldest ranges are evicted first. Stops one large scan from flushing the working set.
|
|
122
|
+
*/
|
|
123
|
+
admissionFraction: number; /** Upper bound on previously-evicted (ghost) files remembered to guide readmission; resident files are already byte-bounded */
|
|
124
|
+
maxFilesTracked: number;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Cumulative cache event counters. Surfaced both as lifetime totals (persisted across restarts)
|
|
128
|
+
* and as a per-process session view, @see CacheMetrics.
|
|
129
|
+
*/
|
|
130
|
+
type CacheCounters = {
|
|
131
|
+
/** Requests fully served from cache */hits: number; /** Requests that fell through to upstream */
|
|
132
|
+
misses: number; /** Bytes served from cache */
|
|
133
|
+
bytesServed: number; /** Bytes downloaded from upstream on misses */
|
|
134
|
+
bytesFetched: number; /** Bytes evicted to keep the cache within its total size budget, @see CacheConfig.maxSizeBytes */
|
|
135
|
+
bytesEvictedByBudget: number; /** Bytes evicted because a single file exceeded its allowed share of the budget, @see CacheConfig.admissionFraction */
|
|
136
|
+
bytesEvictedByFileCap: number; /** Files promoted on observed reuse, so they are retained longer than first-time entries */
|
|
137
|
+
promotions: number; /** Previously evicted files that were re-requested and readmitted */
|
|
138
|
+
ghostReadmissions: number;
|
|
139
|
+
};
|
|
140
|
+
/** Snapshot of cache state and counters, @see CachingObjectStore.getMetrics */
|
|
141
|
+
type CacheMetrics = {
|
|
142
|
+
/** Current resident bytes */sizeBytes: number; /** Number of files with resident (cached) bytes */
|
|
143
|
+
residentFiles: number; /** Number of previously-evicted (ghost) files remembered, <= @see CacheConfig.maxFilesTracked */
|
|
144
|
+
ghostFiles: number; /** Counters cumulative across all sessions (persisted) */
|
|
145
|
+
lifetime: CacheCounters; /** The same counters scoped to the current process */
|
|
146
|
+
session: CacheCounters;
|
|
147
|
+
};
|
|
148
|
+
/**
|
|
149
|
+
* Options for caching object store creation, @see HttpHelpers.createCachingObjectStore.
|
|
150
|
+
* Standalone (not extending {@link ObjectStoreOptions}): a caching store is a decorator over
|
|
151
|
+
* `upstream`, so source-store options do not apply to it.
|
|
152
|
+
*/
|
|
153
|
+
interface CachingObjectStoreOptions {
|
|
154
|
+
/** Upstream store consulted on cache misses */
|
|
155
|
+
upstream: ObjectStore;
|
|
156
|
+
/** Cache configuration */
|
|
157
|
+
config: CacheConfig;
|
|
158
|
+
/** Logger instance, no logging is performed when not provided */
|
|
159
|
+
logger?: Logger;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* An {@link ObjectStore} that serves byte ranges from a persistent local cache, fetching misses
|
|
163
|
+
* from an upstream store. This is the single handle for the cache: pass it as
|
|
164
|
+
* {@link RequestHandlerOptions.store}, read {@link CachingObjectStore.getMetrics}, and dispose it
|
|
165
|
+
* to release the cache, @see HttpHelpers.createCachingObjectStore.
|
|
166
|
+
*/
|
|
167
|
+
interface CachingObjectStore extends ObjectStore, AsyncDisposable {
|
|
168
|
+
/** Instantaneous cache state plus lifetime/session counters */
|
|
169
|
+
getMetrics(): CacheMetrics;
|
|
170
|
+
/** Drop all cached data and zero the counters (test/benchmark use) */
|
|
171
|
+
reset(): Promise<void>;
|
|
172
|
+
}
|
|
115
173
|
/** Object store base URL in format accepted by Apache DataFusion and DuckDB */
|
|
116
174
|
type ObjectStoreUrl = Branded<string, "PFrameInternal.ObjectStoreUrl">;
|
|
117
175
|
/** HTTP(S) request handler creation options */
|
|
118
176
|
type RequestHandlerOptions = {
|
|
119
|
-
/**
|
|
177
|
+
/**
|
|
178
|
+
* Object store to serve files from. Compose caching by wrapping the upstream store with
|
|
179
|
+
* {@link HttpHelpers.createCachingObjectStore} and passing the result here,
|
|
180
|
+
* @see HttpHelpers.createFsStore
|
|
181
|
+
*/
|
|
182
|
+
store: ObjectStore;
|
|
120
183
|
};
|
|
121
184
|
/** Server configuration options */
|
|
122
185
|
type HttpServerOptions = {
|
|
@@ -169,6 +232,12 @@ interface HttpHelpers {
|
|
|
169
232
|
* Rejects if the provided path does not exist or is not a directory.
|
|
170
233
|
*/
|
|
171
234
|
createFsStore(options: FsStoreOptions): Promise<ObjectStore>;
|
|
235
|
+
/**
|
|
236
|
+
* Wrap an upstream object store in a persistent byte-range cache backed by SQLite.
|
|
237
|
+
* The returned store is itself an {@link ObjectStore} (pass it to {@link createRequestHandler})
|
|
238
|
+
* and additionally exposes metrics and reset. Dispose it to close the cache database.
|
|
239
|
+
*/
|
|
240
|
+
createCachingObjectStore(options: CachingObjectStoreOptions): Promise<CachingObjectStore>;
|
|
172
241
|
/**
|
|
173
242
|
* Create an HTTP request handler for serving files from an object store.
|
|
174
243
|
* Accepts only paths of the form `/<filename>.parquet`, returns 410 otherwise.
|
|
@@ -201,5 +270,5 @@ interface HttpHelpers {
|
|
|
201
270
|
createHttpServer(options: HttpServerOptions): Promise<HttpServer>;
|
|
202
271
|
}
|
|
203
272
|
//#endregion
|
|
204
|
-
export { BaseObjectStore, FileRange, FsStoreOptions, HttpAuthorizationToken, HttpHelpers, HttpMethod, HttpRange, HttpServer, HttpServerInfo, HttpServerOptions, ObjectStore, ObjectStoreOptions, ObjectStoreResponse, ObjectStoreUrl, ParquetExtension, ParquetFileName, PemCertificate, RequestHandlerOptions };
|
|
273
|
+
export { BaseObjectStore, CacheConfig, CacheCounters, CacheMetrics, CachingObjectStore, CachingObjectStoreOptions, FileRange, FsStoreOptions, HttpAuthorizationToken, HttpHelpers, HttpMethod, HttpRange, HttpServer, HttpServerInfo, HttpServerOptions, ObjectStore, ObjectStoreOptions, ObjectStoreResponse, ObjectStoreUrl, ParquetExtension, ParquetFileName, PemCertificate, RequestHandlerOptions };
|
|
205
274
|
//# sourceMappingURL=http_helpers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http_helpers.d.ts","names":[],"sources":["../../../src/pframe/internal_api/http_helpers.ts"],"mappings":";;;;;;;cAMa,gBAAA;AAAb;AAAA,KAGY,eAAA,GAAkB,OAAA;AAAA,KAElB,SAAA;EALuC,sCAOjD,KAAA,UAJU;EAMV,GAAA;AAAA;;KAIU,SAAA;EARA;;;;;AAQZ;;;;EAWM,IAAA,aAEA;EAAA,KAAA,UAcA;EAZA,GAAA;AAAA;EA4BA;;;AAIN;;;;;AAGA;EAvBM,IAAA;EAEA,MAAA;AAAA;EA+BA;;;;;;;;;EAnBA,IAAA,YAmCe;EAjCf,MAAA;AAAA;;KAIM,UAAA;;KAGA,mBAAA;EAoCoB;;;;EA9B1B,IAAA;AAAA;2DAIA,IAAA;AAAA;EAyCQ,qEArCR,IAAA,yBAuCqB;EArCrB,IAAA;AAAA;EAqCoD,yEAjCpD,IAAA,QA4BQ;EA1BR,IAAA,UA4BA;EA1BA,KAAA,EAAO,SAAA,EA2BP;EAzBA,IAAA,GAAO,QAAA;AAAA;;UAII,kBAAA;EAuBU;EArBzB,MAAA,GAAS,MAAA;AAAA;;UAIM,cAAA,SAAuB,kBAAA;EAkBnC;EAhBH,OAAA;AAAA;AAAA,UAGe,WAAA;EAmBY;;;;;EAb3B,OAAA,CACE,QAAA,EAAU,eAAA,EACV,MAAA;IACE,MAAA,EAAQ,UAAA;IACR,KAAA,GAAQ,SAAA;IACR,MAAA,EAAQ,WAAA;IACR,QAAA,GAAW,QAAA,EAAU,mBAAA,KAAwB,OAAA;EAAA;AAAA;;uBAM7B,eAAA,YAA2B,WAAA;EAAA,mBAC5B,MAAA,EAAQ,MAAA;cAEf,OAAA,EAAS,kBAAA;EAFM;EAAA,UAOjB,SAAA,CAAU,QAAA,UAAkB,KAAA,GAAQ,SAAA,GAAY,SAAA;EALrC;;;;;EAAA,SAyBZ,OAAA,CACP,QAAA,EAAU,eAAA,EACV,MAAA;IACE,MAAA,EAAQ,UAAA;IACR,KAAA,GAAQ,SAAA;IACR,MAAA,EAAQ,WAAA;IACR,QAAA,GAAW,QAAA,EAAU,mBAAA,KAAwB,OAAA;EAAA,IAE9C,OAAA;AAAA;;KAIO,cAAA,GAAiB,OAAA;;KAGjB,qBAAA;
|
|
1
|
+
{"version":3,"file":"http_helpers.d.ts","names":[],"sources":["../../../src/pframe/internal_api/http_helpers.ts"],"mappings":";;;;;;;cAMa,gBAAA;AAAb;AAAA,KAGY,eAAA,GAAkB,OAAA;AAAA,KAElB,SAAA;EALuC,sCAOjD,KAAA,UAJU;EAMV,GAAA;AAAA;;KAIU,SAAA;EARA;;;;;AAQZ;;;;EAWM,IAAA,aAEA;EAAA,KAAA,UAcA;EAZA,GAAA;AAAA;EA4BA;;;AAIN;;;;;AAGA;EAvBM,IAAA;EAEA,MAAA;AAAA;EA+BA;;;;;;;;;EAnBA,IAAA,YAmCe;EAjCf,MAAA;AAAA;;KAIM,UAAA;;KAGA,mBAAA;EAoCoB;;;;EA9B1B,IAAA;AAAA;2DAIA,IAAA;AAAA;EAyCQ,qEArCR,IAAA,yBAuCqB;EArCrB,IAAA;AAAA;EAqCoD,yEAjCpD,IAAA,QA4BQ;EA1BR,IAAA,UA4BA;EA1BA,KAAA,EAAO,SAAA,EA2BP;EAzBA,IAAA,GAAO,QAAA;AAAA;;UAII,kBAAA;EAuBU;EArBzB,MAAA,GAAS,MAAA;AAAA;;UAIM,cAAA,SAAuB,kBAAA;EAkBnC;EAhBH,OAAA;AAAA;AAAA,UAGe,WAAA;EAmBY;;;;;EAb3B,OAAA,CACE,QAAA,EAAU,eAAA,EACV,MAAA;IACE,MAAA,EAAQ,UAAA;IACR,KAAA,GAAQ,SAAA;IACR,MAAA,EAAQ,WAAA;IACR,QAAA,GAAW,QAAA,EAAU,mBAAA,KAAwB,OAAA;EAAA;AAAA;;uBAM7B,eAAA,YAA2B,WAAA;EAAA,mBAC5B,MAAA,EAAQ,MAAA;cAEf,OAAA,EAAS,kBAAA;EAFM;EAAA,UAOjB,SAAA,CAAU,QAAA,UAAkB,KAAA,GAAQ,SAAA,GAAY,SAAA;EALrC;;;;;EAAA,SAyBZ,OAAA,CACP,QAAA,EAAU,eAAA,EACV,MAAA;IACE,MAAA,EAAQ,UAAA;IACR,KAAA,GAAQ,SAAA;IACR,MAAA,EAAQ,WAAA;IACR,QAAA,GAAW,QAAA,EAAU,mBAAA,KAAwB,OAAA;EAAA,IAE9C,OAAA;AAAA;;KAIO,WAAA;EAPN,wDASJ,SAAA,UARI;EAUJ,YAAA;EAVe;;;;EAef,iBAAA,UAbU;EAeV,eAAA;AAAA;;;;;KAOU,aAAA;EAPV,uCASA,IAAA,UATe;EAWf,MAAA,UAJuB;EAMvB,WAAA,UANuB;EAQvB,YAAA,UAJA;EAMA,oBAAA,UAFA;EAIA,qBAAA;EAEA,UAAA,UAEA;EAAA,iBAAA;AAAA;AAIF;AAAA,KAAY,YAAA;+BAEV,SAAA;EAEA,aAAA,UAEA;EAAA,UAAA,UAEU;EAAV,QAAA,EAAU,aAAA,EAED;EAAT,OAAA,EAAS,aAAA;AAAA;AAQX;;;;;AAAA,UAAiB,yBAAA;EAMA;EAJf,QAAA,EAAU,WAAA;EAAV;EAEA,MAAA,EAAQ,WAAA;EAAR;EAEA,MAAA,GAAS,MAAA;AAAA;;;;AASX;;;UAAiB,kBAAA,SAA2B,WAAA,EAAa,eAAA;EAI9C;EAFT,UAAA,IAAc,YAAA;EAFyC;EAIvD,KAAA,IAAS,OAAA;AAAA;;KAIC,cAAA,GAAiB,OAAA;;KAGjB,qBAAA;EAPV;;;;AAIF;EASE,KAAA,EAAO,WAAA;AAAA;;KAIG,iBAAA;EAVA,8EAYV,OAAA,EAAS,eAAA;EAET,IAAA,WARkB;EAUlB,MAAA,SAN2B;EAQ3B,OAAA;AAAA;;;;;;;;AAWF;KAAY,sBAAA,GAAyB,OAAA;;;;AAcrC;;;;;AAGA;;;;KAHY,cAAA,GAAiB,OAAA;;KAGjB,cAAA;EAMmB,wEAJ7B,GAAA,EAAK,cAAA,EAAL;EAEA,SAAA,GAAY,sBAAA,EAAZ;EAEA,aAAA,GAAgB,aAAA,CAAc,cAAA;AAAA;;UAIf,UAAA;EAJ6B;EAAA,IAMxC,IAAA,IAAQ,cAAA;EAFG;EAAA,IAIX,OAAA,IAAW,OAAA;;EAEf,IAAA,IAAQ,OAAA;AAAA;;UAIO,WAAA;EAJA;;;;EASf,aAAA,CAAc,OAAA,EAAS,cAAA,GAAiB,OAAA,CAAQ,WAAA;EAThD;;;;AAIF;EAYE,wBAAA,CAAyB,OAAA,EAAS,yBAAA,GAA4B,OAAA,CAAQ,kBAAA;;;;;;EAOtE,oBAAA,CAAqB,OAAA,EAAS,qBAAA,GAAwB,eAAA;EAPQ;;;;;;;;;;;;;;;;;;;;;;;EAgC9D,gBAAA,CAAiB,OAAA,EAAS,iBAAA,GAAoB,OAAA,CAAQ,UAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http_helpers.js","names":[],"sources":["../../../src/pframe/internal_api/http_helpers.ts"],"sourcesContent":["import type { Readable } from \"node:stream\";\nimport type { RequestListener } from \"node:http\";\nimport type { Branded, Base64Encoded } from \"@milaboratories/pl-model-common\";\nimport type { Logger } from \"./common\";\n\n/** Parquet file extension */\nexport const ParquetExtension = \".parquet\" as const;\n\n/** Parquet file name */\nexport type ParquetFileName = Branded<`${string}.parquet`, \"PFrameInternal.ParquetFileName\">;\n\nexport type FileRange = {\n /** Start byte position (inclusive) */\n start: number;\n /** End byte position (inclusive) */\n end: number;\n};\n\n/** HTTP range as of RFC 9110 <https://datatracker.ietf.org/doc/html/rfc9110#name-range> */\nexport type HttpRange =\n | {\n /**\n * Get file content in the specified byte range\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=0-1023\n * ```\n */\n type: \"bounded\";\n /** Start byte position (inclusive) */\n start: number;\n /** End byte position (inclusive) */\n end: number;\n }\n | {\n /**\n * Get byte range starting from the specified offset\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=1024-\n * ```\n */\n type: \"offset\";\n /** Start byte position (inclusive) */\n offset: number;\n }\n | {\n /**\n * Get byte range starting from the specified suffix\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=-1024\n * ```\n */\n type: \"suffix\";\n /** End byte position (inclusive) */\n suffix: number;\n };\n\n/** HTTP method passed to object store */\nexport type HttpMethod = \"GET\" | \"HEAD\";\n\n/** HTTP response from object store */\nexport type ObjectStoreResponse =\n | {\n /**\n * Will be translated to 500 Internal Server Error by the handler\n * or 408 Request Timeout if the request was aborted\n */\n type: \"InternalError\";\n }\n | {\n /** Will be translated to 404 Not Found by the handler */\n type: \"NotFound\";\n }\n | {\n /** Will be translated to 416 Range Not Satisfiable by the handler */\n type: \"RangeNotSatisfiable\";\n /** Total file size in bytes */\n size: number;\n }\n | {\n /** Will be translated to 200 OK or 206 Partial Content by the handler */\n type: \"Ok\";\n /** Total file size in bytes */\n size: number;\n /** File range translated from HTTP range */\n range: FileRange;\n /** Stream of file content, undefined for HEAD requests */\n data?: Readable;\n };\n\n/** Common options for object store creation */\nexport interface ObjectStoreOptions {\n /** Logger instance, no logging is performed when not provided */\n logger?: Logger;\n}\n\n/** Options for file system object store creation */\nexport interface FsStoreOptions extends ObjectStoreOptions {\n /** Local directory to serve files from */\n rootDir: string;\n}\n\nexport interface ObjectStore {\n /**\n * Proxy HTTP(S) request for parquet file to object store.\n * Callback promise resolves when stream is closed by handler @see HttpHelpers.createRequestHandler\n * Callback API is used so that ObjectStore can limit the number of concurrent requests.\n */\n request(\n filename: ParquetFileName,\n params: {\n method: HttpMethod;\n range?: HttpRange;\n signal: AbortSignal;\n callback: (response: ObjectStoreResponse) => Promise<void>;\n },\n ): void;\n}\n\n/** File system abstraction for request handler factory, @see HttpHelpers.createRequestHandler */\nexport abstract class BaseObjectStore implements ObjectStore {\n protected readonly logger: Logger;\n\n constructor(options: ObjectStoreOptions) {\n this.logger = options.logger ?? (() => {});\n }\n\n /** Translate HTTP range to file range, @returns null if the range is not satisfiable */\n protected translate(fileSize: number, range?: HttpRange): FileRange | null {\n if (!range) return { start: 0, end: fileSize - 1 };\n switch (range.type) {\n case \"bounded\":\n if (range.end >= fileSize) return null;\n return { start: range.start, end: range.end };\n case \"offset\":\n if (range.offset >= fileSize) return null;\n return { start: range.offset, end: fileSize - 1 };\n case \"suffix\":\n if (range.suffix > fileSize) return null;\n return { start: fileSize - range.suffix, end: fileSize - 1 };\n }\n }\n\n /**\n * Proxy HTTP(S) request for parquet file to object store.\n * Callback promise resolves when stream is closed by handler @see HttpHelpers.createRequestHandler\n * Callback API is used so that ObjectStore can limit the number of concurrent requests.\n */\n abstract request(\n filename: ParquetFileName,\n params: {\n method: HttpMethod;\n range?: HttpRange;\n signal: AbortSignal;\n callback: (response: ObjectStoreResponse) => Promise<void>;\n },\n ): Promise<void>;\n}\n\n/** Object store base URL in format accepted by Apache DataFusion and DuckDB */\nexport type ObjectStoreUrl = Branded<string, \"PFrameInternal.ObjectStoreUrl\">;\n\n/** HTTP(S) request handler creation options */\nexport type RequestHandlerOptions = {\n /** Object store to serve files from, @see HttpHelpers.createFsStore */\n store: ObjectStore;\n /** Here will go caching options... */\n};\n\n/** Server configuration options */\nexport type HttpServerOptions = {\n /** HTTP(S) request handler function, @see HttpHelpers.createRequestHandler */\n handler: RequestListener;\n /** Port to bind to, @default 0 for auto-assignment */\n port?: number;\n /** Do not apply authorization middleware to @param handler */\n noAuth?: true;\n /** Downgrade default HTTPS server to plain HTTP, @warning use only for testing */\n noHttps?: true;\n};\n\n/**\n * Long unique opaque string for use in Bearer authorization header\n *\n * @example\n * ```ts\n * request.setHeader('Authorization', `Bearer ${authToken}`);\n * ```\n */\nexport type HttpAuthorizationToken = Branded<string, \"PFrameInternal.HttpAuthorizationToken\">;\n\n/**\n * TLS certificate in PEM format\n *\n * @example\n * ```txt\n * -----BEGIN CERTIFICATE-----\n * MIIC2zCCAcOgAwIBAgIJaVW7...\n * ...\n * ...Yf9CRK8fgnukKM7TJ\n * -----END CERTIFICATE-----\n * ```\n */\nexport type PemCertificate = Branded<string, \"PFrameInternal.PemCertificate\">;\n\n/** HTTP(S) server connection settings, {@link HttpHelpers.createHttpServer} */\nexport type HttpServerInfo = {\n /** URL of the HTTP(S) server formatted as `http{s}://<host>:<port>/` */\n url: ObjectStoreUrl;\n /** Authorization token for Bearer scheme, undefined when @see HttpServerOptions.noAuth flag is set */\n authToken?: HttpAuthorizationToken;\n /** Encoded CA certificate of HTTPS server, undefined when @see HttpServerOptions.noHttps flag is set */\n encodedCaCert?: Base64Encoded<PemCertificate>;\n};\n\n/** HTTP(S) server information and controls, @see HttpHelpers.createHttpServer */\nexport interface HttpServer {\n /** Server configuration information for initiating connections from clients */\n get info(): HttpServerInfo;\n /** Promise that resolves when the server is stopped */\n get stopped(): Promise<void>;\n /** Request server stop, returns the same promise as @see HttpServer.stopped */\n stop(): Promise<void>;\n}\n\n/** List of HTTP(S) related helper functions exposed by PFrame module */\nexport interface HttpHelpers {\n /**\n * Create an object store for serving files from a local directory.\n * Rejects if the provided path does not exist or is not a directory.\n */\n createFsStore(options: FsStoreOptions): Promise<ObjectStore>;\n\n /**\n * Create an HTTP request handler for serving files from an object store.\n * Accepts only paths of the form `/<filename>.parquet`, returns 410 otherwise.\n * Assumes that files are immutable (and sets cache headers accordingly).\n */\n createRequestHandler(options: RequestHandlerOptions): RequestListener;\n\n /**\n * Serve HTTP(S) requests using the provided handler on localhost port.\n * @returns promise that resolves when the server has stopped.\n *\n * @example\n * ```ts\n * const rootDir = '/path/to/directory/with/parquet/files';\n *\n * let store = await HttpHelpers.createFsStore({ rootDir }).catch((err: unknown) => {\n * throw new Error(`Failed to create file store for ${rootDir} - ${ensureError(err)}`);\n * });\n *\n * const server = await HttpHelpers.createHttpServer({\n * handler: HttpHelpers.createRequestHandler({ store }),\n * }).catch((err: unknown) => {\n * throw new Error(`Failed to start HTTPS server - ${ensureError(err)}`);\n * });\n *\n * const { url, authToken, encodedCaCert } = server.info;\n *\n * await server.stop();\n * ```\n */\n createHttpServer(options: HttpServerOptions): Promise<HttpServer>;\n}\n"],"mappings":";;AAMA,MAAa,mBAAmB;;AA0HhC,IAAsB,kBAAtB,MAA6D;CAC3D;CAEA,YAAY,SAA6B;AACvC,OAAK,SAAS,QAAQ,iBAAiB;;;CAIzC,UAAoB,UAAkB,OAAqC;AACzE,MAAI,CAAC,MAAO,QAAO;GAAE,OAAO;GAAG,KAAK,WAAW;GAAG;AAClD,UAAQ,MAAM,MAAd;GACE,KAAK;AACH,QAAI,MAAM,OAAO,SAAU,QAAO;AAClC,WAAO;KAAE,OAAO,MAAM;KAAO,KAAK,MAAM;KAAK;GAC/C,KAAK;AACH,QAAI,MAAM,UAAU,SAAU,QAAO;AACrC,WAAO;KAAE,OAAO,MAAM;KAAQ,KAAK,WAAW;KAAG;GACnD,KAAK;AACH,QAAI,MAAM,SAAS,SAAU,QAAO;AACpC,WAAO;KAAE,OAAO,WAAW,MAAM;KAAQ,KAAK,WAAW;KAAG"}
|
|
1
|
+
{"version":3,"file":"http_helpers.js","names":[],"sources":["../../../src/pframe/internal_api/http_helpers.ts"],"sourcesContent":["import type { Readable } from \"node:stream\";\nimport type { RequestListener } from \"node:http\";\nimport type { Branded, Base64Encoded } from \"@milaboratories/pl-model-common\";\nimport type { Logger } from \"./common\";\n\n/** Parquet file extension */\nexport const ParquetExtension = \".parquet\" as const;\n\n/** Parquet file name */\nexport type ParquetFileName = Branded<`${string}.parquet`, \"PFrameInternal.ParquetFileName\">;\n\nexport type FileRange = {\n /** Start byte position (inclusive) */\n start: number;\n /** End byte position (inclusive) */\n end: number;\n};\n\n/** HTTP range as of RFC 9110 <https://datatracker.ietf.org/doc/html/rfc9110#name-range> */\nexport type HttpRange =\n | {\n /**\n * Get file content in the specified byte range\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=0-1023\n * ```\n */\n type: \"bounded\";\n /** Start byte position (inclusive) */\n start: number;\n /** End byte position (inclusive) */\n end: number;\n }\n | {\n /**\n * Get byte range starting from the specified offset\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=1024-\n * ```\n */\n type: \"offset\";\n /** Start byte position (inclusive) */\n offset: number;\n }\n | {\n /**\n * Get byte range starting from the specified suffix\n *\n * @example\n * ```\n * GET /file.parquet HTTP/1.1\n * Range: bytes=-1024\n * ```\n */\n type: \"suffix\";\n /** End byte position (inclusive) */\n suffix: number;\n };\n\n/** HTTP method passed to object store */\nexport type HttpMethod = \"GET\" | \"HEAD\";\n\n/** HTTP response from object store */\nexport type ObjectStoreResponse =\n | {\n /**\n * Will be translated to 500 Internal Server Error by the handler\n * or 408 Request Timeout if the request was aborted\n */\n type: \"InternalError\";\n }\n | {\n /** Will be translated to 404 Not Found by the handler */\n type: \"NotFound\";\n }\n | {\n /** Will be translated to 416 Range Not Satisfiable by the handler */\n type: \"RangeNotSatisfiable\";\n /** Total file size in bytes */\n size: number;\n }\n | {\n /** Will be translated to 200 OK or 206 Partial Content by the handler */\n type: \"Ok\";\n /** Total file size in bytes */\n size: number;\n /** File range translated from HTTP range */\n range: FileRange;\n /** Stream of file content, undefined for HEAD requests */\n data?: Readable;\n };\n\n/** Common options for object store creation */\nexport interface ObjectStoreOptions {\n /** Logger instance, no logging is performed when not provided */\n logger?: Logger;\n}\n\n/** Options for file system object store creation */\nexport interface FsStoreOptions extends ObjectStoreOptions {\n /** Local directory to serve files from */\n rootDir: string;\n}\n\nexport interface ObjectStore {\n /**\n * Proxy HTTP(S) request for parquet file to object store.\n * Callback promise resolves when stream is closed by handler @see HttpHelpers.createRequestHandler\n * Callback API is used so that ObjectStore can limit the number of concurrent requests.\n */\n request(\n filename: ParquetFileName,\n params: {\n method: HttpMethod;\n range?: HttpRange;\n signal: AbortSignal;\n callback: (response: ObjectStoreResponse) => Promise<void>;\n },\n ): void;\n}\n\n/** File system abstraction for request handler factory, @see HttpHelpers.createRequestHandler */\nexport abstract class BaseObjectStore implements ObjectStore {\n protected readonly logger: Logger;\n\n constructor(options: ObjectStoreOptions) {\n this.logger = options.logger ?? (() => {});\n }\n\n /** Translate HTTP range to file range, @returns null if the range is not satisfiable */\n protected translate(fileSize: number, range?: HttpRange): FileRange | null {\n if (!range) return { start: 0, end: fileSize - 1 };\n switch (range.type) {\n case \"bounded\":\n if (range.end >= fileSize) return null;\n return { start: range.start, end: range.end };\n case \"offset\":\n if (range.offset >= fileSize) return null;\n return { start: range.offset, end: fileSize - 1 };\n case \"suffix\":\n if (range.suffix > fileSize) return null;\n return { start: fileSize - range.suffix, end: fileSize - 1 };\n }\n }\n\n /**\n * Proxy HTTP(S) request for parquet file to object store.\n * Callback promise resolves when stream is closed by handler @see HttpHelpers.createRequestHandler\n * Callback API is used so that ObjectStore can limit the number of concurrent requests.\n */\n abstract request(\n filename: ParquetFileName,\n params: {\n method: HttpMethod;\n range?: HttpRange;\n signal: AbortSignal;\n callback: (response: ObjectStoreResponse) => Promise<void>;\n },\n ): Promise<void>;\n}\n\n/** Configuration for {@link HttpHelpers.createCachingObjectStore} */\nexport type CacheConfig = {\n /** Filesystem path where the cache persists its data */\n cachePath: string;\n /** Hard total size budget in bytes; the cache self-stabilizes near this size */\n maxSizeBytes: number;\n /**\n * Max share of the budget a single file may occupy (0..1); when a file exceeds it, that\n * file's oldest ranges are evicted first. Stops one large scan from flushing the working set.\n */\n admissionFraction: number;\n /** Upper bound on previously-evicted (ghost) files remembered to guide readmission; resident files are already byte-bounded */\n maxFilesTracked: number;\n};\n\n/**\n * Cumulative cache event counters. Surfaced both as lifetime totals (persisted across restarts)\n * and as a per-process session view, @see CacheMetrics.\n */\nexport type CacheCounters = {\n /** Requests fully served from cache */\n hits: number;\n /** Requests that fell through to upstream */\n misses: number;\n /** Bytes served from cache */\n bytesServed: number;\n /** Bytes downloaded from upstream on misses */\n bytesFetched: number;\n /** Bytes evicted to keep the cache within its total size budget, @see CacheConfig.maxSizeBytes */\n bytesEvictedByBudget: number;\n /** Bytes evicted because a single file exceeded its allowed share of the budget, @see CacheConfig.admissionFraction */\n bytesEvictedByFileCap: number;\n /** Files promoted on observed reuse, so they are retained longer than first-time entries */\n promotions: number;\n /** Previously evicted files that were re-requested and readmitted */\n ghostReadmissions: number;\n};\n\n/** Snapshot of cache state and counters, @see CachingObjectStore.getMetrics */\nexport type CacheMetrics = {\n /** Current resident bytes */\n sizeBytes: number;\n /** Number of files with resident (cached) bytes */\n residentFiles: number;\n /** Number of previously-evicted (ghost) files remembered, <= @see CacheConfig.maxFilesTracked */\n ghostFiles: number;\n /** Counters cumulative across all sessions (persisted) */\n lifetime: CacheCounters;\n /** The same counters scoped to the current process */\n session: CacheCounters;\n};\n\n/**\n * Options for caching object store creation, @see HttpHelpers.createCachingObjectStore.\n * Standalone (not extending {@link ObjectStoreOptions}): a caching store is a decorator over\n * `upstream`, so source-store options do not apply to it.\n */\nexport interface CachingObjectStoreOptions {\n /** Upstream store consulted on cache misses */\n upstream: ObjectStore;\n /** Cache configuration */\n config: CacheConfig;\n /** Logger instance, no logging is performed when not provided */\n logger?: Logger;\n}\n\n/**\n * An {@link ObjectStore} that serves byte ranges from a persistent local cache, fetching misses\n * from an upstream store. This is the single handle for the cache: pass it as\n * {@link RequestHandlerOptions.store}, read {@link CachingObjectStore.getMetrics}, and dispose it\n * to release the cache, @see HttpHelpers.createCachingObjectStore.\n */\nexport interface CachingObjectStore extends ObjectStore, AsyncDisposable {\n /** Instantaneous cache state plus lifetime/session counters */\n getMetrics(): CacheMetrics;\n /** Drop all cached data and zero the counters (test/benchmark use) */\n reset(): Promise<void>;\n}\n\n/** Object store base URL in format accepted by Apache DataFusion and DuckDB */\nexport type ObjectStoreUrl = Branded<string, \"PFrameInternal.ObjectStoreUrl\">;\n\n/** HTTP(S) request handler creation options */\nexport type RequestHandlerOptions = {\n /**\n * Object store to serve files from. Compose caching by wrapping the upstream store with\n * {@link HttpHelpers.createCachingObjectStore} and passing the result here,\n * @see HttpHelpers.createFsStore\n */\n store: ObjectStore;\n};\n\n/** Server configuration options */\nexport type HttpServerOptions = {\n /** HTTP(S) request handler function, @see HttpHelpers.createRequestHandler */\n handler: RequestListener;\n /** Port to bind to, @default 0 for auto-assignment */\n port?: number;\n /** Do not apply authorization middleware to @param handler */\n noAuth?: true;\n /** Downgrade default HTTPS server to plain HTTP, @warning use only for testing */\n noHttps?: true;\n};\n\n/**\n * Long unique opaque string for use in Bearer authorization header\n *\n * @example\n * ```ts\n * request.setHeader('Authorization', `Bearer ${authToken}`);\n * ```\n */\nexport type HttpAuthorizationToken = Branded<string, \"PFrameInternal.HttpAuthorizationToken\">;\n\n/**\n * TLS certificate in PEM format\n *\n * @example\n * ```txt\n * -----BEGIN CERTIFICATE-----\n * MIIC2zCCAcOgAwIBAgIJaVW7...\n * ...\n * ...Yf9CRK8fgnukKM7TJ\n * -----END CERTIFICATE-----\n * ```\n */\nexport type PemCertificate = Branded<string, \"PFrameInternal.PemCertificate\">;\n\n/** HTTP(S) server connection settings, {@link HttpHelpers.createHttpServer} */\nexport type HttpServerInfo = {\n /** URL of the HTTP(S) server formatted as `http{s}://<host>:<port>/` */\n url: ObjectStoreUrl;\n /** Authorization token for Bearer scheme, undefined when @see HttpServerOptions.noAuth flag is set */\n authToken?: HttpAuthorizationToken;\n /** Encoded CA certificate of HTTPS server, undefined when @see HttpServerOptions.noHttps flag is set */\n encodedCaCert?: Base64Encoded<PemCertificate>;\n};\n\n/** HTTP(S) server information and controls, @see HttpHelpers.createHttpServer */\nexport interface HttpServer {\n /** Server configuration information for initiating connections from clients */\n get info(): HttpServerInfo;\n /** Promise that resolves when the server is stopped */\n get stopped(): Promise<void>;\n /** Request server stop, returns the same promise as @see HttpServer.stopped */\n stop(): Promise<void>;\n}\n\n/** List of HTTP(S) related helper functions exposed by PFrame module */\nexport interface HttpHelpers {\n /**\n * Create an object store for serving files from a local directory.\n * Rejects if the provided path does not exist or is not a directory.\n */\n createFsStore(options: FsStoreOptions): Promise<ObjectStore>;\n\n /**\n * Wrap an upstream object store in a persistent byte-range cache backed by SQLite.\n * The returned store is itself an {@link ObjectStore} (pass it to {@link createRequestHandler})\n * and additionally exposes metrics and reset. Dispose it to close the cache database.\n */\n createCachingObjectStore(options: CachingObjectStoreOptions): Promise<CachingObjectStore>;\n\n /**\n * Create an HTTP request handler for serving files from an object store.\n * Accepts only paths of the form `/<filename>.parquet`, returns 410 otherwise.\n * Assumes that files are immutable (and sets cache headers accordingly).\n */\n createRequestHandler(options: RequestHandlerOptions): RequestListener;\n\n /**\n * Serve HTTP(S) requests using the provided handler on localhost port.\n * @returns promise that resolves when the server has stopped.\n *\n * @example\n * ```ts\n * const rootDir = '/path/to/directory/with/parquet/files';\n *\n * let store = await HttpHelpers.createFsStore({ rootDir }).catch((err: unknown) => {\n * throw new Error(`Failed to create file store for ${rootDir} - ${ensureError(err)}`);\n * });\n *\n * const server = await HttpHelpers.createHttpServer({\n * handler: HttpHelpers.createRequestHandler({ store }),\n * }).catch((err: unknown) => {\n * throw new Error(`Failed to start HTTPS server - ${ensureError(err)}`);\n * });\n *\n * const { url, authToken, encodedCaCert } = server.info;\n *\n * await server.stop();\n * ```\n */\n createHttpServer(options: HttpServerOptions): Promise<HttpServer>;\n}\n"],"mappings":";;AAMA,MAAa,mBAAmB;;AA0HhC,IAAsB,kBAAtB,MAA6D;CAC3D;CAEA,YAAY,SAA6B;AACvC,OAAK,SAAS,QAAQ,iBAAiB;;;CAIzC,UAAoB,UAAkB,OAAqC;AACzE,MAAI,CAAC,MAAO,QAAO;GAAE,OAAO;GAAG,KAAK,WAAW;GAAG;AAClD,UAAQ,MAAM,MAAd;GACE,KAAK;AACH,QAAI,MAAM,OAAO,SAAU,QAAO;AAClC,WAAO;KAAE,OAAO,MAAM;KAAO,KAAK,MAAM;KAAK;GAC/C,KAAK;AACH,QAAI,MAAM,UAAU,SAAU,QAAO;AACrC,WAAO;KAAE,OAAO,MAAM;KAAQ,KAAK,WAAW;KAAG;GACnD,KAAK;AACH,QAAI,MAAM,SAAS,SAAU,QAAO;AACpC,WAAO;KAAE,OAAO,WAAW,MAAM;KAAQ,KAAK,WAAW;KAAG"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PTableV11, PTableV12 } from "./table.js";
|
|
2
2
|
import { AxisQualification, ColumnAxesWithQualifications, ConstantAxisFilter, Logger, PFrameId, PTableId } from "./common.js";
|
|
3
3
|
import { PFrameReadAPIV14, PFrameReadAPIV15, UniqueValuesRequestV2 } from "./api_read.js";
|
|
4
|
-
import { BaseObjectStore, FileRange, FsStoreOptions, HttpAuthorizationToken, HttpHelpers, HttpMethod, HttpRange, HttpServer, HttpServerInfo, HttpServerOptions, ObjectStore, ObjectStoreOptions, ObjectStoreResponse, ObjectStoreUrl, ParquetExtension, ParquetFileName, PemCertificate, RequestHandlerOptions } from "./http_helpers.js";
|
|
4
|
+
import { BaseObjectStore, CacheConfig, CacheCounters, CacheMetrics, CachingObjectStore, CachingObjectStoreOptions, FileRange, FsStoreOptions, HttpAuthorizationToken, HttpHelpers, HttpMethod, HttpRange, HttpServer, HttpServerInfo, HttpServerOptions, ObjectStore, ObjectStoreOptions, ObjectStoreResponse, ObjectStoreUrl, ParquetExtension, ParquetFileName, PemCertificate, RequestHandlerOptions } from "./http_helpers.js";
|
|
5
5
|
import { AddColumnEntryV2, DataInfo, DataInfoExtension, DataInfoV2, FilePath, PColumnValueTypeSpec, PFrameBlobId, PFrameDataSourceV2, PFrameFactoryAPIV6, SpecExtension } from "./api_factory.js";
|
|
6
6
|
import { DeleteColumnFromColumnsRequest, DeleteColumnFromColumnsResponse } from "./delete_column.js";
|
|
7
7
|
import { DiscoverColumnsConstraints, DiscoverColumnsMappingVariant, DiscoverColumnsRequestV2, DiscoverColumnsResponse, DiscoverColumnsResponseHit, DiscoverColumnsResponseQualifications, DiscoverColumnsStepInfo, MatcherMap, MultiAxisSelector, MultiColumnSelector, StringMatcher } from "./discover_columns.js";
|
|
@@ -13,7 +13,7 @@ import { SingleAxisSelector as SingleAxisSelector$1 } from "@milaboratories/pl-m
|
|
|
13
13
|
|
|
14
14
|
//#region src/pframe/internal_api/index.d.ts
|
|
15
15
|
declare namespace index_d_exports {
|
|
16
|
-
export { AddColumnEntryV2, ArtificialColumnJoinEntry, AxisQualification, BaseObjectStore, ColumnAxesWithQualifications, ColumnJoinEntry, ConstantAxisFilter, CreateTableRequestV4, DataInfo, DataInfoExtension, DataInfoV2, DeleteColumnFromColumnsRequest, DeleteColumnFromColumnsResponse, DiscoverColumnsConstraints, DiscoverColumnsMappingVariant, DiscoverColumnsRequestV2, DiscoverColumnsResponse, DiscoverColumnsResponseHit, DiscoverColumnsResponseQualifications, DiscoverColumnsStepInfo, EvaluateQueryResponse, FilePath, FileRange, FindColumnResponseQualifications, FindColumnsMappingVariant, FindColumnsRequest, FindColumnsResponse, FindColumnsResponseHit, FsStoreOptions, FullJoinV4, HttpAuthorizationToken, HttpHelpers, HttpMethod, HttpRange, HttpServer, HttpServerInfo, HttpServerOptions, InlineColumnJoinEntry, InnerJoinV4, JoinEntryV4, LegacyQuery, Logger, MatcherMap, MultiAxisSelector, MultiColumnSelector, ObjectStore, ObjectStoreOptions, ObjectStoreResponse, ObjectStoreUrl, OuterJoinV4, PColumnValueTypeSpec, PFrameBlobId, PFrameDataSourceV2, PFrameFactoryAPIV6, PFrameFactoryV8, PFrameFactoryV9, PFrameId, PFrameOptionsV2, PFrameReadAPIV14, PFrameReadAPIV15, PFrameV17, PFrameV18, PFrameWasmAPIV2, PFrameWasmAPIV3, PFrameWasmAPIV4, PFrameWasmAPIV5, PFrameWasmV2, PFrameWasmV3, PFrameWasmV4, PTableId, PTableV11, PTableV12, ParquetExtension, ParquetFileName, PemCertificate, RequestHandlerOptions, SingleAxisSelector$1 as SingleAxisSelector, SlicedColumnJoinEntry, SpecExtension, StringMatcher, UniqueValuesRequestV2 };
|
|
16
|
+
export { AddColumnEntryV2, ArtificialColumnJoinEntry, AxisQualification, BaseObjectStore, CacheConfig, CacheCounters, CacheMetrics, CachingObjectStore, CachingObjectStoreOptions, ColumnAxesWithQualifications, ColumnJoinEntry, ConstantAxisFilter, CreateTableRequestV4, DataInfo, DataInfoExtension, DataInfoV2, DeleteColumnFromColumnsRequest, DeleteColumnFromColumnsResponse, DiscoverColumnsConstraints, DiscoverColumnsMappingVariant, DiscoverColumnsRequestV2, DiscoverColumnsResponse, DiscoverColumnsResponseHit, DiscoverColumnsResponseQualifications, DiscoverColumnsStepInfo, EvaluateQueryResponse, FilePath, FileRange, FindColumnResponseQualifications, FindColumnsMappingVariant, FindColumnsRequest, FindColumnsResponse, FindColumnsResponseHit, FsStoreOptions, FullJoinV4, HttpAuthorizationToken, HttpHelpers, HttpMethod, HttpRange, HttpServer, HttpServerInfo, HttpServerOptions, InlineColumnJoinEntry, InnerJoinV4, JoinEntryV4, LegacyQuery, Logger, MatcherMap, MultiAxisSelector, MultiColumnSelector, ObjectStore, ObjectStoreOptions, ObjectStoreResponse, ObjectStoreUrl, OuterJoinV4, PColumnValueTypeSpec, PFrameBlobId, PFrameDataSourceV2, PFrameFactoryAPIV6, PFrameFactoryV8, PFrameFactoryV9, PFrameId, PFrameOptionsV2, PFrameReadAPIV14, PFrameReadAPIV15, PFrameV17, PFrameV18, PFrameWasmAPIV2, PFrameWasmAPIV3, PFrameWasmAPIV4, PFrameWasmAPIV5, PFrameWasmV2, PFrameWasmV3, PFrameWasmV4, PTableId, PTableV11, PTableV12, ParquetExtension, ParquetFileName, PemCertificate, RequestHandlerOptions, SingleAxisSelector$1 as SingleAxisSelector, SlicedColumnJoinEntry, SpecExtension, StringMatcher, UniqueValuesRequestV2 };
|
|
17
17
|
}
|
|
18
18
|
//#endregion
|
|
19
19
|
export { index_d_exports };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@milaboratories/pl-model-middle-layer",
|
|
3
|
-
"version": "1.30.
|
|
3
|
+
"version": "1.30.5",
|
|
4
4
|
"description": "Common model between middle layer and non-block UI code",
|
|
5
5
|
"files": [
|
|
6
6
|
"./dist/**/*",
|
|
@@ -20,14 +20,14 @@
|
|
|
20
20
|
"es-toolkit": "^1.39.10",
|
|
21
21
|
"utility-types": "^3.11.0",
|
|
22
22
|
"zod": "~3.25.76",
|
|
23
|
-
"@milaboratories/
|
|
24
|
-
"@milaboratories/
|
|
23
|
+
"@milaboratories/pl-model-common": "1.46.1",
|
|
24
|
+
"@milaboratories/helpers": "1.14.2"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/node": "~24.5.2",
|
|
28
28
|
"typescript": "~5.9.3",
|
|
29
|
-
"@milaboratories/build-configs": "2.0.0",
|
|
30
29
|
"@milaboratories/ts-builder": "1.5.0",
|
|
30
|
+
"@milaboratories/build-configs": "2.0.0",
|
|
31
31
|
"@milaboratories/ts-configs": "1.2.3"
|
|
32
32
|
},
|
|
33
33
|
"scripts": {
|
|
@@ -165,14 +165,96 @@ export abstract class BaseObjectStore implements ObjectStore {
|
|
|
165
165
|
): Promise<void>;
|
|
166
166
|
}
|
|
167
167
|
|
|
168
|
+
/** Configuration for {@link HttpHelpers.createCachingObjectStore} */
|
|
169
|
+
export type CacheConfig = {
|
|
170
|
+
/** Filesystem path where the cache persists its data */
|
|
171
|
+
cachePath: string;
|
|
172
|
+
/** Hard total size budget in bytes; the cache self-stabilizes near this size */
|
|
173
|
+
maxSizeBytes: number;
|
|
174
|
+
/**
|
|
175
|
+
* Max share of the budget a single file may occupy (0..1); when a file exceeds it, that
|
|
176
|
+
* file's oldest ranges are evicted first. Stops one large scan from flushing the working set.
|
|
177
|
+
*/
|
|
178
|
+
admissionFraction: number;
|
|
179
|
+
/** Upper bound on previously-evicted (ghost) files remembered to guide readmission; resident files are already byte-bounded */
|
|
180
|
+
maxFilesTracked: number;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Cumulative cache event counters. Surfaced both as lifetime totals (persisted across restarts)
|
|
185
|
+
* and as a per-process session view, @see CacheMetrics.
|
|
186
|
+
*/
|
|
187
|
+
export type CacheCounters = {
|
|
188
|
+
/** Requests fully served from cache */
|
|
189
|
+
hits: number;
|
|
190
|
+
/** Requests that fell through to upstream */
|
|
191
|
+
misses: number;
|
|
192
|
+
/** Bytes served from cache */
|
|
193
|
+
bytesServed: number;
|
|
194
|
+
/** Bytes downloaded from upstream on misses */
|
|
195
|
+
bytesFetched: number;
|
|
196
|
+
/** Bytes evicted to keep the cache within its total size budget, @see CacheConfig.maxSizeBytes */
|
|
197
|
+
bytesEvictedByBudget: number;
|
|
198
|
+
/** Bytes evicted because a single file exceeded its allowed share of the budget, @see CacheConfig.admissionFraction */
|
|
199
|
+
bytesEvictedByFileCap: number;
|
|
200
|
+
/** Files promoted on observed reuse, so they are retained longer than first-time entries */
|
|
201
|
+
promotions: number;
|
|
202
|
+
/** Previously evicted files that were re-requested and readmitted */
|
|
203
|
+
ghostReadmissions: number;
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/** Snapshot of cache state and counters, @see CachingObjectStore.getMetrics */
|
|
207
|
+
export type CacheMetrics = {
|
|
208
|
+
/** Current resident bytes */
|
|
209
|
+
sizeBytes: number;
|
|
210
|
+
/** Number of files with resident (cached) bytes */
|
|
211
|
+
residentFiles: number;
|
|
212
|
+
/** Number of previously-evicted (ghost) files remembered, <= @see CacheConfig.maxFilesTracked */
|
|
213
|
+
ghostFiles: number;
|
|
214
|
+
/** Counters cumulative across all sessions (persisted) */
|
|
215
|
+
lifetime: CacheCounters;
|
|
216
|
+
/** The same counters scoped to the current process */
|
|
217
|
+
session: CacheCounters;
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Options for caching object store creation, @see HttpHelpers.createCachingObjectStore.
|
|
222
|
+
* Standalone (not extending {@link ObjectStoreOptions}): a caching store is a decorator over
|
|
223
|
+
* `upstream`, so source-store options do not apply to it.
|
|
224
|
+
*/
|
|
225
|
+
export interface CachingObjectStoreOptions {
|
|
226
|
+
/** Upstream store consulted on cache misses */
|
|
227
|
+
upstream: ObjectStore;
|
|
228
|
+
/** Cache configuration */
|
|
229
|
+
config: CacheConfig;
|
|
230
|
+
/** Logger instance, no logging is performed when not provided */
|
|
231
|
+
logger?: Logger;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* An {@link ObjectStore} that serves byte ranges from a persistent local cache, fetching misses
|
|
236
|
+
* from an upstream store. This is the single handle for the cache: pass it as
|
|
237
|
+
* {@link RequestHandlerOptions.store}, read {@link CachingObjectStore.getMetrics}, and dispose it
|
|
238
|
+
* to release the cache, @see HttpHelpers.createCachingObjectStore.
|
|
239
|
+
*/
|
|
240
|
+
export interface CachingObjectStore extends ObjectStore, AsyncDisposable {
|
|
241
|
+
/** Instantaneous cache state plus lifetime/session counters */
|
|
242
|
+
getMetrics(): CacheMetrics;
|
|
243
|
+
/** Drop all cached data and zero the counters (test/benchmark use) */
|
|
244
|
+
reset(): Promise<void>;
|
|
245
|
+
}
|
|
246
|
+
|
|
168
247
|
/** Object store base URL in format accepted by Apache DataFusion and DuckDB */
|
|
169
248
|
export type ObjectStoreUrl = Branded<string, "PFrameInternal.ObjectStoreUrl">;
|
|
170
249
|
|
|
171
250
|
/** HTTP(S) request handler creation options */
|
|
172
251
|
export type RequestHandlerOptions = {
|
|
173
|
-
/**
|
|
252
|
+
/**
|
|
253
|
+
* Object store to serve files from. Compose caching by wrapping the upstream store with
|
|
254
|
+
* {@link HttpHelpers.createCachingObjectStore} and passing the result here,
|
|
255
|
+
* @see HttpHelpers.createFsStore
|
|
256
|
+
*/
|
|
174
257
|
store: ObjectStore;
|
|
175
|
-
/** Here will go caching options... */
|
|
176
258
|
};
|
|
177
259
|
|
|
178
260
|
/** Server configuration options */
|
|
@@ -239,6 +321,13 @@ export interface HttpHelpers {
|
|
|
239
321
|
*/
|
|
240
322
|
createFsStore(options: FsStoreOptions): Promise<ObjectStore>;
|
|
241
323
|
|
|
324
|
+
/**
|
|
325
|
+
* Wrap an upstream object store in a persistent byte-range cache backed by SQLite.
|
|
326
|
+
* The returned store is itself an {@link ObjectStore} (pass it to {@link createRequestHandler})
|
|
327
|
+
* and additionally exposes metrics and reset. Dispose it to close the cache database.
|
|
328
|
+
*/
|
|
329
|
+
createCachingObjectStore(options: CachingObjectStoreOptions): Promise<CachingObjectStore>;
|
|
330
|
+
|
|
242
331
|
/**
|
|
243
332
|
* Create an HTTP request handler for serving files from an object store.
|
|
244
333
|
* Accepts only paths of the form `/<filename>.parquet`, returns 410 otherwise.
|