feat(git): Repositories gitConnections/brewGitLinks für Mongo und PostgreSQL inkl. Migration und Contract-Suite (ADR 0003 §2)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
400411d736
commit
d2801b2d6c
11 files changed
+454
-3
No files matched your search
@@ -0,0 +1,124 @@
|
||||
// Repositories für Git-Verbindungen und Brew-Verknüpfungen (PostgreSQL, ADR 0003 §2).
|
||||
// Gleicher Vertrag wie mongo/git.js. Ergebnisse: plain objects in camelCase.
|
||||
const UUID = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
const CONN = {
|
||||
label : 'label',
|
||||
repoUrl : 'repo_url',
|
||||
authUsername : 'auth_username',
|
||||
tokenEnc : 'token_enc',
|
||||
defaultBranch : 'default_branch',
|
||||
brewDir : 'brew_dir',
|
||||
assetsDir : 'assets_dir',
|
||||
lastVerifiedAt : 'last_verified_at'
|
||||
};
|
||||
const LINK = {
|
||||
connectionId : 'connection_id',
|
||||
branch : 'branch',
|
||||
path : 'path',
|
||||
lastCommitSha : 'last_commit_sha',
|
||||
lastBlobSha : 'last_blob_sha',
|
||||
lastSyncedAt : 'last_synced_at',
|
||||
lastError : 'last_error'
|
||||
};
|
||||
|
||||
const toRow = (map, patch)=>{
|
||||
const row = {};
|
||||
for (const [field, column] of Object.entries(map)) {
|
||||
if(patch[field] !== undefined) row[column] = patch[field];
|
||||
}
|
||||
return row;
|
||||
};
|
||||
|
||||
const rowToConnection = (r)=>!r ? null : ({
|
||||
id : r.id,
|
||||
ownerUserId : r.owner_user_id,
|
||||
label : r.label,
|
||||
repoUrl : r.repo_url,
|
||||
authUsername : r.auth_username,
|
||||
tokenEnc : r.token_enc,
|
||||
defaultBranch : r.default_branch,
|
||||
brewDir : r.brew_dir,
|
||||
assetsDir : r.assets_dir,
|
||||
createdAt : r.created_at,
|
||||
updatedAt : r.updated_at,
|
||||
lastVerifiedAt : r.last_verified_at ?? null
|
||||
});
|
||||
|
||||
const rowToLink = (r)=>!r ? null : ({
|
||||
brewId : r.brew_id,
|
||||
connectionId : r.connection_id,
|
||||
branch : r.branch,
|
||||
path : r.path,
|
||||
lastCommitSha : r.last_commit_sha ?? null,
|
||||
lastBlobSha : r.last_blob_sha ?? null,
|
||||
lastSyncedAt : r.last_synced_at ?? null,
|
||||
lastError : r.last_error ?? null
|
||||
});
|
||||
|
||||
export const createGitConnectionRepository = (db)=>({
|
||||
async create({ id, ownerUserId, ...rest }) {
|
||||
const values = { owner_user_id: ownerUserId, ...toRow(CONN, rest) };
|
||||
if(id) values.id = id;
|
||||
return rowToConnection(await db.insertInto('git_connections').values(values).returningAll().executeTakeFirstOrThrow());
|
||||
},
|
||||
async findById(id) {
|
||||
if(!UUID.test(String(id))) return null;
|
||||
return rowToConnection(await db.selectFrom('git_connections').selectAll().where('id', '=', id).executeTakeFirst());
|
||||
},
|
||||
async findByIdForOwner(id, userId) {
|
||||
if(!UUID.test(String(id)) || !UUID.test(String(userId))) return null;
|
||||
return rowToConnection(await db.selectFrom('git_connections').selectAll().where('id', '=', id).where('owner_user_id', '=', userId).executeTakeFirst());
|
||||
},
|
||||
async listByOwner(userId) {
|
||||
if(!UUID.test(String(userId))) return [];
|
||||
const rows = await db.selectFrom('git_connections').selectAll().where('owner_user_id', '=', userId).orderBy('created_at').orderBy('id').execute();
|
||||
return rows.map(rowToConnection);
|
||||
},
|
||||
async update(id, patch) {
|
||||
if(!UUID.test(String(id))) return null;
|
||||
const row = toRow(CONN, patch);
|
||||
if(!Object.keys(row).length) return this.findById(id);
|
||||
row.updated_at = new Date();
|
||||
return rowToConnection(await db.updateTable('git_connections').set(row).where('id', '=', id).returningAll().executeTakeFirst());
|
||||
},
|
||||
async delete(id) {
|
||||
if(!UUID.test(String(id))) return false;
|
||||
const res = await db.deleteFrom('git_connections').where('id', '=', id).executeTakeFirst();
|
||||
return res.numDeletedRows > 0n;
|
||||
}
|
||||
});
|
||||
|
||||
export const createBrewGitLinkRepository = (db)=>({
|
||||
// Legt den Link an oder ersetzt ihn (höchstens einer pro Brew)
|
||||
async upsert({ brewId, ...rest }) {
|
||||
const row = { brew_id: brewId, ...toRow(LINK, rest) };
|
||||
const { brew_id, ...set } = row;
|
||||
return rowToLink(await db.insertInto('brew_git_links').values(row)
|
||||
.onConflict((oc)=>oc.column('brew_id').doUpdateSet(set)).returningAll().executeTakeFirstOrThrow());
|
||||
},
|
||||
async findByBrewId(brewId) {
|
||||
if(!UUID.test(String(brewId))) return null;
|
||||
return rowToLink(await db.selectFrom('brew_git_links').selectAll().where('brew_id', '=', brewId).executeTakeFirst());
|
||||
},
|
||||
async findByLocation(connectionId, branch, path) {
|
||||
if(!UUID.test(String(connectionId))) return null;
|
||||
return rowToLink(await db.selectFrom('brew_git_links').selectAll()
|
||||
.where('connection_id', '=', connectionId).where('branch', '=', branch).where('path', '=', path).executeTakeFirst());
|
||||
},
|
||||
async listByConnection(connectionId) {
|
||||
if(!UUID.test(String(connectionId))) return [];
|
||||
return (await db.selectFrom('brew_git_links').selectAll().where('connection_id', '=', connectionId).execute()).map(rowToLink);
|
||||
},
|
||||
async update(brewId, patch) {
|
||||
if(!UUID.test(String(brewId))) return null;
|
||||
const row = toRow(LINK, patch);
|
||||
if(!Object.keys(row).length) return this.findByBrewId(brewId);
|
||||
return rowToLink(await db.updateTable('brew_git_links').set(row).where('brew_id', '=', brewId).returningAll().executeTakeFirst());
|
||||
},
|
||||
async delete(brewId) {
|
||||
if(!UUID.test(String(brewId))) return false;
|
||||
const res = await db.deleteFrom('brew_git_links').where('brew_id', '=', brewId).executeTakeFirst();
|
||||
return res.numDeletedRows > 0n;
|
||||
}
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { createDb, checkServerVersion, migrateToLatest } from './db.js';
|
||||
import { createBrewRepository } from './brews.js';
|
||||
import { createNotificationRepository } from './notifications.js';
|
||||
import { createUserRepository } from './users.js';
|
||||
import { createGitConnectionRepository, createBrewGitLinkRepository } from './gitRepos.js';
|
||||
|
||||
// PostgreSQL-Implementierung der Storage-Schicht (ADR 0002). Kysely + pg, versionierte Migrationen
|
||||
// laufen beim Start (migrateToLatest). Konfiguration: HB_POSTGRES_URL, HB_POSTGRES_POOL_MAX.
|
||||
@@ -14,6 +15,8 @@ export const createPostgresStorage = (config, overrides = {})=>{
|
||||
repos.brews = createBrewRepository(db);
|
||||
repos.notifications = createNotificationRepository(db);
|
||||
repos.users = createUserRepository(db);
|
||||
repos.gitConnections = createGitConnectionRepository(db);
|
||||
repos.brewGitLinks = createBrewGitLinkRepository(db);
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -21,6 +24,8 @@ export const createPostgresStorage = (config, overrides = {})=>{
|
||||
get brews() { return repos.brews; },
|
||||
get notifications() { return repos.notifications; },
|
||||
get users() { return repos.users; },
|
||||
get gitConnections() { return repos.gitConnections; },
|
||||
get brewGitLinks() { return repos.brewGitLinks; },
|
||||
get pool() { return handle?.pool; }, // nur für Tests
|
||||
async connect() {
|
||||
const url = overrides.url ?? config?.get('hb_postgres_url');
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { sql } from 'kysely';
|
||||
|
||||
// ADR 0003 §2: Git-Verbindungen (pro Benutzer) und Brew-Verknüpfungen.
|
||||
export const up = async (db)=>{
|
||||
await sql`
|
||||
CREATE TABLE git_connections (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
owner_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
label text NOT NULL,
|
||||
repo_url text NOT NULL,
|
||||
auth_username text NOT NULL DEFAULT 'git',
|
||||
token_enc text NOT NULL,
|
||||
default_branch text NOT NULL DEFAULT 'main',
|
||||
brew_dir text NOT NULL DEFAULT 'brews',
|
||||
assets_dir text NOT NULL DEFAULT 'assets',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_verified_at timestamptz
|
||||
)`.execute(db);
|
||||
await sql`CREATE INDEX git_connections_owner ON git_connections (owner_user_id)`.execute(db);
|
||||
|
||||
await sql`
|
||||
CREATE TABLE brew_git_links (
|
||||
brew_id uuid PRIMARY KEY REFERENCES brews(id) ON DELETE CASCADE,
|
||||
connection_id uuid NOT NULL REFERENCES git_connections(id) ON DELETE CASCADE,
|
||||
branch text NOT NULL,
|
||||
path text NOT NULL,
|
||||
last_commit_sha text,
|
||||
last_blob_sha text,
|
||||
last_synced_at timestamptz,
|
||||
last_error text,
|
||||
UNIQUE (connection_id, branch, path)
|
||||
)`.execute(db);
|
||||
};
|
||||
|
||||
export const down = async (db)=>{
|
||||
await sql`DROP TABLE IF EXISTS brew_git_links`.execute(db);
|
||||
await sql`DROP TABLE IF EXISTS git_connections`.execute(db);
|
||||
};
|
||||
@@ -1,7 +1,9 @@
|
||||
// Statische Migrationsliste (kein Dateisystem-Scan, damit es mit Vite/Jest/Node gleich läuft).
|
||||
// Neue Migration: Datei `NNNN_beschreibung.js` mit up(db)/down(db) anlegen und hier eintragen.
|
||||
import * as m0001 from './0001_initial.js';
|
||||
import * as m0002 from './0002_git_backend.js';
|
||||
|
||||
export default {
|
||||
'0001_initial' : m0001
|
||||
'0001_initial' : m0001,
|
||||
'0002_git_backend' : m0002
|
||||
};
|
||||
@@ -2,6 +2,7 @@ import { randomBytes } from 'crypto';
|
||||
import pg from 'pg';
|
||||
import { createPostgresStorage } from './index.js';
|
||||
import { runUserRepositoryContract } from '../contract/users.contract.js';
|
||||
import { runGitRepositoryContract } from '../contract/git.contract.js';
|
||||
import { runBrewRepositoryContract, runNotificationRepositoryContract } from '../contract/brews.contract.js';
|
||||
|
||||
const url = process.env.HB_TEST_POSTGRES_URL;
|
||||
@@ -47,6 +48,13 @@ suite('Postgres NotificationRepository (Contract)', ()=>{
|
||||
});
|
||||
});
|
||||
|
||||
suite('Postgres Git-Repositories (Contract)', ()=>{
|
||||
runGitRepositoryContract(async ()=>{
|
||||
const { storage, cleanup } = await createStorage();
|
||||
return { users: storage.users, brews: storage.brews, gitConnections: storage.gitConnections, brewGitLinks: storage.brewGitLinks, cleanup };
|
||||
});
|
||||
});
|
||||
|
||||
suite('Postgres Verbindung und Migrationen', ()=>{
|
||||
test('Start ohne HB_POSTGRES_URL bricht mit klarer Meldung ab', async ()=>{
|
||||
const storage = createPostgresStorage({ get: ()=>undefined });
|
||||
|
||||
Reference in new issue
Block a user