kernel / core / itx / src / context / awake.test.tsmain at 949894f
// The dialing side of the awake socket: when a context opens it, how long it holds it and when it
// closes it. The accepting side is the runtime's hibernation API, which only a deployed stack has
// (core/alchemy/scripts/smoke).
import { expect, onTestFinished, test, vi } from "vitest";
import {
AWAKE_ANSWER_WAIT_MS,
AWAKE_CONTEXT_PATH,
AWAKE_SUMMARY_FAILED,
AWAKE_SUMMARY_KEPT,
AWAKE_MAX_HOLD_MS,
AWAKE_QUIET_MS,
AWAKE_RECOVER_AFTER_MS,
AWAKE_REDIAL_AFTER_MS,
AWAKE_SAY_AGAIN_AFTER_MS,
AWAKE_SAY_AGAIN_TRIES,
AWAKE_SUMMARY_EVERY_MS,
AwakeSocket,
decideAwakeSocket,
unansweredSummaryTries,
} from "./awake.ts";
test.for([
{ name: "work in flight holds it", sinceEntry: 30_000, busy: true, expected: "hold" },
{ name: "an entry just now holds it", sinceEntry: 200, busy: false, expected: "hold" },
{
name: "quiet for the window closes it",
sinceEntry: AWAKE_QUIET_MS,
busy: false,
expected: "close",
},
// a count of work in flight that never returns to zero must not hold a context in memory
{
name: "the longest hold closes it under work",
sinceEntry: AWAKE_MAX_HOLD_MS,
busy: true,
expected: "close",
},
])("$name", ({ sinceEntry, busy, expected }) => {
expect(
decideAwakeSocket({ now: 1_000_000, lastEntryAt: 1_000_000 - sinceEntry, busy }),
).toMatchObject({
action: expected,
});
});
test("a context dials once for a burst of entries and closes its socket a quiet window later", async () => {
vi.useFakeTimers();
const far = farEnd();
const awake = new AwakeSocket({ path: "/agents/a", dial: far.dial, busy: () => false });
awake.entered();
await vi.advanceTimersByTimeAsync(400);
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS - 1);
expect(far).toMatchObject({ dials: 1, open: 1 });
await vi.advanceTimersByTimeAsync(1);
expect(far).toMatchObject({ dials: 1, open: 0 });
// no timer is left: a pending timer holds a Durable Object in memory, billed
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
test("work in flight holds the socket, and it closes within a quiet window of the work's end", async () => {
vi.useFakeTimers();
const far = farEnd();
let busy = true;
const awake = new AwakeSocket({ path: "/agents/a", dial: far.dial, busy: () => busy });
awake.entered();
await vi.advanceTimersByTimeAsync(60_000);
expect(far).toMatchObject({ dials: 1, open: 1 });
busy = false;
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ open: 0 });
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
test("work that never ends holds the socket no longer than the longest hold after the last entry", async () => {
vi.useFakeTimers();
const far = farEnd();
const awake = new AwakeSocket({ path: "/agents/a", dial: far.dial, busy: () => true });
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_MAX_HOLD_MS + AWAKE_QUIET_MS);
expect(far).toMatchObject({ dials: 1, open: 0 });
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
test("a socket the far end closed under a working context is dialed again", async () => {
vi.useFakeTimers();
const far = farEnd();
const awake = new AwakeSocket({ path: "/agents/a", dial: far.dial, busy: () => true });
awake.entered();
await vi.advanceTimersByTimeAsync(10);
far.closeAll();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ dials: 2, open: 1 });
vi.useRealTimers();
});
test("a dial that fails is not tried again for a while, however often the context is entered", async () => {
vi.useFakeTimers();
const far = farEnd();
far.refuse = true;
const awake = new AwakeSocket({ path: "/agents/a", dial: far.dial, busy: () => false });
for (let entry = 0; entry < 50; entry += 1) {
awake.entered();
await vi.advanceTimersByTimeAsync(100);
}
expect(far).toMatchObject({ dials: 1 });
await vi.advanceTimersByTimeAsync(AWAKE_REDIAL_AFTER_MS);
far.refuse = false;
awake.entered();
await vi.advanceTimersByTimeAsync(10);
expect(far).toMatchObject({ dials: 2, open: 1 });
vi.useRealTimers();
});
test("a context sends its summary before it closes, and while it works, only when it changed", async () => {
vi.useFakeTimers();
const far = farEnd();
let busy = true;
let summary = "one";
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => busy,
summary: () => summary,
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_SUMMARY_EVERY_MS * 3);
expect(far).toMatchObject({ sent: ["one"] });
summary = "two";
await vi.advanceTimersByTimeAsync(AWAKE_SUMMARY_EVERY_MS);
expect(far).toMatchObject({ sent: ["one", "two"] });
summary = "three";
busy = false;
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ sent: ["one", "two", "three"], open: 0 });
vi.useRealTimers();
});
test("a dial that lands after the context went quiet still sends the summary, then closes", async () => {
vi.useFakeTimers();
const far = farEnd();
const slowDial = async () => {
await new Promise((resolve) => setTimeout(resolve, AWAKE_QUIET_MS * 3));
return far.dial();
};
const awake = new AwakeSocket({
path: "/agents/a",
dial: slowDial,
busy: () => false,
summary: () => "one",
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS * 4);
expect(far).toMatchObject({ dials: 1, sent: ["one"], open: 0 });
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
test("a summary that cannot be made closes the socket all the same", async () => {
vi.useFakeTimers();
const far = farEnd();
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => {
throw new Error("the log cannot be read");
},
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ sent: [], open: 0 });
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
test("the context that accepts the sockets dials none", async () => {
vi.useFakeTimers();
const far = farEnd();
new AwakeSocket({ path: AWAKE_CONTEXT_PATH, dial: far.dial, busy: () => true }).entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ dials: 0 });
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
test("an entry leaves an alarm, and a quiet close with every summary answered takes it away", async () => {
vi.useFakeTimers();
const far = farEnd();
let changes = 0;
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => "one",
recoveryChanged: () => (changes += 1),
});
expect(awake.recoverAt()).toBeNull();
const enteredAt = Date.now();
awake.entered();
// past the longest hold: a context that lives takes the alarm away before it fires
expect(awake.recoverAt()).toBe(enteredAt + AWAKE_RECOVER_AFTER_MS);
awake.entered();
expect(changes).toBe(1);
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ sent: ["one"], open: 0 });
expect(awake.recoverAt()).toBeNull();
expect(changes).toBe(2);
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
test("a quiet context keeps its socket for the catalog's answer, and no longer than the answer wait", async () => {
vi.useFakeTimers();
const far = farEnd();
far.answers = false;
const unanswered = counted();
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => "one",
unanswered,
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS - 1);
expect(far).toMatchObject({ sent: ["one"], open: 1 });
await vi.advanceTimersByTimeAsync(1);
expect(far).toMatchObject({ open: 0 });
// the alarm wakes the context to say it again
expect(unanswered).toMatchObject({ tries: 1 });
expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS);
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
test("work that comes back during the wait for an answer keeps the socket", async () => {
vi.useFakeTimers();
const far = farEnd();
far.answers = false;
let summary = "one";
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => summary,
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + 100);
expect(far).toMatchObject({ sent: ["one"], open: 1 });
awake.entered();
summary = "two";
far.answers = true;
far.answer();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ dials: 1, sent: ["one", "two"], open: 0 });
expect(awake.recoverAt()).toBeNull();
vi.useRealTimers();
});
test("an unanswered summary is said again by the alarm, at longer waits, and then no more", async () => {
vi.useFakeTimers();
const far = farEnd();
far.answers = false;
const unanswered = counted();
const warned = vi.spyOn(console, "warn").mockImplementation(() => {});
vi.spyOn(console, "info").mockImplementation(() => {});
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => "one",
unanswered,
});
awake.entered();
const waits: number[] = [];
for (let tried = 1; tried <= AWAKE_SAY_AGAIN_TRIES; tried++) {
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS);
expect(unanswered, `try ${tried}`).toMatchObject({ tries: tried });
const at = awake.recoverAt()!;
waits.push(at - Date.now());
// the alarm is not due before its time
expect(awake.recover(at - 1)).toBe(false);
await vi.advanceTimersByTimeAsync(at - Date.now());
expect(awake.recover(Date.now())).toBe(true);
}
expect(waits).toEqual([30_000, 60_000, 120_000, 240_000, 480_000, 960_000, 1_800_000, 1_800_000]);
// the last try is unanswered too: a warning, and nothing is owed
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS);
// each try said the summary again, on a socket of its own
expect(far).toMatchObject({ dials: AWAKE_SAY_AGAIN_TRIES + 1, open: 0 });
expect(far.sent).toHaveLength(AWAKE_SAY_AGAIN_TRIES + 1);
expect(warned).toHaveBeenCalledWith(
expect.objectContaining({ event: "context.awake-summary-gave-up", path: "/agents/a" }),
);
expect(awake.recoverAt()).toBeNull();
expect(unanswered).toMatchObject({ tries: 0 });
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
test("the catalog's answer to a summary said again takes the count away", async () => {
vi.useFakeTimers();
vi.spyOn(console, "info").mockImplementation(() => {});
const far = farEnd();
far.answers = false;
const unanswered = counted();
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => "one",
unanswered,
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS);
expect(unanswered).toMatchObject({ tries: 1 });
far.answers = true;
expect(awake.recover(awake.recoverAt()!)).toBe(true);
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ sent: ["one", "one"], open: 0 });
expect(unanswered).toMatchObject({ tries: 0 });
expect(awake.recoverAt()).toBeNull();
vi.useRealTimers();
});
test("a socket that ends with a summary unanswered under a working context: the next socket says it at once", async () => {
vi.useFakeTimers();
const far = farEnd();
far.answers = false;
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => true,
summary: () => "one",
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ dials: 1, sent: ["one"] });
far.closeAll();
far.answers = true;
// the same words again, and long before the next summary would be due
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ dials: 2, sent: ["one", "one"], open: 1 });
vi.useRealTimers();
});
test("a context that goes quiet with no socket owes its summary to the alarm", async () => {
vi.useFakeTimers();
vi.spyOn(console, "info").mockImplementation(() => {});
const far = farEnd();
far.refuse = true;
const unanswered = counted();
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => "one",
unanswered,
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ dials: 1, sent: [] });
expect(unanswered).toMatchObject({ tries: 1 });
expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS);
vi.useRealTimers();
});
test("the answer to an earlier summary does not settle a later one that could not be made", async () => {
vi.useFakeTimers();
onTestFinished(() => void vi.useRealTimers());
vi.spyOn(console, "info").mockImplementation(() => {});
const far = farEnd();
far.answers = false;
let busy = true;
let readable = true;
const unanswered = counted();
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => busy,
summary: () => {
if (!readable) throw new Error("the log cannot be read");
return "one";
},
unanswered,
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_SUMMARY_EVERY_MS + AWAKE_QUIET_MS);
expect(far).toMatchObject({ sent: ["one"], open: 1 });
// the context goes quiet, and its last summary cannot be made while "one" is unanswered
readable = false;
busy = false;
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ sent: ["one"], open: 1 });
// the catalog answers "one": that is no answer to the summary that never went
far.answer();
await vi.advanceTimersByTimeAsync(1);
expect(far).toMatchObject({ open: 0 });
expect(unanswered).toMatchObject({ tries: 1 });
expect(awake.recoverAt()).toBe(Date.now() - 1 + AWAKE_SAY_AGAIN_AFTER_MS);
});
test("a summary that the catalog could not keep is owed, and the context says it again", async () => {
vi.useFakeTimers();
onTestFinished(() => void vi.useRealTimers());
vi.spyOn(console, "info").mockImplementation(() => {});
const far = farEnd();
far.answerWith = AWAKE_SUMMARY_FAILED;
const unanswered = counted();
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => "one",
unanswered,
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
// answered, and not kept: no wait, and the alarm has the context say it again
expect(far).toMatchObject({ sent: ["one"], open: 0 });
expect(unanswered).toMatchObject({ tries: 1 });
expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS);
far.answerWith = AWAKE_SUMMARY_KEPT;
await vi.advanceTimersByTimeAsync(AWAKE_SAY_AGAIN_AFTER_MS);
expect(awake.recover(Date.now())).toBe(true);
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ sent: ["one", "one"], open: 0 });
expect(unanswered).toMatchObject({ tries: 0 });
expect(awake.recoverAt()).toBeNull();
});
test("an answer that this release does not know settles a summary, as kept does", async () => {
vi.useFakeTimers();
onTestFinished(() => void vi.useRealTimers());
const far = farEnd();
far.answerWith = "kept-and-more";
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => "one",
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ sent: ["one"], open: 0 });
expect(awake.recoverAt()).toBeNull();
});
test("an alarm in an object that never entered says the summary: the object before it may have died with it unsaid", async () => {
vi.useFakeTimers();
onTestFinished(() => void vi.useRealTimers());
const far = farEnd();
// a new object: nothing in its memory says whether a summary is owed
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => "one",
});
expect(awake.recoverAt()).toBeNull();
expect(awake.recover(Date.now())).toBe(true);
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ dials: 1, sent: ["one"], open: 0 });
// the catalog answered: nothing is owed, and a later alarm of another kind says nothing
expect(awake.recoverAt()).toBeNull();
expect(awake.recover(Date.now())).toBe(false);
expect(far).toMatchObject({ dials: 1 });
});
test("an alarm while the context works moves the recovery on and makes no entry", async () => {
vi.useFakeTimers();
onTestFinished(() => void vi.useRealTimers());
const far = farEnd();
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => true,
summary: () => "one",
});
const enteredAt = Date.now();
awake.entered();
// real entries, the last in the fifth minute, keep the socket past the time of the alarm that
// the first one left
for (let minute = 1; minute <= 5; minute++) {
await vi.advanceTimersByTimeAsync(60_000);
awake.entered();
}
await vi.advanceTimersByTimeAsync(AWAKE_RECOVER_AFTER_MS - 5 * 60_000);
expect(awake.recoverAt()).toBe(enteredAt + AWAKE_RECOVER_AFTER_MS);
expect(awake.recover(Date.now())).toBe(false);
expect(awake.recoverAt()).toBe(Date.now() + AWAKE_RECOVER_AFTER_MS);
expect(far).toMatchObject({ dials: 1, open: 1 });
// No entry was made by the alarm: the longest hold still ends the socket five minutes after
// the entry in the fifth minute.
await vi.advanceTimersByTimeAsync(
enteredAt + 5 * 60_000 + AWAKE_MAX_HOLD_MS - Date.now() - AWAKE_QUIET_MS,
);
expect(far).toMatchObject({ open: 1 });
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ dials: 1, open: 0 });
expect(awake.recoverAt()).toBeNull();
});
test("a summary that cannot be made is owed, as an unanswered one is", async () => {
vi.useFakeTimers();
onTestFinished(() => void vi.useRealTimers());
vi.spyOn(console, "info").mockImplementation(() => {});
const far = farEnd();
const unanswered = counted();
let readable = false;
const awake = new AwakeSocket({
path: "/agents/a",
dial: far.dial,
busy: () => false,
summary: () => {
if (!readable) throw new Error("the log cannot be read");
return "one";
},
unanswered,
});
awake.entered();
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
// no wait for an answer that cannot come
expect(far).toMatchObject({ sent: [], open: 0 });
expect(unanswered).toMatchObject({ tries: 1 });
expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS);
readable = true;
await vi.advanceTimersByTimeAsync(AWAKE_SAY_AGAIN_AFTER_MS);
expect(awake.recover(Date.now())).toBe(true);
await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS);
expect(far).toMatchObject({ sent: ["one"], open: 0 });
expect(unanswered).toMatchObject({ tries: 0 });
expect(awake.recoverAt()).toBeNull();
});
test("the tries that a context keeps are in a row by time: a count older than an hour counts for nothing", () => {
vi.useFakeTimers();
onTestFinished(() => void vi.useRealTimers());
const stored = new Map<string, unknown>();
const tries = unansweredSummaryTries({
get: (key: string) => stored.get(key),
put: (key: string, value: unknown) => void stored.set(key, value),
delete: (key: string) => stored.delete(key),
} as Pick<SyncKvStorage, "get" | "put" | "delete">);
expect(tries.count()).toBe(0);
tries.set(3);
vi.advanceTimersByTime(59 * 60_000);
expect(tries.count()).toBe(3);
// the object died before the catalog answered, and the context next went unanswered a day later
vi.advanceTimersByTime(24 * 60 * 60_000);
expect(tries.count()).toBe(0);
tries.set(1);
expect(tries.count()).toBe(1);
tries.set(0);
expect(stored).toMatchObject({ size: 0 });
});
/** Where a context keeps how often its summary went unanswered: its own storage, here a field. */
function counted() {
const kept = {
tries: 0,
count: () => kept.tries,
set: (tries: number) => void (kept.tries = tries),
};
return kept;
}
/** The accepting context, as the dialer sees it: counts dials and the sockets that are open, and
* answers each summary as the catalog does, unless `answers` is off. */
function farEnd() {
const closers = new Set<() => void>();
const answerers = new Set<() => void>();
const far = {
dials: 0,
open: 0,
sent: [] as string[],
refuse: false,
answers: true,
/** What the catalog says of each summary. */
answerWith: AWAKE_SUMMARY_KEPT as string,
closeAll: () => closers.forEach((close) => close()),
/** One answer on each open socket: what a catalog that was slow sends at last. */
answer: () => answerers.forEach((answer) => answer()),
dial: async () => {
far.dials += 1;
if (far.refuse) return { status: 503 };
const listeners: Record<string, ((event?: { data: string }) => void)[]> = {};
const answer = () =>
(listeners.message || []).forEach((listener) => listener({ data: far.answerWith }));
const close = () => {
if (!closers.delete(close)) return;
answerers.delete(answer);
far.open -= 1;
(listeners.close || []).forEach((listener) => listener());
};
return {
status: 101,
webSocket: {
accept: () => {
far.open += 1;
closers.add(close);
answerers.add(answer);
},
close,
send: (message: string) => {
far.sent.push(message);
if (far.answers) queueMicrotask(answer);
},
// the one cast: a test socket has only what the dialer uses
addEventListener: ((type: string, listener: (event?: { data: string }) => void) =>
void (listeners[type] ||= []).push(listener)) as WebSocket["addEventListener"],
},
};
},
};
return far;
}