Files
n8n/packages/cli/test/integration/executions/execution-persistence.test.ts

325 lines
11 KiB
TypeScript

import { createWorkflow, testDb } from '@n8n/backend-test-utils';
import type { CreateExecutionPayload, WorkflowEntity } from '@n8n/db';
import { ExecutionRepository } from '@n8n/db';
import type { PolicyCleared } from '@n8n/decorators';
import { Container } from '@n8n/di';
import { UnexpectedError } from '@n8n/errors';
import {
createEmptyRunExecutionData,
createRunExecutionData,
WAIT_INDEFINITELY,
} from 'n8n-workflow';
import { DuplicateExecutionError } from '@/errors/duplicate-execution.error';
import { ExecutionPersistence } from '@/executions/execution-persistence';
import { PolicyEnforcementService } from '@/policy/policy-enforcement.service';
import { admissionFor } from '@test/admission';
describe('ExecutionPersistence', () => {
let executionPersistence: ExecutionPersistence;
let executionRepository: ExecutionRepository;
beforeAll(async () => {
await testDb.init();
executionPersistence = Container.get(ExecutionPersistence);
executionRepository = Container.get(ExecutionRepository);
});
beforeEach(async () => {
await testDb.truncate(['ExecutionEntity']);
});
afterAll(async () => {
await testDb.terminate();
});
it('keeps only the first response to an indefinite wait', async () => {
const workflow = await createWorkflow();
const executionId = await executionPersistence.createRecordWithoutRun({
workflowData: workflow,
workflowId: workflow.id,
mode: 'manual',
finished: false,
status: 'waiting',
waitTill: WAIT_INDEFINITELY,
data: createEmptyRunExecutionData(),
});
const conditions = { requireStatus: 'waiting' as const, requireWaitTill: WAIT_INDEFINITELY };
for (const [index, approved] of [true, false].entries()) {
const saved = await executionPersistence.updateExistingExecution(
executionId,
{
waitTill: new Date(),
data: createRunExecutionData({
resultData: { pinData: { Review: [{ json: { approved } }] } },
}),
},
conditions,
);
expect(saved).toBe(index === 0);
}
const saved = await executionPersistence.findSingleExecution(executionId, {
includeData: true,
unflattenData: true,
});
expect(saved?.data.resultData.pinData?.Review[0].json).toEqual({ approved: true });
expect((await executionRepository.getWaitingExecutions()).map(({ id }) => id)).toContain(
executionId,
);
});
describe('createForAdmittedRun', () => {
const payloadFor = (workflow: WorkflowEntity): CreateExecutionPayload => ({
data: createEmptyRunExecutionData(),
workflowData: workflow,
mode: 'trigger',
finished: false,
status: 'new',
workflowId: workflow.id,
});
it('creates the row with the admission token of its workflow', async () => {
const workflow = await createWorkflow();
const executionId = await executionPersistence.createForAdmittedRun(payloadFor(workflow), {
policyCleared: await admissionFor(workflow.id),
});
expect(await executionRepository.findOneBy({ id: executionId })).not.toBeNull();
});
it.each([
['no token', async () => undefined],
[
'a forged token',
async (workflowId: string) =>
({
point: 'executionAdmission',
subject: { type: 'workflow', id: workflowId },
}) as unknown as PolicyCleared<'executionAdmission'>,
],
[
'a token for another point',
async (workflowId: string) =>
await new PolicyEnforcementService().enforceWorkflowStart(
{ workflow: { id: workflowId, name: 'test', nodes: [] }, projectId: null },
{ kind: 'system', reason: 'execution' },
),
],
['a token for another workflow', async () => await admissionFor('another-workflow')],
] as const)('rejects %s and writes no row', async (_case, tokenFor) => {
const workflow = await createWorkflow();
await expect(
executionPersistence.createForAdmittedRun(payloadFor(workflow), {
// The type rejects these tokens. The cast reaches the check at run time.
policyCleared: (await tokenFor(workflow.id)) as PolicyCleared<'executionAdmission'>,
}),
).rejects.toThrow(UnexpectedError);
expect(await executionRepository.findBy({ workflowId: workflow.id })).toEqual([]);
});
describe('for a run without a workflow id', () => {
const idlessAdmission = async () => await admissionFor(undefined as unknown as string);
it('writes no row, even with the matching token', async () => {
const workflow = await createWorkflow();
const idless = { ...workflow, id: undefined } as unknown as WorkflowEntity;
const payload = { ...payloadFor(idless), workflowId: undefined as unknown as string };
// The column is required, so the token of an id-less run can never create a row.
await expect(
executionPersistence.createForAdmittedRun(payload, {
policyCleared: await idlessAdmission(),
}),
).rejects.toThrow();
expect(await executionRepository.count()).toBe(0);
});
it('rejects its token for a saved workflow', async () => {
const workflow = await createWorkflow();
await expect(
executionPersistence.createForAdmittedRun(payloadFor(workflow), {
policyCleared: await idlessAdmission(),
}),
).rejects.toThrow(UnexpectedError);
});
});
it('rejects a snapshot of another workflow than the row', async () => {
const workflow = await createWorkflow();
const other = await createWorkflow();
await expect(
executionPersistence.createForAdmittedRun(
{ ...payloadFor(workflow), workflowData: other },
{ policyCleared: await admissionFor(workflow.id) },
),
).rejects.toThrow(UnexpectedError);
expect(await executionRepository.findBy({ workflowId: workflow.id })).toEqual([]);
});
});
describe('create with deduplicationKey', () => {
const buildPayload = (
workflow: WorkflowEntity,
deduplicationKey?: string,
status: CreateExecutionPayload['status'] = 'new',
): CreateExecutionPayload => ({
data: createEmptyRunExecutionData(),
workflowData: workflow,
mode: 'trigger',
finished: false,
status,
workflowId: workflow.id,
deduplicationKey,
});
it('creates multiple executions when deduplicationKey is null', async () => {
const workflow = await createWorkflow();
const id1 = await executionPersistence.createRecordWithoutRun(buildPayload(workflow));
const id2 = await executionPersistence.createRecordWithoutRun(buildPayload(workflow));
const id3 = await executionPersistence.createRecordWithoutRun(buildPayload(workflow));
expect(new Set([id1, id2, id3]).size).toBe(3);
});
it('creates executions with distinct deduplicationKeys', async () => {
const workflow = await createWorkflow();
const id1 = await executionPersistence.createRecordWithoutRun(
buildPayload(workflow, 'wf:node:t1'),
);
const id2 = await executionPersistence.createRecordWithoutRun(
buildPayload(workflow, 'wf:node:t2'),
);
expect(id1).not.toBe(id2);
});
it('throws DuplicateExecutionError when a dispatched execution already holds the key', async () => {
const workflow = await createWorkflow();
const key = 'wf:node:t1';
// A dispatched execution (status past `new`) is a real effect, not a tombstone.
await executionPersistence.createRecordWithoutRun(buildPayload(workflow, key, 'running'));
await expect(
executionPersistence.createRecordWithoutRun(buildPayload(workflow, key)),
).rejects.toBeInstanceOf(DuplicateExecutionError);
await expect(
executionPersistence.createRecordWithoutRun(buildPayload(workflow, key)),
).rejects.toMatchObject({
deduplicationKey: key,
});
});
it('reclaims a tombstone (never-dispatched `new` row) when the key is reused', async () => {
const workflow = await createWorkflow();
const key = 'wf:node:t1';
// A prior attempt inserted the execution `new`, then died before dispatch.
const tombstoneId = await executionPersistence.createRecordWithoutRun(
buildPayload(workflow, key),
);
// The redelivery takes over the key instead of colliding, yielding a fresh row.
const reclaimedId = await executionPersistence.createRecordWithoutRun(
buildPayload(workflow, key),
);
expect(reclaimedId).not.toBe(tombstoneId);
expect(await executionRepository.findOneBy({ id: tombstoneId })).toBeNull();
expect(await executionRepository.findOneBy({ id: reclaimedId })).not.toBeNull();
});
});
describe('unsaved manual executions', () => {
/** A finished manual run that n8n did not save, soft-deleted when it finished. */
const createUnsavedManualExecution = async () => {
const workflow = await createWorkflow();
const executionId = await executionPersistence.createRecordWithoutRun({
data: createRunExecutionData({ resultData: { lastNodeExecuted: 'Get Message' } }),
workflowData: workflow,
mode: 'manual',
finished: false,
status: 'error',
workflowId: workflow.id,
});
await executionRepository.softDelete(executionId);
return { workflow, executionId };
};
it('writes run data to a soft-deleted execution only when asked to', async () => {
const { executionId } = await createUnsavedManualExecution();
const finished = {
status: 'error' as const,
data: createRunExecutionData({ resultData: { lastNodeExecuted: 'Get Message' } }),
};
expect(await executionPersistence.updateExistingExecution(executionId, finished)).toBe(false);
expect(
await executionPersistence.updateExistingExecution(executionId, finished, {
includeDeleted: true,
}),
).toBe(true);
});
it('does not restore an execution deleted between the read and the write of an update', async () => {
const workflow = await createWorkflow();
const executionId = await executionPersistence.createRecordWithoutRun({
data: createEmptyRunExecutionData(),
workflowData: workflow,
mode: 'manual',
finished: false,
status: 'running',
workflowId: workflow.id,
});
// A caller writing back what it read earlier, like stopping a run.
const snapshot = await executionPersistence.findSingleExecution(executionId, {
includeData: true,
unflattenData: true,
});
const findOne = executionRepository.findOne.bind(executionRepository);
vi.spyOn(executionRepository, 'findOne').mockImplementationOnce(async (options) => {
const entity = await findOne(options);
await executionRepository.softDelete(executionId);
return entity;
});
await executionPersistence.updateExistingExecution(
executionId,
{ ...snapshot, status: 'canceled' },
{ requireStatus: 'running' },
);
const row = await executionRepository.findOne({
where: { id: executionId },
withDeleted: true,
});
expect(row?.status).toBe('canceled');
expect(row?.deletedAt).toBeInstanceOf(Date);
});
it('returns the run data of an unsaved manual execution', async () => {
const { workflow, executionId } = await createUnsavedManualExecution();
const execution = await executionPersistence.findUnsavedManualExecution(executionId);
expect(execution).toMatchObject({ id: executionId, workflowId: workflow.id, mode: 'manual' });
expect(execution?.data.resultData.lastNodeExecuted).toBe('Get Message');
expect(
await executionPersistence.findSingleExecution(executionId, {
includeData: true,
unflattenData: true,
}),
).toBeUndefined();
});
});
});