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
6 changes: 5 additions & 1 deletion hub/docs/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ Keep ordinary value and shape validation in application code. Add a database gua

For prototypes, one active branch has one identity per repository, including concurrent writes. Retired branches keep their history. A registered prototype must have a nonblank name and cannot be a replica branch.

A Build number is positive and unique within its prototype. A prototype's current Build, if set, belongs to that prototype.
A Build number is positive and unique within its prototype. A known commit SHA uses 40 or 64 lowercase hexadecimal characters and is also unique within its prototype. A prototype's current Build, if set, belongs to that prototype.

Builds retain the author's provider, issuer, and provider user ID independently of Hub user IDs. For a workflow Build, the author is the Git commit author. Those three identity values must be present together or absent together. Login, name, and avatar are snapshots and may be unavailable. When Build timestamps are present, they must match its state; older Builds may keep both timestamps unknown. A failure summary belongs only to a failed Build and is limited to 1,000 bytes.

Builds created before commit metadata was stored retain `NULL` for unknown values during the upgrade. A later detail API must represent missing values rather than inventing them. This migration does not import Rails records or map their integer IDs.

PostgreSQL `CHECK` expressions accept `NULL` unless the expression explicitly rejects it. Write nullable-branch checks so every invalid `NULL` combination evaluates to false. Design indexes from the real equality, range, ordering, and partial predicates used by lock, restore, and lookup queries.

