feat: platform backbone and field capture, first part (checkpoint)
Platform backbone (plan 2026-10-13-plattform-rueckgrat), reviewed tasks: - run roles api/worker/job/all with shared startup checks (Task 1) - schema and migration for DomainEvent, deliveries, JobRun, ThrottlerHit (Task 2) - audit, notifications and domain events written in the same transaction (Task 3) - dispatcher with SKIP LOCKED claims, retries and stale release (Task 4) - worker building blocks: tick, LISTEN/NOTIFY wake-up, health (Task 5) - worker process and entry points (Task 6) - throttler counters in Postgres (Task 19) - separate keys per purpose with key ring (Task 20) - public origin page without exact location (Task 22) - shop keys split into read and write (Task 23) - Kustomize base, components, overlay encry, CI validation (Task 26) Field capture T3 (plan 2026-10-13-t3-erfassung-am-stand), reviewed tasks: - brood frames, read endpoints, apiary overview and offline pack - network basics, offline queue v3, navigation sheets, form building blocks - new inspection with last-time hints and weather, varroa per day, treatment prefill, apiary page with round - inspection photo (Task 10) is implemented, review pending Not rolled out. Remaining tasks follow in later commits. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
10cbe9bf2d
commit
c01a38835a
340 files changed
+25695
-1808
No files matched your search
@@ -0,0 +1,25 @@
|
||||
import { assertTransactionClient } from './db-client';
|
||||
|
||||
describe('assertTransactionClient', () => {
|
||||
it('refuses the root client and names the caller', () => {
|
||||
const root = { $connect: jest.fn(), $transaction: jest.fn() };
|
||||
|
||||
expect(() =>
|
||||
assertTransactionClient(root as never, 'DomainEventsService.recordAll'),
|
||||
).toThrow('DomainEventsService.recordAll needs the transaction client');
|
||||
});
|
||||
|
||||
it('accepts a transaction client that can open nested transactions (Prisma 7)', () => {
|
||||
const nestingTx = { $transaction: jest.fn(), $executeRaw: jest.fn() };
|
||||
|
||||
expect(() =>
|
||||
assertTransactionClient(nestingTx as never, 'caller'),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('accepts a plain transaction client', () => {
|
||||
expect(() =>
|
||||
assertTransactionClient({ $executeRaw: jest.fn() } as never, 'caller'),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Prisma } from '../../generated/prisma';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
/**
|
||||
* The root client or the client of an interactive transaction, for helpers
|
||||
* that work on either (e.g. notifyWorker). A helper that must run inside the
|
||||
* caller's business transaction takes Prisma.TransactionClient instead and
|
||||
* checks it with assertTransactionClient.
|
||||
*/
|
||||
export type DbClient = PrismaService | Prisma.TransactionClient;
|
||||
|
||||
/**
|
||||
* Throws if `db` is the root client: a write through it would commit on its
|
||||
* own, even if the caller's business transaction rolls back. `$connect` is
|
||||
* withheld from transaction clients; `$transaction` does not tell the two
|
||||
* apart, because a Prisma 7 transaction client can open nested transactions.
|
||||
* `caller` names the method in the error, e.g. "DomainEventsService.recordAll".
|
||||
*/
|
||||
export function assertTransactionClient(db: DbClient, caller: string): void {
|
||||
if ('$connect' in db) {
|
||||
throw new Error(`${caller} needs the transaction client`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
DB_SESSION_OPTIONS,
|
||||
DB_SESSION_TIME_ZONE,
|
||||
dbSessionConfig,
|
||||
} from './db-session';
|
||||
|
||||
describe('dbSessionConfig', () => {
|
||||
const url = 'postgresql://apicore:s3cret@db:5432/apicore?schema=public';
|
||||
|
||||
it('pins every session to UTC through the startup options', () => {
|
||||
expect(DB_SESSION_TIME_ZONE).toBe('UTC');
|
||||
expect(DB_SESSION_OPTIONS).toBe('-c TimeZone=UTC');
|
||||
expect(dbSessionConfig(url)).toEqual({
|
||||
connectionString: url,
|
||||
options: '-c TimeZone=UTC',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps a missing connection string for pg to report', () => {
|
||||
expect(dbSessionConfig(undefined)).toEqual({
|
||||
connectionString: undefined,
|
||||
options: '-c TimeZone=UTC',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
'postgresql://apicore:s3cret@db/apicore?options=-c%20TimeZone%3DEurope%2FBerlin',
|
||||
'postgresql://apicore:s3cret@db/apicore?schema=public&OPTIONS=-c%20x%3Dy',
|
||||
'postgresql://apicore:s3cret@db/apicore?options',
|
||||
'postgresql://apicore:s3cret@db/apicore?options&schema=public',
|
||||
])(
|
||||
'refuses a URL with its own options - pg would let them override the pin: %s',
|
||||
(withOptions) => {
|
||||
expect(() => dbSessionConfig(withOptions)).toThrow(
|
||||
'DATABASE_URL must not set "options"',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
'postgresql://apicore:s3cret@db/apicore?schema=public&optionsx=1',
|
||||
'postgresql://apicore:s3cret@db/options?schema=public',
|
||||
])('accepts a URL that only looks similar: %s', (similar) => {
|
||||
expect(dbSessionConfig(similar).options).toBe('-c TimeZone=UTC');
|
||||
});
|
||||
|
||||
it('never echoes the connection string (password) in the error', () => {
|
||||
let message = '';
|
||||
try {
|
||||
dbSessionConfig('postgresql://apicore:s3cret@db/apicore?options=x');
|
||||
} catch (error) {
|
||||
message = (error as Error).message;
|
||||
}
|
||||
|
||||
expect(message).toContain('DATABASE_URL must not set "options"');
|
||||
expect(message).not.toContain('s3cret');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Guard: every Postgres client in src gets its settings from
|
||||
* dbSessionConfig, so no session escapes the UTC pin. prisma/seed.ts is the
|
||||
* documented exception: it lives outside src (its build cannot import from
|
||||
* src) and writes only through Prisma, whose timestamps do not depend on
|
||||
* the session time zone.
|
||||
*/
|
||||
describe('database clients in src', () => {
|
||||
const SRC = join(__dirname, '..');
|
||||
const CLIENT_CONSTRUCTION =
|
||||
/new\s+(PrismaPg|Pool|Client)\s*\(([\s\S]{0,120})/g;
|
||||
const FROM_SESSION_CONFIG = /^\s*(?:\{\s*\.\.\.)?\s*dbSessionConfig\(/;
|
||||
const IMPORTS_PG = /from\s+['"]pg['"]/;
|
||||
|
||||
/** `new X(` calls that do not start from dbSessionConfig(...). */
|
||||
function clientsWithoutSessionConfig(source: string): string[] {
|
||||
const usesPg = IMPORTS_PG.test(source);
|
||||
return [...source.matchAll(CLIENT_CONSTRUCTION)]
|
||||
.filter(([, type]) => type === 'PrismaPg' || usesPg)
|
||||
.filter(([, , args]) => !FROM_SESSION_CONFIG.test(args))
|
||||
.map(([, type]) => type);
|
||||
}
|
||||
|
||||
it('builds every PrismaPg, pg Pool and pg Client from dbSessionConfig', () => {
|
||||
const offenders = readdirSync(SRC, { recursive: true, encoding: 'utf8' })
|
||||
.filter((file) => file.endsWith('.ts') && !file.endsWith('.spec.ts'))
|
||||
.flatMap((file) =>
|
||||
clientsWithoutSessionConfig(readFileSync(join(SRC, file), 'utf8')).map(
|
||||
(client) => `${file}: new ${client}`,
|
||||
),
|
||||
);
|
||||
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'a pg Pool',
|
||||
"import { Pool } from 'pg';\nconst pool = new Pool({ connectionString: url });",
|
||||
],
|
||||
[
|
||||
'a pg Client',
|
||||
"import { Client } from 'pg';\nconst client = new Client({ connectionString, keepAlive: true });",
|
||||
],
|
||||
[
|
||||
'a PrismaPg adapter',
|
||||
'const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });',
|
||||
],
|
||||
])('flags %s built without the session config', (_name, source) => {
|
||||
expect(clientsWithoutSessionConfig(source)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'the Prisma adapter',
|
||||
'const adapter = new PrismaPg(dbSessionConfig(process.env.DATABASE_URL));',
|
||||
],
|
||||
[
|
||||
'the LISTEN client',
|
||||
"import { Client } from 'pg';\nreturn new Client({\n ...dbSessionConfig(connectionString),\n keepAlive: true,\n});",
|
||||
],
|
||||
[
|
||||
'a Client that is not pg',
|
||||
"import { Client } from 'openid-client';\nconst oidc = new Client(metadata);",
|
||||
],
|
||||
])('accepts %s', (_name, source) => {
|
||||
expect(clientsWithoutSessionConfig(source)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Every database session runs in UTC. Columns are `timestamp without time
|
||||
* zone`: Prisma fills @default(now()) and writes Dates as UTC wall clock,
|
||||
* while SQL now() (claims, backoff, throttler) is stored in the session's
|
||||
* time zone. Only a UTC session keeps both on one clock, whatever the
|
||||
* server or database default is.
|
||||
*/
|
||||
export const DB_SESSION_TIME_ZONE = 'UTC';
|
||||
export const DB_SESSION_OPTIONS = `-c TimeZone=${DB_SESSION_TIME_ZONE}`;
|
||||
|
||||
export interface DbSessionConfig {
|
||||
connectionString: string | undefined;
|
||||
/** Startup options sent with every new connection. */
|
||||
options: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connection settings for every Postgres client of the app (Prisma pool,
|
||||
* LISTEN client). pg lets an `options` parameter in the URL override the
|
||||
* config, which would silently drop the UTC pin - such a URL is refused.
|
||||
*/
|
||||
export function dbSessionConfig(
|
||||
connectionString: string | undefined,
|
||||
): DbSessionConfig {
|
||||
if (
|
||||
connectionString !== undefined &&
|
||||
/[?&]options(?:=|&|$)/i.test(connectionString)
|
||||
) {
|
||||
throw new Error(
|
||||
'DATABASE_URL must not set "options": the session time zone is pinned to UTC in db-session.ts',
|
||||
);
|
||||
}
|
||||
return { connectionString, options: DB_SESSION_OPTIONS };
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from '../../generated/prisma';
|
||||
import { dbSessionConfig } from './db-session';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService
|
||||
@@ -9,7 +10,8 @@ export class PrismaService
|
||||
{
|
||||
constructor() {
|
||||
super({
|
||||
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
|
||||
// Every pooled connection runs in UTC, see db-session.ts.
|
||||
adapter: new PrismaPg(dbSessionConfig(process.env.DATABASE_URL)),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user