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
45 changes: 44 additions & 1 deletion newborns/app-nextjs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@
// what the build task's cache holds. The image built from that directory alone
// holds it and nothing else, and becomes healthy under the app's compose file,
// a stateful app migrated first from what the directory holds; that needs docker.
// The repo's `publish` pushes that image to a registry on loopback under
// build-<hash> and the commit, and after a commit that changes no input of the
// build only adds the new commit's tag to it; that needs docker too.
import assert from 'node:assert/strict';
import { randomBytes } from 'node:crypto';
import { cpSync, existsSync, readdirSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { after, before, test } from 'node:test';
import { born, close, freePort, open, pass, plxNew, put, relock, sh, start, tryRun } from './helpers.ts';
import { born, close, freePort, git, open, pass, plxNew, put, relock, sh, start, tryRun } from './helpers.ts';

let here = '';
let repo = '';
Expand Down Expand Up @@ -260,6 +263,46 @@ for (const profile of PROFILES) {
});
}

test("publish pushes the image of the app's output under build-<hash> and the commit, and a commit that changes no input of the build only tags it", async () => {
// The forge's registry: one on loopback, and a Docker config of the test's own, which holds no login.
const limits = ['--cpus', '4', '--memory', '6g', '--pids-limit', '1000'];
const started = await sh('docker', ['run', '-d', '--rm', ...limits, '-p', '127.0.0.1::5000', 'registry:2'], here);
const container = /^[0-9a-f]{64}$/m.exec(started)?.[0] ?? '';
assert.ok(container, started);
const registry = (await sh('docker', ['port', container, '5000/tcp'], here)).trim().split('\n')[0] ?? '';
const env = { IMAGE_PREFIX: `${registry}/acme`, DOCKER_CONFIG: join(here, 'docker-config') };
put(here, { 'docker-config/config.json': {} });
const digest = async (ref: string) =>
JSON.parse(
await sh('docker', ['buildx', 'imagetools', 'inspect', '--format', '{{json .Manifest}}', ref], here, env),
).digest as string;
const commit = async (...args: string[]) => {
const ran = await git(repo, 'commit', '-q', '--no-verify', ...args);
assert.ok(ran.ok, ran.output);
return (await sh('git', ['rev-parse', 'HEAD'], repo)).trim();
};
try {
const first = await commit('-m', 'the app');
const pushed = await tryRun('mise', ['run', 'publish', 'stateless'], repo, env);
assert.ok(pushed.ok, pushed.output);
const { build } = await hashes('stateless');
const image = `${registry}/acme/stateless`;
assert.match(pushed.output, new RegExp(`${image}:build-${build} is missing, building it from the build output`));
const built = await digest(`${image}:build-${build}`);
assert.equal(await digest(`${image}:${first}`), built);

const second = await commit('--allow-empty', '-m', 'nothing the build reads');
const tagged = await tryRun('mise', ['run', 'publish', 'stateless'], repo, env);
assert.ok(tagged.ok, tagged.output);
assert.match(tagged.output, new RegExp(`${image}:build-${build} is there already, tagging it ${second}`));
assert.doesNotMatch(tagged.output, /buildx build|building it/);
assert.equal(await digest(`${image}:${second}`), built);
} finally {
await tryRun('docker', ['rm', '-f', container], here);
await tryRun('sh', ['-c', `docker image ls -q '${registry}/acme/stateless' | xargs -r docker image rm -f`], here);
}
});

test('the repo around the apps passes its own test, which includes check', async () => {
await pass(repo, 'acme', 'test');
});
6 changes: 3 additions & 3 deletions packages/cli-ci/src/commands/displayVersions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
// plx-ci tag-display-version 1.4 "$GITHUB_SHA"
import { appendFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { UsageError } from '@plexus-ms/lib';
import { imagePrefix, UsageError } from '@plexus-ms/lib';
import type { Command } from 'commander';
import { displayVersions, tagDisplayVersion } from '../core/displayVersions.ts';
import { contextOf } from '../program.ts';
import { imagePrefix, need } from './shared.ts';
import { need } from './shared.ts';

/** The app names of _e2e.yml's output `deploys`. */
export function appsOfDeploys(json: string): string[] {
Expand Down Expand Up @@ -57,7 +57,7 @@ export function register(program: Command): void {
environment,
sha,
apps: appsOfDeploys(opts.deploys),
prefix: imagePrefix(),
prefix: imagePrefix(process.env),
});
ctx.result(result, (r) =>
[
Expand Down
258 changes: 258 additions & 0 deletions packages/cli-ci/src/commands/image.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
// plx-ci image as a process, in an app's directory of a checkout, against the
// fake builder and registry of testing/fakeDocker.ts. The machine is told to
// the process through Node's own process.platform and process.arch.
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { afterEach, test } from 'node:test';
import { LOCKFILE } from '../testing/checkout.ts';
import { type Call, fakeDocker } from '../testing/fakeDocker.ts';

const BIN = join(import.meta.dirname, '..', 'bin.ts');
const HASH = '0f2a3f35123dfd73';
const SOLVER = '9e1d5b7a0c3f2e41';
const KEY = 'the-apps-key';

const dirs: string[] = [];
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});

const write = (path: string, content: string) => {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, content);
};

