Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions packages/core/src/NodeExecuteFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1653,10 +1653,24 @@ export function getAdditionalKeys(
customData: runExecutionData
? {
set(key: string, value: string): void {
setWorkflowExecutionMetadata(runExecutionData, key, value);
try {
setWorkflowExecutionMetadata(runExecutionData, key, value);
} catch (e) {
if (mode === 'manual') {
throw e;
}
Logger.verbose(e.message);
}
},
setAll(obj: Record<string, string>): void {
setAllWorkflowExecutionMetadata(runExecutionData, obj);
try {
setAllWorkflowExecutionMetadata(runExecutionData, obj);
} catch (e) {
if (mode === 'manual') {
throw e;
}
Logger.verbose(e.message);
}
},
get(key: string): string {
return getWorkflowExecutionMetadata(runExecutionData, key);
Expand Down
49 changes: 45 additions & 4 deletions packages/core/src/WorkflowExecutionMetadata.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
import type { IRunExecutionData } from 'n8n-workflow';
import { LoggerProxy as Logger } from 'n8n-workflow';

export const KV_LIMIT = 10;

export class ExecutionMetadataValidationError extends Error {
constructor(
public type: 'key' | 'value',
key: unknown,
message?: string,
options?: ErrorOptions,
) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
super(message ?? `Custom data ${type}s must be a string (key "${key}")`, options);
}
}

export function setWorkflowExecutionMetadata(
executionData: IRunExecutionData,
key: string,
Expand All @@ -17,16 +30,44 @@ export function setWorkflowExecutionMetadata(
) {
return;
}
executionData.resultData.metadata[String(key).slice(0, 50)] = String(value).slice(0, 255);
if (typeof key !== 'string') {
throw new ExecutionMetadataValidationError('key', key);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should also accept numbers. It's become very annoying, if I have a number that is generated I simply can't save it as is.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use this workflow as an example to see the error.

{
  "meta": {
    "instanceId": "27cc9b56542ad45b38725555722c50a1c3fee1670bbb67980558314ee08517c4"
  },
  "nodes": [
    {
      "parameters": {
        "path": "a59cd802-3f21-4672-a208-c5bbb45711f6",
        "responseMode": "lastNode",
        "options": {}
      },
      "id": "5d434c5e-7794-46da-acee-1cee883c2d6e",
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        780,
        540
      ],
      "webhookId": "a59cd802-3f21-4672-a208-c5bbb45711f6"
    },
    {
      "parameters": {
        "jsCode": "// Loop over input items and add a new field\n// called 'myNewField' to the JSON of each one\n\nconst generatedNumber = Math.floor(Math.random() * 5);\n\nconst large = Math.floor(Math.random() * 1000);\n\n\n$execution.customData.set(`potato${generatedNumber}`, generatedNumber);\n$execution.customData.set(`name${generatedNumber}`, generatedNumber);\n\n\n$execution.customData.set(`large${large}`, '0');\n\nfor (const item of $input.all()) {\n  item.json.generatedNumber = generatedNumber;\n}\n\nreturn $input.all();"
      },
      "id": "3943cd3f-db65-468c-993a-4543fe340e6f",
      "name": "Code",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        980,
        540
      ]
    },
    {
      "parameters": {
        "keepOnlySet": true,
        "values": {
          "string": [
            {
              "name": "coolStuff",
              "value": "={{ $execution.customData.getAll() }}"
            }
          ]
        },
        "options": {}
      },
      "id": "dee79bb5-b0a8-4916-aa88-2a87f576f579",
      "name": "Set",
      "type": "n8n-nodes-base.set",
      "typeVersion": 1,
      "position": [
        1420,
        540
      ]
    },
    {
      "parameters": {
        "amount": 2,
        "unit": "seconds"
      },
      "id": "f085cf4f-b71b-46fe-96a6-4c201e8db2ab",
      "name": "Wait",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1,
      "position": [
        1200,
        540
      ],
      "webhookId": "c084fefc-6bcc-484d-b0c8-c16188d602f5",
      "disabled": true
    }
  ],
  "connections": {
    "Webhook": {
      "main": [
        [
          {
            "node": "Code",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code": {
      "main": [
        [
          {
            "node": "Wait",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait": {
      "main": [
        [
          {
            "node": "Set",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

}
if (key.replace(/[A-Za-z0-9_]/g, '').length !== 0) {
throw new ExecutionMetadataValidationError(
'key',
key,
`Custom date key can only contain characters "A-Za-z0-9_" (key "${key}")`,
);
}
if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'bigint') {
throw new ExecutionMetadataValidationError('value', key);
}
const val = String(value);
if (key.length > 50) {
Logger.error('Custom data key over 50 characters long. Truncating to 50 characters.');
}
if (val.length > 255) {
Logger.error('Custom data value over 255 characters long. Truncating to 255 characters.');
}
executionData.resultData.metadata[key.slice(0, 50)] = val.slice(0, 255);
}

export function setAllWorkflowExecutionMetadata(
executionData: IRunExecutionData,
obj: Record<string, string>,
) {
Object.entries(obj).forEach(([key, value]) =>
setWorkflowExecutionMetadata(executionData, key, value),
);
const errors: Error[] = [];
Object.entries(obj).forEach(([key, value]) => {
try {
setWorkflowExecutionMetadata(executionData, key, value);
} catch (e) {
errors.push(e as Error);
}
});
if (errors.length) {
throw errors[0];
}
}

export function getAllWorkflowExecutionMetadata(
Expand Down
71 changes: 68 additions & 3 deletions packages/core/test/WorkflowExecutionMetadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,22 @@ import {
KV_LIMIT,
setAllWorkflowExecutionMetadata,
setWorkflowExecutionMetadata,
ExecutionMetadataValidationError,
} from '@/WorkflowExecutionMetadata';
import type { IRunExecutionData } from 'n8n-workflow';
import { LoggerProxy } from 'n8n-workflow';
import type { ILogger, IRunExecutionData } from 'n8n-workflow';

beforeAll(() => {
const fakeLogger = {
log: () => {},
debug: () => {},
verbose: () => {},
info: () => {},
warn: () => {},
error: () => {},
} as ILogger;
LoggerProxy.init(fakeLogger);
});

describe('Execution Metadata functions', () => {
test('setWorkflowExecutionMetadata will set a value', () => {
Expand Down Expand Up @@ -42,17 +56,68 @@ describe('Execution Metadata functions', () => {
});
});

test('setWorkflowExecutionMetadata should convert values to strings', () => {
test('setWorkflowExecutionMetadata should only convert numbers to strings', () => {
const metadata = {};
const executionData = {
resultData: {
metadata,
},
} as IRunExecutionData;

expect(() => setWorkflowExecutionMetadata(executionData, 'test1', 1234)).not.toThrow(
ExecutionMetadataValidationError,
);

expect(metadata).toEqual({
test1: '1234',
});

expect(() => setWorkflowExecutionMetadata(executionData, 'test2', {})).toThrow(
ExecutionMetadataValidationError,
);

expect(metadata).not.toEqual({
test1: '1234',
test2: {},
});
});

test('setAllWorkflowExecutionMetadata should not convert values to strings and should set other values correctly', () => {
const metadata = {};
const executionData = {
resultData: {
metadata,
},
} as IRunExecutionData;

setWorkflowExecutionMetadata(executionData, 'test1', 1234);
expect(() =>
setAllWorkflowExecutionMetadata(executionData, {
test1: {} as unknown as string,
test2: [] as unknown as string,
test3: 'value3',
test4: 'value4',
}),
).toThrow(ExecutionMetadataValidationError);

expect(metadata).toEqual({
test3: 'value3',
test4: 'value4',
});
});

test('setWorkflowExecutionMetadata should validate key characters', () => {
const metadata = {};
const executionData = {
resultData: {
metadata,
},
} as IRunExecutionData;

expect(() => setWorkflowExecutionMetadata(executionData, 'te$t1$', 1234)).toThrow(
ExecutionMetadataValidationError,
);

expect(metadata).not.toEqual({
test1: '1234',
});
});
Expand Down