mirror of
https://github.com/nestriness/nestri.git
synced 2026-11-23 15:39:51 +02:00
feat(session): let the owner end a run
POST /session/:id/stop. A run no host has claimed ends at once; one that is starting or live is marked with time_stop_requested and its host is handed a session.stop with reason `user` on every poll until it reports the run ended. The host already ends a run the same way whatever the reason, so no host change is needed. Asking twice keeps the first time asked, and asking of a finished run changes nothing. Somebody else's run answers 404, and a host cannot stop a run as its owner.
This commit is contained in:
@@ -308,6 +308,48 @@ export namespace SessionApi {
|
||||
return c.json({ data: session });
|
||||
}
|
||||
)
|
||||
.post(
|
||||
'/:id/stop',
|
||||
notPublic,
|
||||
describeRoute({
|
||||
tags: ['Session'],
|
||||
summary: 'End a run',
|
||||
description:
|
||||
'Asks for the run to end. A run no host has picked up yet ends at once. One that is starting or live keeps its state, with `timeStopRequested` set, until its host has stopped the box and reported it `ended` — poll the run to see that happen. Asking again, or asking of a run already over, changes nothing and answers with the run as it stands.',
|
||||
responses: {
|
||||
200: {
|
||||
content: { 'application/json': { schema: Result(Session.Info) } },
|
||||
description: 'The run, with the stop recorded'
|
||||
},
|
||||
401: ErrorResponses[401],
|
||||
403: ErrorResponses[403],
|
||||
404: ErrorResponses[404]
|
||||
}
|
||||
}),
|
||||
validator(
|
||||
'param',
|
||||
z.object({
|
||||
id: z.string().meta({
|
||||
description: 'The run to end',
|
||||
example: Examples.Session.id
|
||||
})
|
||||
})
|
||||
),
|
||||
async (c) => {
|
||||
const session = await Session.requestStop({
|
||||
id: c.req.valid('param').id,
|
||||
userId: actingPerson()
|
||||
});
|
||||
if (!session) {
|
||||
throw new VisibleError(
|
||||
'not_found',
|
||||
ErrorCodes.NotFound.RESOURCE_NOT_FOUND,
|
||||
'No such session, or it is not yours'
|
||||
);
|
||||
}
|
||||
return c.json({ data: session });
|
||||
}
|
||||
)
|
||||
.post(
|
||||
'/:id/state',
|
||||
machineOnly,
|
||||
@@ -423,7 +465,7 @@ export namespace SessionApi {
|
||||
tags: ['Session'],
|
||||
summary: 'Ask for work',
|
||||
description:
|
||||
'Returns the work for the calling host, and only that host — it comes from its own credentials and the scope is the query, so a box cannot see work for another. `session.start` is a run waiting to be started; `session.stop` is a run to end now because the terms it started under ran out, repeated on every poll until the host reports it ended. Poll at the cadence the heartbeat hands down. An agent skips a kind it does not know.',
|
||||
'Returns the work for the calling host, and only that host — it comes from its own credentials and the scope is the query, so a box cannot see work for another. `session.start` is a run waiting to be started; `session.stop` is a run to end now, because its owner asked or the terms it started under ran out, repeated on every poll until the host reports it ended. Poll at the cadence the heartbeat hands down. An agent skips a kind it does not know.',
|
||||
responses: {
|
||||
200: {
|
||||
content: { 'application/json': { schema: Result(z.array(Session.Job)) } },
|
||||
|
||||
@@ -161,6 +161,7 @@ describe('POST /session', () => {
|
||||
ticket: null,
|
||||
timeStarted: null,
|
||||
timeStopped: null,
|
||||
timeStopRequested: null,
|
||||
trial: false,
|
||||
errorMessage: null
|
||||
});
|
||||
@@ -726,6 +727,7 @@ describe('POST /session/:id/ticket', () => {
|
||||
'state',
|
||||
'ticket',
|
||||
'timeStarted',
|
||||
'timeStopRequested',
|
||||
'timeStopped',
|
||||
'trial'
|
||||
]);
|
||||
@@ -873,3 +875,78 @@ describe('Session routes in the spec', () => {
|
||||
expect(paths).toContain('/machine/jobs');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /session/:id/stop', () => {
|
||||
const stop = (s: Awaited<ReturnType<typeof scene>>, id: string) =>
|
||||
app.request(`/session/${id}/stop`, { method: 'POST', headers: s.user });
|
||||
const report = (s: Awaited<ReturnType<typeof scene>>, id: string, state: string) =>
|
||||
app.request(`/session/${id}/state`, {
|
||||
method: 'POST',
|
||||
headers: s.host,
|
||||
body: JSON.stringify({ state, claimToken: HOLDER })
|
||||
});
|
||||
const stops = async (s: Awaited<ReturnType<typeof scene>>) => {
|
||||
const res = await app.request('/machine/jobs', { headers: s.host });
|
||||
return (((await res.json()) as any).data as any[]).filter((j) => j.kind === 'session.stop');
|
||||
};
|
||||
|
||||
test('a run no host has picked up ends at once, and is never handed out', async () => {
|
||||
const s = await scene('stop-unclaimed', 5601);
|
||||
const { body } = await requestSession(s);
|
||||
const res = await stop(s, body.data.id);
|
||||
expect(res.status).toBe(200);
|
||||
const out = (await res.json()) as any;
|
||||
expect(out.data.state).toBe('ended');
|
||||
expect(out.data.timeStopped).not.toBeNull();
|
||||
const res2 = await app.request('/machine/jobs', { headers: s.host });
|
||||
expect(((await res2.json()) as any).data).toEqual([]);
|
||||
});
|
||||
|
||||
test('a live run stays live until its host has stopped it', async () => {
|
||||
const s = await scene('stop-live', 5602);
|
||||
const { body } = await requestSession(s);
|
||||
const id = body.data.id;
|
||||
await report(s, id, 'starting');
|
||||
await report(s, id, 'live');
|
||||
|
||||
const res = await stop(s, id);
|
||||
expect(res.status).toBe(200);
|
||||
const out = (await res.json()) as any;
|
||||
expect(out.data.state).toBe('live');
|
||||
expect(out.data.timeStopRequested).not.toBeNull();
|
||||
expect(await stops(s)).toEqual([
|
||||
{ kind: 'session.stop', sessionId: id, boxId: s.box.id, reason: 'user' }
|
||||
]);
|
||||
|
||||
// Asking twice is the same request: the time asked is the first one.
|
||||
const again = (await (await stop(s, id)).json()) as any;
|
||||
expect(again.data.timeStopRequested).toBe(out.data.timeStopRequested);
|
||||
|
||||
await report(s, id, 'ended');
|
||||
expect(await stops(s)).toEqual([]);
|
||||
const over = (await (await stop(s, id)).json()) as any;
|
||||
expect(over.data.state).toBe('ended');
|
||||
});
|
||||
|
||||
test('somebody else’s run is not there to stop', async () => {
|
||||
const s = await scene('stop-owner', 5603);
|
||||
const other = await scene('stop-other', 5604);
|
||||
const { body } = await requestSession(s);
|
||||
const res = await stop(other, body.data.id);
|
||||
expect(res.status).toBe(404);
|
||||
expect(
|
||||
((await (await app.request(`/session/${body.data.id}`, { headers: s.user })).json()) as any)
|
||||
.data.state
|
||||
).toBe('requested');
|
||||
});
|
||||
|
||||
test('a host cannot stop a run as its owner', async () => {
|
||||
const s = await scene('stop-host', 5605);
|
||||
const { body } = await requestSession(s);
|
||||
const res = await app.request(`/session/${body.data.id}/stop`, {
|
||||
method: 'POST',
|
||||
headers: s.host
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "session" ADD COLUMN "time_stop_requested" timestamp with time zone;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -155,6 +155,13 @@
|
||||
"when": 1791534844848,
|
||||
"tag": "0021_machine_gpus",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 22,
|
||||
"version": "7",
|
||||
"when": 1791537816909,
|
||||
"tag": "0022_session_stop_requested",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm';
|
||||
import { and, desc, eq, inArray, isNotNull, isNull, sql } from 'drizzle-orm';
|
||||
import z from 'zod';
|
||||
|
||||
import { Burn } from '../billing/burn.js';
|
||||
@@ -67,6 +67,11 @@ export namespace Session {
|
||||
description: 'When this run ended',
|
||||
example: Examples.Session.timeStopped
|
||||
}),
|
||||
timeStopRequested: z.string().nullable().optional().meta({
|
||||
description:
|
||||
'When the owner asked for this run to end. The run stays `live` until its host has stopped it',
|
||||
example: null
|
||||
}),
|
||||
trial: z.boolean().optional().meta({
|
||||
description:
|
||||
'Whether this run is on Nestri GPUs under the free weekend rather than a plan. A trial run is stopped when its hours or its window run out',
|
||||
@@ -349,8 +354,8 @@ export namespace Session {
|
||||
});
|
||||
|
||||
/**
|
||||
* A run the agent must end now, because the terms it started under have
|
||||
* run out. The agent ends it as it would end any run and reports `ended`;
|
||||
* A run the agent must end now, because its owner asked or the terms it
|
||||
* started under have run out. The agent ends it as it would end any run and reports `ended`;
|
||||
* the job repeats on every poll until it does.
|
||||
*/
|
||||
export const StopJob = z
|
||||
@@ -367,9 +372,9 @@ export namespace Session {
|
||||
description: 'The box it runs in',
|
||||
example: Examples.Session.boxId
|
||||
}),
|
||||
reason: z.enum(['window', 'hours']).meta({
|
||||
reason: z.enum(['user', 'window', 'hours']).meta({
|
||||
description:
|
||||
'`window`: the free weekend closed. `hours`: this weekend’s free hours are used',
|
||||
'`user`: its owner asked. `window`: the free weekend closed. `hours`: this weekend’s free hours are used',
|
||||
example: 'hours'
|
||||
})
|
||||
})
|
||||
@@ -391,9 +396,31 @@ export namespace Session {
|
||||
* `where` clause rather than by whoever is holding them.
|
||||
*/
|
||||
export const listJobsForMachine = fn(z.string(), async (machineId): Promise<Job[]> => {
|
||||
const stops = (await Trial.overdue(machineId)).map(
|
||||
(run): Job => ({ kind: 'session.stop', ...run })
|
||||
const asked = await Database.use((tx) =>
|
||||
tx
|
||||
.select({ sessionId: SessionTable.id, boxId: BoxTable.id })
|
||||
.from(SessionTable)
|
||||
.innerJoin(BoxTable, eq(SessionTable.boxId, BoxTable.id))
|
||||
.where(
|
||||
and(
|
||||
eq(BoxTable.machineId, machineId),
|
||||
inArray(SessionTable.state, ['starting', 'live']),
|
||||
isNotNull(SessionTable.timeStopRequested),
|
||||
isNull(SessionTable.timeDeleted),
|
||||
isNull(BoxTable.timeDeleted)
|
||||
)
|
||||
)
|
||||
.orderBy(SessionTable.timeStopRequested)
|
||||
);
|
||||
// One stop per run: when the owner asked and the trial also ran out,
|
||||
// the owner's reason is the one the run ended for.
|
||||
const seen = new Set(asked.map((r) => r.sessionId));
|
||||
const stops: Job[] = [
|
||||
...asked.map((run): Job => ({ kind: 'session.stop', ...run, reason: 'user' })),
|
||||
...(await Trial.overdue(machineId))
|
||||
.filter((run) => !seen.has(run.sessionId))
|
||||
.map((run): Job => ({ kind: 'session.stop', ...run }))
|
||||
];
|
||||
const starts = await Database.use(async (tx) => {
|
||||
return tx
|
||||
.select({ session: SessionTable, box: BoxTable, game: GameTable })
|
||||
@@ -486,6 +513,48 @@ export namespace Session {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The owner asks for a run to end.
|
||||
*
|
||||
* A run nobody has claimed yet ends here and now: no host holds it, so
|
||||
* there is nothing to stop and it never cost anything. One a host holds is
|
||||
* only marked, and the host is handed a stop on its next poll; it stays
|
||||
* `starting` or `live` until the host reports it ended, because only the
|
||||
* host knows when the box is gone. Asking twice is the same request, and
|
||||
* asking of a run already over changes nothing.
|
||||
*
|
||||
* Null when the run is not there or not this person's.
|
||||
*/
|
||||
export const requestStop = fn(z.object({ id: Info.shape.id, userId: z.string() }), async (input) => {
|
||||
return Database.transaction(async (tx) => {
|
||||
const mine = tx
|
||||
.select({ id: BoxTable.id })
|
||||
.from(BoxTable)
|
||||
.where(and(eq(BoxTable.userId, input.userId), isNull(BoxTable.timeDeleted)));
|
||||
const scope = and(
|
||||
eq(SessionTable.id, input.id),
|
||||
inArray(SessionTable.boxId, mine),
|
||||
isNull(SessionTable.timeDeleted)
|
||||
);
|
||||
// Unclaimed: the state is in the `where`, so a host claiming it at
|
||||
// the same moment wins or loses cleanly, never both.
|
||||
const [cancelled] = await tx
|
||||
.update(SessionTable)
|
||||
.set({ state: 'ended', timeStopRequested: sql`now()`, timeStopped: sql`now()` })
|
||||
.where(and(scope, eq(SessionTable.state, 'requested')))
|
||||
.returning();
|
||||
if (cancelled) return serialize(cancelled);
|
||||
const [marked] = await tx
|
||||
.update(SessionTable)
|
||||
.set({ timeStopRequested: sql`coalesce(${SessionTable.timeStopRequested}, now())` })
|
||||
.where(and(scope, inArray(SessionTable.state, ['starting', 'live'])))
|
||||
.returning();
|
||||
if (marked) return serialize(marked);
|
||||
const [over] = await tx.select().from(SessionTable).where(scope);
|
||||
return over ? serialize(over) : null;
|
||||
});
|
||||
});
|
||||
|
||||
/** The boxes one host is responsible for, as a subquery to scope a write. */
|
||||
function boxesOn(tx: Parameters<Parameters<typeof Database.use>[0]>[0], machineId: string) {
|
||||
return tx
|
||||
@@ -844,6 +913,7 @@ export namespace Session {
|
||||
ticket: input.ticket,
|
||||
timeStarted: input.timeStarted?.toISOString() ?? null,
|
||||
timeStopped: input.timeStopped?.toISOString() ?? null,
|
||||
timeStopRequested: input.timeStopRequested?.toISOString() ?? null,
|
||||
trial: input.trial,
|
||||
errorMessage: input.errorMessage
|
||||
};
|
||||
|
||||
@@ -61,6 +61,12 @@ export const SessionTable = pgTable(
|
||||
/** Null until the box actually starts, which is not when the row appears. */
|
||||
timeStarted: utc('time_started'),
|
||||
timeStopped: utc('time_stopped'),
|
||||
/**
|
||||
* When the person asked for this run to end, or null if nobody has. The
|
||||
* host is handed a stop for every running row that has one, until it
|
||||
* reports the run ended; the request is the record, not a queue entry.
|
||||
*/
|
||||
timeStopRequested: utc('time_stop_requested'),
|
||||
// A run on rented GPUs under the free weekend rather than a plan. Its
|
||||
// time is counted against the trial and not the plan's allowance, and
|
||||
// it is the run that is stopped when the trial's hours or its window
|
||||
|
||||
Reference in New Issue
Block a user