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
106 changes: 106 additions & 0 deletions .github/workflows/data-update.yml
Original file line number Diff line number Diff line change
@@ -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"
1 change: 1 addition & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ on:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:

permissions:
contents: read
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)。
44 changes: 44 additions & 0 deletions data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
108 changes: 108 additions & 0 deletions scripts/check-data-update.mjs
Original file line number Diff line number Diff line change
@@ -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;
});
}
Loading
Loading