/**
* A committed checkout with two apps: website from app-nextjs, its build output in place with the build ID `id`
* (none where it is null), and solver with a Dockerfile of its own, its build ID where Next leaves it.
*/
function checkout(id: string | null = HASH): { root: string; sha: string } {
const root = mkdtempSync(join(tmpdir(), 'plx-ci-image-'));
dirs.push(root);
write(join(root, 'package.json'), JSON.stringify({ devDependencies: { turbo: '^2.9.0' } }));
write(join(root, 'pnpm-lock.yaml'), LOCKFILE);
write(join(root, '.dockerignore'), '**/node_modules\n');
write(join(root, 'apps/website/package.json'), JSON.stringify({ name: '@acme/website' }));
write(join(root, 'apps/website/docker/Dockerfile'), 'FROM scratch\n');
write(join(root, 'apps/website/.next/standalone/apps/website/server.js'), '\n');
if (id !== null) write(join(root, 'apps/website/.next/standalone/apps/website/.next/BUILD_ID'), id);
write(join(root, 'apps/solver/package.json'), JSON.stringify({ name: '@acme/solver' }));
write(join(root, 'apps/solver/docker/Dockerfile'), 'FROM scratch\n');
write(join(root, 'apps/solver/.next/BUILD_ID'), SOLVER);
const git = (...args: string[]) =>
execFileSync('git', ['-c', 'user.name=t', '-c', '[email protected]', ...args], {
cwd: root,
encoding: 'utf8',
}).trim();
git('init', '-q');
git('add', '-A');
git('-c', 'commit.gpgsign=false', 'commit', '-q', '-m', 'one');
return { root, sha: git('rev-parse', 'HEAD') };
}

interface Ran {
status: number | null;
stdout: string;
stderr: string;
}

/** plx-ci with `args` in `cwd`, the fakes first on the PATH, `env` and nothing else of this process's, on `machine`. */
function plxCi(
cwd: string,
args: string[],
bin: string,
env: Record<string, string> = {},
machine: [string, string] = ['linux', 'x64'],
): Ran {
const [platform, arch] = machine;
const as = `data:text/javascript,Object.defineProperty(process,'platform',{value:'${platform}'});Object.defineProperty(process,'arch',{value:'${arch}'})`;
const ran = spawnSync(process.execPath, ['--import', as, BIN, ...args], {
cwd,
encoding: 'utf8',
env: { PATH: `${bin}:${process.env.PATH}`, HOME: process.env.HOME ?? '', ...env },
});
return { status: ran.status, stdout: ran.stdout, stderr: ran.stderr };
}

const builds = (calls: Call[]) => calls.filter((c) => c.args[1] === 'build');
const flagged = (args: string[], flag: string) => args.filter((_, i) => args[i - 1] === flag);

test('an image the registry holds under build-<hash> gets the commit’s tag, and nothing is built', () => {
const { root, sha } = checkout();
const fake = fakeDocker(root, { holds: [`ghcr.io/acme/website:build-${HASH}`] });
const ran = plxCi(join(root, 'apps', 'website'), ['image'], fake.bin, { GITHUB_REPOSITORY: 'Acme/web' });
assert.equal(ran.status, 0, ran.stderr);
assert.equal(ran.stdout, `ghcr.io/acme/website:${sha} (tagged)\n`);
assert.deepEqual(
fake.calls().map((c) => c.args),
[
['buildx', 'imagetools', 'inspect', '--format', '{{json .Manifest}}', `ghcr.io/acme/website:build-${HASH}`],
[
'buildx',
'imagetools',
'create',
'--prefer-index=false',
'--tag',
`ghcr.io/acme/website:${sha}`,
`ghcr.io/acme/website:build-${HASH}`,
],
],
);
// The commit's tag names the very manifest build-<hash> does.
assert.equal(fake.held()[`ghcr.io/acme/website:${sha}`], fake.held()[`ghcr.io/acme/website:build-${HASH}`]);
});

