Skip to content
Open
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
196 changes: 98 additions & 98 deletions .github/cli/apify-test-tools.mjs

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions bin/build-from-local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,13 +208,14 @@ export const runBuildsFromLocal = async ({
const preparedBuilds = await Promise.all(
actorConfigs.map(async (actorConfig) => {
const actorInfo = await ApifyBuilder.fromActorConfig(actorConfig).getActorInfo();
if (requireEnvVarsInSync) {
if (requireEnvVarsInSync && dryRun) {
const { defaultVersion } = resolveDefaultVersion(actorConfig.actorFullName, actorInfo);
assertEnvVarsMatchDefaultVersion(
actorConfig.actorFullName,
actorInfo,
defaultVersion,
LOCAL_SOURCE_VERSION_NUMBER,
true,
);
}
// Zipped and uploaded like `apify push` does, since inline SOURCE_FILES are capped at ~9 MB.
Expand Down Expand Up @@ -257,6 +258,9 @@ export const runBuildsFromLocal = async ({
tarballUrl: await builder.uploadSourceZip(LOCAL_SOURCE_VERSION_NUMBER, zipBuffer),
sourceType: ActorSourceType.Tarball,
};
return builder.createVersionAndBuild(LOCAL_SOURCE_VERSION_NUMBER, actorVersion, false, actorInfo);
return builder.createVersionAndBuild(LOCAL_SOURCE_VERSION_NUMBER, actorVersion, false, {
actorInfo,
requireEnvVarsInSync,
});
});
};
51 changes: 38 additions & 13 deletions bin/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,20 @@ export const assertEnvVarsMatchDefaultVersion = (
actorInfo: ApifyClientTypes.Actor,
defaultVersion: ApifyClientTypes.ActorVersion | undefined,
versionNumber: string,
dryRun = false,
) => {
if (!defaultVersion) {
throw new Error(
`[${actorFullName}] The version of the default build no longer exists. ${ACTOR_SETUP_REQUIREMENT}`,
);
}
const version = actorInfo.versions.find((v) => v.versionNumber === versionNumber);
if (!version && dryRun) {
logger.info(
`[DRY RUN][${actorFullName}] Would create version ${versionNumber} before checking its env vars against ` +
`default version ${defaultVersion.versionNumber}.`,
);
}
const defaultNames = getEnvVarNames(defaultVersion);
const names = getEnvVarNames(version);
const missing = defaultNames.filter((name) => !names.includes(name));
Expand All @@ -116,7 +123,6 @@ export const assertEnvVarsMatchDefaultVersion = (
throw new Error(
`[${actorFullName}] Env vars of version ${versionNumber} are out of sync with default version ` +
`${defaultVersion.versionNumber} (${differences.join('; ')}). ` +
`${version ? '' : `Version ${versionNumber} doesn't exist yet, so create it on the platform first. `}` +
`Add or remove the env vars in version ${versionNumber} so their names match the default version's.`,
);
};
Expand Down Expand Up @@ -160,19 +166,34 @@ export class ApifyBuilder {
versionNumber: string,
actorVersion: ApifyClientTypes.ActorVersion,
useCache: boolean,
actorInfo?: ApifyClientTypes.Actor,
{
actorInfo,
requireEnvVarsInSync = false,
}: { actorInfo?: ApifyClientTypes.Actor; requireEnvVarsInSync?: boolean } = {},
): Promise<BuildData> => {
const actorClient = this.apifyClient.actor(this.actorFullName);
const { versions } = actorInfo ?? (await this.getActorInfo());
let preparedActorInfo = actorInfo ?? (await this.getActorInfo());

// Prepare version
const versionMissing = !versions.find((version) => version.versionNumber === versionNumber);
const versionMissing = !preparedActorInfo.versions.find((version) => version.versionNumber === versionNumber);
// Create a missing version first so the env var check can inspect the version returned by the API.
if (versionMissing) {
// create new version
await actorClient.versions().create(actorVersion);
} else {
const version = actorClient.version(versionNumber);
await version.update(actorVersion);
const createdVersion = await actorClient.versions().create(actorVersion);
preparedActorInfo = {
...preparedActorInfo,
versions: [...preparedActorInfo.versions, createdVersion],
};
}

// Validate env vars before updating an existing version or starting a build.
// If this fails, a newly created version remains available for the user to configure its env vars.
if (requireEnvVarsInSync) {
const { defaultVersion } = resolveDefaultVersion(this.actorFullName, preparedActorInfo);
assertEnvVarsMatchDefaultVersion(this.actorFullName, preparedActorInfo, defaultVersion, versionNumber);
}

// Update existing versions only after validation; new versions already have actorVersion from creation.
if (!versionMissing) {
await actorClient.version(versionNumber).update(actorVersion);
}

// We also get back actId so the testing actor can both match by actor ID and name
Expand Down Expand Up @@ -416,12 +437,13 @@ export const runBuilds = async ({
}
const targetVersionNumber =
versionNumber === DEFAULT_VERSION_KEYWORD ? defaultVersionNumber : versionNumber;
if (requireEnvVarsInSync) {
if (requireEnvVarsInSync && dryRun) {
assertEnvVarsMatchDefaultVersion(
actorConfig.actorFullName,
actorInfo,
defaultVersion,
targetVersionNumber,
true,
);
}

Expand All @@ -439,7 +461,7 @@ export const runBuilds = async ({
}),
);

// Everything above only reads, so a dry run has checked what the real run would, short of writing
// Dry runs treat missing versions as having no env vars and report their planned creation.
if (dryRun) {
logger.info('[DRY RUN] Would build:');
const builds = buildConfigs.map((buildConfig) => ({
Expand All @@ -466,7 +488,10 @@ export const runBuilds = async ({
sourceType: ActorSourceType.GitRepo,
};
// Always with the Docker cache: CI always asked for it, and a clean build can still be started on the platform
return builder.createVersionAndBuild(buildConfig.versionNumber, actorVersion, true, buildConfig.actorInfo);
return builder.createVersionAndBuild(buildConfig.versionNumber, actorVersion, true, {
actorInfo: buildConfig.actorInfo,
requireEnvVarsInSync,
});
});
};

Expand Down
7 changes: 4 additions & 3 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,10 @@ To build from a different repository on purpose, e.g. when moving an Actor, pass
Tests should run the Actor with the same env vars users run it with. Pass `--require-env-vars-in-sync` to `build` or
`build-from-local` to compare the env vars of the version they build (e.g. `0.99`, or `0.98` for `build-from-local`)
with those of the default version, and fail if a name is missing or extra. Only names are compared, since the API
doesn't return secret values. A version that doesn't exist yet counts as having no env vars, so if the default
version has any, create the test version on the platform with the same env vars first. A dry run checks the env vars
too.
doesn't return secret values. A missing version is created before its env vars are checked. If they still differ,
the command fails before building; add or remove env vars on the created version so their names match. A dry run
reports that a missing version would be created and treats it as having no env vars: it passes if the default
version has none, and fails otherwise.

The CLI leaves it off by default, so a one-off build, e.g. of a debug branch, isn't held up by it.
[`public_pr-build-test.yaml`](workflows.md#public_pr-build-testyaml) turns it on by default; set its
Expand Down
5 changes: 4 additions & 1 deletion test/unit/bin/build-from-local.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,10 @@ describe('build-from-local helpers', () => {
getActorInfo: async () => ({
defaultRunOptions: { build: 'latest' },
taggedBuilds: { latest: { buildNumber: '0.1.5' } },
versions: [{ versionNumber: '0.1', sourceType: 'GIT_REPO', envVars: [{ name: 'API_KEY' }] }],
versions: [
{ versionNumber: '0.1', sourceType: 'GIT_REPO', envVars: [{ name: 'API_KEY' }] },
{ versionNumber: '0.98', sourceType: 'GIT_REPO' },
],
}),
} as unknown as ApifyBuilder);
// Only the name matters, the check runs before the sources are read
Expand Down
141 changes: 135 additions & 6 deletions test/unit/bin/build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ import {
resolveDefaultVersion,
runBuilds,
} from '../../../bin/build.js';
import { runBuildsFromLocal } from '../../../bin/build-from-local.js';
import * as Git from '../../../bin/git.js';
import { logger } from '../../../bin/logger.js';
import type { ActorConfig } from '../../../bin/types.js';
import * as Utils from '../../../bin/utils.js';
import { ExistingDir, ExistingFile, RelativeDir } from '../../../bin/utils/path/repo-relative.js';

// Only the client is faked, so the tests exercise the real builder code against a stubbed API
Expand Down Expand Up @@ -192,8 +194,8 @@ describe('assertEnvVarsMatchDefaultVersion', () => {
);
});

it('should ask to create the version when it does not exist yet', () => {
expect(() => check(makeActorInfoWithEnvVars(['A']))).toThrow("Version 0.99 doesn't exist yet");
it('should report missing env vars when the version does not exist', () => {
expect(() => check(makeActorInfoWithEnvVars(['A']))).toThrow('missing A');
});

it('should throw when the default version no longer exists', () => {
Expand All @@ -203,7 +205,7 @@ describe('assertEnvVarsMatchDefaultVersion', () => {
});
});

describe('dry run', () => {
describe('build execution and dry run', () => {
const TOKEN_ENV_VAR = 'APIFY_TOKEN_OWNER';
const originalCwd = process.cwd();
let fixtureRoot: string;
Expand Down Expand Up @@ -235,14 +237,25 @@ describe('dry run', () => {
});
const deleteBuild = vi.fn();
const startBuild = vi.fn();
const createVersion = vi.fn();
const buildClient = vi.fn(() => ({ delete: deleteBuild }));
const makeCreatedVersion = (version: ApifyClientTypes.ActorVersion): ApifyClientTypes.FinalActorVersion => {
if (!version.versionNumber) throw new Error('Version creation requires a version number');
return { ...version, versionNumber: version.versionNumber, buildTag: 'test' };
};
const createVersion =
vi.fn<(version: ApifyClientTypes.ActorVersion) => Promise<ApifyClientTypes.FinalActorVersion>>();
const updateVersion = vi.fn();
const buildClient = vi.fn(() => ({
delete: deleteBuild,
waitForFinish: async () => ({ status: 'SUCCEEDED', buildNumber: '0.99.1' }),
}));

let actorInfo: ApifyClientTypes.Actor;

beforeEach(() => {
vi.stubEnv(TOKEN_ENV_VAR, 'token');
actorInfo = makeActorInfo();
createVersion.mockImplementation(async (version) => makeCreatedVersion(version));
startBuild.mockResolvedValue({ id: 'build-id', actId: 'actor-id', buildNumber: '0.99.1' });
const fakeClient = {
actor: () => ({
get: async () => actorInfo,
Expand All @@ -251,7 +264,7 @@ describe('dry run', () => {
list: async () => ({ items: [{ id: 'old-build', buildNumber: '0.0.1', startedAt: new Date(0) }] }),
}),
versions: () => ({ create: createVersion }),
version: () => ({ update: createVersion }),
version: () => ({ update: updateVersion }),
build: startBuild,
}),
build: buildClient,
Expand All @@ -263,6 +276,7 @@ describe('dry run', () => {

afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
vi.clearAllMocks();
});

Expand Down Expand Up @@ -325,14 +339,129 @@ describe('dry run', () => {
});

it('should still check the env vars when asked to', async () => {
actorInfo.versions.push({
versionNumber: '0.99',
sourceType: ActorSourceType.GitRepo,
gitRepoUrl: REPO_URL,
});
await expect(runDryBuilds(true)).rejects.toThrow('missing API_KEY');
});

it('should report the planned creation and reject missing env vars in a dry run', async () => {
const info = vi.spyOn(logger, 'info');
await expect(runDryBuilds(true)).rejects.toThrow('missing API_KEY');
expect(info).toHaveBeenCalledWith(expect.stringContaining('Would create version 0.99'));
expect(createVersion).not.toHaveBeenCalled();
expect(updateVersion).not.toHaveBeenCalled();
expect(startBuild).not.toHaveBeenCalled();
});

it('should not check the env vars unless asked to', async () => {
await expect(runDryBuilds()).resolves.toMatchObject({ dryRun: true });
});
});

describe.each(['git', 'local'] as const)('%s build version creation', (source) => {
const versionNumber = source === 'git' ? '0.99' : '0.98';
const run = async (dryRun = false, requireEnvVarsInSync = true) => {
if (source === 'local') {
return runBuildsFromLocal({ actorConfigs: [actorConfig], dryRun, requireEnvVarsInSync });
}
return runBuilds({
actorConfigs: [actorConfig],
repoUrl: REPO_URL,
shouldVerifyRepoUrl: true,
branch: 'feature',
dryRun,
versionNumber,
requireEnvVarsInSync,
});
};

beforeEach(() => {
actorInfo.versions[0].envVars = [{ name: 'API_KEY', isSecret: true }];
if (source === 'local') {
const builder = ApifyBuilder.fromActorConfig(actorConfig);
vi.spyOn(builder, 'uploadSourceZip').mockResolvedValue('https://example.com/source.zip');
vi.spyOn(ApifyBuilder, 'fromActorConfig').mockReturnValue(builder);
vi.spyOn(Utils, 'listRepoFilePaths').mockResolvedValue(['actors/a/.actor/actor.json']);
vi.spyOn(Utils, 'getGitignoredPaths').mockResolvedValue(new Set());
}
});

it('creates a missing version and checks its returned env vars before building', async () => {
createVersion.mockImplementation(async (version) => ({
...makeCreatedVersion(version),
envVars: [{ name: 'API_KEY', isSecret: true }],
}));
await expect(run()).resolves.toEqual([
{ actorFullName: ACTOR, buildId: 'build-id', actorRawId: 'actor-id', buildNumber: '0.99.1' },
]);
expect(createVersion).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ versionNumber }));
expect(startBuild).toHaveBeenCalledWith(versionNumber, { useCache: source === 'git' });
expect(createVersion.mock.invocationCallOrder[0]).toBeLessThan(startBuild.mock.invocationCallOrder[0]);
expect(updateVersion).not.toHaveBeenCalled();
});

it('creates the missing version but does not build if its env vars still differ', async () => {
await expect(run()).rejects.toThrow(`Env vars of version ${versionNumber} are out of sync`);
expect(createVersion).toHaveBeenCalledOnce();
expect(startBuild).not.toHaveBeenCalled();
});

it('does not build if version creation fails', async () => {
createVersion.mockRejectedValue(new Error('Version creation failed'));
await expect(run()).rejects.toThrow('Version creation failed');
expect(startBuild).not.toHaveBeenCalled();
});

it('rejects an existing version with different env vars without creating or updating it', async () => {
actorInfo.versions.push({ versionNumber, sourceType: ActorSourceType.GitRepo, gitRepoUrl: REPO_URL });
await expect(run()).rejects.toThrow('missing API_KEY');
expect(createVersion).not.toHaveBeenCalled();
expect(updateVersion).not.toHaveBeenCalled();
expect(startBuild).not.toHaveBeenCalled();
});

it('updates and builds an existing version whose env vars match', async () => {
actorInfo.versions.push({
versionNumber,
sourceType: ActorSourceType.GitRepo,
gitRepoUrl: REPO_URL,
envVars: [{ name: 'API_KEY', isSecret: true }],
});
await expect(run()).resolves.toHaveLength(1);
expect(createVersion).not.toHaveBeenCalled();
expect(updateVersion).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ versionNumber }));
expect(startBuild).toHaveBeenCalledOnce();
});

it('reports the planned creation and passes a dry run when the default has no env vars', async () => {
actorInfo.versions[0].envVars = [];
const info = vi.spyOn(logger, 'info');
await expect(run(true)).resolves.toMatchObject({ dryRun: true });
expect(info).toHaveBeenCalledWith(expect.stringContaining(`Would create version ${versionNumber}`));
expect(createVersion).not.toHaveBeenCalled();
expect(updateVersion).not.toHaveBeenCalled();
expect(startBuild).not.toHaveBeenCalled();
});

it('reports the planned creation and fails a dry run when the default has env vars', async () => {
const info = vi.spyOn(logger, 'info');
await expect(run(true)).rejects.toThrow('missing API_KEY');
expect(info).toHaveBeenCalledWith(expect.stringContaining(`Would create version ${versionNumber}`));
expect(createVersion).not.toHaveBeenCalled();
expect(updateVersion).not.toHaveBeenCalled();
expect(startBuild).not.toHaveBeenCalled();
});

it('can build with different env vars when the check is disabled', async () => {
await expect(run(false, false)).resolves.toHaveLength(1);
expect(createVersion).toHaveBeenCalledOnce();
expect(startBuild).toHaveBeenCalledOnce();
});
});

it('should not delete old builds', async () => {
await deleteOldBuilds([actorConfig], { dryRun: true });
expect(deleteBuild).not.toHaveBeenCalled();
Expand Down
Loading