Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Save new version of the workflow instead of the previous (no-changelog) #7428

Merged
merged 5 commits into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type express from 'express';
import { Container } from 'typedi';
import type { FindOptionsWhere } from 'typeorm';
import { In } from 'typeorm';
import { v4 as uuid } from 'uuid';

import { ActiveWorkflowRunner } from '@/ActiveWorkflowRunner';
import config from '@/config';
Expand Down Expand Up @@ -36,6 +37,7 @@ export = {
const workflow = req.body;

workflow.active = false;
workflow.versionId = uuid();

await replaceInvalidCredentials(workflow);

Expand All @@ -45,6 +47,14 @@ export = {

const createdWorkflow = await createWorkflow(workflow, req.user, role);

if (isWorkflowHistoryLicensed()) {
await Container.get(WorkflowHistoryService).saveVersion(
req.user,
createdWorkflow,
createdWorkflow.id,
);
}

await Container.get(ExternalHooks).run('workflow.afterCreate', [createdWorkflow]);
void Container.get(InternalHooks).onWorkflowCreated(req.user, createdWorkflow, true);

Expand Down Expand Up @@ -151,6 +161,7 @@ export = {
const updateData = new WorkflowEntity();
Object.assign(updateData, req.body);
updateData.id = id;
updateData.versionId = uuid();

const sharedWorkflow = await getSharedWorkflow(req.user, id);

Expand Down Expand Up @@ -179,10 +190,6 @@ export = {
}
}

if (isWorkflowHistoryLicensed()) {
await Container.get(WorkflowHistoryService).saveVersion(req.user, sharedWorkflow.workflow);
}

if (sharedWorkflow.workflow.active) {
try {
await workflowRunner.add(sharedWorkflow.workflowId, 'update');
Expand All @@ -195,6 +202,14 @@ export = {

const updatedWorkflow = await getWorkflowById(sharedWorkflow.workflowId);

if (isWorkflowHistoryLicensed() && updatedWorkflow) {
await Container.get(WorkflowHistoryService).saveVersion(
req.user,
updatedWorkflow,
sharedWorkflow.workflowId,
);
}

await Container.get(ExternalHooks).run('workflow.afterUpdate', [updateData]);
void Container.get(InternalHooks).onWorkflowSaved(req.user, updateData, true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@ export class WorkflowHistoryService {
return hist;
}

async saveVersion(user: User, workflow: WorkflowEntity) {
async saveVersion(user: User, workflow: WorkflowEntity, workflowId: string) {
if (isWorkflowHistoryEnabled()) {
await this.workflowHistoryRepository.insert({
authors: user.firstName + ' ' + user.lastName,
connections: workflow.connections,
nodes: workflow.nodes,
versionId: workflow.versionId,
workflowId: workflow.id,
workflowId,
});
}
}
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/src/workflows/workflows.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import { RoleService } from '@/services/role.service';
import * as utils from '@/utils';
import { listQueryMiddleware } from '@/middlewares';
import { TagService } from '@/services/tag.service';
import { isWorkflowHistoryLicensed } from './workflowHistory/workflowHistoryHelper.ee';
import { WorkflowHistoryService } from './workflowHistory/workflowHistory.service.ee';

export const workflowsController = express.Router();

Expand Down Expand Up @@ -99,6 +101,14 @@ workflowsController.post(
throw new ResponseHelper.InternalServerError('Failed to save workflow');
}

if (isWorkflowHistoryLicensed()) {
await Container.get(WorkflowHistoryService).saveVersion(
req.user,
savedWorkflow,
savedWorkflow.id,
);
}

if (tagIds && !config.getEnv('workflowTagsDisabled') && savedWorkflow.tags) {
savedWorkflow.tags = Container.get(TagService).sortByRequestOrder(savedWorkflow.tags, {
requestOrder: tagIds,
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/workflows/workflows.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,8 @@ export class WorkflowsService {
);
}

if (isWorkflowHistoryLicensed()) {
await Container.get(WorkflowHistoryService).saveVersion(user, shared.workflow);
if (isWorkflowHistoryLicensed() && workflow.versionId !== shared.workflow.versionId) {
Copy link
Member

Choose a reason for hiding this comment

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

@valya @krynble
This change is breaking workflow activation/deactivation when isWorkflowHistoryLicensed returns true.

await Container.get(WorkflowHistoryService).saveVersion(user, workflow, workflowId);
}

const relations = config.getEnv('workflowTagsDisabled') ? [] : ['tags'];
Expand Down
204 changes: 203 additions & 1 deletion packages/cli/test/integration/publicApi/workflows.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import * as utils from '../shared/utils/';
import * as testDb from '../shared/testDb';
import type { INode } from 'n8n-workflow';
import { STARTING_NODES } from '@/constants';
import { License } from '@/License';
import { WorkflowHistoryRepository } from '@/databases/repositories';
import Container from 'typedi';

let workflowOwnerRole: Role;
let owner: User;
Expand All @@ -20,6 +23,11 @@ let workflowRunner: ActiveWorkflowRunner;

const testServer = utils.setupTestServer({ endpointGroups: ['publicApi'] });

const licenseLike = utils.mockInstance(License, {
isWorkflowHistoryLicensed: jest.fn().mockReturnValue(false),
isWithinUsersLimit: jest.fn().mockReturnValue(true),
});

beforeAll(async () => {
const [globalOwnerRole, globalMemberRole, fetchedWorkflowOwnerRole] = await testDb.getAllRoles();

Expand All @@ -41,10 +49,18 @@ beforeAll(async () => {
});

beforeEach(async () => {
await testDb.truncate(['SharedCredentials', 'SharedWorkflow', 'Tag', 'Workflow', 'Credentials']);
await testDb.truncate([
'SharedCredentials',
'SharedWorkflow',
'Tag',
'Workflow',
'Credentials',
WorkflowHistoryRepository,
]);

authOwnerAgent = testServer.publicApiAgentFor(owner);
authMemberAgent = testServer.publicApiAgentFor(member);
licenseLike.isWorkflowHistoryLicensed.mockReturnValue(false);
});

afterEach(async () => {
Expand Down Expand Up @@ -679,6 +695,90 @@ describe('POST /workflows', () => {
expect(sharedWorkflow?.role).toEqual(workflowOwnerRole);
});

test('should create workflow history version', async () => {
valya marked this conversation as resolved.
Show resolved Hide resolved
licenseLike.isWorkflowHistoryLicensed.mockReturnValue(true);
const payload = {
name: 'testing',
nodes: [
{
id: 'uuid-1234',
parameters: {},
name: 'Start',
type: 'n8n-nodes-base.start',
typeVersion: 1,
position: [240, 300],
},
],
connections: {},
staticData: null,
settings: {
saveExecutionProgress: true,
saveManualExecutions: true,
saveDataErrorExecution: 'all',
saveDataSuccessExecution: 'all',
executionTimeout: 3600,
timezone: 'America/New_York',
},
};

const response = await authMemberAgent.post('/workflows').send(payload);

expect(response.statusCode).toBe(200);

const { id } = response.body;

expect(id).toBeDefined();
expect(
await Container.get(WorkflowHistoryRepository).count({ where: { workflowId: id } }),
).toBe(1);
const historyVersion = await Container.get(WorkflowHistoryRepository).findOne({
where: {
workflowId: id,
},
});
expect(historyVersion).not.toBeNull();
expect(historyVersion!.connections).toEqual(payload.connections);
expect(historyVersion!.nodes).toEqual(payload.nodes);
});

test('should not create workflow history version', async () => {
valya marked this conversation as resolved.
Show resolved Hide resolved
licenseLike.isWorkflowHistoryLicensed.mockReturnValue(false);
const payload = {
name: 'testing',
nodes: [
{
id: 'uuid-1234',
parameters: {},
name: 'Start',
type: 'n8n-nodes-base.start',
typeVersion: 1,
position: [240, 300],
},
],
connections: {},
staticData: null,
settings: {
saveExecutionProgress: true,
saveManualExecutions: true,
saveDataErrorExecution: 'all',
saveDataSuccessExecution: 'all',
executionTimeout: 3600,
timezone: 'America/New_York',
},
};

const response = await authMemberAgent.post('/workflows').send(payload);

expect(response.statusCode).toBe(200);

const { id } = response.body;

expect(id).toBeDefined();
expect(
await Container.get(WorkflowHistoryRepository).count({ where: { workflowId: id } }),
).toBe(0);
});

test('should not add a starting node if the payload has no starting nodes', async () => {
const response = await authMemberAgent.post('/workflows').send({
name: 'testing',
Expand Down Expand Up @@ -835,6 +935,108 @@ describe('PUT /workflows/:id', () => {
);
});

test('should create workflow history version', async () => {
valya marked this conversation as resolved.
Show resolved Hide resolved
licenseLike.isWorkflowHistoryLicensed.mockReturnValue(true);
const workflow = await testDb.createWorkflow({}, member);
const payload = {
name: 'name updated',
nodes: [
{
id: 'uuid-1234',
parameters: {},
name: 'Start',
type: 'n8n-nodes-base.start',
typeVersion: 1,
position: [240, 300],
},
{
id: 'uuid-1234',
parameters: {},
name: 'Cron',
type: 'n8n-nodes-base.cron',
typeVersion: 1,
position: [400, 300],
},
],
connections: {},
staticData: '{"id":1}',
settings: {
saveExecutionProgress: false,
saveManualExecutions: false,
saveDataErrorExecution: 'all',
saveDataSuccessExecution: 'all',
executionTimeout: 3600,
timezone: 'America/New_York',
},
};

const response = await authMemberAgent.put(`/workflows/${workflow.id}`).send(payload);

const { id } = response.body;

expect(response.statusCode).toBe(200);

expect(id).toBe(workflow.id);
expect(
await Container.get(WorkflowHistoryRepository).count({ where: { workflowId: id } }),
).toBe(1);
const historyVersion = await Container.get(WorkflowHistoryRepository).findOne({
where: {
workflowId: id,
},
});
expect(historyVersion).not.toBeNull();
expect(historyVersion!.connections).toEqual(payload.connections);
expect(historyVersion!.nodes).toEqual(payload.nodes);
});

test('should create workflow history when not licensed', async () => {
licenseLike.isWorkflowHistoryLicensed.mockReturnValue(false);
const workflow = await testDb.createWorkflow({}, member);
const payload = {
name: 'name updated',
nodes: [
{
id: 'uuid-1234',
parameters: {},
name: 'Start',
type: 'n8n-nodes-base.start',
typeVersion: 1,
position: [240, 300],
},
{
id: 'uuid-1234',
parameters: {},
name: 'Cron',
type: 'n8n-nodes-base.cron',
typeVersion: 1,
position: [400, 300],
},
],
connections: {},
staticData: '{"id":1}',
settings: {
saveExecutionProgress: false,
saveManualExecutions: false,
saveDataErrorExecution: 'all',
saveDataSuccessExecution: 'all',
executionTimeout: 3600,
timezone: 'America/New_York',
},
};

const response = await authMemberAgent.put(`/workflows/${workflow.id}`).send(payload);

const { id } = response.body;

expect(response.statusCode).toBe(200);

expect(id).toBe(workflow.id);
expect(
await Container.get(WorkflowHistoryRepository).count({ where: { workflowId: id } }),
).toBe(0);
});

test('should update non-owned workflow if owner', async () => {
const workflow = await testDb.createWorkflow({}, member);

Expand Down
Loading
Loading