Expand Down
2 changes: 1 addition & 1 deletion hub/docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ When you sign in through GitHub or Entra instead, find your `userId` in the brow
NODE_ENV=development npm run db:seed:index -- USER_UUID
```

The command requires an active Hub member and a local development database. It accepts a loopback PostgreSQL URL or the exact devcontainer database URL, and rejects query parameters that override the host, address, port, or service. It creates a sample repository and six prototypes with fixed IDs. Five show each Build state, and one has no Build. Running it again restores those samples. All active Hub members can currently read every non-removed repository. Repository discovery and per-repository authorization are not connected; do not add real repository data until those controls exist.
The command requires an active Hub member and a local development database. It accepts a loopback PostgreSQL URL or the exact devcontainer database URL, and rejects query parameters that override the host, address, port, or service. It creates a sample repository and six prototypes with fixed IDs. Five show each Build state, and one has no Build. Their commit and author values are synthetic. Running it again restores those samples, including metadata added after an upgrade. All active Hub members can currently read every non-removed repository. Repository discovery and per-repository authorization are not connected; do not add real repository data until those controls exist.

Vite also forwards WebSocket upgrades under `/api`. The `/api/realtime` endpoint rejects connections until application access checks are connected; see [WebSocket updates](websockets.md). Stopping the API closes its WebSocket connections as well.

Expand Down
17 changes: 14 additions & 3 deletions hub/schema/build.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,26 @@ model Build {
currentFor Prototype[] @relation("CurrentPrototypeBuild")

// Attribute columns
number Int
state BuildState @default(queued)
workflowCreatedAt DateTime? @map("workflow_created_at") @db.Timestamptz(3)
number Int
state BuildState @default(queued)
commitSha String? @map("commit_sha") @db.VarChar(64)
authorProvider String? @map("author_provider") @db.VarChar(100)
authorIssuer String? @map("author_issuer") @db.VarChar(500)
authorProviderUserId String? @map("author_provider_user_id") @db.VarChar(500)
authorLogin String? @map("author_login") @db.VarChar(255)
authorName String? @map("author_name") @db.VarChar(255)
authorAvatarUrl String? @map("author_avatar_url") @db.VarChar(2048)
workflowCreatedAt DateTime? @map("workflow_created_at") @db.Timestamptz(3)
startedAt DateTime? @map("started_at") @db.Timestamptz(3)
finishedAt DateTime? @map("finished_at") @db.Timestamptz(3)
failureSummary String? @map("failure_summary") @db.VarChar(1000)

// Timestamp columns
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3)

@@unique([id, prototypeId])
@@unique([prototypeId, number])
@@unique([prototypeId, commitSha])
@@map("builds")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
ALTER TABLE "builds"
ADD COLUMN "commit_sha" VARCHAR(64),
ADD COLUMN "author_provider" VARCHAR(100),
ADD COLUMN "author_issuer" VARCHAR(500),
ADD COLUMN "author_provider_user_id" VARCHAR(500),
ADD COLUMN "author_login" VARCHAR(255),
ADD COLUMN "author_name" VARCHAR(255),
ADD COLUMN "author_avatar_url" VARCHAR(2048),
ADD COLUMN "started_at" TIMESTAMPTZ(3),
ADD COLUMN "finished_at" TIMESTAMPTZ(3),
ADD COLUMN "failure_summary" VARCHAR(1000);

CREATE UNIQUE INDEX "builds_prototype_id_commit_sha_key"
ON "builds"("prototype_id", "commit_sha");

-- A canonical SHA keeps the same commit from being recorded under different spellings.
ALTER TABLE "builds" ADD CONSTRAINT "builds_commit_sha_check"
CHECK ("commit_sha" IS NULL OR "commit_sha" ~ '^([0-9a-f]{40}|[0-9a-f]{64})$');

-- A provider user ID identifies an author only with its provider and issuer.
ALTER TABLE "builds" ADD CONSTRAINT "builds_author_identity_check"
CHECK (
(
"author_provider" IS NULL
AND "author_issuer" IS NULL
AND "author_provider_user_id" IS NULL
) OR (
"author_provider" IS NOT NULL
AND "author_issuer" IS NOT NULL
AND "author_provider_user_id" IS NOT NULL
AND translate(
"author_provider",
chr(9) || chr(10) || chr(11) || chr(12) || chr(13) || chr(32) ||
chr(133) || chr(160) || chr(5760) || chr(8192) || chr(8193) || chr(8194) ||
chr(8195) || chr(8196) || chr(8197) || chr(8198) || chr(8199) ||
chr(8200) || chr(8201) || chr(8202) || chr(8232) || chr(8233) ||
chr(8239) || chr(8287) || chr(12288) || chr(65279),
''
) <> ''
AND translate(
"author_issuer",
chr(9) || chr(10) || chr(11) || chr(12) || chr(13) || chr(32) ||
chr(133) || chr(160) || chr(5760) || chr(8192) || chr(8193) || chr(8194) ||
chr(8195) || chr(8196) || chr(8197) || chr(8198) || chr(8199) ||
chr(8200) || chr(8201) || chr(8202) || chr(8232) || chr(8233) ||
chr(8239) || chr(8287) || chr(12288) || chr(65279),
''
) <> ''
AND translate(
"author_provider_user_id",
chr(9) || chr(10) || chr(11) || chr(12) || chr(13) || chr(32) ||
chr(133) || chr(160) || chr(5760) || chr(8192) || chr(8193) || chr(8194) ||
chr(8195) || chr(8196) || chr(8197) || chr(8198) || chr(8199) ||
chr(8200) || chr(8201) || chr(8202) || chr(8232) || chr(8233) ||
chr(8239) || chr(8287) || chr(12288) || chr(65279),
''
) <> ''
)
);

ALTER TABLE "builds" ADD CONSTRAINT "builds_failure_summary_check"
CHECK (
"failure_summary" IS NULL
OR ("state" = 'failed' AND octet_length("failure_summary") BETWEEN 1 AND 1000)
);

ALTER TABLE "builds" ADD CONSTRAINT "builds_state_timestamps_check"
CHECK (
("started_at" IS NULL AND "finished_at" IS NULL)
OR ("state" = 'running' AND "started_at" IS NOT NULL AND "finished_at" IS NULL)
OR ("state" = 'superseded' AND "started_at" IS NULL AND "finished_at" IS NOT NULL)
Comment thread
nshki marked this conversation as resolved.
Resolved
OR ("state" IN ('failed', 'successful') AND "started_at" IS NOT NULL AND "finished_at" IS NOT NULL)
);
97 changes: 97 additions & 0 deletions hub/server/scripts/seed-prototype-index/index.db.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest"

import { prisma } from "../../integrations/prisma"
import { seedPrototypeIndexData } from "./seed-prototype-index-data"

describe("prototype index seed", () => {
it("seeds a member's prototypes and restores their Build metadata on rerun", async () => {
const user = await prisma.user.create({ data: {} })
await prisma.membership.create({ data: { userId: user.id } })
await seedPrototypeIndexData(prisma, user.id)
const select = {
id: true,
number: true,
state: true,
workflowCreatedAt: true,
commitSha: true,
authorProvider: true,
authorIssuer: true,
authorProviderUserId: true,
authorLogin: true,
authorName: true,
authorAvatarUrl: true,
startedAt: true,
finishedAt: true,
failureSummary: true,
} as const
const samples = await prisma.build.findMany({ select, orderBy: { id: "asc" } })
expect(samples).toHaveLength(5)
const prototypes = await prisma.prototype.findMany({ select: { authorId: true } })
expect(prototypes.every((prototype) => prototype.authorId === user.id)).toBe(true)
expect(samples.map((build) => build.state)).toEqual(
expect.arrayContaining(["queued", "running", "successful", "failed", "superseded"]),
)
for (const build of samples) {
expect(build.commitSha).toMatch(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/)
expect(build.authorProvider).toMatch(/\S/)
expect(build.authorIssuer).toMatch(/\S/)
expect(build.authorProviderUserId).toMatch(/\S/)
expect(build.authorLogin).toMatch(/\S/)
expect(build.authorName).toMatch(/\S/)
expect(build.authorProviderUserId).not.toBe(user.id)
if (build.state === "queued") {
expect(build.startedAt).toBeNull()
expect(build.finishedAt).toBeNull()
}
if (build.state === "running") {
expect(build.startedAt).toBeInstanceOf(Date)
expect(build.finishedAt).toBeNull()
}
if (build.state === "successful" || build.state === "failed") {
expect(build.startedAt).toBeInstanceOf(Date)
expect(build.finishedAt).toBeInstanceOf(Date)
}
if (build.state === "superseded") {
expect(build.startedAt).toBeNull()
expect(build.finishedAt).toBeInstanceOf(Date)
}
if (build.workflowCreatedAt && build.startedAt) {
expect(build.startedAt.getTime()).toBeGreaterThanOrEqual(build.workflowCreatedAt.getTime())
}
if (build.startedAt && build.finishedAt) {
expect(build.finishedAt.getTime()).toBeGreaterThanOrEqual(build.startedAt.getTime())
}
if (build.state === "failed") {
expect(build.failureSummary).toEqual(expect.stringMatching(/\S/))
} else {
expect(build.failureSummary).toBeNull()
}
}

for (const build of samples) {
await prisma.build.update({
where: { id: build.id },
data: {
commitSha: null,
authorProvider: "changed-provider",
authorIssuer: "https://changed.example.test",
authorProviderUserId: "changed-external-id",
authorLogin: "changed-login",
authorName: "Changed Author",
authorAvatarUrl: "https://example.test/changed.png",
startedAt:
build.state === "running" || build.state === "successful" || build.state === "failed"
? new Date("2000-01-01T00:00:00Z")
: null,
finishedAt:
build.state === "superseded" || build.state === "successful" || build.state === "failed"
? new Date("2000-01-01T00:01:00Z")
: null,
failureSummary: build.state === "failed" ? "Changed failure" : null,
},
})
}
await seedPrototypeIndexData(prisma, user.id)
expect(await prisma.build.findMany({ select, orderBy: { id: "asc" } })).toEqual(samples)
}, 60_000)
})
28 changes: 27 additions & 1 deletion hub/server/scripts/seed-prototype-index/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,34 @@
import { spawnSync } from "node:child_process"
import { fileURLToPath } from "node:url"
import { describe, expect, it } from "vitest"
import { describe, expect, it, vi } from "vitest"

describe("prototype index seed", () => {
it("seeds the selected local member and closes the database connection", async () => {
const userId = "00000000-0000-4000-8000-000000000001"
const prisma = { $disconnect: vi.fn() }
const seed = vi.fn()
const originalArgv = process.argv

try {
process.argv = [process.execPath, "seed-prototype-index", userId]
vi.stubEnv("NODE_ENV", "development")
vi.stubEnv("DATABASE_URL", "postgresql://replica:replica@127.0.0.1:5432/replica")
vi.stubEnv("DOTENV_CONFIG_OVERRIDE", "false")
vi.doMock("../../integrations/prisma/index.ts", () => ({ prisma }))
vi.doMock("./seed-prototype-index-data/index.ts", () => ({ seedPrototypeIndexData: seed }))
vi.spyOn(console, "log").mockImplementation(() => {})

await import(".")

expect(seed).toHaveBeenCalledExactlyOnceWith(prisma, userId)
expect(prisma.$disconnect).toHaveBeenCalledOnce()
} finally {
process.argv = originalArgv
vi.doUnmock("../../integrations/prisma/index.ts")
vi.doUnmock("./seed-prototype-index-data/index.ts")
}
})

it("rejects unsafe configuration before initializing Prisma", () => {
const script = fileURLToPath(new URL("./index.ts", import.meta.url))
const result = spawnSync(process.execPath, [script, "00000000-0000-4000-8000-000000000001"], {
Expand Down
Loading
Loading