test('a missing image is built from the build output with the app’s Dockerfile, for linux/amd64, and pushed under both tags', () => {
const { root, sha } = checkout();
const fake = fakeDocker(root);
const app = join(root, 'apps', 'website');
// IMAGE_PREFIX names another registry than the forge's; no key is needed, the output holds what the image runs.
const ran = plxCi(app, ['--json', 'image'], fake.bin, {
IMAGE_PREFIX: 'registry.example/Acme/',
GITHUB_REPOSITORY: 'o/r',
});
assert.equal(ran.status, 0, ran.stderr);
assert.deepEqual(JSON.parse(ran.stdout), {
app: 'website',
image: `registry.example/acme/website:${sha}`,
built: true,
tags: [`build-${HASH}`, sha],
digest: 'sha256:built',
});
const [build, ...more] = builds(fake.calls());
assert.equal(more.length, 0);
const args = build?.args ?? [];
assert.deepEqual(args.slice(0, 7), [
'buildx',
'build',
join(app, '.next', 'standalone'),
'--file',
join(app, 'docker', 'Dockerfile'),
'--platform',
'linux/amd64',
]);
assert.deepEqual(flagged(args, '--tag'), [
`registry.example/acme/website:build-${HASH}`,
`registry.example/acme/website:${sha}`,
]);
assert.deepEqual(flagged(args, '--build-arg'), ['APP=website']);
assert.deepEqual(flagged(args, '--output'), ['type=image,push=true,oci-mediatypes=true']);
assert.ok(args.includes('--provenance=false') && args.includes('--sbom=false'), args.join(' '));
// No layer cache, no secret and no builder of the BuildKit service: this machine's Docker builds.
assert.doesNotMatch(args.join(' '), /--cache-from|--cache-to|--secret|--builder|BUILD_HASH/);
assert.equal(build?.env.SOURCE_DATE_EPOCH, '0');
assert.deepEqual(fake.held(), {
[`registry.example/acme/website:build-${HASH}`]: 'sha256:built',
[`registry.example/acme/website:${sha}`]: 'sha256:built',
});
});

test('with BUILDKIT_HOST the image is built by that BuildKit service, through a builder made once', () => {
const { root } = checkout();
const fake = fakeDocker(root);
const app = join(root, 'apps', 'website');
const env = { GITHUB_REPOSITORY: 'acme/web', BUILDKIT_HOST: 'tcp://127.0.0.1:4321' };
assert.equal(plxCi(app, ['image'], fake.bin, env).status, 0);
assert.deepEqual(
fake
.calls()
.filter((c) => ['inspect', 'create'].includes(c.args[1] ?? ''))
.map((c) => c.args),
[
['buildx', 'inspect', 'plexus-buildkit'],
['buildx', 'create', '--name', 'plexus-buildkit', '--driver', 'remote', 'tcp://127.0.0.1:4321'],
],
);
assert.deepEqual(flagged(builds(fake.calls())[0]?.args ?? [], '--builder'), ['plexus-buildkit']);
const again = fakeDocker(join(root, 'again'), { builders: ['plexus-buildkit'] });
assert.equal(plxCi(app, ['image'], again.bin, env).status, 0);
assert.ok(!again.calls().some((c) => c.args[1] === 'create'));
});

