Skip to content

Open-source status page, incident response and uptime monitoring

feat(services): scaffold domain service layer package (#2100)

Maximilian Kaske58ccc38a0edb
diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts
index 2e05a8b86..c4746fbc9 100644
--- a/packages/db/src/index.ts
+++ b/packages/db/src/index.ts
@@ -1,5 +1,6 @@
export * as schema from "./schema";
export * from "drizzle-orm";
+export { SQLiteTransaction } from "drizzle-orm/sqlite-core";
export * from "./db";
// doing this because the external module not working see : https://github.com/vercel/next.js/issues/43433
// export * from "./sync-db";
diff --git a/packages/services/package.json b/packages/services/package.json
new file mode 100644
index 000000000..4fb6d59c1
--- /dev/null
+++ b/packages/services/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@openstatus/services",
+ "version": "0.0.0",
+ "type": "module",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": {
+ "import": "./src/index.ts",
+ "types": "./src/index.ts"
+ }
+ },
+ "scripts": {
+ "test": "bun test"
+ },
+ "dependencies": {
+ "@logtape/logtape": "2.0.1",
+ "@openstatus/db": "workspace:*",
+ "zod": "4.1.13"
+ },
+ "devDependencies": {
+ "@openstatus/tsconfig": "workspace:*",
+ "@types/bun": "latest",
+ "typescript": "5.9.3"
+ }
+}
diff --git a/packages/services/src/__tests__/with-transaction.test.ts b/packages/services/src/__tests__/with-transaction.test.ts
new file mode 100644
index 000000000..1bb9c4770
--- /dev/null
+++ b/packages/services/src/__tests__/with-transaction.test.ts
@@ -0,0 +1,59 @@
+import { beforeAll, describe, expect, test } from "bun:test";
+
+import { SEEDED_WORKSPACE_TEAM_ID } from "../../test/fixtures";
+import { loadSeededWorkspace } from "../../test/helpers";
+import type { DB, ServiceContext } from "../context";
+import { isTx, withTransaction } from "../context";
+
+describe("withTransaction", () => {
+ let ctx: ServiceContext;
+
+ beforeAll(async () => {
+ const workspace = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
+ ctx = {
+ workspace,
+ actor: { type: "user", userId: 1 },
+ };
+ });
+
+ test("opens a tx when ctx.db is a client", async () => {
+ let received: DB | undefined;
+ const result = await withTransaction(ctx, async (tx) => {
+ received = tx;
+ return 42;
+ });
+ expect(result).toBe(42);
+ expect(received).toBeDefined();
+ expect(isTx(received as DB)).toBe(true);
+ });
+
+ test("reuses ctx.db when it is already a tx (identity preserved)", async () => {
+ await withTransaction(ctx, async (outerTx) => {
+ let reusedTx: DB | undefined;
+ await withTransaction({ ...ctx, db: outerTx }, async (innerTx) => {
+ reusedTx = innerTx;
+ });
+ expect(reusedTx).toBe(outerTx);
+ });
+ });
+
+ test("nested withTransaction calls all reuse the outermost tx", async () => {
+ await withTransaction(ctx, async (level1) => {
+ await withTransaction({ ...ctx, db: level1 }, async (level2) => {
+ await withTransaction({ ...ctx, db: level2 }, async (level3) => {
+ expect(level3).toBe(level1);
+ expect(level2).toBe(level1);
+ });
+ });
+ });
+ });
+
+ test("error thrown inside reused tx propagates to outer caller", async () => {
+ const outerPromise = withTransaction(ctx, async (outerTx) => {
+ await withTransaction({ ...ctx, db: outerTx }, async () => {
+ throw new Error("boom");
+ });
+ });
+ await expect(outerPromise).rejects.toThrow("boom");
+ });
+});
diff --git a/packages/services/src/audit.ts b/packages/services/src/audit.ts
new file mode 100644
index 000000000..566c824aa
--- /dev/null
+++ b/packages/services/src/audit.ts
@@ -0,0 +1,74 @@
+import { getLogger } from "@logtape/logtape";
+
+import {
+ type Actor,
+ type DB,
+ type ServiceContext,
+ extractActorId,
+} from "./context";
+
+const logger = getLogger(["services", "audit"]);
+
+export type AuditEntry = {
+ /** Canonical action identifier, e.g. "status_report.create". */
+ action: string;
+ /** Entity type the action targets, e.g. "status_report". */
+ entityType: string;
+ entityId: number | string;
+ /**
+ * Accepted at the call site for audit log v2 (dedicated table with scrub/redact
+ * policy) but dropped before writing in v1 — logs are not the right place for
+ * PII-bearing payloads. Callers still emit full entries so v2 only needs to
+ * change emitAudit's body, not the ~200 future emitter sites.
+ */
+ before?: unknown;
+ after?: unknown;
+ metadata?: Record<string, unknown>;
+};
+
+export type AuditLogRecord = {
+ workspaceId: number;
+ actorType: Actor["type"];
+ actorId: string;
+ action: string;
+ entityType: string;
+ entityId: string;
+ requestId: string | undefined;
+};
+
+// Test-only audit buffer. Tests opt in via installTestAuditBuffer(); when
+// active, emitAudit pushes records into the buffer so tests can assert against
+// them without parsing logs.
+let testBuffer: AuditLogRecord[] | null = null;
+
+export function installTestAuditBuffer(): AuditLogRecord[] {
+ const buffer: AuditLogRecord[] = [];
+ testBuffer = buffer;
+ return buffer;
+}
+
+export function uninstallTestAuditBuffer(): void {
+ testBuffer = null;
+}
+
+export async function emitAudit(
+ // `tx` is unused in v1 but part of the contract: audit rows will be written
+ // inside the caller's transaction in v2. Signature stays stable.
+ _tx: DB,
+ ctx: ServiceContext,
+ entry: AuditEntry,
+): Promise<void> {
+ const record: AuditLogRecord = {
+ workspaceId: ctx.workspace.id,
+ actorType: ctx.actor.type,
+ actorId: extractActorId(ctx.actor),
+ action: entry.action,
+ entityType: entry.entityType,
+ entityId: String(entry.entityId),
+ requestId: ctx.requestId,
+ };
+
+ if (testBuffer) testBuffer.push(record);
+
+ logger.info(`audit: ${record.action}`, { audit: true, ...record });
+}
diff --git a/packages/services/src/context.ts b/packages/services/src/context.ts
new file mode 100644
index 000000000..5c0bb52aa
--- /dev/null
+++ b/packages/services/src/context.ts
@@ -0,0 +1,56 @@
+import { SQLiteTransaction, db as defaultDb, is } from "@openstatus/db";
+import type { Workspace } from "@openstatus/db/src/schema";
+
+// `@openstatus/db` does not export named DrizzleClient / DrizzleTx types today,
+// so we derive them from the db export and re-export from here.
+export type DrizzleClient = typeof defaultDb;
+export type DrizzleTx = Parameters<
+ Parameters<DrizzleClient["transaction"]>[0]
+>[0];
+export type DB = DrizzleClient | DrizzleTx;
+
+export type Actor =
+ | { type: "user"; userId: number }
+ | { type: "apiKey"; keyId: string; userId?: number }
+ | { type: "slack"; teamId: string; slackUserId: string; userId?: number }
+ | { type: "system"; job: string }
+ | { type: "webhook"; source: string; externalId?: string };
+
+export type ServiceContext = {
+ workspace: Workspace;
+ actor: Actor;
+ requestId?: string;
+ span?: unknown;
+ db?: DB;
+};
+
+// drizzle's `is()` helper is identity-safe across module copies (uses a
+// symbol-based entityKind), which `instanceof` is not under pnpm when multiple
+// resolution paths exist.
+export function isTx(db: DB): db is DrizzleTx {
+ return is(db, SQLiteTransaction);
+}
+
+export async function withTransaction<T>(
+ ctx: ServiceContext,
+ fn: (tx: DB) => Promise<T>,
+): Promise<T> {
+ const db = ctx.db ?? defaultDb;
+ if (isTx(db)) return fn(db);
+ return (db as DrizzleClient).transaction(fn);
+}
+
+export function extractActorId(actor: Actor): string {
+ switch (actor.type) {
+ case "user":
+ return String(actor.userId);
+ case "apiKey":
+ return actor.keyId;
+ case "slack":
+ return actor.slackUserId;
+ case "system":
+ return actor.job;
+ case "webhook":
+ return actor.externalId ?? actor.source;
+ }
+}
diff --git a/packages/services/src/errors.ts b/packages/services/src/errors.ts
new file mode 100644
index 000000000..3a8d1a109
--- /dev/null
+++ b/packages/services/src/errors.ts
@@ -0,0 +1,61 @@
+export type ServiceErrorCode =
+ | "NOT_FOUND"
+ | "FORBIDDEN"
+ | "UNAUTHORIZED"
+ | "CONFLICT"
+ | "VALIDATION"
+ | "LIMIT_EXCEEDED"
+ | "INTERNAL";
+
+export class ServiceError extends Error {
+ constructor(
+ public code: ServiceErrorCode,
+ message: string,
+ public cause?: unknown,
+ ) {
+ super(message);
+ this.name = this.constructor.name;
+ }
+}
+
+export class NotFoundError extends ServiceError {
+ constructor(entity: string, id: string | number) {
+ super("NOT_FOUND", `${entity} ${id} not found`);
+ }
+}
+
+export class ForbiddenError extends ServiceError {
+ constructor(message: string) {
+ super("FORBIDDEN", message);
+ }
+}
+
+export class UnauthorizedError extends ServiceError {
+ constructor(message: string) {
+ super("UNAUTHORIZED", message);
+ }
+}
+
+export class ConflictError extends ServiceError {
+ constructor(message: string) {
+ super("CONFLICT", message);
+ }
+}
+
+export class ValidationError extends ServiceError {
+ constructor(message: string, cause?: unknown) {
+ super("VALIDATION", message, cause);
+ }
+}
+
+export class LimitExceededError extends ServiceError {
+ constructor(limit: string, max: number) {
+ super("LIMIT_EXCEEDED", `${limit} limit reached (${max})`);
+ }
+}
+
+export class InternalServiceError extends ServiceError {
+ constructor(message: string, cause?: unknown) {
+ super("INTERNAL", message, cause);
+ }
+}
diff --git a/packages/services/src/index.ts b/packages/services/src/index.ts
new file mode 100644
index 000000000..a4ef367f7
--- /dev/null
+++ b/packages/services/src/index.ts
@@ -0,0 +1,38 @@
+export {
+ type Actor,
+ type DB,
+ type DrizzleClient,
+ type DrizzleTx,
+ type ServiceContext,
+ extractActorId,
+ isTx,
+ withTransaction,
+} from "./context";
+
+export {
+ ConflictError,
+ ForbiddenError,
+ InternalServiceError,
+ LimitExceededError,
+ NotFoundError,
+ ServiceError,
+ type ServiceErrorCode,
+ UnauthorizedError,
+ ValidationError,
+} from "./errors";
+
+export {
+ type AuditEntry,
+ type AuditLogRecord,
+ emitAudit,
+ installTestAuditBuffer,
+ uninstallTestAuditBuffer,
+} from "./audit";
+
+export {
+ assertWithinLimit,
+ getPlanLimits,
+ type LimitKey,
+} from "./limits";
+
+export * from "./types";
diff --git a/packages/services/src/limits.ts b/packages/services/src/limits.ts
new file mode 100644
index 000000000..35663ea33
--- /dev/null
+++ b/packages/services/src/limits.ts
@@ -0,0 +1,71 @@
+import { eq } from "@openstatus/db";
+import {
+ selectWorkspaceSchema,
+ workspace as workspaceTable,
+} from "@openstatus/db/src/schema";
+import { getLimits } from "@openstatus/db/src/schema/plan/utils";
+
+import type { DB } from "./context";
+import { LimitExceededError, NotFoundError } from "./errors";
+
+/**
+ * Re-exported plan-defaults lookup. For per-workspace overrides, read
+ * `ctx.workspace.limits` directly (already parsed by selectWorkspaceSchema).
+ */
+export const getPlanLimits = getLimits;
+
+// Count-style limits — the subset of Plan Limits that represent numeric row
+// counts enforceable via COUNT(*) + delta. Heterogeneous fields (booleans,
+// arrays, "Unlimited"|number) are intentionally excluded.
+export type LimitKey =
+ | "monitors"
+ | "status-pages"
+ | "page-components"
+ | "notification-channels"
+ | "synthetic-checks";
+
+/**
+ * Count currently-used resources of `limit` kind for the given workspace.
+ * Cases are filled in per-domain migration PR. Unknown keys throw — the default
+ * branch is a drift signal: a new LimitKey was added without a counter.
+ */
+async function countCurrent(
+ _tx: DB,
+ _workspaceId: number,
+ limit: LimitKey,
+): Promise<number> {
+ switch (limit) {
+ // Per-domain cases land in PR 1+ as each domain migrates.
+ default:
+ throw new Error(
+ `assertWithinLimit: counter for "${limit}" not implemented. Add a case in countCurrent in packages/services/src/limits.ts.`,
+ );
+ }
+}
+
+export async function assertWithinLimit(args: {
+ tx: DB;
+ workspaceId: number;
+ limit: LimitKey;
+ delta?: number;
+}): Promise<void> {
+ const { tx, workspaceId, limit, delta = 1 } = args;
+
+ const row = await tx
+ .select()
+ .from(workspaceTable)
+ .where(eq(workspaceTable.id, workspaceId))
+ .get();
+ if (!row) throw new NotFoundError("workspace", workspaceId);
+
+ const fresh = selectWorkspaceSchema.parse(row);
+ const max = fresh.limits[limit];
+ if (typeof max !== "number") {
+ throw new Error(
+ `assertWithinLimit: limit "${limit}" resolved to non-numeric value`,
+ );
+ }
+
+ const count = await countCurrent(tx, workspaceId, limit);
+ if (count + delta > max) throw new LimitExceededError(limit, max);
+}
diff --git a/packages/services/src/types.ts b/packages/services/src/types.ts
new file mode 100644
index 000000000..a0e5199f6
--- /dev/null
+++ b/packages/services/src/types.ts
@@ -0,0 +1,15 @@
+// Type re-exports for surface files (routers / handlers) that must reference
+// domain row shapes without importing `@openstatus/db` directly once the Biome
+// ban is in effect.
+//
+// Policy: rows + enums only. Insert/select Zod schemas, Drizzle table objects,
+// and db-internal types stay inside this package.
+//
+// Types are added incrementally per domain migration PR to keep the surface
+// lean; re-exports are by reference so schema column evolution flows through.
+
+export type {
+ Workspace,
+ WorkspacePlan,
+ WorkspaceRole,
+} from "@openstatus/db/src/schema";
diff --git a/packages/services/test/fixtures.ts b/packages/services/test/fixtures.ts
new file mode 100644
index 000000000..52d27e797
--- /dev/null
+++ b/packages/services/test/fixtures.ts
@@ -0,0 +1,5 @@
+// Shared fixture constants for service tests. Keep this file deliberately tiny
+// — per-domain fixtures belong next to the tests that use them.
+
+export const SEEDED_WORKSPACE_TEAM_ID = 1;
+export const SEEDED_WORKSPACE_FREE_ID = 2;
diff --git a/packages/services/test/helpers.ts b/packages/services/test/helpers.ts
new file mode 100644
index 000000000..262d4b782
--- /dev/null
+++ b/packages/services/test/helpers.ts
@@ -0,0 +1,134 @@
+import { expect } from "bun:test";
+import { db, eq } from "@openstatus/db";
+import {
+ selectWorkspaceSchema,
+ workspace as workspaceTable,
+} from "@openstatus/db/src/schema";
+
+import type { AuditLogRecord } from "../src/audit";
+import { installTestAuditBuffer, uninstallTestAuditBuffer } from "../src/audit";
+import type { Actor, ServiceContext } from "../src/context";
+import type { Workspace } from "../src/types";
+
+/**
+ * Load a seeded workspace by id (defaults to id=1, the `team` plan fixture).
+ * Tests that need a fresh workspace should insert one explicitly and clean up;
+ * isolating every test with its own workspace is the prevailing convention.
+ */
+export async function loadSeededWorkspace(id = 1): Promise<Workspace> {
+ const row = await db
+ .select()
+ .from(workspaceTable)
+ .where(eq(workspaceTable.id, id))
+ .get();
+ if (!row) {
+ throw new Error(
+ `loadSeededWorkspace(${id}): workspace not found. Did you seed the db?`,
+ );
+ }
+ return selectWorkspaceSchema.parse(row);
+}
+
+export function makeUserCtx(
+ workspace: Workspace,
+ opts: { userId: number; requestId?: string } = { userId: 1 },
+): ServiceContext {
+ return {
+ workspace,
+ actor: { type: "user", userId: opts.userId },
+ requestId: opts.requestId,
+ };
+}
+
+export function makeApiKeyCtx(
+ workspace: Workspace,
+ opts: { keyId: string; userId?: number; requestId?: string },
+): ServiceContext {
+ return {
+ workspace,
+ actor: {
+ type: "apiKey",
+ keyId: opts.keyId,
+ userId: opts.userId,
+ },
+ requestId: opts.requestId,
+ };
+}
+
+export function makeSlackCtx(
+ workspace: Workspace,
+ opts: {
+ teamId: string;
+ slackUserId: string;
+ userId?: number;
+ requestId?: string;
+ },
+): ServiceContext {
+ return {
+ workspace,
+ actor: {
+ type: "slack",
+ teamId: opts.teamId,
+ slackUserId: opts.slackUserId,
+ userId: opts.userId,
+ },
+ requestId: opts.requestId,
+ };
+}
+
+export function makeSystemCtx(
+ workspace: Workspace,
+ opts: { job: string; requestId?: string },
+): ServiceContext {
+ return {
+ workspace,
+ actor: { type: "system", job: opts.job },
+ requestId: opts.requestId,
+ };
+}
+
+/**
+ * Install the audit buffer for the scope of a test. Returns the live buffer
+ * plus a cleanup fn — use in beforeEach / afterEach or with { using } semantics.
+ */
+export function withAuditBuffer(): {
+ buffer: AuditLogRecord[];
+ reset: () => void;
+} {
+ const buffer = installTestAuditBuffer();
+ return {
+ buffer,
+ reset: () => {
+ uninstallTestAuditBuffer();
+ },
+ };
+}
+
+/**
+ * Assert an audit row matching `match` was recorded during the test.
+ * Requires an active audit buffer (installTestAuditBuffer / withAuditBuffer).
+ * In v1 this scans the in-memory buffer; in v2 it will query the audit_log
+ * table. Call sites do not change.
+ */
+export async function expectAuditRow(
+ buffer: AuditLogRecord[],
+ match: {
+ action: string;
+ entityType: string;
+ entityId: string | number;
+ actorType?: Actor["type"];
+ },
+): Promise<void> {
+ const expectedEntityId = String(match.entityId);
+ const hit = buffer.find(
+ (row) =>
+ row.action === match.action &&
+ row.entityType === match.entityType &&
+ row.entityId === expectedEntityId &&
+ (match.actorType === undefined || row.actorType === match.actorType),
+ );
+ expect(
+ hit,
+ `expected audit row for ${match.action} on ${match.entityType}#${expectedEntityId}`,
+ ).toBeDefined();
+}
diff --git a/packages/services/tsconfig.json b/packages/services/tsconfig.json
new file mode 100644
index 000000000..a4b10770f
--- /dev/null
+++ b/packages/services/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "extends": "@openstatus/tsconfig/base.json",
+ "include": ["src", "test"],
+ "exclude": ["dist", "build", "node_modules"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ad217e80d..5a7a7bfa7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1174,7 +1174,7 @@ importers:
version: 2.6.2
drizzle-orm:
specifier: 0.44.4
- version: 0.44.4(@libsql/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])
+ version: 0.44.4(@libsql/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])
effect:
specifier: 3.19.12
version: 3.19.12
@@ -1391,10 +1391,10 @@ importers:
version: 3.0.3
drizzle-orm:
specifier: 0.44.4
- version: 0.44.4(@libsql/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])
+ version: 0.44.4(@libsql/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])
drizzle-zod:
specifier: 0.8.3
zod:
specifier: 4.1.13
version: 4.1.13
@@ -2015,6 +2015,28 @@ importers:
specifier: 5.9.3
version: 5.9.3
+ packages/services:
+ dependencies:
+ '@logtape/logtape':
+ specifier: 2.0.1
+ version: 2.0.1
+ '@openstatus/db':
+ specifier: workspace:*
+ version: link:../db
+ zod:
+ specifier: 4.1.13
+ version: 4.1.13
+ devDependencies:
+ '@openstatus/tsconfig':
+ specifier: workspace:*
+ version: link:../tsconfig
+ '@types/bun':
+ specifier: latest
+ version: 1.3.13
+ typescript:
+ specifier: 5.9.3
+ version: 5.9.3
+
packages/status-fetcher:
dependencies:
node-html-parser:
@@ -7260,6 +7282,9 @@ packages:
resolution: {integrity: sha512-DBv81elK+/VSwXHDlnH3Qduw+KxkTIWi7TXkAeh24zpi5l0B2kUg9Ga3tb4nJaPcOFswflgi/yAvMVBPrxMB+A==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw==}
+
resolution: {integrity: sha512-hWtVTC2q7hc7xZ/RLbxapMvDMgUnDvKvMOpKal4DrMyfGBUfB1oKaZlIRr6mJL+If3bAP6sV/QneGzF6tJjZDg==}
@@ -7871,6 +7896,9 @@ packages:
resolution: {integrity: sha512-HqOLj5PoFajAQciOMRiIZGNoKxDJSr6qigAttOX40vJuSp6DN/CxWp9s3C1Xwm4oH7ybueITwiaOcWXoYVoRkA==}
+ resolution: {integrity: sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA==}
+
resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==}
engines: {node: '>=18'}
@@ -18070,6 +18098,10 @@ snapshots:
dependencies:
bun-types: 1.3.12
+ '@types/[email protected]':
+ dependencies:
+ bun-types: 1.3.13
+
'@types/[email protected]': {}
@@ -18848,6 +18880,10 @@ snapshots:
dependencies:
'@types/node': 24.0.8
+ dependencies:
+ '@types/node': 24.0.8
+
dependencies:
run-applescript: 7.1.0
@@ -19390,16 +19426,16 @@ snapshots:
transitivePeerDependencies:
- supports-color
optionalDependencies:
'@libsql/client': 0.15.15
'@opentelemetry/api': 1.9.0
'@types/pg': 8.15.6
- bun-types: 1.3.12
+ bun-types: 1.3.13
dependencies:
- drizzle-orm: 0.44.4(@libsql/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])
+ drizzle-orm: 0.44.4(@libsql/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])
zod: 4.1.13