Skip to content
Draft
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
2 changes: 1 addition & 1 deletion .github/workflows/changelog.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: changelog

on:
pull_request:
branches: [main]
branches: [main, feat/d1-store]
types: [opened, synchronize, reopened, labeled, unlabeled]

permissions:
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ name: CI and documentation

on:
pull_request:
branches: [main]
branches: [main, feat/d1-store]
types: [opened, synchronize, reopened, edited, ready_for_review]
push:
branches: [main]
branches: [main, feat/d1-store]
workflow_dispatch:

permissions:
Expand Down
25 changes: 10 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,13 @@
"@effect/platform": "0.97.2",
"@effect/platform-node": "0.108.2",
"@effect/sql": "0.52.1",
"@effect/sql-mysql2": "0.53.0",
"@modelcontextprotocol/sdk": "^1.31.0",
"@sanctum/contracts": "*",
"@sanctum/sdk": "*",
"aws4fetch": "1.0.20",
"better-auth": "1.7.7",
"effect": "3.22.2",
"jose": "^6.2.12",
"mysql2": "3.24.4",
"openid-client": "6.8.8"
},
"devDependencies": {
Expand Down
15 changes: 4 additions & 11 deletions server/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Process configuration and the plan section 02 engineering defaults.
* Defaults are acceptance-test inputs and calibration starting points, not measured optima.
*/
import { Config, Effect, Option, Redacted, Schema } from 'effect';
import { Config, Effect, Option, Schema } from 'effect';
import { AccessScopeName, type JobKind, Unavailable } from '@sanctum/contracts';

/** Plan section 02 "Recommended engineering defaults"; change here, never as scattered literals. */
Expand Down Expand Up @@ -159,16 +159,9 @@ export const serverConfig = Config.all({
seatLimit: defaultSeatLimit,
workspacePurgeGraceDays,
apiPort: port('API_PORT', 7102),
mysql: Config.all({
host: Config.string('MYSQL_HOST').pipe(Config.withDefault('127.0.0.1')),
port: port('MYSQL_PORT', 3306),
database: Config.string('MYSQL_DATABASE').pipe(Config.withDefault('sanctum')),
username: Config.string('MYSQL_USER').pipe(Config.withDefault('sanctum')),
password: Config.redacted('MYSQL_PASSWORD').pipe(Config.withDefault(Redacted.make(''))),
maxConnections: Config.integer('MYSQL_POOL_SIZE').pipe(Config.withDefault(10)),
queueLimit: Config.integer('MYSQL_POOL_QUEUE').pipe(Config.withDefault(100)),
/** PEM CA certificate; when set, connections require TLS verified against it, host name included. */
caCert: Config.option(Config.string('MYSQL_CA_CERT')).pipe(Config.map(Option.getOrUndefined)),
/** `file:<path>`, `:memory:`, or the D1 gateway `http://d1.internal`. */
db: Config.all({
url: Config.string('SANCTUM_DB_URL').pipe(Config.withDefault('file:./sanctum.db')),
}),
/** Decisions an operator has explicitly selected and configured, comma-separated. */
selectedDecisions: Config.array(Config.literal(...activationDecisions)(), 'SANCTUM_SELECTED_DECISIONS').pipe(Config.withDefault(noDecisions)),
Expand Down
40 changes: 40 additions & 0 deletions server/src/db-d1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* D1 backend: HTTP to the gateway Worker (`deploy/cloudflare/src/d1-gate.ts`) that the container reaches at
* `http://d1.internal`. Bytes travel as `{"$b":"<base64>"}` in both directions.
*/
import { SqlError } from '@effect/sql';
import { Effect } from 'effect';
import type { DbBackend, DbResult, DbStatement } from './db-types.ts';

const encode = (value: unknown): unknown => {
if (value instanceof Uint8Array) return { $b: Buffer.from(value).toString('base64') };
if (typeof value === 'boolean') return Number(value);
return value === undefined ? null : value;
};

const decode = (value: unknown): unknown =>
typeof value === 'object' && value !== null && '$b' in value && typeof value.$b === 'string' ? new Uint8Array(Buffer.from(value.$b, 'base64')) : value;

const decodeResult = (result: DbResult): DbResult => ({
changes: result.changes,
rows: result.rows.map(row => Object.fromEntries(Object.entries(row).map(([column, value]) => [column, decode(value)]))),
});

const toBody = ({ sql, params }: DbStatement) => ({ sql, params: params.map(encode) });

export const d1Backend = (baseUrl: string): DbBackend => {
const post = <A>(path: string, body: unknown) =>
Effect.tryPromise({
try: async signal => {
const response = await fetch(new URL(path, baseUrl), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal });
const payload = (await response.json()) as A & { readonly error?: string };
if (!response.ok) throw new Error(payload.error ?? `D1 gateway answered ${response.status}`);
return payload;
},
catch: cause => new SqlError.SqlError({ cause, message: cause instanceof Error ? cause.message : String(cause) }),
});
return {
run: statement => Effect.map(post<DbResult>('/run', toBody(statement)), decodeResult),
batch: statements => Effect.map(post<{ readonly results: ReadonlyArray<DbResult> }>('/batch', { statements: statements.map(toBody) }), payload => payload.results.map(decodeResult)),
};
};
51 changes: 51 additions & 0 deletions server/src/db-sqlite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/** `node:sqlite` backend for local runs, CI and compose: one synchronous connection, so each statement and batch is atomic. */
import { DatabaseSync, type SQLInputValue } from 'node:sqlite';
import { SqlError } from '@effect/sql';
import { Effect, type Scope } from 'effect';
import type { DbBackend, DbResult, DbStatement } from './db-types.ts';

const sqlError = (cause: unknown) => new SqlError.SqlError({ cause, message: cause instanceof Error ? cause.message : String(cause) });

const bind = (params: ReadonlyArray<unknown>) => params.map(value => (typeof value === 'boolean' ? Number(value) : value === undefined ? null : value) as SQLInputValue);

const execute = (database: DatabaseSync, { sql, params }: DbStatement): DbResult => {
const statement = database.prepare(sql);
if (statement.columns().length > 0) {
const rows = statement.all(...bind(params)) as Array<Record<string, unknown>>;
return { rows, changes: rows.length };
}
return { rows: [], changes: Number(statement.run(...bind(params)).changes) };
};

/** `path` is `:memory:`, `file:<path>`, a bare path, or a `file:` URI with a query (`file:name?mode=memory&cache=shared` shares one memory database between connections). */
export const sqliteBackend = (path: string): Effect.Effect<DbBackend, SqlError.SqlError, Scope.Scope> =>
Effect.acquireRelease(
Effect.try({
try: () => {
const database = new DatabaseSync(path.includes('?') ? path : path.replace(/^file:/, ''));
database.exec('PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL');
return database;
},
catch: sqlError,
}),
database => Effect.sync(() => database.close()),
).pipe(
Effect.map((database): DbBackend => ({
run: statement => Effect.try({ try: () => execute(database, statement), catch: sqlError }),
batch: statements =>
Effect.try({
try: () => {
database.exec('BEGIN IMMEDIATE');
try {
const results = statements.map(statement => execute(database, statement));
database.exec('COMMIT');
return results;
} catch (error) {
database.exec('ROLLBACK');
throw error;
}
},
catch: sqlError,
}),
})),
);
12 changes: 12 additions & 0 deletions server/src/db-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { Effect } from 'effect';
import type { SqlError } from '@effect/sql';

/** `SANCTUM_DB_URL`: `file:<path>`, `:memory:`, or the D1 gateway `http://d1.internal`. */
export interface DbOptions { readonly url: string }
export interface DbStatement { readonly sql: string; readonly params: ReadonlyArray<unknown> }
export interface DbResult { readonly rows: ReadonlyArray<Record<string, unknown>>; readonly changes: number }
export interface DbBackend {
readonly run: (statement: DbStatement) => Effect.Effect<DbResult, SqlError.SqlError>;
/** All statements commit together or none does. */
readonly batch: (statements: ReadonlyArray<DbStatement>) => Effect.Effect<ReadonlyArray<DbResult>, SqlError.SqlError>;
}
Loading
Loading