Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 56 additions & 14 deletions apps/server/src/jobs/runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { MemoryStorage } from "../storage/memory/adapter";

import type { JobDefinition } from "./registry";
import type { JobExecutionDiagnostic } from "./registry";
import type { JobRunnerOptions, ResolvedJobCredential } from "./runner";
import type { JobRunnerOptions, ResolvedJobCredential, RunnerScheduler } from "./runner";
import type { JsonValue } from "../storage/model";

function deferred<T>() {
Expand All @@ -20,6 +20,34 @@ function deferred<T>() {
return { promise, resolve, reject };
}

/** A clock that moves only when the test moves it, running each timer that comes due in order. */
function manualClock() {
let now = Date.now();
let timers = new Set<{ at: number; action: () => void }>();
let scheduler: RunnerScheduler = {
now: () => new Date(now),
after(delayMs, action) {
let timer = { at: now + delayMs, action };
timers.add(timer);
return () => void timers.delete(timer);
},
};
return {
scheduler,
advance(ms: number): void {
let until = now + ms;
for (;;) {
let due = [...timers].filter(timer => timer.at <= until).sort((a, b) => a.at - b.at)[0];
if (!due) break;
timers.delete(due);
now = due.at;
due.action();
}
now = until;
},
};
}

async function waitFor(check: () => boolean | Promise<boolean>, timeoutMs = 1_000): Promise<void> {
let deadline = Date.now() + timeoutMs;
while (!await check()) {
Expand Down Expand Up @@ -71,9 +99,10 @@ async function setup(
resolve: () => Promise<ResolvedJobCredential | undefined> = async () => undefined,
enabled = true,
attemptFailed?: JobRunnerOptions["attemptFailed"],
scheduler?: RunnerScheduler,
) {
let storage = new MemoryStorage();
let now = new Date();
let now = scheduler?.now() ?? new Date();
let userId = crypto.randomUUID();
let channelId = crypto.randomUUID();
await storage.users.put({ id: userId, login: "mona", avatarUrl: "", now });
Expand All @@ -94,6 +123,7 @@ async function setup(
storage,
registry,
lease: () => lease,
now: scheduler?.now,
onChange: job => runner?.notify(job),
});
let errors: unknown[] = [];
Expand All @@ -113,6 +143,7 @@ async function setup(
retryMaxMs: 20,
shutdownGraceMs: 50,
attemptFailed,
scheduler,
fatal: err => errors.push(err),
});
return { storage, channelId, lease, service, runner, errors };
Expand Down Expand Up @@ -218,13 +249,14 @@ describe("background job runner", () => {
});

it("renews a claim after delayed owner resolution without reclaiming the attempt", async () => {
let started = deferred<void>();
let clock = manualClock();
let asked = deferred<void>();
let resolved = deferred<ResolvedJobCredential>();
let release = deferred<JsonValue>();
let registered = {
...definition(
async execution => {
await execution.progress("work", "started");
started.resolve();
return release.promise;
},
"active-planner",
Expand All @@ -235,23 +267,33 @@ describe("background job runner", () => {
};
let value = await setup(
registered,
async () => {
await Bun.sleep(150);
return owner();
() => {
asked.resolve();
return resolved.promise;
},
true,
undefined,
clock.scheduler,
);
try {
let queued = await enqueue(value.service, value.channelId);
let job = async () => (await value.service.get(value.channelId, queued.job.id))?.job;
value.runner.start();
await started.promise;
await Bun.sleep(350);
expect(await value.service.get(value.channelId, queued.job.id)).toMatchObject({
job: { state: "running", attempts: 1, failures: 0, progress: [{ state: "started" }] },
await asked.promise;
// The owner resolves on the clock reading the first heartbeat renews the claim at.
clock.advance(100);
resolved.resolve(owner());
await waitFor(async () => (await job())?.progress.length === 1);
expect(await job()).toMatchObject({
state: "running",
attempts: 1,
failures: 0,
progress: [{ attempt: 1, state: "started" }],
});
release.resolve({ report: "complete" });
await waitFor(async () =>
(await value.service.get(value.channelId, queued.job.id))?.job.state === "completed"
);
await waitFor(async () => (await job())?.state === "completed");
expect(await job()).toMatchObject({ attempts: 1, failures: 0 });
expect(value.errors).toEqual([]);
} finally {
release.resolve({ report: "complete" });
await value.runner.shutdown();
Expand Down
50 changes: 24 additions & 26 deletions apps/server/src/jobs/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -438,19 +438,7 @@ export class JobRunner {
void this.#pause(attempt, "owner-unavailable");
}, { once: true });
}
await this.#serial(attempt, async () => {
attempt.job = await this.#options.storage.jobs.renew({
channelId: attempt.job.channelId,
jobId: attempt.job.id,
claimOwner: this.#claimOwner,
claimGeneration: attempt.job.claimGeneration,
expectedRevision: attempt.job.revision,
claimBinding: credential.binding,
ttlMs: this.#options.claimTtlMs + this.#options.heartbeatMs + 1,
now: this.#scheduler.now(),
lease: this.#options.lease(),
});
});
await this.#renew(attempt, credential.binding);
this.#heartbeat(attempt);
if (!this.#accepted(attempt, credential)) return;
attempt.releaseOwner = await this.#owner(credential.ownerKey);
Expand Down Expand Up @@ -586,19 +574,7 @@ export class JobRunner {
attempt.heartbeat = this.#scheduler.after(this.#options.heartbeatMs, () => {
attempt.heartbeat = undefined;
if (!attempt.accepting || this.#stopped) return;
void this.#serial(attempt, async () => {
attempt.job = await this.#options.storage.jobs.renew({
channelId: attempt.job.channelId,
jobId: attempt.job.id,
claimOwner: this.#claimOwner,
claimGeneration: attempt.job.claimGeneration,
expectedRevision: attempt.job.revision,
claimBinding: attempt.credential?.binding,
ttlMs: this.#options.claimTtlMs + this.#options.heartbeatMs + 1,
now: this.#scheduler.now(),
lease: this.#options.lease(),
});
}).then(async () => {
void this.#renew(attempt, attempt.credential?.binding).then(async () => {
if (!attempt.accepting) return;
try {
if (
Expand Down Expand Up @@ -672,6 +648,28 @@ export class JobRunner {
return result;
}

/**
* Storage refuses a renewal that does not move the claim's expiry on, and a heartbeat and the
* owner's binding can renew on one clock reading, so each renewal reaches past the last.
*/
#renew(attempt: Attempt, claimBinding: JsonValue | undefined): Promise<void> {
return this.#serial(attempt, async () => {
let now = this.#scheduler.now();
let held = (attempt.job.claimExpiresAt?.getTime() ?? 0) - now.getTime();
attempt.job = await this.#options.storage.jobs.renew({
channelId: attempt.job.channelId,
jobId: attempt.job.id,
claimOwner: this.#claimOwner,
claimGeneration: attempt.job.claimGeneration,
expectedRevision: attempt.job.revision,
claimBinding,
ttlMs: Math.max(this.#options.claimTtlMs + this.#options.heartbeatMs + 1, held + 1),
now,
lease: this.#options.lease(),
});
});
}

#accepted(attempt: Attempt, credential?: ResolvedJobCredential): boolean {
return attempt.accepting
&& !attempt.controller.signal.aborted
Expand Down
9 changes: 4 additions & 5 deletions e2e/jev-wire.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ import type { ConversationPlan } from "../packages/protocol/index";
import type { Page } from "@playwright/test";

/**
* A second writer with the document open beside `page`'s, closed with `page`'s context. A person
* alone in a document is talking to chopin, so their room message goes to the Planner and is never
* analysed; with company it stays the conversation's.
* A second writer with the document open beside `page`'s, closed with the test's other contexts as
* `join` ends it. A person alone in a document is talking to chopin, so their room message goes to
* the Planner and is never analysed; with company it stays the conversation's.
*/
export async function keepCompany(page: Page, channelId: string, handle = "cy"): Promise<void> {
let browser = page.context().browser();
if (!browser) throw new Error("keepCompany needs a page from a launched browser");
let company = await openIsolatedRoom(browser, new URL(page.url()).origin, channelId, handle, {});
page.context().once("close", () => void company.close().catch(() => {}));
await openIsolatedRoom(browser, new URL(page.url()).origin, channelId, handle, {});
}

export type WireFrame = { kind: string; rid?: string; [key: string]: unknown };
Expand Down
12 changes: 8 additions & 4 deletions e2e/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,11 @@ export async function openIsolatedRoom(
type Fixtures = {
/** The channel this test has to itself. */
room: string;
/** Open the channel as somebody. Options always receive an isolated context. */
/**
* Open the channel as somebody. Options always receive an isolated context. Every context the
* test opened, a helper's beside it too (`keepCompany`), is closed before the test ends: the next
* test starts a trace chunk in each context still open, and one still closing fails it.
*/
join: (handle: string, options?: BrowserContextOptions) => Promise<Page>;
/** Set the channel's source and optional sidecar before anyone opens it. */
seed: (source: string, state?: SeedState) => Promise<void>;
Expand All @@ -104,7 +108,6 @@ export const test = base.extend<Fixtures>({

join: async ({ baseURL, browser, context, page, room }, use) => {
let first = true;
let opened: BrowserContext[] = [];
await use(async (handle, options) => {
let target: Page;
if (first && !options) {
Expand All @@ -113,15 +116,16 @@ export const test = base.extend<Fixtures>({
} else {
first = false;
let isolated = await browser.newContext({ ...options, baseURL });
opened.push(isolated);
target = await isolated.newPage();
}
await authenticate(target, handle, baseURL!);
await target.goto(testChannelPath(room));
await ready(target);
return target;
});
await Promise.all(opened.map(item => item.close()));
await Promise.all(
browser.contexts().filter(item => item !== context).map(item => item.close()),
);
await context.clearCookies();
},

Expand Down
Loading