From aca11415683955f09f412abcb0cf81ad5f36393f Mon Sep 17 00:00:00 2001 From: Yourtion Guo Date: Sun, 25 Oct 2026 05:21:30 +0000 Subject: [PATCH] ci: propose validated upstream data updates on a daily schedule --- .github/workflows/data-update.yml | 106 +++++++++++++++++++++++++++++ .github/workflows/test.yml | 1 + README.md | 2 + data/README.md | 44 ++++++++++++ docs/development.md | 6 ++ scripts/check-data-update.mjs | 108 ++++++++++++++++++++++++++++++ scripts/update-data.test.mjs | 104 ++++++++++++++++++++++++++++ 7 files changed, 371 insertions(+) create mode 100644 .github/workflows/data-update.yml create mode 100644 scripts/check-data-update.mjs diff --git a/.github/workflows/data-update.yml b/.github/workflows/data-update.yml new file mode 100644 index 0000000..79a2400 --- /dev/null +++ b/.github/workflows/data-update.yml @@ -0,0 +1,106 @@ +name: Data updates + +on: + schedule: + # Daily at 03:17 UTC (11:17 Asia/Shanghai), away from the hourly rush. + - cron: "17 3 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: bundled-data-update + cancel-in-progress: false + +jobs: + update: + # Scheduled writes belong only to the upstream repository and default branch. + if: github.repository == 'yourtion/node-ip2region' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: write + pull-requests: write + actions: write + env: + DATA_BRANCH: automation/update-ip-data + steps: + - uses: actions/checkout@v4 + with: + ref: main + persist-credentials: false + - uses: pnpm/action-setup@v4 + with: + version: 9.15.9 + - uses: actions/setup-node@v4 + with: + node-version: 24.x + cache: pnpm + - run: pnpm install --frozen-lockfile --ignore-scripts + - run: npm run build + - name: Resolve upstream commit and pending snapshot + id: resolve + env: + GH_TOKEN: ${{ github.token }} + run: | + revision=$(gh api repos/lionsoul2014/ip2region/commits/HEAD --jq .sha) + [[ "$revision" =~ ^[0-9a-f]{40}$ ]] + echo "revision=$revision" >> "$GITHUB_OUTPUT" + head=$(gh pr list --repo "$GITHUB_REPOSITORY" --base main --head "$DATA_BRANCH" --state open --json headRefOid,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].headRefOid // empty') + if [[ -n "$head" ]]; then + [[ "$head" =~ ^[0-9a-f]{40}$ ]] + gh api "repos/$GITHUB_REPOSITORY/contents/data/manifest.json?ref=$head" --jq .content | + base64 --decode > "$RUNNER_TEMP/pending-manifest.json" + fi + - name: Stage, compare, validate and apply changed snapshots + id: candidate + env: + UPSTREAM_REVISION: ${{ steps.resolve.outputs.revision }} + run: | + args=() + if [[ -f "$RUNNER_TEMP/pending-manifest.json" ]]; then + args+=(--pending "$RUNNER_TEMP/pending-manifest.json") + fi + node scripts/check-data-update.mjs --revision "$UPSTREAM_REVISION" \ + --stage "$RUNNER_TEMP/ip2region-candidate" --body "$RUNNER_TEMP/data-pr.md" "${args[@]}" + - name: Retain the validation report + if: always() && steps.candidate.outcome == 'success' + uses: actions/upload-artifact@v4 + with: + name: data-update-report + path: | + ${{ runner.temp }}/ip2region-candidate/report.json + ${{ runner.temp }}/ip2region-candidate/report.sha256 + retention-days: 30 + if-no-files-found: error + - name: Check quality and the updated package + if: steps.candidate.outputs.status == 'updated' + run: | + npm run check + npm run test:package + - name: Create or update the data PR + if: steps.candidate.outputs.status != 'pending' + id: pr + uses: peter-evans/create-pull-request@22a9089034f40e5a961c8808d113e2c98fb63676 # v7 + with: + token: ${{ github.token }} + branch: ${{ env.DATA_BRANCH }} + base: main + title: "chore(data): update bundled ip2region snapshots" + commit-message: "chore(data): update bundled ip2region snapshots" + body-path: ${{ runner.temp }}/data-pr.md + add-paths: | + data/ip2region_v4.xdb + data/ip2region_v6.xdb + data/LICENSE.ip2region.md + data/manifest.json + data/README.md + src/bundled.ts + - name: Run cross-platform CI on the data PR + # GITHUB_TOKEN PR/push events do not start CI; workflow_dispatch does. + # Also retry this for an unchanged pending PR if a previous dispatch failed. + if: steps.pr.outputs.pull-request-number != '' || steps.candidate.outputs.status == 'pending' + env: + GH_TOKEN: ${{ github.token }} + run: gh workflow run test.yml --repo "$GITHUB_REPOSITORY" --ref "$DATA_BRANCH" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 768389f..32bdf56 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -5,6 +5,7 @@ on: branches: [main] pull_request: branches: [main] + workflow_dispatch: permissions: contents: read diff --git a/README.md b/README.md index 17a1e7d..d043c71 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,8 @@ settled 版本保留每项成功或失败的结果并继续查询。并发上限 仓库提供显式的 `data:stage`、`data:validate`、`data:apply` 命令,用于固定 upstream revision、 暂存候选快照、校验两份文件并生成变化报告,再更新数据与元信息。 +GitHub Actions 的 `Data updates` 每天 UTC 03:17(北京时间 11:17)检查上游,内容变化且校验通过后 +自动创建或更新数据 PR,也可手动运行。PR 合并和 npm 发布仍由维护者决定。 这是仓库维护工具,不会在导入、安装或查询时联网;操作与失败恢复说明见[数据维护](data/README.md)。 代码采用 [MIT](LICENSE) 许可;内置数据许可见[数据来源](data/README.md)。 diff --git a/data/README.md b/data/README.md index 03f0ed2..5911f5f 100644 --- a/data/README.md +++ b/data/README.md @@ -39,6 +39,50 @@ recording new digests and rerunning reference and native-runtime validation. ## Stage, validate and apply updates +### Scheduled pull requests + +[Data updates](../.github/workflows/data-update.yml) checks the upstream default +branch daily at **03:17 UTC** (11:17 Asia/Shanghai); GitHub may delay scheduled runs. +It can also be run from Actions → Data updates → Run workflow on `main`. +The scheduled workflow starts operating after it is merged into the default branch. +This repository's development/release branch is `main`; set **Settings → General → +Default branch** to `main` before enabling the schedule. A workflow present only +on `main` cannot run on a schedule while `master` remains the default branch. + +Each run resolves a full upstream commit SHA, then uses the same staging and +validation pipeline described below. Only changes to XDB bytes or the license +create an update: upstream code-only commits and retrieval dates do not create PRs. +The fixed `automation/update-ip-data` branch keeps a single open PR. An identical +pending snapshot is left intact, including its first retrieval date, even if the +upstream commit advances. A newer snapshot updates that PR; if upstream matches +`main` again, the obsolete PR is closed by the PR action. This branch is reserved +for the automation; make manual changes on a separate branch. +Closing an unmerged data PR does not blacklist that snapshot: the next run can +recreate it. To pause proposals, disable Data updates from the Actions menu. + +Before creating/updating a PR, the job reruns validation during apply, runs +`npm run check` and `npm run test:package`, and limits the commit to both XDBs, +license, manifest, generated module and this file's metadata. The PR describes +range changes and license changes. Each successful check retains `report.json` +and `report.sha256` as a 30-day Actions artifact. Download, schema, license or test +failures fail the run without publishing a new candidate PR. + +The workflow uses only `GITHUB_TOKEN`; no PAT or npm credential is needed. Enable +**Settings → Actions → General → Workflow permissions → Allow GitHub Actions to +create and approve pull requests**. Repository/organization policies must permit +the declared `contents: write`, `pull-requests: write` and `actions: write` +permissions. No approval or auto-merge is performed by this workflow. + +PRs created with `GITHUB_TOKEN` do not trigger ordinary `pull_request`/`push` +workflows. The updater explicitly dispatches **Native runtime CI** (`test.yml`) +on the PR branch to run the full Node/Bun/Deno and OS matrix, including on a +subsequent run with the same pending candidate so interrupted dispatches recover. +Check that CI run on the PR's head commit before merging. After merging data, +publish a version through the normal [release process](../docs/releasing.md); +the scheduled job does not merge PRs, tag commits or publish packages. + +### Manual maintenance + `data/manifest.json` is the maintainer source of truth for the paired snapshots, license digest, declared upstream revision and retrieval date. The explicit updater regenerates `src/bundled.ts` and the marked metadata section above. diff --git a/docs/development.md b/docs/development.md index 666dd99..7ae71b1 100644 --- a/docs/development.md +++ b/docs/development.md @@ -59,6 +59,12 @@ See [data maintenance](../data/README.md) for commands and recovery limits. Network staging needs `curl`; offline staging and tests do not. Formatting uses the repository's existing development formatter. +The scheduled Data updates workflow wraps the same updater with content-based +change detection and one reusable PR branch. See [scheduled pull requests](../data/README.md#scheduled-pull-requests) +for timing, GitHub permissions, CI dispatch and manual invocation. Its orchestration +tests run offline with the update-tool tests, including unchanged data, pending +candidates, license-only updates and failures that preserve the checkout. + `npm test` includes offline update-tool tests in temporary repositories: invalid files, provenance, changed stages/baselines, locks, and replacement-failure rollback. Native composition and async batch tests are shared across all three runtime diff --git a/scripts/check-data-update.mjs b/scripts/check-data-update.mjs new file mode 100644 index 0000000..6e28690 --- /dev/null +++ b/scripts/check-data-update.mjs @@ -0,0 +1,108 @@ +import assert from "node:assert/strict"; +import { appendFileSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { isDeepStrictEqual, parseArgs } from "node:util"; +import { applyStage, stageData } from "./update-data.mjs"; + +const rootDirectory = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const repository = "lionsoul2014/ip2region"; + +function snapshot(manifest) { + assert.equal(manifest.version, 1, "Unsupported data manifest"); + assert.equal(manifest.upstream.repository, repository); + assert.match(manifest.upstream.revision, /^[0-9a-f]{40}$/); + assert.equal(manifest.upstream.source, "upstream-download"); + assert.equal(manifest.files.length, 2); + for (const [i, family] of [4, 6].entries()) { + const file = manifest.files[i]; + assert.equal(file.family, family); + assert.equal(file.file, `ip2region_v${family}.xdb`); + assert.match(file.sha256, /^[0-9a-f]{64}$/); + assert.ok(Number.isSafeInteger(file.bytes) && file.bytes > 0); + } + assert.equal(manifest.license.file, "LICENSE.ip2region.md"); + assert.match(manifest.license.sha256, /^[0-9a-f]{64}$/); + return { + fields: manifest.fields, + license: manifest.license, + files: manifest.files.map(({ family, file, bytes, sha256 }) => ({ family, file, bytes, sha256 })), + }; +} + +// A new repository commit or retrieval date is not a new data snapshot. +export function sameSnapshot(left, right) { + return isDeepStrictEqual(snapshot(left), snapshot(right)); +} + +export function renderUpdateBody(before, report) { + const after = report.manifest; + return `Update the bundled IPv4/IPv6 snapshots from a pinned upstream commit. + +Upstream: [${before.upstream.revision} → ${after.upstream.revision}](https://github.com/${repository}/compare/${before.upstream.revision}...${after.upstream.revision}). + +| Family | Bytes | Header build time (UTC) | Added ranges | Removed ranges | Changed records | Reference checks | +| --- | ---: | --- | ---: | ---: | ---: | ---: | +${report.checks.map((check) => `| IPv${check.family} | ${check.bytes} | ${check.builtAt ?? "unknown"} | ${check.changes.addedRanges} | ${check.changes.removedRanges} | ${check.changes.changedRecords} | ${check.referenceChecks} |`).join("\n")} + +| File | SHA-256 | +| --- | --- | +${after.files.map((file) => `| ${file.file} | \`${file.sha256}\` |`).join("\n")} +| ${after.license.file} | \`${after.license.sha256}\` | + +License content changed: **${report.licenseChanged ? "yes — review the license diff" : "no"}**. + +The updater checked both complete indexes, all referenced UTF-8/five-column records, +and boundary queries against the independent upstream reader. Apply repeated the +checks against the current checkout. Quality and real-package tests pass before +this PR is created; Native runtime CI is dispatched on its branch after creation. +The Data updates run retains the full report as an artifact. + +Review the data/schema and license changes before merging. Range splits count as +added/removed ranges; header build times and passing checks do not establish +geographic accuracy. This PR does not publish an npm version. +`; +} + +export async function prepareDataUpdate({ root = rootDirectory, stage, revision, pending, fetchFile }) { + const before = JSON.parse(readFileSync(join(root, "data/manifest.json"), "utf8")); + // Automatic updates operate only on the repository's authenticated upstream snapshots. + snapshot(before); + if (pending) snapshot(pending); + const report = await stageData({ root, stage, revision, fetchFile }); + if (sameSnapshot(before, report.manifest)) { + return { status: "unchanged", report, body: "The bundled data and license already match upstream.\n" }; + } + if (pending && sameSnapshot(pending, report.manifest)) { + // Preserve the first retrieval date and avoid daily commits to the same pending PR. + return { status: "pending", report, body: "The existing data PR already contains this snapshot.\n" }; + } + await applyStage({ root, stage }); + return { status: "updated", report, body: renderUpdateBody(before, report) }; +} + +async function main() { + const { values } = parseArgs({ + options: { + revision: { type: "string" }, + stage: { type: "string" }, + body: { type: "string" }, + pending: { type: "string" }, + }, + }); + if (!values.body) throw new Error("--body is required"); + const pending = values.pending ? JSON.parse(readFileSync(values.pending, "utf8")) : undefined; + const result = await prepareDataUpdate({ ...values, pending }); + writeFileSync(values.body, result.body); + if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `status=${result.status}\n`); + if (process.env.GITHUB_STEP_SUMMARY) + appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Data check: **${result.status}**\n\n${result.body}`); + console.log(`Data check: ${result.status}`); +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + main().catch((error) => { + console.error(error.message); + process.exitCode = 1; + }); +} diff --git a/scripts/update-data.test.mjs b/scripts/update-data.test.mjs index df59d8e..cf94769 100644 --- a/scripts/update-data.test.mjs +++ b/scripts/update-data.test.mjs @@ -17,6 +17,7 @@ import { test } from "node:test"; import { format } from "oxfmt"; import { xdbFixture } from "../tests/fixtures.mjs"; import { applyStage, inspectDatabase, renderBundled, renderReadme, stageData, validateStage } from "./update-data.mjs"; +import { prepareDataUpdate } from "./check-data-update.mjs"; const revision = "a".repeat(40); const fields = ["country_name", "region_name", "city_name", "isp", "country_code"]; @@ -72,6 +73,109 @@ function fixture(t) { const snapshot = (root) => Object.fromEntries(names.map((name) => [name, hash(readFileSync(join(root, name)))])); +function automatic(options) { + return { + ...options, + revision: "b".repeat(40), + fetchFile: async (url) => + readFileSync(join(options.from, url.endsWith("LICENSE.md") ? "LICENSE.ip2region.md" : url.split("/").at(-1))), + }; +} + +test("automatic checks ignore upstream code-only commits and retrieval dates", async (t) => { + const options = fixture(t); + const before = snapshot(options.root); + const result = await prepareDataUpdate(automatic(options)); + assert.equal(result.status, "unchanged"); + assert.deepEqual(snapshot(options.root), before); + assert.equal(result.report.manifest.upstream.revision, "b".repeat(40)); + assert.ok(existsSync(join(options.stage, "report.json"))); +}); + +test("automatic changes update both snapshot metadata and the review report, then become a no-op", async (t) => { + const options = fixture(t); + writeFileSync( + join(options.from, "ip2region_v6.xdb"), + xdbFixture({ family: 6, exclusive: false, region: "New|Area|City|ISP|NX" }) + ); + const result = await prepareDataUpdate(automatic(options)); + assert.equal(result.status, "updated"); + assert.deepEqual(JSON.parse(readFileSync(join(options.root, "data/manifest.json"))), result.report.manifest); + assert.ok(result.report.checks[1].changes.changedRecords > 0); + assert.match(result.body, /IPv4.*\n.*IPv6/); + assert.match(result.body, /License content changed: \*\*no\*\*/); + assert.ok(result.body.includes(result.report.manifest.files[1].sha256)); + const before = snapshot(options.root); + const repeated = await prepareDataUpdate({ ...automatic(options), stage: options.stage + "-repeat" }); + assert.equal(repeated.status, "unchanged"); + assert.deepEqual(snapshot(options.root), before); +}); + +test("an identical pending snapshot preserves its existing PR even when the upstream SHA advances", async (t) => { + const options = fixture(t); + writeFileSync( + join(options.from, "ip2region_v4.xdb"), + xdbFixture({ exclusive: false, region: "New|Area|City|ISP|NX" }) + ); + const pending = (await stageData({ ...automatic(options), from: undefined, stage: options.stage + "-pending" })) + .manifest; + const before = snapshot(options.root); + const result = await prepareDataUpdate({ ...automatic(options), revision: "c".repeat(40), pending }); + assert.equal(result.status, "pending"); + assert.deepEqual(snapshot(options.root), before); +}); + +test("a newer snapshot replaces an older pending candidate", async (t) => { + const options = fixture(t); + const pending = JSON.parse(readFileSync(join(options.root, "data/manifest.json"))); + writeFileSync( + join(options.from, "ip2region_v4.xdb"), + xdbFixture({ exclusive: false, region: "New|Area|City|ISP|NX" }) + ); + const result = await prepareDataUpdate({ ...automatic(options), pending }); + assert.equal(result.status, "updated"); + assert.notEqual(result.report.manifest.files[0].sha256, pending.files[0].sha256); +}); + +test("license-only updates produce a PR and unsupported licenses fail without changing the checkout", async (t) => { + const options = fixture(t); + writeFileSync( + join(options.from, "LICENSE.ip2region.md"), + Buffer.concat([license, Buffer.from("\nCopyright update\n")]) + ); + const result = await prepareDataUpdate(automatic(options)); + assert.equal(result.status, "updated"); + assert.match(result.body, /yes — review the license diff/); + const before = snapshot(options.root); + writeFileSync(join(options.from, "LICENSE.ip2region.md"), "An unsupported license"); + await assert.rejects( + () => prepareDataUpdate({ ...automatic(options), stage: options.stage + "-invalid" }), + /Upstream license changed/ + ); + assert.deepEqual(snapshot(options.root), before); +}); + +test("automatic checks reject invalid candidates, download failures and unverified pending manifests", async (t) => { + const options = fixture(t); + const before = snapshot(options.root); + await assert.rejects( + () => + prepareDataUpdate({ + ...automatic(options), + fetchFile: async () => { + throw new Error("download failed"); + }, + }), + /download failed/ + ); + const pending = JSON.parse(readFileSync(join(options.root, "data/manifest.json"))); + pending.upstream.source = "local-files"; + await assert.rejects(() => prepareDataUpdate({ ...automatic(options), pending }), /upstream-download/); + writeFileSync(join(options.from, "ip2region_v6.xdb"), xdbFixture({ family: 6, region: "bad|schema" })); + await assert.rejects(() => prepareDataUpdate(automatic(options)), /five columns/); + assert.deepEqual(snapshot(options.root), before); +}); + test("local staging validates both families, records honest provenance and preserves installed files", async (t) => { const options = fixture(t); const before = snapshot(options.root);