fix: Paket 0 – data integrity, security hardening and field usability
Backend - Backup covers every Prisma model (bundle v3); a guard test fails for any new model that is neither backed up nor explicitly excluded. Unsealed bundles may only add rows to 27 legacy master/field tables and never overwrite; counters, ledgers, settings, roles etc. need a sealed file. Shared import limit BACKUP_MAX_IMPORT_BYTES (default 50 MB, max 256 MB) with warnings in log and UI; replaced document files are removed after commit. - Post-commit side effects (automation, calendar sync, webhooks) run via runAfterCommit and never turn a committed write into a 500, so retries with the same Idempotency-Key no longer create duplicates. - Calendar outbox is multi-replica safe: per-entry claims with stale takeover, revision-based settle, new Graph event only on 404/410, transactionId on create, 30 s Graph timeout, URL-encoded ids, GUID validation for groupId, "run now" in background and resets FAILED. - Automation tasks are deduplicated under a row lock on the rule. - Update DTOs follow one null rule: omitted = unchanged, null clears a nullable field, null on a required field is a 400. - Varroa mites/day is recomputed on correction; withdrawal status is checked against the harvest date (?at=), bounded colonyIds; inspection create is audited; updates re-enqueue calendar entries. - Dashboard, statistics and apiary/colony guards treat WEAK, CONSPICUOUS and QUEENLESS colonies as living. - Prisma errors and body-parser errors are logged without query values or request bodies. - Migration 20261012100000_calendar_sync_claims; schema index name aligned with the existing database object. Frontend - Sticky save bar sticks again (no scroll container ancestors, card uses overflow-clip), safe-area insets, scroll-padding, FAB hidden on forms, sticky desktop sidebar. - Inspections record yes / no / not checked instead of silent defaults. - All living colonies are selectable; shared RecordSelect, EnumSelect, ChoiceGroup and TriStateField replace per-page copies; selects show names instead of ids; labels point at real controls. - Emptied optional fields are sent as null (emptyToNull) so every field can be cleared; dates default to the local day and are sent via toApiDate. - Harvest withdrawal warning uses the harvest date; backup page warns when a backup outgrows the import limit and lists skipped tables. Build and docs - Docker builds fail unless lint, typecheck and unit tests pass. - ARCHITECTURE.md updated (assumptions 9-12, 19-21, section 8) and spec docs/superpowers/specs/2026-10-12-plattform-rueckgrat-und-fahrplan-design.md for the backbone (api/worker/job roles, domain event outbox) and the feature roadmap T3-T7. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
f5b1964223
commit
10cbe9bf2d
310 files changed
+12177
-3746
No files matched your search
@@ -1,7 +1,9 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { CalendarSyncService } from './calendar-sync.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CalendarSyncSettingsService } from './calendar-sync-settings.service';
|
||||
import { GraphClientService } from './graph-client.service';
|
||||
import { GraphClientService, GraphRequestError } from './graph-client.service';
|
||||
import { Prisma } from '../../generated/prisma';
|
||||
|
||||
describe('CalendarSyncService', () => {
|
||||
let service: CalendarSyncService;
|
||||
@@ -10,6 +12,7 @@ describe('CalendarSyncService', () => {
|
||||
upsert: jest.Mock;
|
||||
findUnique: jest.Mock;
|
||||
update: jest.Mock;
|
||||
updateMany: jest.Mock;
|
||||
findMany: jest.Mock;
|
||||
count: jest.Mock;
|
||||
};
|
||||
@@ -41,13 +44,47 @@ describe('CalendarSyncService', () => {
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
const pendingEntry = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'entry-1',
|
||||
sourceType: 'TASK',
|
||||
sourceId: 'task-1',
|
||||
status: 'PENDING',
|
||||
graphEventId: null,
|
||||
attempts: 0,
|
||||
revision: 3,
|
||||
claimedAt: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
/** Derived from the outbox entry, shaped like a GUID. */
|
||||
const TRANSACTION_ID = expect.stringMatching(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
|
||||
) as string;
|
||||
|
||||
/** Free, or held by a worker that gave up long ago (cut-off time). */
|
||||
const CLAIMABLE = {
|
||||
OR: [{ claimedAt: null }, { claimedAt: { lt: expect.any(Date) as Date } }],
|
||||
};
|
||||
|
||||
type UpdateManyArgs = {
|
||||
where: Record<string, unknown>;
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
const updateManyCalls = () =>
|
||||
prisma.calendarSyncOutboxEntry.updateMany.mock.calls.map(
|
||||
([args]) => args as UpdateManyArgs,
|
||||
);
|
||||
/** The claim taken by this pass - every later write is conditional on it. */
|
||||
const claimedAt = () => updateManyCalls()[0].data.claimedAt as Date;
|
||||
|
||||
beforeEach(() => {
|
||||
prisma = {
|
||||
calendarSyncOutboxEntry: {
|
||||
upsert: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
update: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
|
||||
findMany: jest.fn().mockResolvedValue([]),
|
||||
count: jest.fn().mockResolvedValue(0),
|
||||
},
|
||||
task: { findUnique: jest.fn() },
|
||||
@@ -94,7 +131,7 @@ describe('CalendarSyncService', () => {
|
||||
expect(prisma.calendarSyncOutboxEntry.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('upserts a PENDING row, resetting attempts and lastError', async () => {
|
||||
it('upserts a PENDING row, resetting attempts and lastError and counting the revision up', async () => {
|
||||
await service.enqueue('TASK', 'task-1');
|
||||
|
||||
expect(prisma.calendarSyncOutboxEntry.upsert).toHaveBeenCalledWith({
|
||||
@@ -102,11 +139,58 @@ describe('CalendarSyncService', () => {
|
||||
sourceType_sourceId: { sourceType: 'TASK', sourceId: 'task-1' },
|
||||
},
|
||||
create: { sourceType: 'TASK', sourceId: 'task-1' },
|
||||
update: { status: 'PENDING', attempts: 0, lastError: null },
|
||||
update: {
|
||||
status: 'PENDING',
|
||||
attempts: 0,
|
||||
lastError: null,
|
||||
revision: { increment: 1 },
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// enqueue()/cancel() run after the source record is committed: a failure
|
||||
// must not fail that request (the client would retry and store it twice).
|
||||
describe('post-commit calls', () => {
|
||||
let errorSpy: jest.SpyInstance;
|
||||
|
||||
beforeEach(() => {
|
||||
errorSpy = jest
|
||||
.spyOn(Logger.prototype, 'error')
|
||||
.mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
errorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('enqueue never throws and logs the failure with the record', async () => {
|
||||
settingsService.get.mockRejectedValue(new Error('db down'));
|
||||
|
||||
await expect(
|
||||
service.enqueue('INSPECTION', 'inspection-1'),
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(errorSpy).toHaveBeenCalledTimes(1);
|
||||
const [message] = errorSpy.mock.calls[0] as [string];
|
||||
expect(message).toContain('INSPECTION inspection-1');
|
||||
expect(message).toContain('db down');
|
||||
});
|
||||
|
||||
it('cancel never throws and logs the failure with the record', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findUnique.mockRejectedValue(
|
||||
new Error('db down'),
|
||||
);
|
||||
|
||||
await expect(service.cancel('TASK', 'task-1')).resolves.toBeUndefined();
|
||||
|
||||
expect(errorSpy).toHaveBeenCalledTimes(1);
|
||||
const [message] = errorSpy.mock.calls[0] as [string];
|
||||
expect(message).toContain('TASK task-1');
|
||||
expect(message).toContain('db down');
|
||||
});
|
||||
});
|
||||
|
||||
describe('cancel', () => {
|
||||
it('does nothing when no outbox row exists', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findUnique.mockResolvedValue(null);
|
||||
@@ -151,6 +235,25 @@ describe('CalendarSyncService', () => {
|
||||
});
|
||||
|
||||
describe('processOutbox', () => {
|
||||
const dueTask = {
|
||||
id: 'task-1',
|
||||
title: 'Beute prüfen',
|
||||
dueDate: new Date('2026-03-07'),
|
||||
};
|
||||
|
||||
/** The outcome write: only lands if the row is unchanged since the claim. */
|
||||
const expectSettled = (data: Record<string, unknown>) => {
|
||||
expect(updateManyCalls()[1]).toEqual({
|
||||
where: {
|
||||
id: 'entry-1',
|
||||
status: 'PENDING',
|
||||
revision: 3,
|
||||
claimedAt: claimedAt(),
|
||||
},
|
||||
data: { ...data, claimedAt: null },
|
||||
});
|
||||
};
|
||||
|
||||
it('does nothing when sync is disabled, unconfigured, or no groupId', async () => {
|
||||
settingsService.get.mockResolvedValue({
|
||||
...enabledSettings,
|
||||
@@ -160,76 +263,170 @@ describe('CalendarSyncService', () => {
|
||||
expect(prisma.calendarSyncOutboxEntry.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates a Graph event for a new TASK entry and marks it SYNCED', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 'entry-1',
|
||||
sourceType: 'TASK',
|
||||
sourceId: 'task-1',
|
||||
graphEventId: null,
|
||||
attempts: 0,
|
||||
},
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
title: 'Beute prüfen',
|
||||
dueDate: new Date('2026-03-07'),
|
||||
it('only picks PENDING rows that nobody holds, or whose holder gave up long ago', async () => {
|
||||
await service.processOutbox();
|
||||
const after = Date.now();
|
||||
|
||||
const [[query]] = prisma.calendarSyncOutboxEntry.findMany.mock.calls as [
|
||||
[{ where: Record<string, unknown> }],
|
||||
];
|
||||
expect(query.where).toEqual({
|
||||
status: 'PENDING',
|
||||
...CLAIMABLE,
|
||||
});
|
||||
const staleBefore = (
|
||||
query.where.OR as [unknown, { claimedAt: { lt: Date } }]
|
||||
)[1].claimedAt.lt;
|
||||
// A claim counts as abandoned only after several minutes - far longer
|
||||
// than one entry can take with bounded Graph requests.
|
||||
expect(after - staleBefore.getTime()).toBeGreaterThanOrEqual(
|
||||
5 * 60 * 1000,
|
||||
);
|
||||
});
|
||||
|
||||
it('claims a row with a conditional update before working on it', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry(),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue(dueTask);
|
||||
graphClient.createEvent.mockResolvedValue('graph-event-1');
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(graphClient.createEvent).toHaveBeenCalledWith('group-1', {
|
||||
title: 'Beute prüfen',
|
||||
date: new Date('2026-03-07'),
|
||||
});
|
||||
expect(prisma.calendarSyncOutboxEntry.update).toHaveBeenCalledWith({
|
||||
where: { id: 'entry-1' },
|
||||
data: {
|
||||
status: 'SYNCED',
|
||||
graphEventId: 'graph-event-1',
|
||||
lastError: null,
|
||||
expect(updateManyCalls()[0]).toEqual({
|
||||
where: {
|
||||
id: 'entry-1',
|
||||
status: 'PENDING',
|
||||
revision: 3,
|
||||
...CLAIMABLE,
|
||||
},
|
||||
data: { claimedAt: expect.any(Date) as Date },
|
||||
});
|
||||
const [claimOrder] =
|
||||
prisma.calendarSyncOutboxEntry.updateMany.mock.invocationCallOrder;
|
||||
const [createOrder] = graphClient.createEvent.mock.invocationCallOrder;
|
||||
expect(claimOrder).toBeLessThan(createOrder);
|
||||
});
|
||||
|
||||
it('marks the entry SKIPPED when the Task no longer has a dueDate', async () => {
|
||||
it('leaves a row alone when another pod or run claimed it first', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 'entry-1',
|
||||
sourceType: 'TASK',
|
||||
sourceId: 'task-1',
|
||||
graphEventId: null,
|
||||
attempts: 0,
|
||||
},
|
||||
pendingEntry(),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
title: 'Beute prüfen',
|
||||
dueDate: null,
|
||||
prisma.calendarSyncOutboxEntry.updateMany.mockResolvedValueOnce({
|
||||
count: 0,
|
||||
});
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(prisma.task.findUnique).not.toHaveBeenCalled();
|
||||
expect(graphClient.createEvent).not.toHaveBeenCalled();
|
||||
expect(prisma.calendarSyncOutboxEntry.update).toHaveBeenCalledWith({
|
||||
where: { id: 'entry-1' },
|
||||
data: { status: 'SKIPPED' },
|
||||
expect(prisma.calendarSyncOutboxEntry.updateMany).toHaveBeenCalledTimes(
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
it('creates a Graph event for a new TASK entry and marks it SYNCED', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry(),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue(dueTask);
|
||||
graphClient.createEvent.mockResolvedValue('graph-event-1');
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(graphClient.createEvent).toHaveBeenCalledWith(
|
||||
'group-1',
|
||||
{ title: 'Beute prüfen', date: new Date('2026-03-07') },
|
||||
TRANSACTION_ID,
|
||||
);
|
||||
expectSettled({
|
||||
status: 'SYNCED',
|
||||
graphEventId: 'graph-event-1',
|
||||
lastError: null,
|
||||
});
|
||||
expect(prisma.calendarSyncOutboxEntry.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the new event id but stays PENDING when the source changed during the sync', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry(),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue(dueTask);
|
||||
graphClient.createEvent.mockResolvedValue('graph-event-1');
|
||||
prisma.calendarSyncOutboxEntry.updateMany
|
||||
.mockResolvedValueOnce({ count: 1 }) // claim
|
||||
.mockResolvedValueOnce({ count: 0 }); // re-enqueued meanwhile
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
// Not SYNCED: the newer state still has to reach M365, and the next
|
||||
// pass must update this event rather than create a second one.
|
||||
expect(updateManyCalls()[2]).toEqual({
|
||||
where: { id: 'entry-1', status: 'PENDING', claimedAt: claimedAt() },
|
||||
data: { graphEventId: 'graph-event-1', claimedAt: null },
|
||||
});
|
||||
expect(graphClient.deleteEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('removes the event again when the source left the calendar during the sync', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry(),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue(dueTask);
|
||||
graphClient.createEvent.mockResolvedValue('graph-event-1');
|
||||
prisma.calendarSyncOutboxEntry.updateMany
|
||||
.mockResolvedValueOnce({ count: 1 }) // claim
|
||||
.mockResolvedValueOnce({ count: 0 }) // not unchanged
|
||||
.mockResolvedValueOnce({ count: 0 }) // not PENDING: cancelled
|
||||
.mockResolvedValueOnce({ count: 1 }); // claim released
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(updateManyCalls()[3]).toEqual({
|
||||
where: { id: 'entry-1', claimedAt: claimedAt() },
|
||||
data: { claimedAt: null },
|
||||
});
|
||||
expect(graphClient.deleteEvent).toHaveBeenCalledWith(
|
||||
'group-1',
|
||||
'graph-event-1',
|
||||
);
|
||||
});
|
||||
|
||||
it('marks the entry SKIPPED when the Task no longer has a dueDate', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry(),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue({ ...dueTask, dueDate: null });
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(graphClient.createEvent).not.toHaveBeenCalled();
|
||||
expectSettled({ status: 'SKIPPED' });
|
||||
});
|
||||
|
||||
it('only lets go of the claim when the row changed before SKIPPED could be written', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry(),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue({ ...dueTask, dueDate: null });
|
||||
prisma.calendarSyncOutboxEntry.updateMany
|
||||
.mockResolvedValueOnce({ count: 1 })
|
||||
.mockResolvedValueOnce({ count: 0 });
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(updateManyCalls()[2]).toEqual({
|
||||
where: { id: 'entry-1', claimedAt: claimedAt() },
|
||||
data: { claimedAt: null },
|
||||
});
|
||||
});
|
||||
|
||||
it('updates an existing Graph event when graphEventId is already set', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 'entry-1',
|
||||
sourceType: 'TASK',
|
||||
sourceId: 'task-1',
|
||||
graphEventId: 'graph-event-1',
|
||||
attempts: 0,
|
||||
},
|
||||
pendingEntry({ graphEventId: 'graph-event-1' }),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
...dueTask,
|
||||
title: 'Beute prüfen (geändert)',
|
||||
dueDate: new Date('2026-03-10'),
|
||||
});
|
||||
@@ -243,96 +440,108 @@ describe('CalendarSyncService', () => {
|
||||
{ title: 'Beute prüfen (geändert)', date: new Date('2026-03-10') },
|
||||
);
|
||||
expect(graphClient.createEvent).not.toHaveBeenCalled();
|
||||
expect(prisma.calendarSyncOutboxEntry.update).toHaveBeenCalledWith({
|
||||
where: { id: 'entry-1' },
|
||||
data: {
|
||||
status: 'SYNCED',
|
||||
graphEventId: 'graph-event-1',
|
||||
lastError: null,
|
||||
},
|
||||
expectSettled({
|
||||
status: 'SYNCED',
|
||||
graphEventId: 'graph-event-1',
|
||||
lastError: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to creating a fresh event when updating a stale graphEventId 404s', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 'entry-1',
|
||||
sourceType: 'TASK',
|
||||
sourceId: 'task-1',
|
||||
graphEventId: 'deleted-on-m365',
|
||||
attempts: 0,
|
||||
},
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
title: 'Beute prüfen',
|
||||
dueDate: new Date('2026-03-07'),
|
||||
});
|
||||
graphClient.updateEvent.mockRejectedValue(new Error('404 Not Found'));
|
||||
graphClient.createEvent.mockResolvedValue('graph-event-new');
|
||||
it.each([404, 410])(
|
||||
'falls back to creating a fresh event when the stored event is gone (%i)',
|
||||
async (status) => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry({ graphEventId: 'deleted-on-m365' }),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue(dueTask);
|
||||
graphClient.updateEvent.mockRejectedValue(
|
||||
new GraphRequestError('updateEvent', status, 'gone'),
|
||||
);
|
||||
graphClient.createEvent.mockResolvedValue('graph-event-new');
|
||||
|
||||
await service.processOutbox();
|
||||
await service.processOutbox();
|
||||
|
||||
expect(graphClient.createEvent).toHaveBeenCalled();
|
||||
expect(prisma.calendarSyncOutboxEntry.update).toHaveBeenCalledWith({
|
||||
where: { id: 'entry-1' },
|
||||
data: {
|
||||
expect(graphClient.createEvent).toHaveBeenCalled();
|
||||
expectSettled({
|
||||
status: 'SYNCED',
|
||||
graphEventId: 'graph-event-new',
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['a Graph server error', new GraphRequestError('updateEvent', 503, '')],
|
||||
['a throttled request', new GraphRequestError('updateEvent', 429, '')],
|
||||
['a network failure', new Error('fetch failed')],
|
||||
])(
|
||||
'does not create a second event after %s, but retries the update later',
|
||||
async (_case, failure) => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry({ graphEventId: 'graph-event-1', attempts: 1 }),
|
||||
]);
|
||||
prisma.task.findUnique.mockResolvedValue(dueTask);
|
||||
graphClient.updateEvent.mockRejectedValue(failure);
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(graphClient.createEvent).not.toHaveBeenCalled();
|
||||
expectSettled({
|
||||
status: 'PENDING',
|
||||
attempts: 2,
|
||||
lastError: failure.message,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('retries (stays PENDING) on failure below the max attempt count', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 'entry-1',
|
||||
sourceType: 'TASK',
|
||||
sourceId: 'task-1',
|
||||
graphEventId: null,
|
||||
attempts: 1,
|
||||
},
|
||||
pendingEntry({ attempts: 1 }),
|
||||
]);
|
||||
prisma.task.findUnique.mockRejectedValue(new Error('db error'));
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(prisma.calendarSyncOutboxEntry.update).toHaveBeenCalledWith({
|
||||
where: { id: 'entry-1' },
|
||||
data: { status: 'PENDING', attempts: 2, lastError: 'db error' },
|
||||
expectSettled({ status: 'PENDING', attempts: 2, lastError: 'db error' });
|
||||
});
|
||||
|
||||
// lastError is stored and shown to admins - a Prisma message would carry
|
||||
// query values (titles, names) into it.
|
||||
it('stores a Prisma failure in lastError by name, code and model only', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry({ attempts: 1 }),
|
||||
]);
|
||||
prisma.task.findUnique.mockRejectedValue(
|
||||
new Prisma.PrismaClientKnownRequestError('title "Max Mustermann"', {
|
||||
code: 'P2024',
|
||||
clientVersion: '7.9.1',
|
||||
meta: { modelName: 'Task' },
|
||||
}),
|
||||
);
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expectSettled({
|
||||
status: 'PENDING',
|
||||
attempts: 2,
|
||||
lastError: 'PrismaClientKnownRequestError P2024 (Task)',
|
||||
});
|
||||
});
|
||||
|
||||
it('marks FAILED once the max attempt count is reached', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 'entry-1',
|
||||
sourceType: 'TASK',
|
||||
sourceId: 'task-1',
|
||||
graphEventId: null,
|
||||
attempts: 4,
|
||||
},
|
||||
pendingEntry({ attempts: 4 }),
|
||||
]);
|
||||
prisma.task.findUnique.mockRejectedValue(new Error('db error'));
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(prisma.calendarSyncOutboxEntry.update).toHaveBeenCalledWith({
|
||||
where: { id: 'entry-1' },
|
||||
data: { status: 'FAILED', attempts: 5, lastError: 'db error' },
|
||||
});
|
||||
expectSettled({ status: 'FAILED', attempts: 5, lastError: 'db error' });
|
||||
});
|
||||
|
||||
it('builds titles per source type matching the read-only calendar view', async () => {
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 'e1',
|
||||
sourceType: 'INSPECTION',
|
||||
sourceId: 'i1',
|
||||
graphEventId: null,
|
||||
attempts: 0,
|
||||
},
|
||||
pendingEntry({ sourceType: 'INSPECTION', sourceId: 'i1' }),
|
||||
]);
|
||||
prisma.inspection.findUnique.mockResolvedValue({
|
||||
id: 'i1',
|
||||
@@ -343,10 +552,224 @@ describe('CalendarSyncService', () => {
|
||||
|
||||
await service.processOutbox();
|
||||
|
||||
expect(graphClient.createEvent).toHaveBeenCalledWith('group-1', {
|
||||
title: 'Durchsicht V-001',
|
||||
date: new Date('2026-03-07'),
|
||||
expect(graphClient.createEvent).toHaveBeenCalledWith(
|
||||
'group-1',
|
||||
{ title: 'Durchsicht V-001', date: new Date('2026-03-07') },
|
||||
TRANSACTION_ID,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// A create that timed out may still have reached Graph. The retry - by
|
||||
// this or another pod - sends the same transactionId, so Graph can drop
|
||||
// it instead of adding a second event.
|
||||
describe('transactionId on create', () => {
|
||||
/** Runs one pass over the entry and returns the transactionId sent. */
|
||||
const transactionIdFor = async (entry: Record<string, unknown>) => {
|
||||
graphClient.createEvent.mockClear();
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockResolvedValue([
|
||||
pendingEntry(entry),
|
||||
]);
|
||||
await service.processOutbox();
|
||||
const [[, , transactionId]] = graphClient.createEvent.mock.calls as [
|
||||
[string, unknown, string],
|
||||
];
|
||||
return transactionId;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
prisma.task.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
title: 'Beute prüfen',
|
||||
dueDate: new Date('2026-03-07'),
|
||||
});
|
||||
graphClient.createEvent.mockResolvedValue('graph-event-1');
|
||||
});
|
||||
|
||||
it('is the same for every retry of the same create', async () => {
|
||||
graphClient.createEvent.mockRejectedValueOnce(new Error('timeout'));
|
||||
const first = await transactionIdFor({ attempts: 0 });
|
||||
const retry = await transactionIdFor({ attempts: 1 });
|
||||
|
||||
expect(first).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
|
||||
);
|
||||
expect(retry).toBe(first);
|
||||
});
|
||||
|
||||
it('differs per outbox entry', async () => {
|
||||
const one = await transactionIdFor({ id: 'entry-1' });
|
||||
const other = await transactionIdFor({ id: 'entry-2' });
|
||||
|
||||
expect(other).not.toBe(one);
|
||||
});
|
||||
|
||||
// A cancelled source deleted its event; enqueued again it needs a new
|
||||
// one, which an old transactionId might be matched against.
|
||||
it('is new once the entry was enqueued again', async () => {
|
||||
const before = await transactionIdFor({ revision: 3 });
|
||||
const after = await transactionIdFor({ revision: 4 });
|
||||
|
||||
expect(after).not.toBe(before);
|
||||
});
|
||||
|
||||
it('is new when replacing an event that was deleted in M365', async () => {
|
||||
const initial = await transactionIdFor({ graphEventId: null });
|
||||
graphClient.updateEvent.mockRejectedValue(
|
||||
new GraphRequestError('updateEvent', 404, 'gone'),
|
||||
);
|
||||
const replacement = await transactionIdFor({
|
||||
graphEventId: 'deleted-on-m365',
|
||||
});
|
||||
|
||||
expect(replacement).not.toBe(initial);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runNow', () => {
|
||||
it('gives FAILED entries a fresh set of attempts before processing', async () => {
|
||||
await service.runNow();
|
||||
|
||||
expect(prisma.calendarSyncOutboxEntry.updateMany).toHaveBeenCalledWith({
|
||||
where: { status: 'FAILED' },
|
||||
data: { status: 'PENDING', attempts: 0, lastError: null },
|
||||
});
|
||||
const [resetOrder] =
|
||||
prisma.calendarSyncOutboxEntry.updateMany.mock.invocationCallOrder;
|
||||
const [readOrder] =
|
||||
prisma.calendarSyncOutboxEntry.findMany.mock.invocationCallOrder;
|
||||
expect(resetOrder).toBeLessThan(readOrder);
|
||||
});
|
||||
|
||||
it('leaves FAILED entries alone on a regular cron tick', async () => {
|
||||
await service.processOutbox();
|
||||
|
||||
expect(
|
||||
prisma.calendarSyncOutboxEntry.updateMany,
|
||||
).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { status: 'FAILED' } }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// "Jetzt synchronisieren" must not hold the HTTP request for a whole pass
|
||||
// (up to 20 entries with several Graph calls each): it only starts it.
|
||||
describe('startRun', () => {
|
||||
const flush = async () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
};
|
||||
/** Lets the pass hang on reading the outbox until released. */
|
||||
const holdOutbox = () => {
|
||||
let release: () => void = () => undefined;
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
release = () => resolve([]);
|
||||
}),
|
||||
);
|
||||
return () => release();
|
||||
};
|
||||
|
||||
it('returns while the pass is still running and reports it as running', async () => {
|
||||
const release = holdOutbox();
|
||||
|
||||
service.startRun();
|
||||
await flush();
|
||||
|
||||
expect(prisma.calendarSyncOutboxEntry.updateMany).toHaveBeenCalledWith({
|
||||
where: { status: 'FAILED' },
|
||||
data: { status: 'PENDING', attempts: 0, lastError: null },
|
||||
});
|
||||
expect((await service.getStatus()).running).toBe(true);
|
||||
|
||||
release();
|
||||
await flush();
|
||||
|
||||
expect((await service.getStatus()).running).toBe(false);
|
||||
});
|
||||
|
||||
it('starts only one pass per pod at a time', async () => {
|
||||
const release = holdOutbox();
|
||||
|
||||
service.startRun();
|
||||
service.startRun();
|
||||
await flush();
|
||||
|
||||
expect(prisma.calendarSyncOutboxEntry.findMany).toHaveBeenCalledTimes(1);
|
||||
release();
|
||||
await flush();
|
||||
});
|
||||
|
||||
it('logs a failed pass without query values and clears the indicator', async () => {
|
||||
const errorSpy = jest
|
||||
.spyOn(Logger.prototype, 'error')
|
||||
.mockImplementation(() => undefined);
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockRejectedValue(
|
||||
new Prisma.PrismaClientKnownRequestError('title "Max Mustermann"', {
|
||||
code: 'P2010',
|
||||
clientVersion: '7.9.1',
|
||||
meta: { modelName: 'CalendarSyncOutboxEntry' },
|
||||
}),
|
||||
);
|
||||
|
||||
service.startRun();
|
||||
await flush();
|
||||
|
||||
expect(errorSpy).toHaveBeenCalledTimes(1);
|
||||
const [message, stack] = errorSpy.mock.calls[0] as [string, unknown];
|
||||
expect(message).toContain('P2010');
|
||||
expect(message).not.toContain('Mustermann');
|
||||
expect(stack).toBeUndefined();
|
||||
expect((await service.getStatus()).running).toBe(false);
|
||||
errorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('lets shutdown wait for a running pass', async () => {
|
||||
const release = holdOutbox();
|
||||
service.startRun();
|
||||
let destroyed = false;
|
||||
|
||||
const shutdown = service.onModuleDestroy().then(() => {
|
||||
destroyed = true;
|
||||
});
|
||||
await flush();
|
||||
expect(destroyed).toBe(false);
|
||||
|
||||
release();
|
||||
await shutdown;
|
||||
expect(destroyed).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// The cron tick's own errors would otherwise reach the scheduler's logger
|
||||
// with the full Prisma message and stack.
|
||||
describe('scheduledRun (cron tick)', () => {
|
||||
it('runs the regular pass', async () => {
|
||||
await service.scheduledRun();
|
||||
|
||||
expect(prisma.calendarSyncOutboxEntry.findMany).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('never throws and logs a failed tick without the Prisma message', async () => {
|
||||
const errorSpy = jest
|
||||
.spyOn(Logger.prototype, 'error')
|
||||
.mockImplementation(() => undefined);
|
||||
prisma.calendarSyncOutboxEntry.findMany.mockRejectedValue(
|
||||
new Prisma.PrismaClientKnownRequestError('title "Max Mustermann"', {
|
||||
code: 'P2010',
|
||||
clientVersion: '7.9.1',
|
||||
meta: { modelName: 'CalendarSyncOutboxEntry' },
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(service.scheduledRun()).resolves.toBeUndefined();
|
||||
|
||||
const [message, stack] = errorSpy.mock.calls[0] as [string, unknown];
|
||||
expect(message).toContain('P2010');
|
||||
expect(message).not.toContain('Mustermann');
|
||||
expect(stack).toBeUndefined();
|
||||
errorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -355,7 +778,8 @@ describe('CalendarSyncService', () => {
|
||||
prisma.calendarSyncOutboxEntry.count
|
||||
.mockResolvedValueOnce(2) // PENDING
|
||||
.mockResolvedValueOnce(1) // FAILED
|
||||
.mockResolvedValueOnce(5); // SYNCED
|
||||
.mockResolvedValueOnce(5) // SYNCED
|
||||
.mockResolvedValueOnce(0); // held by a worker right now
|
||||
|
||||
const status = await service.getStatus();
|
||||
|
||||
@@ -366,6 +790,24 @@ describe('CalendarSyncService', () => {
|
||||
pendingCount: 2,
|
||||
failedCount: 1,
|
||||
syncedCount: 5,
|
||||
running: false,
|
||||
});
|
||||
});
|
||||
|
||||
// Another pod (its cron tick or its "Jetzt synchronisieren") may be the
|
||||
// one working - its live claims show that across replicas.
|
||||
it('reports running while any worker holds an entry', async () => {
|
||||
prisma.calendarSyncOutboxEntry.count
|
||||
.mockResolvedValueOnce(0)
|
||||
.mockResolvedValueOnce(0)
|
||||
.mockResolvedValueOnce(0)
|
||||
.mockResolvedValueOnce(1);
|
||||
|
||||
const status = await service.getStatus();
|
||||
|
||||
expect(status.running).toBe(true);
|
||||
expect(prisma.calendarSyncOutboxEntry.count).toHaveBeenLastCalledWith({
|
||||
where: { claimedAt: { gte: expect.any(Date) as Date } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user