From b312a50d3758a5f1cee2894f8ff5b6d1c4f2cb2a Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Sun, 27 Sep 2026 19:52:58 +0900 Subject: [PATCH] Adopt SemVer 2.0.0 and promote release images by digest --- .gitea/workflows/images.yml | 4 +- .gitea/workflows/release.yml | 46 ++++++++++++ README.md | 4 ++ docs/operations/gitea-images.md | 9 ++- docs/operations/versioning.md | 81 +++++++++++++++++++++ tools/ci/release-images.mjs | 99 ++++++++++++++++++++++++++ tools/ci/release-images.test.mjs | 116 +++++++++++++++++++++++++++++++ 7 files changed, 357 insertions(+), 2 deletions(-) create mode 100644 .gitea/workflows/release.yml create mode 100644 docs/operations/versioning.md create mode 100644 tools/ci/release-images.mjs create mode 100644 tools/ci/release-images.test.mjs diff --git a/.gitea/workflows/images.yml b/.gitea/workflows/images.yml index a445f85..29d0520 100644 --- a/.gitea/workflows/images.yml +++ b/.gitea/workflows/images.yml @@ -3,7 +3,6 @@ name: Build and publish container images on: push: branches: [main, mk_district] - tags: ['v*'] workflow_dispatch: jobs: @@ -36,6 +35,9 @@ jobs: [worker.oci] max-parallelism = 2 + - name: Test release tooling + run: node --test tools/ci/release-images.test.mjs + - name: Test uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 with: diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..10fcc04 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,46 @@ +name: Release container images + +on: + push: + tags: ['v*'] + # Retry against the same tag if a registry operation was interrupted. + workflow_dispatch: + +jobs: + release: + if: startsWith(github.ref, 'refs/tags/v') + runs-on: ${{ vars.IMAGE_RUNNER_LABEL || 'ubuntu-latest' }} + container: + image: docker.gitea.com/runner-images:ubuntu-latest@sha256:fd911d7417bfbf0f454530e447da95b58001e1df41bbc5e1a8dd35d432575aae + env: + REGISTRY: ${{ vars.IMAGE_REGISTRY || 'git.anya.jp' }} + IMAGE_OWNER: ${{ vars.IMAGE_OWNER || 'anya' }} + RELEASE_REF: ${{ github.ref }} + PATH: /opt/acttoolcache/node/24.19.0/x64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin + DOCKER_BUILD_SUMMARY: 'false' + DOCKER_BUILD_RECORD_UPLOAD: 'false' + steps: + - name: Checkout release tag + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ github.ref }} + persist-credentials: false + + - name: Validate release version + run: node tools/ci/release-images.mjs --validate + + - name: Set up Buildx tools + uses: https://github.com/docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 + with: + version: v0.34.0 + driver: docker + + - name: Log in to registry + uses: https://github.com/docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0 + with: + registry: ${{ env.REGISTRY }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_TOKEN }} + + - name: Promote existing images without rebuilding + run: node tools/ci/release-images.mjs diff --git a/README.md b/README.md index 49adcdd..514c19d 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,10 @@ See [Gitea image builds and registry setup](docs/operations/gitea-images.md) for runner requirements, registry secrets, and the optional registry Compose overlay. The workflow does not deploy to production. +PagesWiki follows [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html). +Release tags (starting with `v0.1.0`) promote existing tested images without +rebuilding. See the [versioning and release policy](docs/operations/versioning.md). + ## Knowledge City Model Pages Wiki uses urban language for its content hierarchy: diff --git a/docs/operations/gitea-images.md b/docs/operations/gitea-images.md index 802f11d..aea2284 100644 --- a/docs/operations/gitea-images.md +++ b/docs/operations/gitea-images.md @@ -13,7 +13,9 @@ runner の環境構築や Gitea の事前疎通診断は行わず、本番へ自 | `pageswiki-excalidraw-viewer` | `Dockerfile.excalidraw-viewer` | Kroki、Mermaid、code-server は upstream の配布イメージを使用する。 -`main` / `mk_district` への push、`v*` タグ、手動実行でビルド・公開する。 +`main` / `mk_district` への push、手動実行でビルド・公開する。 +`v*` タグは別の `release.yml` でビルド済みイメージを昇格し、再ビルドしない。 +採番は [SemVer 2.0.0 の運用規則](versioning.md) に従う。 本体の `test` ステージで `go test ./...` を実行し、3 イメージのビルドが成功した後に push する。 3 回の push は原子的ではないため、**ワークフロー全体の成功を確認してから利用**する。 最後に当該ジョブのローカル CI タグと専用 builder を後処理する。 @@ -37,6 +39,11 @@ Docker socket を使うジョブは強い権限を持つため、信頼するコ ### 提示された Docker 版 Runner 3 の構成 +ホストの Docker ソケットを利用する場合は **`docker.io/gitea/runner:3`(通常版)** を使う。 +`3-dind` / `3-dind-rootless` とソケットの bind mount を混在させない。 +runner が利用する daemon と `anya-npm-net` が存在する daemon は一致させる。 +別 daemon に同名ネットワークを作っても接続は共有されない。 + Gitea 側 Compose のラベルで Docker 実行方式を明示する。 workflow の `container.image` が実際のジョブ用イメージを指定する。 diff --git a/docs/operations/versioning.md b/docs/operations/versioning.md new file mode 100644 index 0000000..e9a1651 --- /dev/null +++ b/docs/operations/versioning.md @@ -0,0 +1,81 @@ +# バージョニングとリリース + +PagesWiki は [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) を採用する。 +初回リリースは **0.1.0**。Git タグとコンテナタグには接頭辞 `v` を付ける。 +`v` は SemVer のバージョン番号そのものには含まれない。 + +## 互換性の対象 + +PagesWiki の公開インターフェースとして、設計書・利用手順で公開した次の契約を扱う。 + +- HTTP API の URI、認証方式、要求・応答形式、および公開 URI の解決規則。 +- CalDAV / iCalendar 等の外部クライアントとの連携契約。 +- CLI の公開コマンド・オプション、および機械処理向けに明文化した出力形式。 +- 文書化した設定キー、環境変数、インポート/エクスポート形式。 +- 公開した連携アダプタ・システム拡張のインターフェース。 + +内部関数、DB の内部テーブル構造、非公開エンドポイント、HTML/CSS の内部構造は +安定 API としない。ただし DB・ファイル正本の移行が必要な場合は必ず移行手順と +バックアップ条件を記載し、ダウングレード可能とは仮定しない。 + +## 番号の更新 + +| 変更 | 1.0.0 以降 | 初期開発期間 0.y.z の運用 | +| --- | --- | --- | +| 後方互換な不具合修正 | PATCH を増やす | PATCH を増やす | +| 後方互換な機能追加・公開 API の非推奨化 | MINOR を増やし PATCH を 0 に戻す | MINOR を増やし PATCH を 0 に戻す | +| 公開インターフェースの非互換変更 | MAJOR を増やし MINOR/PATCH を 0 に戻す | MINOR を増やし非互換点・移行方法を明記 | + +0.x は SemVer 上の初期開発期間であり、公開 API の安定性はまだ保証しない。 +1.0.0 は上記公開契約を安定化させた時点で明示的に採番する。 +CI はバージョンを自動で繰り上げない。変更の意味を確認してリリース担当者が選ぶ。 + +`0.2.0-rc.1` 等のプレリリースを認める。数値識別子の先頭ゼロは禁止する。 +ビルドメタデータ `+build.001` は認めるが、バージョンの優先順位には影響しない。 +Gitea のコンテナタグは大文字小文字を区別しないため、**配布タグの識別子は小文字に限定**する。 +これは配布側の命名制限であり、SemVer 自体では大文字も有効。 + +## Git とコンテナタグの対応 + +| Git | コンテナタグ | +| --- | --- | +| 通常の main コミット | `sha-<40桁コミットID>` | +| `v0.1.0` | `v0.1.0` | +| `v0.2.0-rc.1` | `v0.2.0-rc.1` | +| `v0.2.0+build.001` | `v0.2.0_build.001` | + +Docker タグには `+` を使えないため `_` へ置換する。SemVer では `_` が使えないので +この変換は衝突しない。コンテナタグの 128 文字制限を超えるリリース名は拒否する。 +`latest`、`v0`、`v0.1` 等の可変エイリアスは自動更新しない。 + +## リリース手順 + +1. main の Build and publish container images が成功したコミットを選ぶ。 +2. 差分・互換性・移行要否を確認し、そのコミットに注釈付き Git タグを付けて push。 +3. Release container images が、そのコミットの SHA タグを digest に解決し、 + 3 イメージの revision ラベルと既存リリースタグを確認して同名タグへ昇格する。 +4. ワークフロー全体の成功と、ログに記録された 3 つの digest を確認して利用する。 + +```bash +# リリース対象のビルド成功済みコミットを明示する。以下は例。 +git tag -a v0.1.0 <成功済みコミットID> -m "PagesWiki 0.1.0" +git push origin refs/tags/v0.1.0 +``` + +昇格では再ビルドもレイヤーのダウンロードも行わず、元の manifest digest を維持する。 +イメージのラベルを後付けで書き換えることもしない(digest が変わるため)。 +元の `org.opencontainers.image.revision` が Git タグのコミットと一致することを確認する。 +ソースイメージが欠けていれば停止する。自動でビルドへフォールバックしない。 + +公開済み Git タグの付け替えや、異なる digest によるリリースタグの上書きを禁止する。 +内容を変更する場合は新しいバージョンを発行する。同じ digest の再実行だけは許可する。 +3 イメージの更新は原子的ではない。途中失敗時は同じタグのジョブを再実行し、 +すでに正しい digest を指しているものはスキップして残りを処理する。 + +registry の比較・更新は単一トランザクションではないため、リリースは同一 runner で +直列実行し、別クライアントで同じタグを更新しない。管理者は Git の `v*` 保護と +レジストリ側で利用可能なタグ保護も検討する。CI の検査は権限管理の代替ではない。 +公開後の SHA タグを再ビルドで更新しても、リリースタグを追従更新してはならない。 + +本番への自動デプロイはしない。`PAGESWIKI_IMAGE_TAG=v0.1.0` のように指定して +[レジストリ用 Compose](gitea-images.md) を利用する。 diff --git a/tools/ci/release-images.mjs b/tools/ci/release-images.mjs new file mode 100644 index 0000000..cbfff71 --- /dev/null +++ b/tools/ci/release-images.mjs @@ -0,0 +1,99 @@ +import {spawnSync} from 'node:child_process'; +import {pathToFileURL} from 'node:url'; + +export const images = ['pageswiki-app', 'pageswiki-adaptor-gateway', 'pageswiki-excalidraw-viewer']; +// SemVer 2.0.0: numeric prerelease identifiers cannot have leading zeroes. +const number = '(0|[1-9][0-9]*)'; +const identifier = '(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)'; +const semver = new RegExp(`^${number}\\.${number}\\.${number}(?:-${identifier}(?:\\.${identifier})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$`); + +export function imageTag(ref) { + if (!ref.startsWith('refs/tags/v')) throw new Error('Release must run on a refs/tags/v… Git tag'); + const tag = ref.slice('refs/tags/'.length); + if (!semver.test(tag.slice(1)) || /\s/.test(tag)) throw new Error(`Invalid SemVer 2.0.0 tag: ${tag}`); + // Gitea stores container tags case-insensitively; reject instead of silently + // collapsing distinct SemVer identifiers. '+' is not a Docker tag character. + if (/[A-Z]/.test(tag)) throw new Error('Release identifiers must be lowercase for the Gitea registry'); + const result = tag.replace('+', '_'); + if (result.length > 128) throw new Error('Container release tag exceeds 128 characters'); + return result; +} + +function run(command, args) { + const result = spawnSync(command, args, {encoding: 'utf8', timeout: 120000, maxBuffer: 4 * 1024 * 1024}); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`${command} failed: ${result.stderr.trim()}`); + return result.stdout.trim(); +} + +export function dockerClient(execute = run) { + function inspect(ref, field, optional = false) { + try { + return JSON.parse(execute('docker', ['buildx', 'imagetools', 'inspect', '--format', `{{json .${field}}}`, ref])); + } catch (error) { + // Only an explicit missing manifest is absence, never auth/TLS/timeouts. + if (optional && (error.message.endsWith(`ERROR: ${ref}: not found`) || /\bmanifest unknown\b/i.test(error.message))) return null; + throw error; + } + } + return { + digest(ref, optional = false) { + const manifest = inspect(ref, 'Manifest', optional); + if (manifest === null) return null; + if (!/^sha256:[0-9a-f]{64}$/.test(manifest.digest)) throw new Error(`Invalid registry digest: ${ref}`); + return manifest.digest; + }, + revision(ref) { + const config = inspect(ref, 'Image'); + if (config.os !== 'linux' || config.architecture !== 'amd64') throw new Error(`Expected linux/amd64 source: ${ref}`); + return config.config?.Labels?.['org.opencontainers.image.revision']; + }, + copy(source, destination) { + execute('docker', ['buildx', 'imagetools', 'create', '--prefer-index=false', '--tag', destination, source]); + }, + }; +} + +export function promote({ref, revision, prefix}, client = dockerClient(), log = console.log) { + const tag = imageTag(ref); + if (!/^[0-9a-f]{40}$/.test(revision)) throw new Error('Expected the release commit SHA'); + if (!/^[a-z0-9][a-z0-9.-]*(?::[0-9]+)?\/[a-z0-9][a-z0-9_-]*$/.test(prefix)) throw new Error('Invalid registry/owner prefix'); + // Resolve every source to a digest and check every destination before writes. + const plan = images.map(image => { + const repository = `${prefix}/${image}`; + const digest = client.digest(`${repository}:sha-${revision}`); + const source = `${repository}@${digest}`; + if (client.revision(source) !== revision) throw new Error(`Image revision does not match Git tag: ${image}`); + const destination = `${repository}:${tag}`; + const existing = client.digest(destination, true); + if (existing !== null && existing !== digest) throw new Error(`Refusing to overwrite released image: ${destination}`); + return {source, destination, digest}; + }); + for (const item of plan) { + // Recheck before writing. Registry tag protection/serialized releases are + // still required: the registry does not offer a portable compare-and-swap. + const existing = client.digest(item.destination, true); + if (existing !== null && existing !== item.digest) throw new Error(`Release changed concurrently: ${item.destination}`); + if (existing === null) client.copy(item.source, item.destination); + if (client.digest(item.destination) !== item.digest) throw new Error(`Promoted digest mismatch: ${item.destination}`); + log(`${item.destination} -> ${item.digest}`); + } + return plan; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + const ref = process.env.RELEASE_REF || ''; + const tag = imageTag(ref); + if (process.argv[2] === '--validate') { + console.log(`Release ${ref.slice('refs/tags/'.length)}; container tag ${tag}`); + } else if (process.argv.length !== 2) { + throw new Error('Usage: node tools/ci/release-images.mjs [--validate]'); + } else { + promote({ref, revision: run('git', ['rev-parse', 'HEAD^{commit}']), prefix: `${process.env.REGISTRY}/${process.env.IMAGE_OWNER}`}); + } + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} diff --git a/tools/ci/release-images.test.mjs b/tools/ci/release-images.test.mjs new file mode 100644 index 0000000..66fabb0 --- /dev/null +++ b/tools/ci/release-images.test.mjs @@ -0,0 +1,116 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {dockerClient, imageTag, images, promote} from './release-images.mjs'; + +test('SemVer release and prerelease tags', () => { + for (const version of ['0.1.0', '1.0.0', '1.2.3-rc.1', '1.0.0-0', '1.0.0-01a', '1.0.0-x-y-z.--', '12345678901234567890.0.1']) { + assert.equal(imageTag(`refs/tags/v${version}`), `v${version}`); + } + assert.equal(imageTag('refs/tags/v1.2.3-rc.1+build.001'), 'v1.2.3-rc.1_build.001'); +}); + +test('reject malformed SemVer and ambiguous registry tags', () => { + for (const version of ['1', '1.2', '01.2.3', '1.02.3', '1.2.03', '1.2.3-01', '1.2.3-a.01', '1.2.3-', '1.2.3-a..b', '1.2.3+', '1.2.3+foo..bar', '1.2.3+foo+bar', '1.2.3_bad', '1.2.3\n', '1.2.3-RC.1', '1.2.3+BUILD', '1.2.3-'+ 'a'.repeat(128)]) { + assert.throws(() => imageTag(`refs/tags/v${version}`)); + } + assert.throws(() => imageTag('refs/heads/v1.2.3')); + assert.throws(() => imageTag('refs/tags/1.2.3')); +}); + +const revision = 'a'.repeat(40); +const options = {ref: 'refs/tags/v0.1.0', revision, prefix: 'registry.example.test/anya'}; +function registry() { + const entries = new Map(images.map((image, index) => [`${options.prefix}/${image}:sha-${revision}`, `sha256:${String(index + 1).repeat(64)}`])); + const copies = []; + const client = { + digest(ref, optional = false) { + if (entries.has(ref)) return entries.get(ref); + if (optional) return null; + throw new Error('source missing'); + }, + revision: () => revision, + copy(source, destination) { + copies.push({source, destination}); + entries.set(destination, source.split('@')[1]); + }, + }; + return {client, entries, copies}; +} + +test('promotes three sources by digest and retry does not rewrite', () => { + const {client, copies} = registry(); + const plan = promote(options, client, () => {}); + assert.equal(copies.length, 3); + for (const item of plan) assert.ok(item.source.endsWith(`@${item.digest}`)); + promote(options, client, () => {}); + assert.equal(copies.length, 3); +}); + +test('missing source, wrong revision or existing release conflict prevents all writes', () => { + for (const failure of ['missing', 'revision', 'conflict']) { + const {client, entries, copies} = registry(); + const last = `${options.prefix}/${images[2]}`; + if (failure === 'missing') entries.delete(`${last}:sha-${revision}`); + if (failure === 'revision') client.revision = () => 'b'.repeat(40); + if (failure === 'conflict') entries.set(`${last}:v0.1.0`, `sha256:${'f'.repeat(64)}`); + assert.throws(() => promote(options, client)); + assert.equal(copies.length, 0); + } +}); + +test('partial promotion is safely resumable', () => { + const {client, copies} = registry(); + const copy = client.copy; + client.copy = (source, destination) => { + if (copies.length === 1) throw new Error('registry unavailable'); + copy(source, destination); + }; + assert.throws(() => promote(options, client, () => {}), /unavailable/); + client.copy = copy; + promote(options, client, () => {}); + assert.equal(copies.length, 3); +}); + +test('destination digest mismatch and concurrent overwrite are failures', () => { + const {client} = registry(); + client.copy = () => {}; + assert.throws(() => promote(options, client, () => {})); + const other = registry(); + const get = other.client.digest; + let reads = 0; + other.client.digest = (ref, optional) => { + if (ref.endsWith(':v0.1.0') && ++reads > 3) return `sha256:${'f'.repeat(64)}`; + return get(ref, optional); + }; + assert.throws(() => promote(options, other.client), /concurrently/); + assert.equal(other.copies.length, 0); +}); + +test('inspect distinguishes missing manifests from authorization and network errors', () => { + const ref = 'registry.example.test/anya/image:v0.1.0'; + for (const message of [`docker failed: ERROR: ${ref}: not found`, 'docker failed: manifest unknown']) { + const client = dockerClient(() => { throw new Error(message); }); + assert.equal(client.digest(ref, true), null); + assert.throws(() => client.digest(ref)); + } + for (const message of ['unauthorized', 'TLS handshake timeout', 'no such host', '404 page not found']) { + const client = dockerClient(() => { throw new Error(message); }); + assert.throws(() => client.digest(ref, true)); + } +}); + +test('Docker adapter preserves manifest format and validates metadata', () => { + const calls = []; + const client = dockerClient((command, args) => { + calls.push([command, ...args]); + if (args.includes('{{json .Manifest}}')) return JSON.stringify({digest: `sha256:${'a'.repeat(64)}`}); + if (args.includes('{{json .Image}}')) return JSON.stringify({os: 'linux', architecture: 'amd64', config: {Labels: {'org.opencontainers.image.revision': revision}}}); + return ''; + }); + assert.equal(client.revision('source'), revision); + assert.equal(client.digest('source'), `sha256:${'a'.repeat(64)}`); + client.copy('source@sha256:abc', 'destination:v0.1.0'); + assert.deepEqual(calls.at(-1), ['docker', 'buildx', 'imagetools', 'create', '--prefer-index=false', '--tag', 'destination:v0.1.0', 'source@sha256:abc']); + assert.throws(() => dockerClient(() => '{}').digest('source'), /Invalid registry digest/); + assert.throws(() => dockerClient(() => '{}').revision('source'), /linux\/amd64/); +});