feat(storage): Compose-Profil postgres, CI-Matrix mongo/postgres, API-Smoke-Test, Doku
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
23d9b83567
commit
bbfebc0095
5 files changed
+224
-1
No files matched your search
@@ -3,6 +3,12 @@ APP_PORT=8000
|
||||
MONGODB_URI=mongodb://mongodb/homebrewery
|
||||
MONGO_TAG=8
|
||||
|
||||
# Storage-Backend (ADR 0002, docs/storage/): mongo (Standard) oder postgres.
|
||||
# Postgres: docker compose --profile postgres up --build homebrewery-pg
|
||||
HB_DB_DRIVER=mongo
|
||||
# HB_POSTGRES_URL=postgres://homebrewery:homebrewery-dev@postgres:5432/homebrewery
|
||||
# HB_POSTGRES_POOL_MAX=10
|
||||
|
||||
# Profil postgres
|
||||
POSTGRES_DB=homebrewery
|
||||
POSTGRES_USER=homebrewery
|
||||
|
||||
@@ -58,3 +58,43 @@ jobs:
|
||||
# Kommt ohne MongoDB aus (Mongoose wird in den Specs gemockt).
|
||||
- name: Jest (npm test)
|
||||
run: npm test
|
||||
|
||||
# Storage-Contract-Suite und API-Smoke gegen beide Backends (ADR 0002 §5, Gitea #7).
|
||||
# Service-Container: act_runner startet sie im selben Docker-Netz, Hostname = Service-Name.
|
||||
storage:
|
||||
name: Storage (${{ matrix.backend }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
backend: [mongo, postgres]
|
||||
services:
|
||||
mongo:
|
||||
image: mongo:8
|
||||
postgres:
|
||||
image: postgres:18
|
||||
env:
|
||||
POSTGRES_PASSWORD: hb-ci-only
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U postgres"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
env:
|
||||
HB_TEST_MONGODB_URI: ${{ matrix.backend == 'mongo' && 'mongodb://mongo:27017' || '' }}
|
||||
HB_TEST_POSTGRES_URL: ${{ matrix.backend == 'postgres' && 'postgres://postgres:hb-ci-only@postgres:5432/postgres' || '' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Abhängigkeiten und Build (npm ci)
|
||||
run: npm ci --no-audit --no-fund
|
||||
|
||||
- name: Contract-Suite und API-Smoke (${{ matrix.backend }})
|
||||
run: npx jest server/storage tests/fork --runInBand
|
||||
|
||||
@@ -16,6 +16,8 @@ services:
|
||||
mongodb:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
# Storage-Backend (ADR 0002): mongo (Standard) oder postgres. Postgres: Compose-Profil `postgres`, Service `homebrewery-pg`.
|
||||
HB_DB_DRIVER: ${HB_DB_DRIVER:-mongo}
|
||||
MONGODB_URI: ${MONGODB_URI:-mongodb://mongodb/homebrewery}
|
||||
# Auth (ADR 0001). Leer lassen = Upstream-Verhalten (nur naturalcrit-Login). Siehe docs/auth/.
|
||||
HB_AUTH_PROVIDERS: ${HB_AUTH_PROVIDERS:-}
|
||||
@@ -33,7 +35,22 @@ services:
|
||||
ports: !override
|
||||
- "${APP_PORT:-8000}:8000"
|
||||
|
||||
# --- Profil: postgres (ab M2) ---
|
||||
# --- Profil: postgres (ADR 0002) ---
|
||||
# Startet die App mit PostgreSQL 18 ohne Mongo:
|
||||
# docker compose --profile postgres up --build homebrewery-pg
|
||||
# (Die Service-Namen müssen angegeben werden, sonst startet Compose zusätzlich `homebrewery` und `mongodb`.)
|
||||
homebrewery-pg:
|
||||
profiles: ["postgres"]
|
||||
extends:
|
||||
service: homebrewery
|
||||
image: homebrewery
|
||||
depends_on: !override
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
HB_DB_DRIVER: postgres
|
||||
HB_POSTGRES_URL: ${HB_POSTGRES_URL:-postgres://${POSTGRES_USER:-homebrewery}:${POSTGRES_PASSWORD:-homebrewery-dev}@postgres:5432/${POSTGRES_DB:-homebrewery}}
|
||||
HB_POSTGRES_POOL_MAX: ${HB_POSTGRES_POOL_MAX:-10}
|
||||
postgres:
|
||||
profiles: ["postgres"]
|
||||
image: postgres:18
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# Storage: MongoDB oder PostgreSQL pro Instanz
|
||||
|
||||
Umsetzung von [ADR 0002](../adr/0002-storage-mongo-postgres.md) (Gitea #7). Pro Instanz ist **genau ein**
|
||||
Backend aktiv. Einen Datenumzug zwischen den Backends gibt es nicht (einzelne Brews: Download/Import).
|
||||
|
||||
## Konfiguration
|
||||
|
||||
| Variable | Bedeutung |
|
||||
| --- | --- |
|
||||
| `HB_DB_DRIVER` | `mongo` (Standard) oder `postgres` |
|
||||
| `MONGODB_URI` | wie Upstream (nur bei `mongo`) |
|
||||
| `HB_POSTGRES_URL` | z. B. `postgres://hb:…@postgres:5432/homebrewery` (Pflicht bei `postgres`) |
|
||||
| `HB_POSTGRES_POOL_MAX` | Pool-Größe, Standard `10` |
|
||||
|
||||
Beim Start wird nur das gewählte Backend verbunden (bei `postgres` verbindet sich Mongoose nicht). Fehlt
|
||||
`HB_POSTGRES_URL` oder ist der Server älter als PostgreSQL 18 (`server_version_num` < 180000), bricht der Start mit
|
||||
klarer Meldung ab. Die Migrationen (`server/storage/postgres/migrations/`) laufen beim Start automatisch
|
||||
(Kysely-Migrator mit Lock-Tabelle, bei Fehler Abbruch).
|
||||
|
||||
## Compose
|
||||
|
||||
```bash
|
||||
# Standard (Mongo, wie bisher)
|
||||
docker compose up --build
|
||||
|
||||
# PostgreSQL 18, ganz ohne Mongo: Profil `postgres`, Service `homebrewery-pg`
|
||||
docker compose --profile postgres up --build homebrewery-pg
|
||||
```
|
||||
|
||||
Die Service-Namen gehören dazu: Mit `--profile postgres up` ohne Namen startet Compose zusätzlich die
|
||||
profillosen Services `homebrewery` und `mongodb` (beide auf `APP_PORT`).
|
||||
|
||||
## Repository-Schicht
|
||||
|
||||
`server/storage/` – `getStorage()` liefert `{ brews, notifications, users }` (`gitConnections`, `brewGitLinks`,
|
||||
`brewAssets` kommen mit M3/M4). Alle Methoden sind `async` und liefern plain objects mit `id`, `text` immer
|
||||
entpackt, nie `textBin`. Nicht gefunden: `findBy…` liefert `null`.
|
||||
|
||||
Abweichungen von ADR 0002 (Details beim Umsetzen ergeben):
|
||||
|
||||
- `searchPublished(params)` liefert `{ brews, total }`; `total` nur mit `withTotal: true`, Brews nicht mit
|
||||
`limit: 0` (für `/api/vault/total`).
|
||||
- Sperren: `setLock(shareId, lock, { overwrite })`, `removeLock`, `requestReview`, `removeReviewRequest` liefern
|
||||
`{ result, brew }` (`'locked' | 'not-found' | 'already-locked'` usw.), damit die Fehlercodes der Admin-API
|
||||
unverändert bleiben und die Prüfung atomar ist (PG: eine Transaktion mit `FOR UPDATE`).
|
||||
- Notifications: `list()`, `create(data)`, `deleteByDismissKey(key)`; das Feld heißt jetzt `id` statt `_id`.
|
||||
- `/admin/clean/script/:id` läuft über Repository und `updateBrew` und funktioniert damit auch unter PG
|
||||
(ADR: 501). Nur `cleanupJunk`, `cleanupLost`, `finduncompressed` und `compress` antworten unter PG mit `501`.
|
||||
- Die Upstream-Modelle (`homebrew.model.js`, `notifications.model.js`, `db.js`) sind unverändert.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
# Postgres (frisches Schema test_<random> je Suite, wird danach gelöscht)
|
||||
HB_TEST_POSTGRES_URL=postgres://postgres:pw@127.0.0.1:5432/postgres npm run test:storage
|
||||
# Mongo (frische DB test_<random>)
|
||||
HB_TEST_MONGODB_URI=mongodb://127.0.0.1:27017 npm run test:storage
|
||||
```
|
||||
|
||||
Ohne die Variablen überspringen sich die Specs mit Warnung. `npm test` läuft weiter ohne Datenbank.
|
||||
Beide Variablen gleichzeitig sind erlaubt. Die CI (`storage`-Job, Matrix `mongo`/`postgres`) setzt je eine.
|
||||
|
||||
Hinweise zu Mongo unter Jest: Der Mongo-Treiber braucht dort `runtimeAdapters: { os }` (sonst sendet er keine
|
||||
Client-Metadaten und der Server lehnt den Handshake ab; die Specs setzen das). `Model.init()`/`syncIndexes()` auf
|
||||
`Homebrew` scheitert auf aktuellen Servern am Upstream-Index `{ lock: 1, sparse: true }`; die Specs legen die
|
||||
nötigen Indizes selbst an. MongoDB ≥ 5 braucht eine CPU mit AVX; auf Hosts ohne AVX hilft lokal `mongo:4.4`.
|
||||
@@ -0,0 +1,94 @@
|
||||
// API-Smoke-Test (ADR 0002 §5): Neuanlage, Laden, Update, Teilen-Lookup, Löschen gegen das echte Backend.
|
||||
// Läuft pro konfiguriertem Backend: HB_TEST_POSTGRES_URL (postgres) bzw. HB_TEST_MONGODB_URI (mongo).
|
||||
import os from 'os';
|
||||
import { randomBytes } from 'crypto';
|
||||
import supertest from 'supertest';
|
||||
import pg from 'pg';
|
||||
import mongoose from 'mongoose';
|
||||
import { md5 } from 'hash-wasm';
|
||||
import { makePatches, stringifyPatches } from '@sanity/diff-match-patch';
|
||||
import createApp from '../../server/app.js';
|
||||
import storage from '../../server/storage/index.js';
|
||||
import packageJSON from '../../package.json' with { type: 'json' };
|
||||
|
||||
const backends = [
|
||||
{ driver: 'postgres', url: process.env.HB_TEST_POSTGRES_URL },
|
||||
{ driver: 'mongo', url: process.env.HB_TEST_MONGODB_URI }
|
||||
];
|
||||
|
||||
const auth = `Basic ${Buffer.from('admin:password3').toString('base64')}`;
|
||||
const version = { 'Homebrewery-Version': packageJSON.version };
|
||||
|
||||
for (const { driver, url } of backends) {
|
||||
const suite = url ? describe : describe.skip;
|
||||
if(!url) console.warn(`API-Smoke (${driver}): HB_TEST_${driver === 'postgres' ? 'POSTGRES_URL' : 'MONGODB_URI'} fehlt, übersprungen.`);
|
||||
|
||||
suite(`API-Smoke gegen ${driver}`, ()=>{
|
||||
let request;
|
||||
let cleanup;
|
||||
|
||||
beforeAll(async ()=>{
|
||||
const name = `test_${randomBytes(4).toString('hex')}`;
|
||||
const values = { hb_db_driver: driver, node_env: 'test', local_environments: ['local'] };
|
||||
if(driver === 'postgres') {
|
||||
const admin = new pg.Client({ connectionString: url });
|
||||
await admin.connect();
|
||||
await admin.query(`CREATE SCHEMA ${name}`);
|
||||
// Schema per search_path der Verbindung: hängt die URL-Option an
|
||||
values.hb_postgres_url = `${url}${url.includes('?') ? '&' : '?'}options=-c%20search_path%3D${name}`;
|
||||
cleanup = async ()=>{ await storage.disconnect(); await admin.query(`DROP SCHEMA ${name} CASCADE`); await admin.end(); };
|
||||
} else {
|
||||
values.mongodb_uri = url;
|
||||
cleanup = async ()=>{ await mongoose.connection.dropDatabase(); await storage.disconnect(); };
|
||||
}
|
||||
// Unter Jest scheitert der dynamische import('os') des Mongo-Treibers (Handshake ohne Metadaten)
|
||||
const connect = mongoose.connect.bind(mongoose);
|
||||
jest.spyOn(mongoose, 'connect').mockImplementation((u, o)=>connect(u, { ...o, dbName: name, runtimeAdapters: { os } }));
|
||||
await storage.connect({ get: (key)=>values[key] });
|
||||
request = supertest.agent(await createApp()).set('X-Forwarded-Proto', 'https');
|
||||
});
|
||||
afterAll(async ()=>{ await cleanup?.(); });
|
||||
|
||||
test('Neuanlage, Laden, Update, Löschen', async ()=>{
|
||||
// Neuanlage
|
||||
const created = await request.post('/api').set(version).send({ text: 'Hallo Smoke', title: 'Smoke Brew', tags: ['meta:theme'], renderer: 'V3' });
|
||||
expect(created.status).toBe(200);
|
||||
const { editId, shareId } = created.body;
|
||||
expect(editId).toHaveLength(12);
|
||||
expect(shareId).toHaveLength(12);
|
||||
|
||||
// Laden (Admin-Lookup per Edit- oder Share-ID)
|
||||
const byEdit = await request.get(`/admin/lookup/${editId}`).set('Authorization', auth);
|
||||
expect(byEdit.status).toBe(200);
|
||||
expect(byEdit.body).toMatchObject({ title: 'Smoke Brew', shareId, editId });
|
||||
const byShare = await request.get(`/admin/lookup/${shareId}`).set('Authorization', auth);
|
||||
expect(byShare.body.shareId).toBe(shareId);
|
||||
|
||||
// Teilen: Theme-Bundle lädt den Brew über die Share-ID
|
||||
const shared = await request.get(`/api/theme/V3/${shareId}`);
|
||||
expect(shared.status).toBe(200);
|
||||
|
||||
// Update mit Patches (wie der Editor)
|
||||
const loaded = byEdit.body;
|
||||
const oldText = loaded.text.normalize('NFC');
|
||||
const newText = `${oldText}\nZweite Zeile`;
|
||||
const updated = await request.put(`/api/update/${editId}`).set(version).send({
|
||||
...loaded,
|
||||
text : newText,
|
||||
hash : await md5(oldText),
|
||||
patches : stringifyPatches(makePatches(encodeURI(oldText), encodeURI(newText)))
|
||||
});
|
||||
expect(updated.status).toBe(200);
|
||||
expect(updated.body.version).toBe(2);
|
||||
const reloaded = await request.get(`/admin/lookup/${editId}`).set('Authorization', auth);
|
||||
expect(reloaded.body.version).toBe(2);
|
||||
expect(reloaded.body.text).toContain('Zweite Zeile');
|
||||
|
||||
// Löschen (anonymer Brew ohne Autoren)
|
||||
const removed = await request.get(`/api/remove/${editId}`).set(version);
|
||||
expect(removed.status).toBe(204);
|
||||
const gone = await request.get(`/admin/lookup/${editId}`).set('Authorization', auth);
|
||||
expect(gone.body.shareId).toBeUndefined(); // Fehlerseite statt Brew
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user