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:
dev-bot BotandClaude Sonnet 5.5 committed 2026-11-25 14:19:58 +00:00
1 parent 400411d736
commit d2801b2d6c
11 files changed
+454 -3

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
// Contract-Suite für gitConnections und brewGitLinks (ADR 0002 §5, ADR 0003 §2).
// Aufruf: runGitRepositoryContract(async ()=>({ users, brews, gitConnections, brewGitLinks, cleanup }))
export const runGitRepositoryContract = (createRepos)=>{
let r;
let alice;
let bob;
let conn;
let brew;
beforeAll(async ()=>{
r = await createRepos();
alice = await r.users.create({ username: 'alice-git' });
bob = await r.users.create({ username: 'bob-git' });
brew = await r.brews.create({ title: 'Git-Brew', text: 'Hallo', authors: ['alice-git'] });
});
afterAll(async ()=>{ await r.cleanup?.(); });
test('Verbindung anlegen: Standardwerte, plain object, Token nur als Chiffrat', async ()=>{
conn = await r.gitConnections.create({ ownerUserId: alice.id, label: 'Gitea', repoUrl: 'https://git.example.test/a/b.git', tokenEnc: 'v1.x.y.z.t' });
expect(conn.id).toEqual(expect.any(String));
expect(conn).toMatchObject({ ownerUserId: alice.id, label: 'Gitea', authUsername: 'git', defaultBranch: 'main', brewDir: 'brews', assetsDir: 'assets', tokenEnc: 'v1.x.y.z.t', lastVerifiedAt: null });
expect(conn.constructor).toBe(Object);
});
test('Besitz: findByIdForOwner mit fremder userId liefert null, listByOwner nur eigene', async ()=>{
expect((await r.gitConnections.findByIdForOwner(conn.id, alice.id)).id).toBe(conn.id);
expect(await r.gitConnections.findByIdForOwner(conn.id, bob.id)).toBeNull();
expect(await r.gitConnections.findByIdForOwner('unbekannt', alice.id)).toBeNull();
expect((await r.gitConnections.listByOwner(alice.id)).map((c)=>c.id)).toEqual([conn.id]);
expect(await r.gitConnections.listByOwner(bob.id)).toEqual([]);
expect(await r.gitConnections.findById('unbekannt')).toBeNull();
});
test('update ändert Felder und updatedAt, nie den Besitzer', async ()=>{
const upd = await r.gitConnections.update(conn.id, { label: 'Neu', ownerUserId: bob.id, lastVerifiedAt: new Date(), defaultBranch: 'dev' });
expect(upd).toMatchObject({ label: 'Neu', ownerUserId: alice.id, defaultBranch: 'dev' });
expect(upd.lastVerifiedAt).toBeInstanceOf(Date);
expect(await r.gitConnections.update('unbekannt', { label: 'x' })).toBeNull();
});
test('Link: upsert, find, (Verbindung, Branch, Pfad) ist eindeutig', async ()=>{
const link = await r.brewGitLinks.upsert({ brewId: brew.id, connectionId: conn.id, branch: 'main', path: 'brews/a.md', lastCommitSha: 'c1', lastBlobSha: 'b1', lastSyncedAt: new Date() });
expect(link).toMatchObject({ brewId: brew.id, connectionId: conn.id, branch: 'main', path: 'brews/a.md', lastCommitSha: 'c1', lastBlobSha: 'b1', lastError: null });
expect((await r.brewGitLinks.findByBrewId(brew.id)).path).toBe('brews/a.md');
expect((await r.brewGitLinks.findByLocation(conn.id, 'main', 'brews/a.md')).brewId).toBe(brew.id);
expect(await r.brewGitLinks.findByLocation(conn.id, 'main', 'andere.md')).toBeNull();
const other = await r.brews.create({ title: 'Zweiter', text: 'x', authors: ['alice-git'] });
await expect(r.brewGitLinks.upsert({ brewId: other.id, connectionId: conn.id, branch: 'main', path: 'brews/a.md' })).rejects.toBeDefined();
await r.brewGitLinks.upsert({ brewId: other.id, connectionId: conn.id, branch: 'main', path: 'brews/b.md' });
expect((await r.brewGitLinks.listByConnection(conn.id)).length).toBe(2);
await r.brews.deleteById(other.id);
});
test('upsert ersetzt den Link des Brews (höchstens einer pro Brew)', async ()=>{
await r.brewGitLinks.upsert({ brewId: brew.id, connectionId: conn.id, branch: 'dev', path: 'brews/a.md' });
expect(await r.brewGitLinks.findByLocation(conn.id, 'main', 'brews/a.md')).toBeNull();
expect((await r.brewGitLinks.findByBrewId(brew.id)).branch).toBe('dev');
expect((await r.brewGitLinks.listByConnection(conn.id)).length).toBe(1);
});
test('update des Links setzt SHA und Fehlercode', async ()=>{
const upd = await r.brewGitLinks.update(brew.id, { lastCommitSha: 'c2', lastBlobSha: 'b2', lastError: 'G04' });
expect(upd).toMatchObject({ lastCommitSha: 'c2', lastBlobSha: 'b2', lastError: 'G04' });
expect((await r.brewGitLinks.update(brew.id, { lastError: null })).lastError).toBeNull();
expect(await r.brewGitLinks.update('unbekannt', { lastError: 'x' })).toBeNull();
});
test('Rename eines Autors lässt Verbindungen und Links unverändert', async ()=>{
await r.brews.renameAuthor('alice-git', 'alice-neu');
expect((await r.gitConnections.listByOwner(alice.id)).map((c)=>c.id)).toEqual([conn.id]);
expect((await r.brewGitLinks.findByBrewId(brew.id)).connectionId).toBe(conn.id);
});
test('Brew löschen entfernt den Link, Verbindung bleibt', async ()=>{
const tmp = await r.brews.create({ title: 'Tmp', text: 'x', authors: ['alice-git'] });
await r.brewGitLinks.upsert({ brewId: tmp.id, connectionId: conn.id, branch: 'main', path: 'brews/tmp.md' });
expect(await r.brews.deleteById(tmp.id)).toBe(true);
expect(await r.brewGitLinks.findByBrewId(tmp.id)).toBeNull();
const tmp2 = await r.brews.create({ title: 'Tmp2', text: 'x', authors: ['alice-git'], editId: 'tmp2editid12' });
await r.brewGitLinks.upsert({ brewId: tmp2.id, connectionId: conn.id, branch: 'main', path: 'brews/tmp2.md' });
expect(await r.brews.deleteByEditId('tmp2editid12')).toBe(true);
expect(await r.brewGitLinks.findByBrewId(tmp2.id)).toBeNull();
expect(await r.gitConnections.findById(conn.id)).not.toBeNull();
});
test('Verbindung löschen entfernt ihre Links, der Brew bleibt', async ()=>{
const c2 = await r.gitConnections.create({ ownerUserId: bob.id, label: 'B', repoUrl: 'https://git.example.test/b/c.git', tokenEnc: 't' });
const b2 = await r.brews.create({ title: 'B2', text: 'x', authors: ['bob-git'] });
await r.brewGitLinks.upsert({ brewId: b2.id, connectionId: c2.id, branch: 'main', path: 'x.md' });
expect(await r.gitConnections.delete(c2.id)).toBe(true);
expect(await r.gitConnections.delete(c2.id)).toBe(false);
expect(await r.brewGitLinks.findByBrewId(b2.id)).toBeNull();
expect(await r.brews.findByEditId(b2.editId)).not.toBeNull();
});
test('Benutzer löschen entfernt Verbindungen und Links, Brews bleiben', async ()=>{
expect(await r.users.delete(alice.id)).toBe(true);
expect(await r.gitConnections.findById(conn.id)).toBeNull();
expect(await r.brewGitLinks.findByBrewId(brew.id)).toBeNull();
expect(await r.brews.findByEditId(brew.editId)).not.toBeNull();
});
};
+16 -2
View File
@@ -1,7 +1,9 @@
import _ from 'lodash';
import mongoose from 'mongoose';
import zlib from 'zlib';
import { nanoid } from 'nanoid';
import { model as HomebrewModel } from '../../homebrew.model.js';
import { getGitModels } from './git.js';
// BrewRepository (Mongo, ADR 0002): ruft exakt die Statics/Methoden auf, die der Upstream-Code
// bisher direkt aufgerufen hat (HomebrewModel.get, getByUser, increaseView, findOne …).
@@ -41,6 +43,13 @@ const mapIds = (docs)=>docs.map((doc)=>{
const asProjection = (fields)=>fields && !Array.isArray(fields) ? Object.keys(fields).filter((k)=>fields[k]) : fields;
// Kaskade (ADR 0003 §2): beim Löschen eines Brews fällt seine Git-Verknüpfung weg.
// Ohne Verbindung (Unit-Specs mit gemocktem Modell) gibt es nichts zu löschen.
const connected = ()=>mongoose.connection.readyState === 1;
const removeGitLink = async (brewId)=>{
if(connected()) await getGitModels().Link.deleteOne({ brewId });
};
export const createBrewRepository = ()=>{
const find = async (query, fields)=>{
const doc = await (fields ? HomebrewModel.get(query, asProjection(fields)) : HomebrewModel.get(query))
@@ -98,11 +107,16 @@ export const createBrewRepository = ()=>{
async deleteById(id) {
const res = await HomebrewModel.deleteOne({ _id: id });
return (res?.deletedCount ?? 0) > 0;
const deleted = (res?.deletedCount ?? 0) > 0;
if(deleted) await removeGitLink(String(id));
return deleted;
},
async deleteByEditId(editId) {
const doc = connected() ? await HomebrewModel.findOne({ editId }, { _id: 1 }) : null;
const res = await HomebrewModel.deleteOne({ editId });
return (res?.deletedCount ?? 0) > 0;
const deleted = (res?.deletedCount ?? 0) > 0;
if(deleted && doc) await removeGitLink(String(doc._id));
return deleted;
},
async incrementViews(shareId) {
+120
View File
@@ -0,0 +1,120 @@
import { randomUUID } from 'crypto';
import mongoose from 'mongoose';
// Fork-Entitäten "GitConnection" und "BrewGitLink" (ADR 0003 §2). Eigene Collections, keine Upstream-Modelle.
const ConnectionSchema = new mongoose.Schema({
id : { type: String, required: true, unique: true },
ownerUserId : { type: String, required: true, index: true },
label : { type: String, required: true },
repoUrl : { type: String, required: true },
authUsername : { type: String, default: 'git' },
tokenEnc : { type: String, required: true },
defaultBranch : { type: String, default: 'main' },
brewDir : { type: String, default: 'brews' },
assetsDir : { type: String, default: 'assets' },
createdAt : { type: Date, default: Date.now },
updatedAt : { type: Date, default: Date.now },
lastVerifiedAt : { type: Date }
}, { collection: 'gitconnections', versionKey: false });
const LinkSchema = new mongoose.Schema({
brewId : { type: String, required: true, unique: true },
connectionId : { type: String, required: true, index: true },
branch : { type: String, required: true },
path : { type: String, required: true },
lastCommitSha : { type: String },
lastBlobSha : { type: String },
lastSyncedAt : { type: Date },
lastError : { type: String }
}, { collection: 'brewgitlinks', versionKey: false });
LinkSchema.index({ connectionId: 1, branch: 1, path: 1 }, { unique: true });
export const getGitModels = (connection = mongoose.connection)=>({
Connection : connection.models.ForkGitConnection ?? connection.model('ForkGitConnection', ConnectionSchema),
Link : connection.models.ForkBrewGitLink ?? connection.model('ForkBrewGitLink', LinkSchema)
});
const nul = (v)=>v ?? null;
const connToPlain = (doc)=>{
if(!doc) return null;
const o = doc.toObject ? doc.toObject() : doc;
return {
id : o.id,
ownerUserId : o.ownerUserId,
label : o.label,
repoUrl : o.repoUrl,
authUsername : o.authUsername,
tokenEnc : o.tokenEnc,
defaultBranch : o.defaultBranch,
brewDir : o.brewDir,
assetsDir : o.assetsDir,
createdAt : o.createdAt,
updatedAt : o.updatedAt,
lastVerifiedAt : nul(o.lastVerifiedAt)
};
};
const linkToPlain = (doc)=>{
if(!doc) return null;
const o = doc.toObject ? doc.toObject() : doc;
return {
brewId : o.brewId,
connectionId : o.connectionId,
branch : o.branch,
path : o.path,
lastCommitSha : nul(o.lastCommitSha),
lastBlobSha : nul(o.lastBlobSha),
lastSyncedAt : nul(o.lastSyncedAt),
lastError : nul(o.lastError)
};
};
const CONN_FIELDS = ['label', 'repoUrl', 'authUsername', 'tokenEnc', 'defaultBranch', 'brewDir', 'assetsDir', 'lastVerifiedAt'];
const LINK_FIELDS = ['connectionId', 'branch', 'path', 'lastCommitSha', 'lastBlobSha', 'lastSyncedAt', 'lastError'];
const pick = (obj, fields)=>Object.fromEntries(fields.filter((f)=>obj[f] !== undefined).map((f)=>[f, obj[f]]));
export const createGitConnectionRepository = (connection = mongoose.connection)=>{
const { Connection, Link } = getGitModels(connection);
return {
Model : Connection,
async create({ id, ownerUserId, ...rest }) {
return connToPlain(await Connection.create({ id: id ?? randomUUID(), ownerUserId: String(ownerUserId), ...pick(rest, CONN_FIELDS) }));
},
async findById(id) { return connToPlain(await Connection.findOne({ id: String(id) })); },
async findByIdForOwner(id, userId) {
return connToPlain(await Connection.findOne({ id: String(id), ownerUserId: String(userId) }));
},
async listByOwner(userId) {
return (await Connection.find({ ownerUserId: String(userId) }).sort({ createdAt: 1, id: 1 })).map(connToPlain);
},
async update(id, patch) {
return connToPlain(await Connection.findOneAndUpdate({ id: String(id) }, { $set: { ...pick(patch, CONN_FIELDS), updatedAt: new Date() } }, { returnDocument: 'after' }));
},
async delete(id) {
const res = await Connection.deleteOne({ id: String(id) });
if(res.deletedCount > 0) await Link.deleteMany({ connectionId: String(id) });
return res.deletedCount > 0;
}
};
};
export const createBrewGitLinkRepository = (connection = mongoose.connection)=>{
const { Link } = getGitModels(connection);
return {
Model : Link,
async upsert({ brewId, ...rest }) {
return linkToPlain(await Link.findOneAndUpdate({ brewId: String(brewId) }, { $set: pick(rest, LINK_FIELDS) },
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true }));
},
async findByBrewId(brewId) { return linkToPlain(await Link.findOne({ brewId: String(brewId) })); },
async findByLocation(connectionId, branch, path) {
return linkToPlain(await Link.findOne({ connectionId: String(connectionId), branch, path }));
},
async listByConnection(connectionId) { return (await Link.find({ connectionId: String(connectionId) })).map(linkToPlain); },
async update(brewId, patch) {
return linkToPlain(await Link.findOneAndUpdate({ brewId: String(brewId) }, { $set: pick(patch, LINK_FIELDS) }, { returnDocument: 'after' }));
},
async delete(brewId) { return (await Link.deleteOne({ brewId: String(brewId) })).deletedCount > 0; }
};
};
+13
View File
@@ -3,6 +3,7 @@ import DB from '../../db.js';
import { createUserRepository } from './users.js';
import { createBrewRepository } from './brews.js';
import { createNotificationRepository } from './notifications.js';
import { createGitConnectionRepository, createBrewGitLinkRepository } from './git.js';
// Mongo-Implementierung der Storage-Schicht (ADR 0002). Ruft die Statics und Methoden der
// unveränderten Upstream-Modelle (homebrew.model.js, notifications.model.js) auf.
@@ -10,6 +11,8 @@ export const createMongoStorage = (config)=>{
const brews = createBrewRepository();
const notifications = createNotificationRepository();
let users;
let gitConnections;
let brewGitLinks;
return {
driver : 'mongo',
brews,
@@ -18,6 +21,8 @@ export const createMongoStorage = (config)=>{
await DB.connect(config);
if(!config.get('local_environments').includes(config.get('node_env'))) {
await this.users.Model.syncIndexes(); // nur Fork-Modelle, nie Homebrew
await this.gitConnections.Model.syncIndexes();
await this.brewGitLinks.Model.syncIndexes();
}
},
async disconnect() {
@@ -29,6 +34,14 @@ export const createMongoStorage = (config)=>{
get users() {
users ??= createUserRepository();
return users;
},
get gitConnections() {
gitConnections ??= createGitConnectionRepository();
return gitConnections;
},
get brewGitLinks() {
brewGitLinks ??= createBrewGitLinkRepository();
return brewGitLinks;
}
};
};
+15
View File
@@ -7,6 +7,8 @@ import { createNotificationRepository } from './notifications.js';
import { model as HomebrewModel } from '../../homebrew.model.js';
import { model as NotificationModel } from '../../notifications.model.js';
import { runUserRepositoryContract } from '../contract/users.contract.js';
import { createGitConnectionRepository, createBrewGitLinkRepository } from './git.js';
import { runGitRepositoryContract } from '../contract/git.contract.js';
import { runBrewRepositoryContract, runNotificationRepositoryContract } from '../contract/brews.contract.js';
const uri = process.env.HB_TEST_MONGODB_URI;
@@ -45,3 +47,16 @@ suite('Mongo BrewRepository (Contract)', ()=>{
suite('Mongo NotificationRepository (Contract)', ()=>{
runNotificationRepositoryContract(async ()=>({ notifications: createNotificationRepository(), cleanup: await connectGlobal() }));
});
suite('Mongo Git-Repositories (Contract)', ()=>{
runGitRepositoryContract(async ()=>{
const cleanup = await connectGlobal();
const users = createUserRepository();
const gitConnections = createGitConnectionRepository();
const brewGitLinks = createBrewGitLinkRepository();
await users.Model.init();
await gitConnections.Model.init();
await brewGitLinks.Model.init();
return { users, brews: createBrewRepository(), gitConnections, brewGitLinks, cleanup };
});
});
+8
View File
@@ -1,5 +1,6 @@
import { randomUUID } from 'crypto';
import mongoose from 'mongoose';
import { getGitModels } from './git.js';
// Fork-Entität "User" (ADR 0001 §4). Collection `users`, eigenes Schema, berührt keine Upstream-Modelle.
const UserSchema = new mongoose.Schema({
@@ -92,6 +93,13 @@ export const createUserRepository = (connection = mongoose.connection)=>{
async delete(id) {
const res = await User.deleteOne({ id });
if(res.deletedCount > 0) {
// Kaskade (ADR 0002 §5): Verbindungen des Benutzers samt Links entfernen, Brews bleiben
const { Connection, Link } = getGitModels(connection);
const ids = (await Connection.find({ ownerUserId: String(id) }, { id: 1 })).map((c)=>c.id);
await Link.deleteMany({ connectionId: { $in: ids } });
await Connection.deleteMany({ ownerUserId: String(id) });
}
return res.deletedCount > 0;
}
};
+124
View File
@@ -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;
}
});
+5
View File
@@ -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);
};
+3 -1
View File
@@ -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
};
+8
View File
@@ -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 });