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
9 changes: 9 additions & 0 deletions integration-tests/cli/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# @openfn/integration-tests-cli

## 1.0.40

### Patch Changes

- Updated dependencies [82a0cae]
- Updated dependencies [82a0cae]
- @openfn/project@0.24.0
- @openfn/lightning-mock@2.5.10

## 1.0.39

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion integration-tests/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@openfn/integration-tests-cli",
"private": true,
"version": "1.0.39",
"version": "1.0.40",
"description": "CLI integration tests",
"author": "Open Function Group <admin@openfn.org>",
"license": "ISC",
Expand Down
36 changes: 36 additions & 0 deletions integration-tests/cli/test/sync/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// asserting on what lands on disk (.projects state, checkout.yaml, workflows folder)

import test from 'ava';
import fs from 'node:fs';
import path from 'node:path';
import run from '../../src/run';
import { setup } from './helpers';

Expand Down Expand Up @@ -256,3 +258,37 @@ test('checkout by alias', async (t) => {
});

test.todo('merge by alias');

test('pull a sandbox by UUID, reusing the local alias if there is one', async (t) => {
const { workspace, read } = initWorkspace(t);
const project = gen();

// make the remote project a sandbox
lightning.state.projects[project.openfn.uuid].parent_id =
'6a8a6c6e-5c1d-4b0e-8d52-0d4c4f2f9a11';

await run(
`openfn project pull \
--workspace ${workspace} \
--endpoint ${endpoint} \
--api-key abc \
--alias staging \
${project.openfn.uuid}`
);
t.truthy(read('.projects/staging@localhost.yaml'));

// pull again with no alias. The existing alias should be re-used
// rather than defaulting to the sandbox id
await run(
`openfn project pull \
--workspace ${workspace} \
--endpoint ${endpoint} \
--api-key abc \
${project.openfn.uuid}`
);

t.deepEqual(fs.readdirSync(path.resolve(workspace, '.projects')), [
'staging@localhost.yaml',
]);
t.regex(read('.openfn/checkout.yaml'), new RegExp(project.openfn.uuid));
});
11 changes: 11 additions & 0 deletions packages/cli/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# @openfn/cli

## 1.45.2

### Patch Changes

- 82a0cae: Channels are now tracked by their Lightning id, so changing a channel's key in resources.yaml no longer deletes and recreates it on deploy.
- 82a0cae: Workflow, step and channel ids now keep non-ASCII letters and punctuation from their names, matching Lightning. Names with these characters get new ids, so their folders and resources.yaml keys change on the next pull.
- 222473d: When fetching a sandbox, only use the id as an alias if there isn't already an existing alias
- Updated dependencies [82a0cae]
- Updated dependencies [82a0cae]
- @openfn/project@0.24.0

