Files
pikasTech-HWLAB/scripts/refresh-artifact-catalog.mjs
T
2026-05-27 09:21:50 +08:00

372 lines
17 KiB
JavaScript

#!/usr/bin/env node
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { DEV_ENDPOINT, ENVIRONMENT_DEV, SERVICE_IDS } from "../internal/protocol/index.mjs";
import {
resolveDevArtifactServices,
serviceInventoryFromServices
} from "./src/dev-artifact-services.mjs";
import { tempReportPath } from "./src/report-paths.mjs";
const execFileAsync = promisify(execFile);
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const catalogPath = "deploy/artifact-catalog.dev.json";
const deployPath = "deploy/deploy.json";
const defaultPublishReportPath = tempReportPath("dev-artifacts.json");
const defaultRegistryPrefix = process.env.HWLAB_DEV_REGISTRY_PREFIX || process.env.HWLAB_DEV_REGISTRY || "127.0.0.1:5000/hwlab";
const digestPattern = /^sha256:[a-f0-9]{64}$/;
const commitPattern = /^[a-f0-9]{7,40}$/;
const publishReadyStatuses = new Set(["published", "reused"]);
function parseArgs(argv) {
const args = {
targetRef: "HEAD",
publishReportPath: null,
blocked: false,
write: true
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--target-ref") {
args.targetRef = readOption(argv, ++index, arg);
} else if (arg === "--publish-report") {
args.publishReportPath = readOption(argv, ++index, arg);
} else if (arg === "--blocked") {
args.blocked = true;
} else if (arg === "--no-write") {
args.write = false;
} else if (arg === "--help" || arg === "-h") {
args.help = true;
} else {
throw new Error(`unknown argument ${arg}`);
}
}
if (!args.help) {
assert.notEqual(args.blocked && Boolean(args.publishReportPath), true, "--blocked and --publish-report are mutually exclusive");
assert.ok(args.blocked || args.publishReportPath, `choose --blocked or --publish-report ${defaultPublishReportPath}`);
}
return args;
}
function readOption(argv, index, name) {
const value = argv[index];
if (!value || value.startsWith("--")) {
throw new Error(`${name} requires a value`);
}
return value;
}
function usage() {
return [
"usage: node scripts/refresh-artifact-catalog.mjs --target-ref REF (--blocked|--publish-report PATH) [--no-write]",
"",
"Refresh DEV deploy/catalog artifact identity without faking digest evidence.",
"",
"examples:",
" node scripts/refresh-artifact-catalog.mjs --target-ref origin/main --blocked",
` node scripts/refresh-artifact-catalog.mjs --target-ref origin/main --publish-report ${defaultPublishReportPath}`
].join("\n");
}
async function readJson(relativePath) {
const filePath = path.isAbsolute(relativePath) ? relativePath : path.join(repoRoot, relativePath);
return JSON.parse(await readFile(filePath, "utf8"));
}
async function writeJson(relativePath, value) {
await writeFile(path.join(repoRoot, relativePath), `${JSON.stringify(value, null, 2)}\n`);
}
async function gitValue(args) {
const result = await execFileAsync("git", args, {
cwd: repoRoot,
timeout: 5000,
maxBuffer: 1024 * 1024
});
return result.stdout.trim();
}
async function resolveTarget(ref) {
const commitId = await gitValue(["rev-parse", ref]);
const shortCommitId = await gitValue(["rev-parse", "--short=7", ref]);
assert.match(commitId, /^[a-f0-9]{40}$/, `target ref ${ref} must resolve to a full SHA`);
return { ref, commitId, shortCommitId };
}
function parseTaggedImage(image, context) {
assert.equal(typeof image, "string", `${context} image must be a string`);
assert.equal(image.includes("@"), false, `${context} image must not include a digest suffix`);
assert.ok(!/prod|production/iu.test(image), `${context} image must not target prod`);
const slashIndex = image.lastIndexOf("/");
const colonIndex = image.lastIndexOf(":");
assert.ok(colonIndex > slashIndex, `${context} image must be a tagged image reference`);
return {
repository: image.slice(0, colonIndex),
tag: image.slice(colonIndex + 1)
};
}
function targetImage(serviceId, shortCommitId, registryPrefix = defaultRegistryPrefix) {
return `${registryPrefix.replace(/\/+$/u, "")}/${serviceId}:${shortCommitId}`;
}
function commitMatchesTarget(value, target) {
return value === target.commitId || value === target.shortCommitId;
}
function shortCommitForRecord(record, target) {
const value = record?.commitId ?? record?.imageTag ?? null;
if (typeof value === "string" && commitPattern.test(value)) return value.slice(0, 7);
if (typeof record?.sourceCommitId === "string" && commitPattern.test(record.sourceCommitId)) return record.sourceCommitId.slice(0, 7);
return target.shortCommitId;
}
function revisionForRecord(record, target) {
if (typeof record?.sourceCommitId === "string" && commitPattern.test(record.sourceCommitId)) return record.sourceCommitId;
if (typeof record?.commitId === "string" && commitPattern.test(record.commitId)) return record.commitId;
return target.commitId;
}
function assertDevOnlyDeployAndCatalog(deploy, catalog) {
assert.equal(deploy.environment, ENVIRONMENT_DEV, "deploy environment must be dev");
assert.equal(deploy.namespace, "hwlab-dev", "deploy namespace must be hwlab-dev");
assert.equal(deploy.endpoint, DEV_ENDPOINT, "deploy endpoint must stay frozen");
assert.equal(deploy.profiles?.dev?.enabled, true, "deploy dev profile must be enabled");
assert.equal(deploy.profiles?.prod?.enabled, false, "deploy prod profile must stay disabled");
assert.deepEqual((deploy.services ?? []).map((service) => service.serviceId), SERVICE_IDS, "deploy services must cover frozen service IDs in order");
assert.equal(catalog.environment, ENVIRONMENT_DEV, "catalog environment must be dev");
assert.equal(catalog.profile, ENVIRONMENT_DEV, "catalog profile must be dev");
assert.equal(catalog.namespace, "hwlab-dev", "catalog namespace must be hwlab-dev");
assert.equal(catalog.endpoint, DEV_ENDPOINT, "catalog endpoint must stay frozen");
assert.deepEqual(catalog.allowedProfiles, [ENVIRONMENT_DEV], "catalog allowedProfiles must only allow dev");
assert.deepEqual(catalog.forbiddenProfiles, ["prod"], "catalog forbiddenProfiles must forbid prod");
assert.deepEqual((catalog.services ?? []).map((service) => service.serviceId), SERVICE_IDS, "catalog services must cover frozen service IDs in order");
}
function publishRecordsFromReport(report, target) {
const artifactPublish = report.artifactPublish;
assert.ok(artifactPublish && typeof artifactPublish === "object", "publish report missing artifactPublish");
assert.equal(artifactPublish.status, "published", "publish report artifactPublish.status must be published");
assert.ok(commitMatchesTarget(artifactPublish.sourceCommitId, target), "publish report sourceCommitId must match target ref");
assert.equal(artifactPublish.serviceCount, SERVICE_IDS.length, "publish report must cover every frozen service");
assert.ok(artifactPublish.publishPlan && typeof artifactPublish.publishPlan === "object", "publish report missing artifactPublish.publishPlan");
assert.equal(artifactPublish.publishPlan.version, "v2", "publish report plan version must be v2");
const requiredServiceIds = artifactPublish.publishPlan.services
.filter((service) => service.required)
.map((service) => service.serviceId);
const disabledServiceIds = artifactPublish.publishPlan.services
.filter((service) => !service.required)
.map((service) => service.serviceId);
assert.deepEqual(
[...requiredServiceIds, ...disabledServiceIds].sort(),
[...SERVICE_IDS].sort(),
"publish plan must cover every frozen service"
);
assert.equal(
(artifactPublish.publishedCount ?? 0) + (artifactPublish.reusedCount ?? 0),
requiredServiceIds.length,
"publish report must publish or reuse every required enabled service"
);
const records = new Map();
for (const service of artifactPublish.services ?? []) {
assert.ok(SERVICE_IDS.includes(service.serviceId), `unknown service ${service.serviceId} in publish report`);
const image = parseTaggedImage(service.image, service.serviceId);
if (!requiredServiceIds.includes(service.serviceId)) {
assert.equal(service.artifactRequired, false, `${service.serviceId} disabled service must not be required`);
assert.equal(service.digest, "not_published", `${service.serviceId} disabled digest must stay not_published`);
assert.equal(service.notPublishedReason?.startsWith("disabled_"), true, `${service.serviceId} disabled service must state a disabled reason`);
continue;
}
assert.equal(publishReadyStatuses.has(service.status), true, `${service.serviceId} status must be published or reused`);
assert.equal(service.artifactRequired, true, `${service.serviceId} required service must state artifactRequired=true`);
if (service.status === "published") {
assert.equal(image.tag, target.shortCommitId, `${service.serviceId} newly published image tag must match target short commit`);
}
assert.match(service.digest, digestPattern, `${service.serviceId} digest must be a sha256 registry digest`);
records.set(service.serviceId, {
serviceId: service.serviceId,
status: service.status,
commitId: service.commitId ?? image.tag,
sourceCommitId: service.sourceCommitId ?? null,
image: service.image,
imageTag: image.tag,
buildCreatedAt: service.buildCreatedAt ?? null,
buildSource: service.buildSource ?? null,
digest: service.digest,
repositoryDigest: service.repositoryDigest ?? `${image.repository}@${service.digest}`,
componentCommitId: service.componentCommitId ?? null,
componentInputHash: service.componentInputHash ?? null,
dockerfileHash: service.dockerfileHash ?? null,
baseImageReference: service.baseImageReference ?? null,
baseImageDigest: service.baseImageDigest ?? null,
buildArgsHash: service.buildArgsHash ?? null,
ciAffected: service.ciAffected ?? null,
ciReason: service.ciReason ?? [],
reuse: service.reuse ?? null,
reusedFrom: service.reusedFrom ?? null
});
}
assert.deepEqual([...records.keys()], requiredServiceIds, "publish report services must publish required service IDs in order");
return { records, requiredServiceIds, disabledServiceIds };
}
function refreshDocuments({ deploy, catalog, target, publishRecords, serviceInventory, provenancePath, registryPrefix }) {
const published = Boolean(publishRecords);
const records = publishRecords?.records ?? null;
const requiredIds = new Set(publishRecords?.requiredServiceIds ?? serviceInventory.requiredServiceIds);
const catalogByService = new Map(catalog.services.map((service) => [service.serviceId, service]));
const deployByService = new Map(deploy.services.map((service) => [service.serviceId, service]));
const inventoryByService = new Map(serviceInventory.services.map((service) => [service.serviceId, service]));
const refreshedServices = [];
catalog.commitId = target.shortCommitId;
catalog.artifactState = published ? "published" : "contract-skeleton";
catalog.serviceInventory = serviceInventory;
catalog.publish = {
...catalog.publish,
ciPublished: published,
registryVerified: published,
provenance: published ? provenancePath : "not_available_until_publish",
note: published
? "Digest fields were copied from a successful DEV artifact publish report for this source commit."
: "Artifact identity was refreshed to this source commit, but no publish report proved registry digests."
};
for (const serviceId of SERVICE_IDS) {
const deployService = deployByService.get(serviceId);
const catalogService = catalogByService.get(serviceId);
assert.ok(deployService, `${serviceId} missing from deploy manifest`);
assert.ok(catalogService, `${serviceId} missing from catalog`);
const inventory = inventoryByService.get(serviceId);
const required = requiredIds.has(serviceId);
const publishRecord = records?.get(serviceId) ?? null;
const image = publishRecord?.image ?? targetImage(serviceId, target.shortCommitId, registryPrefix);
const imageTag = publishRecord?.imageTag ?? target.shortCommitId;
const serviceCommitId = shortCommitForRecord(publishRecord, target);
catalogService.commitId = serviceCommitId;
catalogService.image = image;
catalogService.imageTag = imageTag;
catalogService.buildCreatedAt = publishRecord?.buildCreatedAt ?? null;
catalogService.buildSource = publishRecord?.buildSource ?? null;
catalogService.digest = publishRecord?.digest ?? "not_published";
catalogService.componentCommitId = publishRecord?.componentCommitId ?? catalogService.componentCommitId ?? null;
catalogService.componentInputHash = publishRecord?.componentInputHash ?? catalogService.componentInputHash ?? null;
catalogService.dockerfileHash = publishRecord?.dockerfileHash ?? catalogService.dockerfileHash ?? null;
catalogService.baseImageReference = publishRecord?.baseImageReference ?? catalogService.baseImageReference ?? null;
catalogService.baseImageDigest = publishRecord?.baseImageDigest ?? catalogService.baseImageDigest ?? null;
catalogService.buildArgsHash = publishRecord?.buildArgsHash ?? catalogService.buildArgsHash ?? null;
catalogService.ciAffected = publishRecord?.ciAffected ?? catalogService.ciAffected ?? null;
catalogService.ciReason = publishRecord?.ciReason ?? catalogService.ciReason ?? [];
catalogService.reuse = publishRecord?.reuse ?? catalogService.reuse ?? null;
catalogService.reusedFrom = publishRecord?.reusedFrom ?? catalogService.reusedFrom ?? null;
catalogService.publishState = publishRecord?.status === "reused" ? "reused" : publishRecord ? "published" : "skeleton-only";
catalogService.publishEnabled = inventory?.publishEnabled ?? required;
catalogService.artifactRequired = required;
catalogService.artifactScope = required ? "required" : "disabled";
catalogService.notPublishedReason = publishRecord
? null
: inventory?.disabledReason ?? (published ? "not_required" : "publish_not_run");
refreshedServices.push({
serviceId,
image,
imageTag,
buildCreatedAt: catalogService.buildCreatedAt,
digest: catalogService.digest,
componentCommitId: catalogService.componentCommitId,
componentInputHash: catalogService.componentInputHash,
dockerfileHash: catalogService.dockerfileHash,
ciAffected: catalogService.ciAffected,
ciReason: catalogService.ciReason,
reusedFrom: catalogService.reusedFrom ?? null,
publishState: catalogService.publishState,
artifactRequired: catalogService.artifactRequired,
notPublishedReason: catalogService.notPublishedReason
});
}
return refreshedServices;
}
function publishReportProvenance(publishReport, fallbackPath) {
const producer = publishReport?.artifactPublish?.producer;
if (producer?.kind && producer?.runId) return `${producer.kind}:${producer.runId}`;
return fallbackPath;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help) {
console.log(usage());
return;
}
const target = await resolveTarget(args.targetRef);
const [deploy, catalog, publishReport] = await Promise.all([
readJson(deployPath),
readJson(catalogPath),
args.publishReportPath ? readJson(args.publishReportPath) : Promise.resolve(null)
]);
assertDevOnlyDeployAndCatalog(deploy, catalog);
const publishRecords = publishReport ? publishRecordsFromReport(publishReport, target) : null;
const serviceInventory = publishReport?.artifactPublish?.serviceInventory ?? serviceInventoryFromServices(
await resolveDevArtifactServices(repoRoot, SERVICE_IDS, SERVICE_IDS)
);
const services = refreshDocuments({
deploy,
catalog,
target,
publishRecords,
serviceInventory,
provenancePath: publishReportProvenance(publishReport, args.publishReportPath ?? defaultPublishReportPath),
registryPrefix: publishReport?.artifactPublish?.registryPrefix ?? defaultRegistryPrefix
});
if (args.write) {
await writeJson(catalogPath, catalog);
}
console.log(JSON.stringify({
status: publishRecords ? "published" : "blocked",
targetRef: target.ref,
sourceCommitId: target.commitId,
artifactCommitId: target.shortCommitId,
wrote: args.write ? [catalogPath] : [],
deployTruthPolicy: "deploy.json is human-authored runtime config; artifact promotion must not rewrite it",
ciPublished: Boolean(publishRecords),
registryVerified: Boolean(publishRecords),
publishedCount: publishRecords?.records.size ?? 0,
requiredServiceCount: serviceInventory.requiredServiceCount,
disabledServiceCount: serviceInventory.disabledServiceCount,
notPublishedCount: services.filter((service) => service.digest === "not_published").length,
digestPolicy: publishRecords
? "catalog digests copied only for required services from a published DEV artifact report; disabled services stay not_published"
: "all catalog digests remain not_published",
services
}, null, 2));
}
main().catch((error) => {
console.error(JSON.stringify({
status: "failed",
error: error instanceof Error ? error.message : String(error)
}, null, 2));
process.exitCode = 1;
});