feat(core): a box is a row, a session is the billing unit

Migration 1 of 0048, and the first of the seven weeks — nothing about a live
feed works without these two tables, so it is not a cleanup during them.

  box      a VM someone owns: an id that is also its DNS label, an editable
           label, an owning user, the machine it sits on, a tier and a state.
           Owned by a person and placed on a team's hardware, which are two
           different relationships, hence both userId and machineId.
  session  one run of one box by one linked Steam account, and what costs
           money. Separate from box because the ticket changes after bind as
           addresses are discovered — the vsock contract calls it "a stream,
           not one value" — so it is a column a client polls, not a value it
           is handed once.

Box states are neslet's own three and no more. `starting` and `stopping` are
the obvious additions and both are omitted because nothing would ever write
them; a failed box is `stopped` with stopClean false, which is how neslet
models it too.

The generated migration would have failed on live rows in three ways, so it
is hand-written and tested against a database seeded at the old schema:

  - machine.team_id becomes notNull, and *every existing row is null* because
    the old registration path passed null. Personal teams are backfilled for
    machine owners first, reusing a team they already own rather than minting
    a second, with the owner membership row repaired where missing.
  - game_download.host_id becomes a foreign key. It held free-form strings,
    so unattributable rows are deleted before the cast — the only destructive
    statement here, and a considered loss: it is a progress report neslet
    re-derives from disk.
  - Team.createPersonal was written and documented in packages/core/CLAUDE.md
    as part of the login flow and never actually called, so no user has a
    team. ensurePersonal is idempotent and now runs on every login, which is
    what backfills accounts the migration does not reach.

Verified on a seeded legacy database: three null-team machines backfilled, an
existing team reused rather than duplicated, a blank display name handled, and
both unattributable download rows dropped while the attributable one survived.

Also fixes two things this work ran into rather than caused:

  - Database.client() built a new postgres pool on every call, and use()
    called it twice per invocation — pools of ten connections held for a 30s
    idle timeout. Invisible in a Worker where requests are short; the suite
    crossed 100 connections and Postgres said "sorry, too many clients
    already" in whichever file ran last, which reads as a flaky test rather
    than a leak. Now one pool per connection string.
  - download.test.ts asserted against `hst_…` host ids, which is exactly the
    unattributable row the new foreign key exists to refuse.

There is no "no team" any more: PATCH /machine/:id took teamId null to mean
"mine alone" and now requires a team, because the personal team is the one to
name. Its test is updated to the new contract rather than deleted.