test('an output without BUILD_ID is refused before the registry is asked', () => {
const { root } = checkout(null);
// Next's own BUILD_ID beside the output, which a build cached without it leaves stale, does not count.
write(join(root, 'apps/website/.next/BUILD_ID'), HASH);
const fake = fakeDocker(root);
const ran = plxCi(join(root, 'apps', 'website'), ['image'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' });
assert.equal(ran.status, 1);
assert.match(ran.stderr, /\.next\/standalone holds no apps\/website\/\.next\/BUILD_ID/);
assert.deepEqual(fake.calls(), []);
});

test('a machine of another platform than Linux x64 is refused before any build, in one line', () => {
const { root } = checkout();
const fake = fakeDocker(root);
const ran = plxCi(join(root, 'apps', 'website'), ['image'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' }, [
'darwin',
'arm64',
]);
assert.equal(ran.status, 1);
assert.equal(ran.stderr.trim().split('\n').length, 1, ran.stderr);
assert.match(ran.stderr, /darwin-arm64.*linux\/amd64/);
assert.deepEqual(builds(fake.calls()), []);
assert.deepEqual(fake.held(), {});
});

test('a refused login is an error, never a missing image', () => {
const { root } = checkout();
const fake = fakeDocker(root, { refused: true });
const ran = plxCi(join(root, 'apps', 'website'), ['image'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' });
assert.equal(ran.status, 1);
assert.match(ran.stderr, /could not look up ghcr\.io\/acme\/website:build-0f2a3f35123dfd73: .*401/s);
assert.deepEqual(builds(fake.calls()), []);
});

test('an app with a Dockerfile of its own builds from a pruned context, with its key and the npmrc as secrets', () => {
const { root, sha } = checkout();
const fake = fakeDocker(root);
const env = {
GITHUB_REPOSITORY: 'acme/web',
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY,
NPM_CONFIG_USERCONFIG: '/run/npmrc',
};
// On any machine: the Dockerfile builds the app itself, for linux/amd64.
const ran = plxCi(join(root, 'apps', 'solver'), ['image', '--pruned'], fake.bin, env, ['darwin', 'arm64']);
assert.equal(ran.status, 0, ran.stderr);
const calls = fake.calls();
const [build] = builds(calls);
const args = build?.args ?? [];
const out = dirname(args[2] ?? '');
assert.equal(args[2], join(out, 'full'));
assert.deepEqual(args.slice(3, 5), ['--file', join(out, 'full', 'apps', 'solver', 'docker', 'Dockerfile')]);
assert.deepEqual(flagged(args, '--build-arg'), ['APP=solver', `BUILD_HASH=${SOLVER}`]);
assert.deepEqual(flagged(args, '--secret'), [
'id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY',
'id=npmrc,src=/run/npmrc',
]);
assert.deepEqual(flagged(args, '--tag'), [`ghcr.io/acme/solver:build-${SOLVER}`, `ghcr.io/acme/solver:${sha}`]);
// The key reaches the build from the environment, never on its command line.
assert.equal(build?.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, KEY);
assert.ok(!args.some((a) => a.includes(KEY)));
// The context was completed to the repo root's layout, and is removed after.
assert.ok(!existsSync(out), `${out} is left behind`);
});

test('a build from a pruned context refuses without the key; a tag needs none', () => {
const { root } = checkout();
const fake = fakeDocker(root);
const solver = join(root, 'apps', 'solver');
const ran = plxCi(solver, ['image', '--pruned'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' });
assert.equal(ran.status, 2);
assert.match(ran.stderr, /NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty/);
assert.deepEqual(builds(fake.calls()), []);
const there = fakeDocker(join(root, 'there'), { holds: [`ghcr.io/acme/solver:build-${SOLVER}`] });
assert.equal(plxCi(solver, ['image', '--pruned'], there.bin, { GITHUB_REPOSITORY: 'acme/web' }).status, 0);
});

test('it runs in an app’s directory, apps/<app> of a checkout, and nowhere else', () => {
const { root } = checkout();
const fake = fakeDocker(root);
const ran = plxCi(root, ['image'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' });
assert.equal(ran.status, 2);
assert.match(ran.stderr, /apps\/<app>/);
assert.deepEqual(fake.calls(), []);
});
46 changes: 46 additions & 0 deletions packages/cli-ci/src/commands/image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// plx-ci image [--pruned]: the image of the app in the current directory,
// apps/<app> of a checkout, for the checkout's commit, in the forge's
// registry: tagged where build-<hash> is there already, else built and pushed
// under both (core/image.ts says how). What an app's `publish` script runs,
// after its build: `plx-ci image` for an app from app-nextjs, whose image
// copies the build output; `plx-ci image --pruned` for an app whose own
// Dockerfile builds it from a pruned context. Needs git, and Docker's client
// with buildx logged in to the registry (DOCKER_CONFIG, else ~/.docker). From
// the environment: IMAGE_PREFIX, where the images live (default
// ghcr.io/<owner of GITHUB_REPOSITORY>); BUILDKIT_HOST, the BuildKit service
// to build through, which a slot of a runner host is handed, else this
// machine's Docker builds; and, for --pruned alone,
// NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, the repo's server-actions key, and
// NPM_CONFIG_USERCONFIG, a user-level npmrc with the token of the tenant's
// private package registry, both handed to the Dockerfile as BuildKit
// secrets. Prints the image under the commit's tag.
//
// "publish": "plx-ci image"

import { imagePrefix } from '@plexus-ms/lib';
import type { Command } from 'commander';
import { image } from '../core/image.ts';
import { contextOf } from '../program.ts';

export function register(program: Command): void {
program
.command('image')
.description(
'the image of the app in this directory for the commit: tag build-<hash> where the registry holds it, else build it from the build output and push both tags',
)
.option('--pruned', 'build with the app’s own Dockerfile, from a context turbo prune makes')
.action(async (opts: { pruned?: boolean }, command: Command) => {
const ctx = contextOf(command);
const env = process.env;
const result = await image(ctx, {
dir: process.cwd(),
context: opts.pruned ? 'pruned' : 'output',
prefix: imagePrefix(env),
machine: `${process.platform}-${process.arch}`,
encryptionKey: env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY || undefined,
npmrc: env.NPM_CONFIG_USERCONFIG || undefined,
buildkit: env.BUILDKIT_HOST || undefined,
});
ctx.result(result, (r) => `${r.image}${r.built ? ` (built, ${r.digest ?? 'no digest'})` : ' (tagged)'}`);
});
}
Loading
Loading