Compare commits

...
Author SHA1 Message Date
claudia-bot Bot e574598a9e Merge pull request 'fix(mongo): Admin-Cleanup räumt verwaiste Git-Links und Bild-Assets auf' (#34) from flw-237-mongo-admin-cleanup-orphans into main
CI / App (npm ci + Build, ESLint, Stylelint, Jest) (push) Canceled after 0s
CI / Storage (mongo) (push) Canceled after 0s
CI / Storage (postgres) (push) Canceled after 0s
Image / Image bauen und pushen (push) Canceled after 0s
2026-11-27 01:56:19 +00:00
dev-bot BotandClaude Sonnet 5.5 ebcd324980 fix(mongo): Admin-Cleanup räumt verwaiste Git-Links und Bild-Assets auf (#27)
CI / App (npm ci + Build, ESLint, Stylelint, Jest) (pull_request) Canceled after 0s
CI / Storage (mongo) (pull_request) Canceled after 0s
CI / Storage (postgres) (pull_request) Canceled after 0s
POST /admin/cleanupJunk und /admin/cleanupLost löschen unter MongoDB per
deleteMany; brewgitlinks und brewassets blieben als Waisen zurück. Ein
Fork-Hook (server/fork/cleanup) läuft nach erfolgreichem Cleanup und entfernt
Links und Assets ohne Brew. server/admin.api.js bleibt unverändert.

Closes #27

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 01:48:17 +00:00
dev-bot Bot 0926dea8b0 Merge pull request 'docs(dockerhub): englische Repo-Beschreibung + Publish-Workflow (#32)' (#33) from flw-263-dockerhub-beschreibung into main
CI / App (npm ci + Build, ESLint, Stylelint, Jest) (push) Successful in 2m27s
CI / Storage (mongo) (push) Successful in 1m39s
CI / Storage (postgres) (push) Successful in 1m37s
Docker Hub Description / Beschreibung nach Docker Hub schreiben (push) Canceled after 0s
Image / Image bauen und pushen (push) Canceled after 0s
2026-11-26 12:51:42 +00:00
3 changed files with 141 additions and 0 deletions

No files matched your search

+4
View File
@@ -37,6 +37,7 @@ import dbCheck from './middleware/dbCheck.js';
import { readAuthConfig, accountMiddleware, createAuthRouter, clientConfig as authClientConfig } from './fork/auth/index.js';
import { getStorage } from './storage/index.js';
import { createGitBackend } from './fork/git/index.js';
import { createAdminCleanupHook } from './fork/cleanup/index.js';
import { createAssetsDeliveryRouter } from './fork/assets/index.js';
import cors from 'cors';
@@ -129,6 +130,9 @@ export default async function createApp(vite) {
// Fork: Git-Backend (ADR 0003): /api/git/* und Abgleich bei GET /edit/:id, vor pageRoutes
app.use(createGitBackend({ getStorage, api, splitTextStyleAndMetadata }).router);
// Fork: räumt nach den Mongo-Admin-Cleanups verwaiste Git-Links und Assets auf (Gitea #27)
app.use(createAdminCleanupHook({ getStorage }));
app.use(homebrewApi);
app.use(adminApi(vite));
app.use(vaultApi);
+56
View File
@@ -0,0 +1,56 @@
import mongoose from 'mongoose';
import { model as HomebrewModel } from '../../homebrew.model.js';
// Admin-Cleanup unter MongoDB (Gitea #27): `POST /admin/cleanupJunk` und `/admin/cleanupLost` löschen Brews per
// `deleteMany` (Upstream, unverändert). Anders als unter Postgres (FK-Kaskade) bleiben dabei Git-Links
// (`brewgitlinks`) und Bild-Assets (`brewassets`) ohne Brew zurück. Dieser Hook räumt sie danach auf.
const COLLECTIONS = ['brewgitlinks', 'brewassets'];
const CLEANUP_ROUTE = /^\/admin\/cleanup(Junk|Lost)\/?$/;
const toObjectId = (id)=>mongoose.isValidObjectId(id) && String(new mongoose.Types.ObjectId(id)) === String(id).toLowerCase()
? new mongoose.Types.ObjectId(id) : null;
/**
* Entfernt Git-Links und Assets, deren Brew nicht mehr existiert.
* @returns {Promise<{ gitLinks: number, assets: number }>}
*/
export const cleanupOrphans = async (connection = mongoose.connection)=>{
const counts = {};
for (const name of COLLECTIONS) {
const coll = connection.collection(name);
const brewIds = (await coll.distinct('brewId')).map(String);
const asObjectId = new Map(brewIds.map((id)=>[id, toObjectId(id)]));
const valid = [...asObjectId.values()].filter(Boolean);
const existing = valid.length
? new Set((await HomebrewModel.find({ _id: { $in: valid } }, { _id: 1 }).lean()).map((d)=>String(d._id)))
: new Set();
const orphans = brewIds.filter((id)=>!existing.has(String(asObjectId.get(id))));
counts[name] = orphans.length ? (await coll.deleteMany({ brewId: { $in: orphans } })).deletedCount : 0;
}
return { gitLinks: counts.brewgitlinks, assets: counts.brewassets };
};
/**
* Express-Middleware vor `adminApi`: Nach einem erfolgreichen POST auf die Cleanup-Routen (HTTP 200, also Admin-Auth
* und Mongo-Prüfung bestanden) wird `cleanupOrphans` ausgeführt, bevor die Antwort rausgeht. Unter Postgres wirkungslos.
*/
export const createAdminCleanupHook = ({ getStorage, cleanup = cleanupOrphans, logger = console })=>(req, res, next)=>{
if(req.method !== 'POST' || !CLEANUP_ROUTE.test(req.path)) return next();
const send = res.json.bind(res);
res.json = async (body)=>{
res.json = send;
if(res.statusCode === 200 && getStorage().driver === 'mongo') {
try {
const orphans = await cleanup();
logger.info?.(`Admin-Cleanup: verwaiste Git-Links (${orphans.gitLinks}) und Assets (${orphans.assets}) entfernt.`);
} catch (err) {
logger.error?.('Admin-Cleanup: Aufräumen verwaister Git-Links/Assets fehlgeschlagen', err);
}
}
return send(body);
};
return next();
};
export default { cleanupOrphans, createAdminCleanupHook };
+81
View File
@@ -0,0 +1,81 @@
// Gitea #27: Die Mongo-Admin-Cleanups (Upstream, deleteMany) lassen keine Git-Links/Assets ohne Brew zurück.
// Läuft nur mit HB_TEST_MONGODB_URI (wie git-backend.db.test.js). Unter Postgres übernimmt die FK-Kaskade.
import os from 'os';
import { randomBytes } from 'crypto';
import supertest from 'supertest';
import mongoose from 'mongoose';
import createApp from '../../server/app.js';
import storage from '../../server/storage/index.js';
import packageJSON from '../../package.json' with { type: 'json' };
const url = process.env.HB_TEST_MONGODB_URI;
const suite = url ? describe : describe.skip;
if(!url) console.warn('Admin-Cleanup-Test: HB_TEST_MONGODB_URI fehlt, übersprungen.');
const auth = `Basic ${Buffer.from('admin:password3').toString('base64')}`;
const version = { 'Homebrewery-Version': packageJSON.version };
const OLD = new Date(Date.now() - 3 * 365 * 24 * 3600 * 1000);
suite('Admin-Cleanup räumt Git-Links und Assets auf (mongo)', ()=>{
let request; let connectSpy; let dbName; let brewsColl;
beforeAll(async ()=>{
dbName = `test_${randomBytes(4).toString('hex')}`;
const values = { hb_db_driver: 'mongo', node_env: 'test', local_environments: ['local'], mongodb_uri: url };
const connect = mongoose.connect.bind(mongoose);
connectSpy = jest.spyOn(mongoose, 'connect').mockImplementation((u, o)=>connect(u, { ...o, dbName, runtimeAdapters: { os } }));
await storage.connect({ get: (key)=>values[key] });
const s = storage.getStorage();
await s.brewGitLinks.Model.init(); await s.brewAssets.Model.init();
brewsColl = mongoose.connection.collection('homebrews');
request = supertest.agent(await createApp()).set('X-Forwarded-Proto', 'https');
});
afterAll(async ()=>{
await mongoose.connection.dropDatabase();
await storage.disconnect();
connectSpy?.mockRestore();
});
// Brew ohne Autor, lange nicht angesehen/geändert, winziges textBin → trifft cleanupLost und cleanupJunk
const insertBrew = async ({ old = true } = {})=>{
const _id = new mongoose.Types.ObjectId();
await brewsColl.insertOne({
_id, title : 'x', authors : [], textBin : new mongoose.mongo.Binary(Buffer.alloc(10)), editId : randomBytes(6).toString('hex'), shareId : randomBytes(6).toString('hex'),
updatedAt : old ? OLD : new Date(), lastViewed : old ? OLD : new Date()
});
return String(_id);
};
const attach = async (brewId)=>{
const s = storage.getStorage();
await s.brewGitLinks.upsert({ brewId, connectionId: 'c1', branch: 'main', path: `brews/${brewId}.md` });
await s.brewAssets.create({ brewId, sha256: 'a'.repeat(64), repoPath: 'assets/a.png', commitSha: 'b'.repeat(40), contentType: 'image/png', size: 3, data: Buffer.from([1, 2, 3]) });
};
const state = async (brewId)=>{
const s = storage.getStorage();
return { link: await s.brewGitLinks.findByBrewId(brewId), assets: await s.brewAssets.listByBrew(brewId), brew: await brewsColl.findOne({ _id: new mongoose.Types.ObjectId(brewId) }) };
};
test.each(['cleanupLost', 'cleanupJunk'])('POST /admin/%s entfernt Link und Asset des gelöschten Brews, lässt andere unberührt', async (route)=>{
const doomed = await insertBrew();
const kept = await insertBrew({ old: false });
await attach(doomed); await attach(kept);
const res = await request.post(`/admin/${route}`).set(version).set('Authorization', auth);
expect(res.status).toBe(200);
const gone = await state(doomed);
expect(gone.brew).toBeNull();
expect(gone.link).toBeNull();
expect(gone.assets).toHaveLength(0);
const stays = await state(kept);
expect(stays.brew).not.toBeNull();
expect(stays.link).not.toBeNull();
expect(stays.assets).toHaveLength(1);
});
test('ohne Admin-Auth wird nichts aufgeräumt', async ()=>{
const orphan = String(new mongoose.Types.ObjectId());
await attach(orphan);
const res = await request.post('/admin/cleanupLost').set(version);
expect(res.status).toBe(401);
expect((await state(orphan)).link).not.toBeNull();
});
});