113 → 128 tests, 0 fail.
This commit is contained in:
Wanjohi
2026-09-03 21:39:27 +03:00
parent 1bfdfcf3cf
commit 6c1d407985
23 changed files with 3681 additions and 44 deletions
+204
View File
@@ -0,0 +1,204 @@
import { and, desc, eq, isNull, sql } from 'drizzle-orm';
import z from 'zod';
import { Database } from '../db/index.js';
import { Examples } from '../examples.js';
import { fn } from '../fn.js';
import { SessionState, SessionTable } from './session.sql.js';
/**
* One run of one box, and the unit that gets billed.
*
* A row appears at `POST /session`, before anything has been placed — so the
* row *is* the job the control plane fulfils, and `requested` is a real state
* rather than a placeholder. The ticket arrives later and changes as addresses
* are discovered, which is why a client polls this rather than being handed a
* value once.
*/
export namespace Session {
export const Info = z
.object({
id: z.string().meta({
description: 'Unique identifier for this run',
example: Examples.Session.id
}),
boxId: z.string().meta({
description: 'The box being run',
example: Examples.Session.boxId
}),
gameId: z.string().meta({
description: 'The game this run launched',
example: Examples.Session.gameId
}),
linkedAccountId: z.string().meta({
description: 'Which linked Steam account is playing',
example: Examples.Session.linkedAccountId
}),
state: z.enum(SessionState.enumValues).meta({
description: 'Where this run is. Only `live` costs money',
example: Examples.Session.state
}),
ticket: z.string().nullable().optional().meta({
description: 'Current iroh connect ticket, or null before neshub mints one',
example: Examples.Session.ticket
}),
timeStarted: z.string().nullable().optional().meta({
description: 'When the box actually started, not when the row appeared',
example: Examples.Session.timeStarted
}),
timeStopped: z.string().nullable().optional().meta({
description: 'When this run ended',
example: Examples.Session.timeStopped
}),
errorMessage: z.string().nullable().optional().meta({
description: 'Why it failed, when it did',
example: Examples.Session.errorMessage
})
})
.meta({
ref: 'Session',
description: 'One live run of one box by one Steam account, and the billing unit',
example: Examples.Session
});
export type Info = z.infer<typeof Info>;
export const create = fn(
Info.pick({ id: true, boxId: true, gameId: true, linkedAccountId: true }),
async (input) => {
return Database.use(async (tx) => {
return tx
.insert(SessionTable)
.values({
id: input.id,
boxId: input.boxId,
gameId: input.gameId,
linkedAccountId: input.linkedAccountId
})
.returning()
.then((rows) => serialize(rows[0]!));
});
}
);
export const fromID = fn(Info.shape.id, async (id) => {
return Database.use(async (tx) => {
return tx
.select()
.from(SessionTable)
.where(and(eq(SessionTable.id, id), isNull(SessionTable.timeDeleted)))
.then((rows) => {
const row = rows.at(0);
return row ? serialize(row) : null;
});
});
});
/**
* The run currently occupying a box, if any.
*
* Newest first and limited to one: a box has at most one live session by
* construction, and if that ever stops being true this is the query that
* should start refusing rather than picking a winner silently.
*/
export const activeForBox = fn(Info.shape.boxId, async (boxId) => {
return Database.use(async (tx) => {
return tx
.select()
.from(SessionTable)
.where(
and(
eq(SessionTable.boxId, boxId),
isNull(SessionTable.timeDeleted),
isNull(SessionTable.timeStopped)
)
)
.orderBy(desc(SessionTable.timeCreated))
.limit(1)
.then((rows) => {
const row = rows.at(0);
return row ? serialize(row) : null;
});
});
});
export const listByBox = fn(Info.shape.boxId, async (boxId) => {
return Database.use(async (tx) => {
return tx
.select()
.from(SessionTable)
.where(and(eq(SessionTable.boxId, boxId), isNull(SessionTable.timeDeleted)))
.orderBy(desc(SessionTable.timeCreated))
.then((rows) => rows.map(serialize));
});
});
/**
* Publish the current ticket.
*
* Overwrites, deliberately: the vsock contract describes the ticket as *"a
* stream, not one value"*, so a later ticket for the same session is a
* better address for the same thing and not a second session.
*/
export const setTicket = fn(Info.pick({ id: true, ticket: true }), async (input) => {
return Database.use(async (tx) => {
return tx
.update(SessionTable)
.set({ ticket: input.ticket ?? null })
.where(and(eq(SessionTable.id, input.id), isNull(SessionTable.timeDeleted)))
.returning()
.then((rows) => {
const row = rows.at(0);
return row ? serialize(row) : null;
});
});
});
/**
* Move a run along.
*
* `live` stamps `timeStarted` and `ended`/`failed` stamp `timeStopped`, both
* only if unset — so a duplicate report does not extend a session someone is
* billed for, and metering can trust the pair.
*/
export const setState = fn(
Info.pick({ id: true, state: true, errorMessage: true }),
async (input) => {
const now = sql`now()`;
return Database.use(async (tx) => {
return tx
.update(SessionTable)
.set({
state: input.state,
errorMessage: input.state === 'failed' ? (input.errorMessage ?? null) : null,
...(input.state === 'live'
? { timeStarted: sql`coalesce(${SessionTable.timeStarted}, ${now})` }
: {}),
...(input.state === 'ended' || input.state === 'failed'
? { timeStopped: sql`coalesce(${SessionTable.timeStopped}, ${now})` }
: {})
})
.where(and(eq(SessionTable.id, input.id), isNull(SessionTable.timeDeleted)))
.returning()
.then((rows) => {
const row = rows.at(0);
return row ? serialize(row) : null;
});
});
}
);
export function serialize(input: typeof SessionTable.$inferSelect): z.infer<typeof Info> {
return {
id: input.id,
boxId: input.boxId,
gameId: input.gameId,
linkedAccountId: input.linkedAccountId,
state: input.state as Info['state'],
ticket: input.ticket,
timeStarted: input.timeStarted?.toISOString() ?? null,
timeStopped: input.timeStopped?.toISOString() ?? null,
errorMessage: input.errorMessage
};
}
}