refactor(server): provide MaintenanceRepository through DI

MaintenanceRepository was built with new over an injected EntityManager
in the readiness probe and in UserCleanupService, outside the container.
MaintenanceModule now provides it, as a factory over the same
context-resolving EntityManager Nest injects everywhere, and both inject
it. The class itself stays free of Nest decorators, like the rest of
src/db, so tests keep building one over their own EntityManager.

No behaviour changes: the probe still pings and the erasure still runs
inside the account deletion's transaction.
This commit is contained in:
Maurice
2026-10-08 15:23:20 +02:00
parent 0a4c6fbace
commit 8ede0dab9e
19 changed files with 81 additions and 41 deletions
@@ -15,15 +15,13 @@ import type { EntityManager } from '@mikro-orm/core';
* all — so `connection.execute()` (the last tier in the program's query-API
* order) is the correct tool, not a shortcut around it.
*
* Constructed directly (`new MaintenanceRepository(em)`), never through Nest
* DI: its only two callers — `backup.impl.ts#createBackup` and
* `demo/demo-reset.ts` (`resetDemoUser`/`saveBaseline`) — are plain function
* modules, not Nest providers, and obtain the `EntityManager` via
* `RequestContext.getEntityManager()` (the same static accessor MikroORM's
* own per-request middleware and `CronRegistrarService`'s `wrappedTick`
* populate) rather than constructor injection. No module registers this
* class as a provider — nothing today asks Nest's DI container to resolve
* it.
* Provided through Nest DI by `MaintenanceModule` (`nest/database/`), a
* factory over the context-resolving global `EntityManager`; the readiness
* probe and `UserCleanupService` inject it. `backup.impl.ts` and
* `demo/demo-reset.ts` still build one over the request's EntityManager until
* they move behind an injected provider of their own. The class stays free of
* Nest decorators like every other file under `db/`, so a test can still
* build one over its own `EntityManager`.
*/
export class MaintenanceRepository {
constructor(private readonly em: EntityManager) {}
+3
View File
@@ -34,6 +34,7 @@ import { UserCleanupService } from './user-cleanup.service';
import { WebauthnConfigService } from './webauthn-config.service';
import { AppConfigModule } from '../app-config/app-config.module';
import { BudgetModule } from '../budget/budget.module';
import { MaintenanceModule } from '../database/maintenance.module';
import { AuditModule } from '../audit/audit.module';
import { MailerModule } from '../notifications/mailer/mailer.module';
import { PermissionsModule } from '../permissions/permissions.module';
@@ -84,6 +85,8 @@ import { AllowedFileTypesModule } from '../files/allowed-file-types.module';
StorageModule,
AllowedFileTypesModule,
EphemeralTokenModule, RateLimitModule, AuditModule, PermissionsModule, TripMembershipModule, MailerModule, AppConfigModule, TokensModule, BudgetModule,
// MaintenanceRepository: UserCleanupService's UC1 plugin-table erasure.
MaintenanceModule,
// AppSettings/Users: AuthService/UserProfileService each pass their own
// AppSettingsRepository/UsersRepository to instance-api-keys.ts's
// resolveApiKey/readInstanceApiKey/writeInstanceApiKey now (Plan 3a Task
+8 -8
View File
@@ -1,7 +1,6 @@
import fs from 'node:fs';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityManager } from '@mikro-orm/core';
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
// Injected since BudgetModule dropped its AuthModule import (BudgetMcp's demo
// guard reads RuntimeEnvService + the users table now), which un-closed the
@@ -48,11 +47,11 @@ import { enqueueHookUserDataErasures } from '../plugins/user-erasure-enqueue';
@Injectable()
export class UserCleanupService {
constructor(
// Plan 4 Task 4: `DatabaseService` dropped — UC1 (below) now goes
// through `MaintenanceRepository`, the rule-4-permitted raw-connection
// home, constructed from this directly-injected `EntityManager`
// Plan 4 Task 4: `DatabaseService` dropped. UC1 (below) goes through
// `MaintenanceRepository`, the rule-4-permitted raw-connection home,
// injected over the context-resolving EntityManager
// (`uow.transactional` below always leaves a request context active).
private readonly em: EntityManager,
private readonly maintenance: MaintenanceRepository,
private readonly budget: BudgetService,
private readonly uow: UnitOfWork,
@InjectRepository(Users) private readonly usersRepo: UsersRepository,
@@ -92,8 +91,9 @@ export class UserCleanupService {
* deleted `DatabaseService` onto `MaintenanceRepository.deletePluginUserData`
* (rule 4's `connection.execute()` escape hatch), not onto a repository
* this domain would otherwise own. This method always runs inside
* `deleteUserCompletely`'s `uow.transactional(...)` — `this.em` is safe to
* pass as-is (MikroORM resolves the active transactional fork through
* `deleteUserCompletely`'s `uow.transactional(...)`. The injected
* repository's EntityManager is safe as-is (MikroORM resolves the active
* transactional fork through
* `EntityManager#getContext()`/`#getTransactionContext()` regardless of
* which EM instance you call them on, via its own `TransactionContext`
* async-local storage); `MaintenanceRepository.deletePluginUserData` is the
@@ -116,7 +116,7 @@ export class UserCleanupService {
* here, now via the same repository.
*/
async erasePluginUserData(userId: number): Promise<void> {
await new MaintenanceRepository(this.em).deletePluginUserData(userId); // UC1 — Plan 4 Task 4
await this.maintenance.deletePluginUserData(userId); // UC1, Plan 4 Task 4
try {
const rows = await this.pluginsRepo.listIdsAndPermissions(); // UC2 — Plan 4 Task 8a
const installed = new Set(rows.map((r) => r.id));
@@ -0,0 +1,25 @@
import { Module } from '@nestjs/common';
import { EntityManager } from '@mikro-orm/core';
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
/**
* Provides `MaintenanceRepository`, the home of the few whole-database
* statements no entity can express (the readiness ping, the WAL checkpoint,
* `VACUUM INTO`, the plugin-table erasure).
*
* A factory over the context-resolving global `EntityManager`, the same one
* Nest injects into every service, so the repository resolves the request or
* transaction fork that is active when a method runs. The class itself stays
* free of Nest, like every other file under `db/`.
*/
@Module({
providers: [
{
provide: MaintenanceRepository,
useFactory: (em: EntityManager) => new MaintenanceRepository(em),
inject: [EntityManager],
},
],
exports: [MaintenanceRepository],
})
export class MaintenanceModule {}
@@ -1,5 +1,4 @@
import { Controller, Get, Res } from '@nestjs/common';
import { EntityManager } from '@mikro-orm/core';
import type { Response } from 'express';
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
import { KitineraryExtractorService } from '../booking-import/kitinerary-extractor.service';
@@ -15,7 +14,7 @@ export class FeaturesController {
constructor(
private readonly extractor: KitineraryExtractorService,
private readonly addons: AddonsService,
private readonly em: EntityManager,
private readonly maintenance: MaintenanceRepository,
) {}
/** The container/uptime probe. The forced-HTTPS redirect and HSTS exempt this
@@ -37,7 +36,7 @@ export class FeaturesController {
async ready(@Res() res: Response): Promise<void> {
res.setHeader('Cache-Control', 'no-store, must-revalidate');
try {
await new MaintenanceRepository(this.em).ping();
await this.maintenance.ping();
res.json({ status: 'ready' });
} catch {
res.status(503).json({ status: 'unavailable' });
+2 -1
View File
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { FeaturesController } from './features.controller';
import { KitineraryExtractorModule } from '../booking-import/kitinerary-extractor.module';
import { AddonsModule } from '../addons/addons.module';
import { MaintenanceModule } from '../database/maintenance.module';
/** Server capability reporting. `GET /api/health/features` tells the client which
* optional server-side features are usable, so it can hide the affordances it
@@ -9,7 +10,7 @@ import { AddonsModule } from '../addons/addons.module';
* redirect and HSTS exempt it by path inside globalMiddleware, so it answers
* plain-HTTP probes no matter where the route itself is registered. */
@Module({
imports: [KitineraryExtractorModule, AddonsModule],
imports: [KitineraryExtractorModule, AddonsModule, MaintenanceModule],
controllers: [FeaturesController],
})
export class HealthModule {}