## 1.45.1

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@openfn/cli",
"version": "1.45.1",
"version": "1.45.2",
"description": "CLI devtools for the OpenFn toolchain",
"repository": {
"url": "https://github.com/OpenFn/kit"
Expand Down
10 changes: 9 additions & 1 deletion packages/cli/src/projects/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,15 @@ export const fetchV2 = async (options: FetchOptions, logger: Logger) => {
const remoteProject = await fetchRemoteProject(workspace, options, logger);

// if there's no alias, and this is a sandbox, set the alias
if (!options.alias && remoteProject.sandbox?.parentId) {
if (
// If the user doesn't set an alias...
!options.alias &&
// And we're pulling a sandbox...
remoteProject.sandbox?.parentId &&
// And the local project doesn't already have an alias set...
!remoteProject.cli?.alias
) {
// ...Use the sandbox id as the alias
options.alias = remoteProject.id;
remoteProject.cli.alias = options.alias;
logger.debug('Defaulting alias to sandbox id', options.alias);
Expand Down
45 changes: 44 additions & 1 deletion packages/cli/test/projects/fetch.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readFile, writeFile } from 'node:fs/promises';
import { readdir, readFile, writeFile } from 'node:fs/promises';
import test from 'ava';
import mock from 'mock-fs';
import { MockAgent, setGlobalDispatcher } from 'undici';
Expand Down Expand Up @@ -646,3 +646,46 @@ test.serial('fetch by alias when local copies share the UUID', async (t) => {
const main = await readFile('/ws/.projects/jam@app.openfn.org.yaml', 'utf-8');
t.is(main, yaml_v1);
});

test.serial(
'fetch a sandbox by UUID, reusing the local alias if there is one',
async (t) => {
const SANDBOX_UUID = 'b2f1c8a4-5d3e-4c1a-9b7e-0a1d2c3e4f50';
const sandbox = {
...myProject_v1,
id: SANDBOX_UUID,
name: 'My Sandbox',
parent_id: PROJECT_UUID,
};

mockAgent
.get(ENDPOINT)
.intercept({ path: `/api/provision/${SANDBOX_UUID}?`, method: 'GET' })
.reply(200, { data: sandbox })
.times(2);

const options = {
project: SANDBOX_UUID,
endpoint: ENDPOINT,
apiKey: 'test-api-key',
workspace: '/ws',
};

// First fetch with an explicit alias
await fetchHandler({ ...options, alias: 'staging' } as any, logger);
t.truthy(await readFile(getYamlPath('staging'), 'utf-8'));

// Ensure the sandbox is not used
await t.throwsAsync(() => readFile(getYamlPath('my-sandbox'), 'utf-8'));

// Now fetch again by UUID, with no alias. This should update the
// existing local project rather than defaulting the alias to the sandbox id
await t.notThrowsAsync(() => fetchHandler(options as any, logger));

// Ensure the sandbox is not used
await t.throwsAsync(() => readFile(getYamlPath('my-sandbox'), 'utf-8'));

const files = await readdir('/ws/.projects');
t.deepEqual(files, ['staging@app.openfn.org.yaml']);
}
);
8 changes: 8 additions & 0 deletions packages/lightning-mock/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# @openfn/lightning-mock

## 2.5.10

### Patch Changes

- Updated dependencies [82a0cae]
- Updated dependencies [82a0cae]
- @openfn/project@0.24.0

## 2.5.9

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/lightning-mock/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@openfn/lightning-mock",
"version": "2.5.9",
"version": "2.5.10",
"private": true,
"description": "A mock Lightning server",
"main": "dist/index.js",
Expand Down
10 changes: 10 additions & 0 deletions packages/project/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# @openfn/project

## 0.24.0

### Minor Changes

- 82a0cae: Workflow, step and channel ids now keep non-ASCII letters and punctuation from their names, matching Lightning. Names with these characters get new ids, so their folders and resources.yaml keys change on the next pull.

### Patch Changes

- 82a0cae: Channels are now tracked by their Lightning id, so changing a channel's key in resources.yaml no longer deletes and recreates it on deploy.

## 0.23.2

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/project/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@openfn/project",
"version": "0.23.2",
"version": "0.24.0",
"description": "Read, serialize, replicate and sync OpenFn projects",
"author": "Open Function Group <admin@openfn.org>",
"license": "ISC",
Expand Down
4 changes: 2 additions & 2 deletions packages/project/src/Project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ type CLIMeta = {
version?: number;
alias?: string | null;
forked_from?: Record<string, string>;
// uuid of each workflow, by local id. Tracked but not used
// uuid of each workflow, by local id
workflow_uuids?: Record<string, string>;
};

Expand All @@ -54,7 +54,7 @@ export class Project {
/** Human readable project name. This corresponds to the label in Lightning */
name?: string;

/** Project id. Must be url safe. May be derived from the name. NOT a UUID */
/** Project id. Must be file safe. May be derived from the name. NOT a UUID */
id: string;

description?: string;
Expand Down
35 changes: 25 additions & 10 deletions packages/project/src/merge/merge-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,10 +201,10 @@ export function merge(
baseMerge(target, source, ['channels'], assigns as any)
);

// target channels with an id that the source dropped have been removed
const kept = new Set(source.channels?.map(channelKey));
// target channels whose id didn't match any source channel have been removed
const kept = new Set(merged.channels?.map((c) => c.id));
merged.removedChannels = source.channels
? (target.channels ?? []).filter((c) => c.id && !kept.has(channelKey(c)))
? (target.channels ?? []).filter((c) => c.id && !kept.has(c.id))
: [];
return merged;
}
Expand All @@ -225,8 +225,9 @@ export function mergeCollections(
}));
}

// Source channels win, but keep the target's id on a key match. Matching on the
// key rather than the name means renaming a channel keeps its id
// Source channels win, but keep the target's id on a match. Like workflows,
// a channel is matched by id (from the checkout file), then key, then name.
// Matching on the id or key means renaming a channel keeps its id
// If the source has no channels at all (no resources.yaml), keep the target's
export function mergeChannels(
source: ChannelState[] | undefined,
Expand All @@ -239,11 +240,25 @@ export function mergeChannels(
if (!source) {
return target;
}
const targetByKey = new Map((target ?? []).map((c) => [channelKey(c), c]));
return source.map((c) => ({
...c,
id: targetByKey.get(channelKey(c))?.id,
}));
const available = [...(target ?? [])];
const claim = (match?: ChannelState) => {
if (match) available.splice(available.indexOf(match), 1);
return match;
};
const matches = new Map<ChannelState, ChannelState | undefined>();
const passes = [
(s: ChannelState, t: ChannelState) => !!s.id && s.id === t.id,
(s: ChannelState, t: ChannelState) => channelKey(s) === channelKey(t),
(s: ChannelState, t: ChannelState) => s.name === t.name,
];
for (const pass of passes) {
for (const s of source) {
if (!matches.get(s)) {
matches.set(s, claim(available.find((t) => pass(s, t))));
}
}
}
return source.map((c) => ({ ...c, id: matches.get(c)?.id }));
}

export const replaceCredentials = (
Expand Down
31 changes: 31 additions & 0 deletions packages/project/src/parse/from-app-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,35 @@ export default (
return workflow;
}) as unknown as l.WorkflowState[];

assertUniqueIds(
Object.values(stateJson.workflows).filter((w) => !w.delete),
'workflow names'
);

assertUniqueIds(channels ?? [], 'channel names');

return new Project(proj as l.ProjectState, config);
};

