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
5 changes: 5 additions & 0 deletions .changeset/upload-skip-revalidate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@scrymore/scry-deployer": patch
---

`scry-deployer upload DIR` is faster on a folder that `capture web` just made. After capture validates its bundle it leaves a small record next to the folder (not inside it). If upload finds the folder exactly as capture left it (same files, sizes, times, scf.json, deployer and validator version) it skips its second validation and says so in the log. Anything else (no record, any change, another tool's folder, `--include-source`) runs the full validation as before, and the new `--validate` flag forces it. What is uploaded does not change. Upload also stores PNG images in the zip instead of compressing them again, which saves zip time at the cost of a slightly larger file.
3 changes: 2 additions & 1 deletion bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -877,11 +877,12 @@ async function main() {
.option('include-source', { describe: "Also upload each capture's component source text (code.componentFile). Off by default: Scry never needs your code", type: 'boolean', default: false })
.option('repo-root', { describe: 'Repository root that code.componentFile paths are relative to (default: cwd)', type: 'string' })
.option('dry-run', { describe: 'Validate and zip only; print where the ZIP is', type: 'boolean', default: false })
.option('validate', { describe: 'Always run the full validation, even when capture web already validated this folder', type: 'boolean', default: false })
.option('allow-partial-bundle', { type: 'boolean', default: false, hidden: true })
.option('verbose', { describe: 'Enable verbose logging', type: 'boolean' });
}, async (argv) => {
const config = loadConfig(argv);
const outcome = await runUploadBundle({ ...config, path: argv.path, includeSource: argv.includeSource, repoRoot: argv.repoRoot, source: argv.source, dryRun: argv.dryRun, allowPartialBundle: argv.allowPartialBundle });
const outcome = await runUploadBundle({ ...config, validate: argv.validate, path: argv.path, includeSource: argv.includeSource, repoRoot: argv.repoRoot, source: argv.source, dryRun: argv.dryRun, allowPartialBundle: argv.allowPartialBundle });
process.exitCode = outcome.exitCode;
})
.command('capture <adapter>', 'Capture stories into a Scry Capture Format bundle (adapters: rn, web)', (yargs) => {
Expand Down
36 changes: 35 additions & 1 deletion lib/bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ const {
listFiles,
} = require('./scf.js');

const { checkCaptureRecord, sha256 } = require('./captureRecord.js');

const SOURCE_TEXT_MAX_BYTES = 1024 * 1024;
const UNZIP_HELPER = path.join(__dirname, 'scf-unzip.mjs');

Expand Down Expand Up @@ -185,6 +187,38 @@ function copySourceFile(file, root, stageDir, skipped) {
return bundlePath;
}

/**
* Validate the staged bundle, unless `capture web` already validated this exact folder: the input
* is a directory, it matches the record capture left (same files, sizes, times, deployer and
* validator), and staging left scf.json byte for byte as it was. Anything else, or `--validate`,
* runs the full validation. Logs which path was taken.
*/
function skipReason(input, stageDir, opts) {
if (opts.validate) return { why: 'forced by --validate' };
if (opts.includeSource) return { why: '--include-source adds files' };
if (!fs.statSync(input).isDirectory()) return { why: 'input is not a folder' };
const check = checkCaptureRecord(input);
if (!check.match) return { why: check.reason };
let staged = null;
try {
staged = sha256(fs.readFileSync(path.join(stageDir, 'scf.json')));
} catch {
staged = null;
}
return staged === check.manifestSha256 ? { skip: true } : { why: 'staging changed scf.json' };
}

function validateOrSkip(input, stageDir, opts) {
const { logger } = opts;
const verdict = skipReason(input, stageDir, opts);
if (verdict.skip) {
logger.info('Validation skipped: capture web validated this exact folder and nothing changed (pass --validate to run it again).');
return { ok: true, errors: [], warnings: [], manifest: null, skipped: true };
}
logger.info(`Running the full validation (${verdict.why}).`);
return validateBundle(stageDir);
}

/**
* Stage, opt-in, validate and zip a bundle. Throws BundleRejectedError (after printing every
* problem) when the validator rejects it.
Expand Down Expand Up @@ -266,7 +300,7 @@ async function prepareBundle(input, opts) {

const { legacy, sourceText, manifest } = stageManifestAndSourceText(stageDir, opts);

const validation = validateBundle(stageDir);
const validation = validateOrSkip(input, stageDir, opts);
if (!validation.ok) {
logger.error(`\n❌ The bundle was rejected by the Scry Capture Format validator. Nothing was uploaded.`);
printValidation(validation, logger);
Expand Down
4 changes: 4 additions & 0 deletions lib/capture/web/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const { changedFiles, selectAffected, buildGraph, toProjectRelative } = require(
const { captureEntry, buildManifest, writeManifest, resetOutDir, sealOutDir, assertOutDirUsable, fileStem, skippedEntry } = require('./scf-writer.js');
const { onSignals } = require('./signals.js');
const { validateBundle, printValidation } = require('../../scf.js');
const { writeCaptureRecord } = require('../../captureRecord.js');

const toPosix = (p) => p.split(path.sep).join('/');

Expand Down Expand Up @@ -171,6 +172,9 @@ function finishRun({ run, selected, options, deps, sb, baseReport, timingsMs, st
logger.error(`The bundle at ${options.outDir} did not pass SCF validation:`);
printValidation(validation, logger);
exitCode = 1;
} else {
// Lets `upload <dir>` skip its own second validation while the folder is untouched.
writeCaptureRecord(options.outDir);
}
}
timingsMs.write = Date.now() - writeStarted;
Expand Down
3 changes: 3 additions & 0 deletions lib/capture/web/scf-writer.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
const fs = require('fs');
const path = require('path');
const { SCF_SCHEMA_URL } = require('../../scf.js');
const { recordPathFor } = require('../../captureRecord.js');
const { CaptureWebError } = require('./storybook-config.js');

const TOOL_NAME = 'scry-deployer capture web';
Expand Down Expand Up @@ -273,6 +274,8 @@ function resetOutDir(outDir) {
removeFiles(path.join(outDir, 'images'), '.png');
removeFiles(path.join(outDir, 'structure'), '.json');
fs.rmSync(path.join(outDir, 'scf.json'), { force: true });
// An old record must not outlive a re-capture that then fails validation.
fs.rmSync(recordPathFor(outDir), { force: true });
fs.mkdirSync(path.join(outDir, 'images'), { recursive: true });
fs.mkdirSync(path.join(outDir, 'structure'), { recursive: true });
}
Expand Down
99 changes: 99 additions & 0 deletions lib/captureRecord.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/**
* The record `capture web` leaves next to its bundle once the validator has passed it, and the
* check `upload DIR` makes before it decides to skip a second validation.
*
* The record lives OUTSIDE the bundle (a sibling file, `<dir>.scry-validated.json`), so the bundle
* format, the zip and the service's own validation never see it. It holds a fingerprint of the
* folder: every file's relative path, size and modification time (sorted), the SHA-256 of
* scf.json, plus the deployer version and the vendored validator version. `upload` recomputes the
* fingerprint and skips validation only on an exact match. No record, any difference (a file
* added, removed, resized, touched, a different deployer or validator) means the full validation
* runs as before. The fingerprint is a stat walk plus one small file read, a fraction of a second.
*/
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { listFiles, vendoredScfVersion } = require('./scf.js');

const RECORD_VERSION = 1;

function deployerVersion() {
try {
return require('../package.json').version;
} catch {
return 'unknown';
}
}

/** `<dir>.scry-validated.json`, next to (never inside) the bundle folder. */
function recordPathFor(dir) {
return `${path.resolve(dir)}.scry-validated.json`;
}

function sha256(buf) {
return crypto.createHash('sha256').update(buf).digest('hex');
}

/**
* Fingerprint a bundle folder.
* @returns {{digest:string, files:number, manifestSha256:string|null}}
*/
function fingerprintDir(dir) {
const files = listFiles(dir);
const hash = crypto.createHash('sha256');
for (const rel of files) {
const st = fs.statSync(path.join(dir, ...rel.split('/')));
hash.update(`${rel}\0${st.size}\0${Math.floor(st.mtimeMs)}\n`);
}
let manifestSha256 = null;
try {
manifestSha256 = sha256(fs.readFileSync(path.join(dir, 'scf.json')));
} catch {
manifestSha256 = null;
}
return { digest: hash.digest('hex'), files: files.length, manifestSha256 };
}

function expectedStamp() {
return { version: RECORD_VERSION, deployer: deployerVersion(), validator: vendoredScfVersion() };
}

/** Write the record after the validator passed `dir`. Never throws: a failed write only costs a later validation. */
function writeCaptureRecord(dir) {
try {
const record = { ...expectedStamp(), ...fingerprintDir(dir) };
fs.writeFileSync(recordPathFor(dir), `${JSON.stringify(record, null, 2)}\n`);
return true;
} catch {
return false;
}
}

/**
* Does `dir` match the record capture left for it?
* @returns {{match:boolean, reason:string, manifestSha256?:string}}
*/
function checkCaptureRecord(dir) {
let record;
try {
record = JSON.parse(fs.readFileSync(recordPathFor(dir), 'utf8'));
} catch {
return { match: false, reason: 'no capture record' };
}
const stamp = expectedStamp();
if (!record || record.version !== stamp.version || record.deployer !== stamp.deployer || record.validator !== stamp.validator) {
return { match: false, reason: 'record is from another deployer or validator version' };
}
let now;
try {
now = fingerprintDir(dir);
} catch {
return { match: false, reason: 'folder could not be read' };
}
if (!record.manifestSha256 || record.digest !== now.digest || record.files !== now.files || record.manifestSha256 !== now.manifestSha256) {
return { match: false, reason: 'folder changed since capture validated it' };
}
return { match: true, reason: 'matches the capture record', manifestSha256: now.manifestSha256 };
}

module.exports = { recordPathFor, fingerprintDir, writeCaptureRecord, checkCaptureRecord, sha256 };
4 changes: 3 additions & 1 deletion lib/scf.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,9 @@ function zipBundleDir(dir, outPath) {
output.on('close', () => resolve({ bytes: fs.statSync(outPath).size, members }));
archive.pipe(output);
for (const rel of members) {
archive.file(path.join(dir, ...rel.split('/')), { name: rel });
// PNG data is already compressed: deflate level 9 costs seconds and saves almost nothing, so
// store those members (zip method 0, which the upload service reads). Text and JSON are deflated.
archive.file(path.join(dir, ...rel.split('/')), { name: rel, store: /\.png$/i.test(rel) });
}
archive.finalize().catch(reject);
});
Expand Down
1 change: 1 addition & 0 deletions lib/uploadCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ async function prepareOrFail(input, argv, logger) {
try {
return await prepareBundle(input, {
includeSource: Boolean(argv.includeSource),
validate: Boolean(argv.validate),
repoRoot: argv.repoRoot,
logger,
});
Expand Down
5 changes: 5 additions & 0 deletions test/capture-web-integration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ maybe('capture web on the fixture project', () => {
expect(report).toBeDefined();
});

test('leaves a capture record next to the folder that matches it, so upload can skip a second validation', () => {
const { checkCaptureRecord } = require('../lib/captureRecord.js');
expect(checkCaptureRecord(out)).toMatchObject({ match: true });
});

test('counts are honest: 15 declared, 13 captured, 2 skipped with reasons', () => {
expect(manifest.counts.declared).toBe(15);
expect(manifest.counts.captured).toBe(13);
Expand Down
Loading
Loading