Files
dev-bot BotandClaude Sonnet 5.5 ebcd324980
CI / Storage (postgres) (pull_request) Canceled after 0s
CI / App (npm ci + Build, ESLint, Stylelint, Jest) (pull_request) Canceled after 0s
CI / Storage (mongo) (pull_request) Canceled after 0s
fix(mongo): Admin-Cleanup räumt verwaiste Git-Links und Bild-Assets auf (#27)
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

82 lines
3.9 KiB
JavaScript

// 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();
});
});