fix(plugins): send file events for attached files while Documents is off

A file that belongs to a booking, place, expense, note or message stays readable with Documents off, so its events now reach subscribed plugins too; loose files still wait for Documents, and a trip's events keep their order.
This commit is contained in:
Maurice
2026-11-23 17:26:31 +01:00
parent e1147504c2
commit 97da0c5ba6
6 changed files with 70 additions and 14 deletions
+1 -1
View File
@@ -13,7 +13,7 @@
"src/nest/doc-sync/providers/synology-drive.client.ts": 1160,
"src/nest/journey/journey-domain.service.ts": 1659,
"src/nest/places/places.service.ts": 1546,
"src/nest/plugins/plugin-runtime.service.ts": 1460,
"src/nest/plugins/plugin-runtime.service.ts": 1459,
"src/nest/plugins/runtime/plugin-sdk.ts": 1093,
"src/nest/reservations/reservations.service.ts": 1163,
"src/nest/vacay/vacay.service.ts": 1393
+6
View File
@@ -380,6 +380,12 @@ export class FilesService {
return isAttachedFile(file, await this.fileLinksRepo.listForFiles([file.id]));
}
/** `isAttached` for a file of the trip named by its id, trashed or not; false when the trip holds no such file. */
async isAttachedById(fileId: number, tripId: number): Promise<boolean> {
const file = await this.getFileById(fileId, tripId);
return file !== undefined && (await this.isAttached(file));
}
/** `attachedOnly` leaves out the files only the file manager shows, for a trip that has Documents off. */
async listFiles(tripId: string | number, showTrash: boolean, attachedOnly = false) {
const tripIdNum = toRowId(tripId) ?? -1;
+16 -3
View File
@@ -31,24 +31,37 @@ export function tripAddonOfEvent(event: string): string | null {
type Deliver = (tripId: number, event: string, meta?: PluginEventMeta) => void;
/** Whether a trip's file belongs to a booking, place, expense, note or message, which Documents does not gate. */
type FileAttached = (fileId: number, tripId: number) => Promise<boolean>;
/**
* The plugin event sink with the trip's addons in front of it: an event of a
* trip addon's family is handed on only once the addon is read as on for the
* trip, any other event at once. An addon that cannot be read sends nothing,
* since events are best-effort and a family the owner switched off must not
* leak through a failed read.
* leak through a failed read. A file event passes with Documents off when its
* file is attached to something, since such a file stays readable then too.
*
* The reads run side by side, but a trip's events go out in the order they
* were emitted: while one of them waits for its read, every later event of the
* same trip queues behind it, a trip event included.
*/
export function tripEventSink(addons: AddonsService, orm: MikroORM | undefined, deliver: Deliver): Deliver {
export function tripEventSink(
addons: AddonsService,
orm: MikroORM | undefined,
deliver: Deliver,
fileAttached?: FileAttached,
): Deliver {
const queues = new Map<number, Promise<void>>();
return (tripId, event, meta) => {
const addonId = tripAddonOfEvent(event);
const before = queues.get(tripId);
if (!addonId && before === undefined) return deliver(tripId, event, meta);
const ask = () => (addonId ? addons.isEnabledForTrip(tripId, addonId) : Promise.resolve(true));
const fileId = event.startsWith('file:') ? meta?.entityId : undefined;
const ask = async () => {
if (!addonId || (await addons.isEnabledForTrip(tripId, addonId))) return true;
return fileId !== undefined && fileAttached !== undefined && (await fileAttached(fileId, tripId));
};
const on = (orm && addonId ? withRequestContext(orm, ask) : ask()).catch(() => false);
const queued = (before ?? Promise.resolve())
.then(() => on)
@@ -67,6 +67,7 @@ import type { TrekRangeBypass } from './install/host-compat';
import { keyFingerprint } from './signature-status';
import { AuditService } from '../audit/audit.service';
import { AddonsService } from '../addons/addons.service';
import { FilesService } from '../files/files.service';
import type { McpToolCapability, PluginDependency } from './install/manifest';
import type { VersionMismatch, PluginDepRow } from './dependencies';
import { parseDependencies, disabledRequiredAddons, resolveDependencyState, enableOrder, findDependentsTransitive, DependencyCycleError } from './dependencies';
@@ -284,16 +285,12 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
// (task-2-fix-report.md's "Concerns").
@Optional() private readonly orm?: MikroORM,
// Plan 3j Task 0 (R-scheduler): the one path this codebase schedules a cron through
// (server/CLAUDE.md). `@Optional()` for the same reason `uow`/`orm` are — the wide
// hand-construction surface this class has across the test suite (plugin-host.ts,
// boot-registry-order.test.ts, settings-isolation.test.ts, plugin-runtime.boot-no-
// orm.test.ts) never passes a 9th positional arg; a hand-built instance without one
// simply never registers the sweep (no log — mirrors how an absent `hostFactory`/
// `registry` produces no boot-time log either, only a failure at first use, and
// registering nothing is exactly what happens today too whenever a test never lets
// the 30s interval actually fire). Nest always injects the real one in production
// (PluginsRuntimeModule imports SchedulingModule).
// (server/CLAUDE.md). `@Optional()` for the same reason `orm` is: a hand-built test
// instance without one never registers the sweep, as an absent `hostFactory`/`registry`
// logs nothing either. Nest always injects the real one (PluginsRuntimeModule imports SchedulingModule).
@Optional() private readonly registrar?: CronRegistrarService,
// Lets a file event through while Documents is off when its file is attached; without it they wait for Documents.
@Optional() private readonly files?: FilesService,
) {}
// Plan 3j Task 3: `discoverPlugins` composes `DiscoveryRepos` from the repositories
@@ -332,7 +329,8 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
applyStagedPluginTrees();
});
// Core trip events go to subscribed plugins, fire-and-forget, unless the trip has the event's addon off.
setPluginEventSink(tripEventSink(this.addons, this.orm, (t, e, m) => this.supervisor.deliverEvent(t, e, m)));
const attached = this.files && this.files.isAttachedById.bind(this.files);
setPluginEventSink(tripEventSink(this.addons, this.orm, (t, e, m) => this.supervisor.deliverEvent(t, e, m), attached));
// Expose plugin notification channels to the (plain, non-Nest) notification
// service. Pull-based: it calls this on every dispatch, so enabling or removing
// a plugin takes effect immediately with nothing to invalidate.
@@ -393,6 +393,18 @@ describe('listFiles', () => {
expect(receiptRow && (await svc.isAttached(receiptRow))).toBe(true);
expect(looseRow && (await svc.isAttached(looseRow))).toBe(false);
});
it('FILE-SVC-014d: isAttachedById answers for a trashed file too, and no for one of another trip', async () => {
const { user, trip } = seedTrip();
const other = seedTrip();
const receipt = await makeFile(trip.id, user.id, {}, { budget_item_id: await insertBudgetItem(trip.id, 'Dinner') });
const loose = await makeFile(trip.id, user.id);
await svc.softDeleteFile(receipt.id);
expect(await svc.isAttachedById(receipt.id, trip.id)).toBe(true);
expect(await svc.isAttachedById(loose.id, trip.id)).toBe(false);
expect(await svc.isAttachedById(receipt.id, other.trip.id)).toBe(false);
});
});
// ── receipts on an expense ────────────────────────────────────────────────────
@@ -113,4 +113,31 @@ describe('the plugin event sink per trip', () => {
sink(5, 'place:created', undefined);
expect(deliver).toHaveBeenLastCalledWith(5, 'place:created', undefined);
});
it('PEVADDON-006: with Documents off a file event goes out when its file is attached, in order', async () => {
const deliver = vi.fn();
const addons = { isEnabledForTrip: vi.fn(async () => false) } as unknown as AddonsService;
const attached = vi.fn(async (fileId: number) => {
if (fileId === 12) throw new Error('db gone');
return fileId === 10;
});
const sink = tripEventSink(addons, undefined, deliver, attached);
sink(5, 'file:created', { entity: 'file', entityId: 10 });
sink(5, 'file:updated', { entity: 'file', entityId: 11 });
sink(5, 'file:updated', { entity: 'file', entityId: 12 });
sink(5, 'file:deleted', undefined);
sink(5, 'budget:created', { entity: 'budget', entityId: 10 });
sink(5, 'file:deleted', { entity: 'file', entityId: 10 });
sink(5, 'place:created', undefined);
await settle();
await settle();
expect(deliver.mock.calls.map(([, event, meta]) => `${event} ${meta?.entityId ?? '-'}`)).toEqual([
'file:created 10',
'file:deleted 10',
'place:created -',
]);
expect(attached).toHaveBeenCalledWith(10, 5);
expect(attached).not.toHaveBeenCalledWith(undefined, 5);
expect(attached).toHaveBeenCalledTimes(4);
});
});