mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 20:44:00 +00:00
feat: profile Enterprise Function workers from official clients
This commit is contained in:
@@ -0,0 +1,334 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { type IncomingHttpHeaders, createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { type Connection, type FunctionProfileKind, connect } from "../lancedb";
|
||||
|
||||
type Response = { body: unknown; status?: number };
|
||||
|
||||
function metadata(kind: FunctionProfileKind, status: string) {
|
||||
return {
|
||||
["profile_id"]: "profile-1",
|
||||
["job_id"]: "job-1",
|
||||
["worker_id"]: "worker-1",
|
||||
["execution_epoch"]: 3,
|
||||
["session_slot"]: 0,
|
||||
kind,
|
||||
["duration_seconds"]: 2,
|
||||
status,
|
||||
["requested_at_millis"]: 1000,
|
||||
["deadline_at_millis"]: 46000,
|
||||
["expires_at_millis"]: 3601000,
|
||||
["completed_at_millis"]: null,
|
||||
error: status === "failed" ? "gpu_unavailable" : null,
|
||||
["artifact_id"]: status === "complete" ? "profile-1" : null,
|
||||
};
|
||||
}
|
||||
|
||||
const artifacts: Record<FunctionProfileKind, Record<string, unknown>> = {
|
||||
cpu: {
|
||||
$schema: "https://www.speedscope.app/file-format-schema.json",
|
||||
shared: { frames: [{ name: "work" }] },
|
||||
profiles: [],
|
||||
futureField: 7,
|
||||
},
|
||||
memory: {
|
||||
format: "lancedb.tracemalloc.v1",
|
||||
allocations: [{ ["size_bytes"]: 4096 }],
|
||||
truncated: false,
|
||||
},
|
||||
gpu: {
|
||||
format: "lancedb.cuda.v1",
|
||||
traceEvents: [{ name: "compute", cat: "kernel", ph: "X", ts: 10, dur: 2 }],
|
||||
truncated: true,
|
||||
},
|
||||
};
|
||||
|
||||
async function withProfileServer(
|
||||
handler: (
|
||||
path: string,
|
||||
body: Record<string, unknown>,
|
||||
headers: IncomingHttpHeaders,
|
||||
) => Response,
|
||||
run: (db: Connection) => Promise<void>,
|
||||
) {
|
||||
let serverError: unknown;
|
||||
const server = createServer(async (request, response) => {
|
||||
try {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of request) chunks.push(chunk);
|
||||
const bytes = Buffer.concat(chunks);
|
||||
const body = bytes.length === 0 ? {} : JSON.parse(bytes.toString());
|
||||
const result = handler(request.url ?? "", body, request.headers);
|
||||
response.writeHead(result.status ?? 200, {
|
||||
"Content-Type": "application/json",
|
||||
});
|
||||
response.end(JSON.stringify(result.body));
|
||||
} catch (error) {
|
||||
serverError = error;
|
||||
response.writeHead(500);
|
||||
response.end("test request handler failed");
|
||||
}
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
try {
|
||||
const db = await connect("db://dev", {
|
||||
apiKey: "fake",
|
||||
hostOverride: `http://127.0.0.1:${port}`,
|
||||
});
|
||||
try {
|
||||
await run(db);
|
||||
} catch (error) {
|
||||
throw serverError ?? error;
|
||||
}
|
||||
if (serverError) throw serverError;
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
describe("Function worker profiles", () => {
|
||||
it.each(
|
||||
(["cpu", "memory", "gpu"] as FunctionProfileKind[]).flatMap((kind) =>
|
||||
[false, true].map((submitted) => [kind, submitted] as const),
|
||||
),
|
||||
)(
|
||||
"captures and exports retained %s evidence (submitted handle: %s)",
|
||||
async (kind, submitted) => {
|
||||
let polls = 0;
|
||||
let finished = false;
|
||||
const paths: string[] = [];
|
||||
const directory = await mkdtemp(join(tmpdir(), "lancedb-profile-"));
|
||||
try {
|
||||
await withProfileServer(
|
||||
(path, body, headers) => {
|
||||
paths.push(path);
|
||||
expect(headers["x-api-key"]).toBe("fake");
|
||||
expect(headers["x-lancedb-database"]).toBe("dev");
|
||||
if (path === "/v1/table/test/describe/")
|
||||
return { body: { version: 1, schema: { fields: [] } } };
|
||||
if (path === "/v1/table/test/backfill_column") {
|
||||
expect(body.column).toBe("result");
|
||||
return { status: 202, body: { ["job_id"]: "job-1" } };
|
||||
}
|
||||
if (path === "/v1/jobs/describe")
|
||||
return {
|
||||
body: {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: finished ? "DONE" : "IN_PROGRESS",
|
||||
},
|
||||
};
|
||||
if (path === "/v1/jobs/profile/capture") {
|
||||
expect(body).toEqual({
|
||||
["job_id"]: "job-1",
|
||||
["worker_id"]: "worker-1",
|
||||
["session_slot"]: 0,
|
||||
kind,
|
||||
["duration_seconds"]: 2,
|
||||
});
|
||||
return { status: 202, body: metadata(kind, "pending") };
|
||||
}
|
||||
expect(body).toEqual({
|
||||
["job_id"]: "job-1",
|
||||
["profile_id"]: "profile-1",
|
||||
});
|
||||
if (path === "/v1/jobs/profile/status")
|
||||
return {
|
||||
body: metadata(kind, ++polls > 1 ? "complete" : "capturing"),
|
||||
};
|
||||
expect(path).toBe("/v1/jobs/profile/artifact");
|
||||
return { body: artifacts[kind] };
|
||||
},
|
||||
async (db) => {
|
||||
const job = submitted
|
||||
? await (await db.openTable("test")).refreshColumnAsync("result")
|
||||
: await db.openJob("job-1");
|
||||
if (submitted) await job.refresh();
|
||||
const capture = await job.captureProfile("worker-1", {
|
||||
kind,
|
||||
durationSeconds: 2,
|
||||
});
|
||||
expect(capture).toMatchObject({
|
||||
profileId: "profile-1",
|
||||
workerId: "worker-1",
|
||||
executionEpoch: 3,
|
||||
sessionSlot: 0,
|
||||
status: "pending",
|
||||
});
|
||||
const complete = await job.waitForProfile(capture.profileId, {
|
||||
timeoutMs: 2000,
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
expect(complete.status).toBe("complete");
|
||||
expect(job.state).toBe("running");
|
||||
finished = true;
|
||||
await job.refresh();
|
||||
expect(job.state).toBe("finished");
|
||||
expect(await job.profileArtifact(capture.profileId)).toEqual(
|
||||
artifacts[kind],
|
||||
);
|
||||
const path = join(directory, "capture.json");
|
||||
await job.exportProfile(capture.profileId, path);
|
||||
expect(JSON.parse(await readFile(path, "utf8"))).toEqual(
|
||||
artifacts[kind],
|
||||
);
|
||||
expect(
|
||||
paths.filter((path) => path === "/v1/jobs/describe"),
|
||||
).toHaveLength(2);
|
||||
expect(paths.some((path) => path.endsWith("/cancel"))).toBe(false);
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("can resume after a wait timeout without cancelling the refresh", async () => {
|
||||
let complete = false;
|
||||
const paths: string[] = [];
|
||||
await withProfileServer(
|
||||
(path) => {
|
||||
paths.push(path);
|
||||
if (path === "/v1/jobs/describe")
|
||||
return {
|
||||
body: {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: "IN_PROGRESS",
|
||||
},
|
||||
};
|
||||
expect(path).toBe("/v1/jobs/profile/status");
|
||||
return { body: metadata("gpu", complete ? "complete" : "pending") };
|
||||
},
|
||||
async (db) => {
|
||||
const job = await db.openJob("job-1");
|
||||
await expect(
|
||||
job.waitForProfile("profile-1", {
|
||||
timeoutMs: 50,
|
||||
pollIntervalMs: 10,
|
||||
}),
|
||||
).rejects.toThrow(/waiting for Function worker profile/);
|
||||
expect(await job.status()).toBe("running");
|
||||
complete = true;
|
||||
expect(
|
||||
(await job.waitForProfile("profile-1", { timeoutMs: 2000 })).status,
|
||||
).toBe("complete");
|
||||
expect(paths.some((path) => path.endsWith("/cancel"))).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("reports failed captures independently of the parent", async () => {
|
||||
await withProfileServer(
|
||||
(path) => ({
|
||||
body:
|
||||
path === "/v1/jobs/describe"
|
||||
? {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: "IN_PROGRESS",
|
||||
}
|
||||
: metadata("gpu", "failed"),
|
||||
}),
|
||||
async (db) => {
|
||||
const job = await db.openJob("job-1");
|
||||
expect(await job.profileStatus("profile-1")).toMatchObject({
|
||||
status: "failed",
|
||||
error: "gpu_unavailable",
|
||||
});
|
||||
await expect(job.waitForProfile("profile-1")).rejects.toThrow(
|
||||
"gpu_unavailable",
|
||||
);
|
||||
expect(job.state).toBe("running");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves permission errors and existing export files", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "lancedb-profile-"));
|
||||
const path = join(directory, "capture.json");
|
||||
await writeFile(path, "previous capture");
|
||||
try {
|
||||
await withProfileServer(
|
||||
(path) => {
|
||||
if (path === "/v1/jobs/describe")
|
||||
return {
|
||||
body: {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: "DONE",
|
||||
},
|
||||
};
|
||||
if (path.endsWith("/status"))
|
||||
return { body: metadata("gpu", "complete") };
|
||||
return { status: 403, body: { error: "System Operate required" } };
|
||||
},
|
||||
async (db) => {
|
||||
const job = await db.openJob("job-1");
|
||||
await expect(job.exportProfile("profile-1", path)).rejects.toThrow(
|
||||
"403",
|
||||
);
|
||||
expect(await readFile(path, "utf8")).toBe("previous capture");
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects invalid options before submitting a capture", async () => {
|
||||
await withProfileServer(
|
||||
(path) => {
|
||||
expect(path).toBe("/v1/jobs/describe");
|
||||
return {
|
||||
body: {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: "IN_PROGRESS",
|
||||
},
|
||||
};
|
||||
},
|
||||
async (db) => {
|
||||
const job = await db.openJob("job-1");
|
||||
for (const durationSeconds of [
|
||||
Number.NaN,
|
||||
Number.POSITIVE_INFINITY,
|
||||
-1,
|
||||
0,
|
||||
6,
|
||||
]) {
|
||||
await expect(
|
||||
job.captureProfile("worker-1", { kind: "gpu", durationSeconds }),
|
||||
).rejects.toThrow(/duration/);
|
||||
}
|
||||
for (const sessionSlot of [
|
||||
-1,
|
||||
0.5,
|
||||
Number.NaN,
|
||||
Number.MAX_SAFE_INTEGER + 1,
|
||||
]) {
|
||||
await expect(
|
||||
job.captureProfile("worker-1", { sessionSlot }),
|
||||
).rejects.toThrow("sessionSlot");
|
||||
}
|
||||
await expect(
|
||||
job.captureProfile("worker-1", { duration: 10 } as never),
|
||||
).rejects.toThrow("Unknown profiling option");
|
||||
await expect(
|
||||
job.waitForProfile("profile-1", { timeoutMs: -1 }),
|
||||
).rejects.toThrow("timeoutMs");
|
||||
await expect(
|
||||
job.waitForProfile("profile-1", { pollIntervalMs: 0 }),
|
||||
).rejects.toThrow("poll interval");
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -124,6 +124,13 @@ export type {
|
||||
JobState,
|
||||
JobWaitOptions,
|
||||
} from "./job";
|
||||
export type {
|
||||
FunctionProfile,
|
||||
FunctionProfileKind,
|
||||
FunctionProfileOptions,
|
||||
FunctionProfileStatus,
|
||||
FunctionProfileWaitOptions,
|
||||
} from "./profiling";
|
||||
|
||||
export {
|
||||
AutoQuery,
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { Table as ArrowTable, tableFromIPC } from "apache-arrow";
|
||||
import { decodeCleanupResult } from "./cleanup";
|
||||
import { decodeCompactionResult } from "./compaction";
|
||||
import type { JobFailureInfo, Job as NativeJob } from "./native";
|
||||
import { decodePrewarmDataResult } from "./prewarm";
|
||||
import {
|
||||
type FunctionProfile,
|
||||
type FunctionProfileOptions,
|
||||
type FunctionProfileWaitOptions,
|
||||
decodeFunctionProfile,
|
||||
validateProfileOptions,
|
||||
} from "./profiling";
|
||||
|
||||
/** Which of a job's events {@link Job.events} returns. */
|
||||
export interface JobEventsOptions {
|
||||
@@ -394,6 +402,95 @@ export class Job<T = void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a profile of a running Enterprise Function worker session.
|
||||
* Returns the accepted identity without waiting for recording to finish.
|
||||
* Requires System Operate permission and server profiling support. The server
|
||||
* pins the worker, Python session and execution epoch. One capture per job
|
||||
* can be active. Captures add workload-dependent overhead.
|
||||
*
|
||||
* GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU sampling requires
|
||||
* readable per-thread procfs and is unavailable in dedicated sandboxes.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const profile = await job.captureProfile("worker-id", {
|
||||
* kind: "gpu", durationSeconds: 2,
|
||||
* });
|
||||
* await job.waitForProfile(profile.profileId, { timeoutMs: 60_000 });
|
||||
* await job.exportProfile(profile.profileId, "gpu.trace.json");
|
||||
* ```
|
||||
*/
|
||||
async captureProfile(
|
||||
workerId: string,
|
||||
options: FunctionProfileOptions = {},
|
||||
): Promise<FunctionProfile> {
|
||||
validateProfileOptions(options, ["kind", "durationSeconds", "sessionSlot"]);
|
||||
const kind = options.kind ?? "cpu";
|
||||
if (!["cpu", "gpu", "memory"].includes(kind)) {
|
||||
throw new TypeError("kind must be cpu, memory or gpu");
|
||||
}
|
||||
return decodeFunctionProfile(
|
||||
await this.inner.captureProfile(
|
||||
workerId,
|
||||
kind,
|
||||
options.durationSeconds,
|
||||
options.sessionSlot,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch capture identity and status, including retained lookup after refresh.
|
||||
* Failed captures return status "failed" with the server's error reason.
|
||||
* This never changes the parent job's cached state.
|
||||
*/
|
||||
async profileStatus(profileId: string): Promise<FunctionProfile> {
|
||||
return decodeFunctionProfile(await this.inner.profileStatus(profileId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a capture with a configurable timeout and polling cadence.
|
||||
* Defaults to 60 seconds with two seconds between requests. A timeout stops
|
||||
* only this wait; the capture and Function refresh continue. A failed capture
|
||||
* rejects with its server-reported reason. Keep its ID to wait again.
|
||||
*/
|
||||
async waitForProfile(
|
||||
profileId: string,
|
||||
options: FunctionProfileWaitOptions = {},
|
||||
): Promise<FunctionProfile> {
|
||||
validateProfileOptions(options, ["timeoutMs", "pollIntervalMs"]);
|
||||
return decodeFunctionProfile(
|
||||
await this.inner.waitForProfile(
|
||||
profileId,
|
||||
options.timeoutMs,
|
||||
options.pollIntervalMs,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a completed capture's actual JSON: speedscope for CPU,
|
||||
* tracemalloc for Python allocations, or Chrome Trace Event JSON for GPU.
|
||||
* Truncation flags are preserved. Retention is at most one hour and eight
|
||||
* captures per job, until earlier scratch reclamation or archival.
|
||||
* Permission, expired-artifact and unsupported-server errors propagate.
|
||||
*/
|
||||
async profileArtifact(profileId: string): Promise<Record<string, unknown>> {
|
||||
return JSON.parse(await this.inner.profileArtifact(profileId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a completed capture's JSON after successful retrieval. Open CPU
|
||||
* exports in speedscope and GPU exports in Perfetto. GPU activity durations
|
||||
* can overlap and are not utilization; Python operator attribution and GPU
|
||||
* allocation stacks are excluded. Filesystem errors propagate to the caller.
|
||||
*/
|
||||
async exportProfile(profileId: string, path: string): Promise<void> {
|
||||
const artifact = await this.inner.profileArtifact(profileId);
|
||||
await writeFile(path, artifact, "utf8");
|
||||
}
|
||||
|
||||
private lastProgress: JobProgress | null = null;
|
||||
|
||||
private enrichProgress(progress: Record<string, unknown>): JobProgress {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
/** Evidence collected from one Function worker's Python execution session. */
|
||||
export type FunctionProfileKind = "cpu" | "gpu" | "memory";
|
||||
|
||||
/** A capture's lifecycle, independent of its parent refresh job. */
|
||||
export type FunctionProfileStatus =
|
||||
| "pending"
|
||||
| "capturing"
|
||||
| "complete"
|
||||
| "failed";
|
||||
|
||||
/** Options for requesting a Function worker capture. */
|
||||
export interface FunctionProfileOptions {
|
||||
/** CPU samples, retained Python allocations, or PyTorch CUDA activities. */
|
||||
kind?: FunctionProfileKind;
|
||||
/** 1–30 seconds for CPU/memory, default 10; 1–5 for GPU, default 5. */
|
||||
durationSeconds?: number;
|
||||
/** Python execution session within the worker; default zero. */
|
||||
sessionSlot?: number;
|
||||
}
|
||||
|
||||
/** Client-side controls while waiting for a Function worker capture. */
|
||||
export interface FunctionProfileWaitOptions {
|
||||
/** Maximum wait including HTTP requests and sleeps; defaults to 60,000 ms. */
|
||||
timeoutMs?: number;
|
||||
/** Delay between status requests; defaults to 2,000 ms and must be positive. */
|
||||
pollIntervalMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A capture identity and status snapshot. Keep profileId for retained lookup
|
||||
* after the Function refresh completes. Timestamp fields are epoch milliseconds.
|
||||
*/
|
||||
export interface FunctionProfile {
|
||||
readonly profileId: string;
|
||||
readonly jobId: string;
|
||||
readonly workerId: string;
|
||||
readonly executionEpoch: number;
|
||||
readonly sessionSlot: number;
|
||||
readonly kind: FunctionProfileKind;
|
||||
readonly durationSeconds: number;
|
||||
readonly status: FunctionProfileStatus;
|
||||
readonly requestedAtMillis: number;
|
||||
readonly deadlineAtMillis: number;
|
||||
/** Upper retention bound; job scratch reclamation can remove artifacts sooner. */
|
||||
readonly expiresAtMillis: number;
|
||||
readonly completedAtMillis: number | null;
|
||||
/** The server's capture failure reason; this is not a refresh job failure. */
|
||||
readonly error: string | null;
|
||||
readonly artifactId: string | null;
|
||||
}
|
||||
|
||||
export function decodeFunctionProfile(value: string): FunctionProfile {
|
||||
const data = JSON.parse(value);
|
||||
return {
|
||||
profileId: data.profile_id,
|
||||
jobId: data.job_id,
|
||||
workerId: data.worker_id,
|
||||
executionEpoch: data.execution_epoch,
|
||||
sessionSlot: data.session_slot,
|
||||
kind: data.kind,
|
||||
durationSeconds: data.duration_seconds,
|
||||
status: data.status,
|
||||
requestedAtMillis: data.requested_at_millis,
|
||||
deadlineAtMillis: data.deadline_at_millis,
|
||||
expiresAtMillis: data.expires_at_millis,
|
||||
completedAtMillis: data.completed_at_millis,
|
||||
error: data.error,
|
||||
artifactId: data.artifact_id,
|
||||
};
|
||||
}
|
||||
|
||||
export function validateProfileOptions(options: object, names: string[]): void {
|
||||
if (
|
||||
typeof options !== "object" ||
|
||||
options === null ||
|
||||
Array.isArray(options)
|
||||
) {
|
||||
throw new TypeError("profiling expects an options object");
|
||||
}
|
||||
for (const key of Object.keys(options)) {
|
||||
if (!names.includes(key)) {
|
||||
throw new TypeError(`Unknown profiling option: ${key}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
+94
-2
@@ -4,7 +4,10 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use arrow_array::RecordBatch;
|
||||
use lancedb::job::{JobEventsRequest, JobWaitOptions};
|
||||
use lancedb::job::{
|
||||
FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions, JobEventsRequest,
|
||||
JobWaitOptions,
|
||||
};
|
||||
use napi::bindgen_prelude::Buffer;
|
||||
use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
|
||||
use napi_derive::napi;
|
||||
@@ -14,6 +17,18 @@ use crate::error::NapiErrorExt;
|
||||
type JobProgressFn =
|
||||
ThreadsafeFunction<serde_json::Value, (), serde_json::Value, napi::Status, false>;
|
||||
|
||||
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
|
||||
|
||||
fn profile_integer(value: f64, name: &str) -> napi::Result<u64> {
|
||||
if !value.is_finite() || value.fract() != 0.0 || !(0.0..=MAX_SAFE_INTEGER).contains(&value) {
|
||||
return Err(napi::Error::new(
|
||||
napi::Status::InvalidArg,
|
||||
format!("{name} must be a nonnegative safe integer"),
|
||||
));
|
||||
}
|
||||
Ok(value as u64)
|
||||
}
|
||||
|
||||
/// A handle to an operation that may still be running.
|
||||
#[napi]
|
||||
pub struct Job {
|
||||
@@ -142,7 +157,6 @@ impl Job {
|
||||
) -> napi::Result<Option<serde_json::Value>> {
|
||||
let mut options = JobWaitOptions::new();
|
||||
if let Some(timeout_ms) = timeout_ms {
|
||||
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
|
||||
if !timeout_ms.is_finite()
|
||||
|| timeout_ms.fract() != 0.0
|
||||
|| !(0.0..=MAX_SAFE_INTEGER).contains(&timeout_ms)
|
||||
@@ -233,6 +247,84 @@ impl Job {
|
||||
self.inner.failure().map(Into::into)
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn capture_profile(
|
||||
&self,
|
||||
worker_id: String,
|
||||
kind: String,
|
||||
duration_seconds: Option<f64>,
|
||||
session_slot: Option<f64>,
|
||||
) -> napi::Result<String> {
|
||||
let kind: FunctionProfileKind =
|
||||
serde_json::from_value(serde_json::json!(kind)).map_err(|_| {
|
||||
napi::Error::new(napi::Status::InvalidArg, "kind must be cpu, memory or gpu")
|
||||
})?;
|
||||
let mut options = FunctionProfileOptions::new(kind);
|
||||
if let Some(slot) = session_slot {
|
||||
options = options.session_slot(profile_integer(slot, "sessionSlot")? as usize);
|
||||
}
|
||||
if let Some(seconds) = duration_seconds {
|
||||
let duration = Duration::try_from_secs_f64(seconds).map_err(|_| {
|
||||
napi::Error::new(
|
||||
napi::Status::InvalidArg,
|
||||
"durationSeconds must be finite and nonnegative",
|
||||
)
|
||||
})?;
|
||||
options = options.duration(duration);
|
||||
}
|
||||
let profile = self
|
||||
.inner
|
||||
.capture_profile(worker_id, options)
|
||||
.await
|
||||
.default_error()?;
|
||||
serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn profile_status(&self, profile_id: String) -> napi::Result<String> {
|
||||
let profile = self
|
||||
.inner
|
||||
.profile_status(profile_id)
|
||||
.await
|
||||
.default_error()?;
|
||||
serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn wait_for_profile(
|
||||
&self,
|
||||
profile_id: String,
|
||||
timeout_ms: Option<f64>,
|
||||
poll_interval_ms: Option<f64>,
|
||||
) -> napi::Result<String> {
|
||||
let mut options = FunctionProfileWaitOptions::new();
|
||||
if let Some(ms) = timeout_ms {
|
||||
options = options.timeout(Duration::from_millis(profile_integer(ms, "timeoutMs")?));
|
||||
}
|
||||
if let Some(ms) = poll_interval_ms {
|
||||
options = options.poll_interval(Duration::from_millis(profile_integer(
|
||||
ms,
|
||||
"pollIntervalMs",
|
||||
)?));
|
||||
}
|
||||
let profile = self
|
||||
.inner
|
||||
.wait_for_profile(profile_id, options)
|
||||
.await
|
||||
.default_error()?;
|
||||
serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn profile_artifact(&self, profile_id: String) -> napi::Result<String> {
|
||||
Ok(self
|
||||
.inner
|
||||
.profile_artifact(profile_id)
|
||||
.await
|
||||
.default_error()?
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// This job's recorded lifecycle events, as an Arrow IPC stream buffer.
|
||||
/// The TypeScript wrapper turns it into an Arrow table.
|
||||
#[napi(catch_unwind)]
|
||||
|
||||
Reference in New Issue
Block a user