// Ids are derived from names, so names that differ only by case or by
// space vs hyphen (eg "Foo Bar" and "foo-bar") share an id and would overwrite
// each other. Lightning's own export rejects these pairs too
const assertUniqueIds = (items: Array<{ name: string }>, what: string) => {
const byId: Record<string, string[]> = {};
for (const { name } of items) {
(byId[slugify(name)] ??= []).push(name);
}
const dupes = Object.entries(byId).filter(([, names]) => names.length > 1);
if (dupes.length) {
const list = dupes
.map(([id, names]) => `${names.map((n) => `"${n}"`).join(', ')} -> ${id}`)
.join('\n ');
throw new Error(
`These ${what} differ only by case or spaces vs hyphens, so they resolve to the same id:\n ${list}\nRename one of them in Lightning so each has a unique id.`
);
}
};

// TODO maybe this is a util and moved out of this file
export const mapEdge = (edge: Provisioner.Edge) => {
const e: any = {
Expand Down Expand Up @@ -156,6 +182,11 @@ export const mapWorkflow = (
mapped.id = slugify(workflow.name);
}

assertUniqueIds(
Object.values(jobs).filter((j) => !j.delete),
`step names in workflow "${workflow.name}"`
);

// TODO what do we do if the condition is disabled?
// I don't think that's the same as edge condition false?
Object.values(triggers).forEach((trigger: Provisioner.Trigger) => {
Expand Down
9 changes: 8 additions & 1 deletion packages/project/src/parse/from-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ export const parseProject = async (options: FromFsConfig) => {
const workflowUuids = isPlainObject(checkout.workflow_uuids)
? (checkout.workflow_uuids as Record<string, string>)
: undefined;
const channelUuids = isPlainObject(checkout.channel_uuids)
? (checkout.channel_uuids as Record<string, string>)
: {};

const proj: any = {
id: options.name ? slugify(options.name) : checkout.id,
Expand All @@ -57,6 +60,7 @@ export const parseProject = async (options: FromFsConfig) => {
'alias',
'forked_from',
'workflow_uuids',
'channel_uuids',
'collections',
]),

Expand All @@ -83,7 +87,10 @@ export const parseProject = async (options: FromFsConfig) => {
});
const parsed = resources ? yamlToJson(resources) : undefined;
if (parsed?.channels) {
proj.channels = fromResourceChannels(parsed.channels);
// If the channel is tracked, we know its id
proj.channels = fromResourceChannels(parsed.channels).map((c) =>
channelUuids[c.key!] ? { ...c, id: channelUuids[c.key!] } : c
);
}
if (parsed && 'collections' in parsed) {
// an empty key means no collections (not the same as no key!)
Expand Down
13 changes: 12 additions & 1 deletion packages/project/src/util/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from 'node:path';
import { pickBy, isNil } from 'lodash-es';
import { yamlToJson, jsonToYaml } from './yaml';
import Project from '../Project';
import { channelKey } from './resources';

// Recursively sort object keys so that config files serialize stably
const sortKeys = (value: any): any => {
Expand Down Expand Up @@ -72,7 +73,6 @@ export const extractCheckout = (
}

// Track the uuid of each workflow, by local id
// This is recorded for future use and isn't read by anything yet
const workflowUuids = source.workflows.reduce((obj: any, wf) => {
if (wf.openfn?.uuid) {
obj[wf.id] = wf.openfn.uuid;
Expand All @@ -83,6 +83,17 @@ export const extractCheckout = (
project.workflow_uuids = workflowUuids;
}

// And the id of each channel, by its key in resources.yaml
const channelUuids = (source.channels ?? []).reduce((obj: any, c) => {
if (c.id) {
obj[channelKey(c)] = c.id;
}
return obj;
}, {});
if (Object.keys(channelUuids).length) {
project.channel_uuids = channelUuids;
}

return {
path: getCheckoutPath(branch),
content: jsonToYaml(sortKeys(project)),
Expand Down
Loading
Loading