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
3 changes: 1 addition & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ name: CI
on:
push:
pull_request:
# Dispatched by update-database.yml, whose GITHUB_TOKEN-created PRs do not
# trigger push or pull_request runs.
# Explicit CI gate for weekly database PRs whose automatic run can require approval.
workflow_dispatch:

jobs:
Expand Down
51 changes: 38 additions & 13 deletions .github/workflows/update-database.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,19 @@ on:
- cron: '0 6 * * 1'
workflow_dispatch:
inputs:
force_rebuild:
description: Rebuild even when both source TSV digests match the bundled manifest
required: false
default: false
type: boolean
allow_large_change:
description: Allow database size or range counts to change by more than 20%
required: false
default: false
type: boolean

# The PR is opened with GITHUB_TOKEN, which does not trigger ci.yml on its own,
# so this workflow dispatches CI on the PR head (workflow_dispatch is the one
# event GITHUB_TOKEN may trigger), waits for it, merges, and publishes the
# Token-created PR runs can require approval. Dispatch CI on the PR head
# explicitly, wait for that run, merge, and publish the
# merged database to the CDN. Every gate is machine-run; recovery from a bad
# publish is republishing the previous commit's pair (see CONTRIBUTING.md).
permissions:
Expand All @@ -31,9 +35,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v6

- name: Build CLI
run: swift build -c release

- name: Download latest TSVs (v4 + v6)
run: |
curl --fail --silent --show-error --location \
Expand All @@ -45,7 +46,28 @@ jobs:
gzip -dc /tmp/ip2asn-v4.tsv.gz > /tmp/ip2asn-v4.tsv
gzip -dc /tmp/ip2asn-v6.tsv.gz > /tmp/ip2asn-v6.tsv

- name: Compare normalized source bytes with bundled manifest
id: inputs
env:
FORCE_REBUILD: ${{ inputs.force_rebuild }}
run: |
v4=$(shasum -a 256 /tmp/ip2asn-v4.tsv | cut -d' ' -f1)
v6=$(shasum -a 256 /tmp/ip2asn-v6.tsv | cut -d' ' -f1)
manifest=Sources/SwiftIP2ASN/Resources/ip2asn.manifest.json
if [[ "$FORCE_REBUILD" != "true" ]] && jq -e --arg v4 "$v4" --arg v6 "$v6" \
'[.sources[].builderInput.sha256] == [$v4, $v6]' "$manifest" >/dev/null; then
echo "Both source TSVs match the bundled database."
echo "rebuild=false" >> "$GITHUB_OUTPUT"
else
echo "rebuild=true" >> "$GITHUB_OUTPUT"
fi

- name: Build CLI
if: steps.inputs.outputs.rebuild == 'true'
run: swift build -c release

- name: Build database and provenance manifest
if: steps.inputs.outputs.rebuild == 'true'
run: |
generated_at="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
.build/release/ip2asn build-ultra \
Expand All @@ -60,6 +82,7 @@ jobs:
Sources/SwiftIP2ASN/Resources/ip2asn.ultra

- name: Check artifact sanity thresholds
if: steps.inputs.outputs.rebuild == 'true'
env:
ALLOW_LARGE_CHANGE: ${{ github.event_name == 'workflow_dispatch' && inputs.allow_large_change }}
run: |
Expand Down Expand Up @@ -108,13 +131,15 @@ jobs:
else
OLD_SIZE=$(git show HEAD:"$database" | wc -c | tr -d ' ')
NEW_SIZE=$(wc -c < "$database" | tr -d ' ')
echo "changed=true" >> "$GITHUB_OUTPUT"
echo "old_size=$OLD_SIZE" >> "$GITHUB_OUTPUT"
echo "new_size=$NEW_SIZE" >> "$GITHUB_OUTPUT"
echo "output_sha=$(jq -r '.output.artifact.sha256' "$manifest")" >> "$GITHUB_OUTPUT"
echo "build_id=$(jq -r '.output.buildIdentifier' "$manifest")" >> "$GITHUB_OUTPUT"
echo "ipv4_count=$(jq -r '.output.ipv4RangeCount' "$manifest")" >> "$GITHUB_OUTPUT"
echo "ipv6_count=$(jq -r '.output.ipv6RangeCount' "$manifest")" >> "$GITHUB_OUTPUT"
{
echo "changed=true"
echo "old_size=$OLD_SIZE"
echo "new_size=$NEW_SIZE"
echo "output_sha=$(jq -r '.output.artifact.sha256' "$manifest")"
echo "build_id=$(jq -r '.output.buildIdentifier' "$manifest")"
echo "ipv4_count=$(jq -r '.output.ipv4RangeCount' "$manifest")"
echo "ipv6_count=$(jq -r '.output.ipv6RangeCount' "$manifest")"
} >> "$GITHUB_OUTPUT"
fi

- name: Run tests
Expand Down
26 changes: 25 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,25 @@

All notable changes to this project will be documented in this file.

## [Unreleased]
## [0.6.0] - 2026-11-22

### Added
- `ip2asn build-ultra` emits a sorted JSON report with input and skipped-row
counts, IPv4 and IPv6 range counts, metadata, and the compressed file’s SHA-256.
- `SourceOracleTests`: checks the first and last address of every IPv4 and
IPv6 source row against the bundled database, when the manifest's exact
builder inputs are available (`IP2ASN_SOURCE_DIR`). The update workflow
requires it to run.

### Changed
- The ULT2 builder streams UTF-8 TSV rows and hashes manifest inputs in chunks.
It still sorts ranges in memory. Blank lines and ASN 0 rows are counted and
skipped. Previously ignored malformed rows now fail the build with a path,
line number, and reason. Each input row can contain up to 1 MiB.
- The weekly workflow skips rebuilding when both normalized source digests
match the bundled manifest. Maintainers can request a rebuild manually.
- The bundled database was generated November 16, 2026. On November 21,
both upstream TSV digests and the hosted artifact matched the bundled manifest.
- The weekly database update now runs CI on its pull request, merges it when
CI passes, and publishes the merged database to the CDN without a manual
step. Publishing lives in `publish-database.yml`, which can also be
Expand All @@ -21,6 +31,20 @@ All notable changes to this project will be documented in this file.
failed upload could pass, because only the served pair's internal
consistency was checked.

### Fixed
- Remote downloads and conditional refreshes bypass URLSession’s local HTTP
cache. The library uses its validated database on disk and sends its own
validators to the CDN. This fixed a warm-cache live refresh returning HTTP 404.
- The ULT2 builder rejects invalid IPv4 octets, malformed ASNs, reversed
ranges, and overlapping routed ranges before replacing the output. Supplying
neither address family throws a recoverable error.
- ULT2 loading retries when a highly compressible payload fills its decode
buffer, so valid names and metadata survive decoding.
- CIDR containment handles partial-byte prefixes such as IPv4 /25 and IPv6
/127. Invalid bit indices and out-of-range prefix lengths return false.
- Both CLI benchmark commands report invalid iteration counts and database
load errors with a diagnostic and a nonzero exit status.

### Removed
- `RandomIPVerificationTest`, which was unconditionally skipped and asserted
nothing.
Expand Down
15 changes: 13 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,19 @@ If you find a security vulnerability, please do not open a public issue. Instead

## Maintainer Database Publication

The weekly database update workflow is unattended end to end. It builds
The weekly workflow compares the SHA-256 of each downloaded, decompressed TSV
with the bundled manifest. If both match, it finishes without changing the
generation timestamp or publishing a new pair. Select `force_rebuild` on a
manual dispatch to rebuild the same data after a builder change.

When a rebuild is needed, the workflow builds
`ip2asn.ultra` and `ip2asn.manifest.json`, checks the ±20% size and range-count
thresholds, runs the full suite (including `SourceOracleTests`, which checks
every source row against the new database), and opens a pull request. It then
dispatches CI on that pull request, merges it when CI passes, and publishes the
merged pair to R2. Any failed gate stops the run before merge or publication
merged pair to R2. For a bot-created PR, GitHub can also show a separate
`pull_request` run that expires waiting for approval. The merge gate watches
the explicitly dispatched CI run on the PR head SHA. Any failed gate stops the run before merge or publication
and marks the workflow failed.

Publication runs in `publish-database.yml`, which uploads over R2's S3 API and
Expand All @@ -204,6 +211,10 @@ and `R2_ENDPOINT` (`https://<account-id>.r2.cloudflarestorage.com`). The
publish step fails until the CDN serves exactly the uploaded pair, allowing
for its 300-second cache.

If a database merge succeeds and publication fails, dispatch
`publish-database.yml` with `ref` set to that merge commit to retry the
same database and manifest. The weekly job skips unchanged source data.

To roll back a bad publication, dispatch `publish-database.yml` with `ref` set
to the last good commit, or publish that commit's pair from a maintainer
machine:
Expand Down
32 changes: 25 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Add the following to your `Package.swift`:

```swift
dependencies: [
.package(url: "https://github.com/Network-Weather/swift-ip2asn", from: "0.5.2")
.package(url: "https://github.com/Network-Weather/swift-ip2asn", from: "0.6.0")
]
```

Expand Down Expand Up @@ -129,7 +129,8 @@ if let result = db.lookupResult(address) {
Results do not claim IP geolocation, address ownership, or canonical CIDR
boundaries. The source stores exact inclusive ranges, but matched boundaries are
deferred until the library has a dedicated non-CIDR range type. Existing
tuple-returning `lookup` and `lookupV6` methods remain available during 0.x.
tuple-returning `lookup` and `lookupV6` methods remain supported through 1.0. For multiple inputs,
`addresses.map { db.lookupResult($0) }` preserves input order and misses.

The static `IP2ASN` API maintains one active remote configuration. The most
recent `remote(bundledPath:)` call selects the configuration used by `refresh()`,
Expand Down Expand Up @@ -225,6 +226,22 @@ produce the legacy ULT2 layout. Supplying the same normalized TSV inputs,
generation timestamp, and source identifier produces identical database bytes
and the same build identifier.

Starting in 0.6, `build-ultra` writes a JSON report to stdout. The
`rows.total` count includes blank and unrouted (ASN 0) rows. Subtract
`rows.blank` and `rows.unrouted` to get `database.totalRangeCount`.
`artifact.sha256` identifies the compressed output. The builder streams UTF-8
rows up to 1 MiB, accepts LF or CRLF, and sorts the accepted ranges in memory.
Malformed rows and overlapping routed ranges stop the build with a source
path and line number. Custom TSVs that previously relied on silent skips may
need correcting.

On a local arm64 macOS release build (Swift 6.4.2), building the November 16
dual-stack inputs with the manifest’s generation time and source took 1.94 s
and 134 MiB peak RSS, compared with 14.30 s and 193 MiB on the pre-0.6 main
branch (`26847e2`). Both produced the same compressed bytes. These are single
runs of `/usr/bin/time -l .build/release/ip2asn build-ultra` with the same
arguments, excluding manifest generation.

Automated database updates also write `ip2asn.manifest.json`. Its versioned JSON
schema records source URLs, SHA-256 digests of the downloaded archives and
decompressed builder inputs, the builder Git revision, output digest, database
Expand Down Expand Up @@ -337,7 +354,8 @@ All database types are `Sendable` and safe for concurrent access:

The library uses data from [iptoasn.com](https://iptoasn.com), which aggregates
BGP routing information from global route collectors. The repository checks for
updates weekly; reviewed database and manifest pairs are then published to
updates weekly. When either source TSV changes, the workflow builds, validates,
and publishes the new database and manifest to
`pkgs.networkweather.com`.

## Requirements
Expand Down Expand Up @@ -402,8 +420,8 @@ https://github.com/Network-Weather/swift-ip2asn

## Documents

- [ROADMAP.md](ROADMAP.md): product direction, principles, and the ordered milestones toward 1.0. (updated 2026-11-02; update when: a milestone ships or its scope changes)
- [CHANGELOG.md](CHANGELOG.md): user-visible changes in each tagged release. (updated 2026-11-02; update when: a release is tagged)
- [CONTRIBUTING.md](CONTRIBUTING.md): development setup, code and test style, PR process, and the automated database publication and rollback. (updated 2026-11-02; update when: the build, test, or publication procedure changes)
- [ROADMAP.md](ROADMAP.md): product direction, principles, and the ordered milestones toward 1.0. (updated 2026-11-21; update when: a milestone ships or its scope changes)
- [CHANGELOG.md](CHANGELOG.md): user-visible changes in each tagged release. (updated 2026-11-21; update when: a release is tagged)
- [CONTRIBUTING.md](CONTRIBUTING.md): development setup, code and test style, PR process, and the automated database publication and rollback. (updated 2026-11-21; update when: the build, test, or publication procedure changes)
- [CLAUDE.md](CLAUDE.md): build commands, module layout, formats, and coding patterns for agents working in this repo. (updated 2026-08-31; update when: a module, format, or build command is added or removed)
- [SwiftIP2ASN.docc/SwiftIP2ASN.md](Sources/SwiftIP2ASN/SwiftIP2ASN.docc/SwiftIP2ASN.md): DocC landing page for the library's API documentation. (updated 2026-08-31; update when: the public API surface changes)
- [SwiftIP2ASN.docc/SwiftIP2ASN.md](Sources/SwiftIP2ASN/SwiftIP2ASN.docc/SwiftIP2ASN.md): DocC landing page for the library's API documentation. (updated 2026-11-21; update when: the public API surface changes)
71 changes: 17 additions & 54 deletions ROADMAP.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
# SwiftIP2ASN Roadmap

Last reviewed: 2026-08-31
Last reviewed: 2026-11-22

This roadmap describes the intended direction of SwiftIP2ASN after the 0.5
provenance release. It is an ordered plan, not a calendar commitment. Minor
release numbers may change as work is scoped, but correctness and compatibility
work should land before feature or platform expansion.
SwiftIP2ASN 0.6.0 focuses on reproducible ULT2
builds, reliable remote refreshes, and correctness of the public address helpers.
See [CHANGELOG.md](CHANGELOG.md) for the release notes.

## Current Baseline

SwiftIP2ASN 0.5.2 provides:
SwiftIP2ASN 0.6.0 provides:

- offline IPv4 and IPv6 ASN lookups from an embedded database;
- the ULT2 ultra-compact database format and builder;
Expand All @@ -20,12 +19,11 @@ SwiftIP2ASN 0.5.2 provides:
and observable status;
- an `ip2asn` command-line tool for bundled lookups, artifact inspection and
validation, database builds, and benchmarks;
- weekly embedded-database update automation and reviewed R2 publication; and
- weekly embedded-database update automation and verified R2 publication; and
- SwiftPM support for current Apple platforms.

There is no committed feature backlog beyond this document. New work should be
opened as a GitHub issue and attached to the relevant milestone before
implementation begins.
New roadmap work should be opened as a GitHub issue and attached to the
relevant milestone before implementation begins.

## Product Direction

Expand All @@ -52,51 +50,16 @@ Roadmap decisions follow these principles:

## Delivery Sequence

`0.6 CLI and API completion → 0.7 Linux → 1.0 contract`
`0.7 Linux → 1.0 contract`

Items are ordered within each milestone. A milestone should satisfy its exit
criteria before work depending on it is considered complete: metadata builds on
the hardened parser and transport, typed results build on the metadata decision,
and Linux support follows the intended long-term API rather than porting symbols
that are about to be retired.
### Lookup contract established in 0.6

Reliability hardening and provenance work completed in the 0.4.x and 0.5 lines
is recorded in `CHANGELOG.md`. Active milestones below contain only remaining
work.

## Milestone 0.6 — Stabilize the Lookup API

Goal: provide an expressive result API while giving existing callers a clear
migration path toward 1.0.

### Typed results

`ASNLookupResult` and type-safe `IPAddress` inputs shipped in 0.5. The
tuple-returning `lookup` API remains available during 0.x because Swift cannot
overload a method only by return type. The 1.0 migration decision remains part
of this milestone.

### Address and batch APIs

- [ ] Add a batch lookup API only after measuring its benefit over a caller loop;
specify input-order preservation and miss representation.

### Builder and CLI usability

- [ ] Replace whole-file TSV loading with streaming parsing to bound peak memory
on large source files.
- [ ] Produce a build summary containing counts, skipped-row reasons, metadata,
and output digest.
- [ ] Make invalid arguments and malformed input return stable, actionable
errors rather than precondition failures.

### Exit criteria

- New applications can use a named, documented result type without tuples.
- Existing 0.4 lookup source continues to compile throughout the 0.6 line.
- All result fields have precise semantics backed by stored source data.
- The builder has bounded input-reading memory and reports rejected records.
- CLI validation can verify both embedded and downloaded production artifacts.
Use `lookupResult` for new code. Keep the named result and tuple methods under
their existing names through 1.0. There is no required migration in 0.6. For
multiple inputs, `addresses.map { db.lookupResult($0) }` preserves input order
and represents each miss with `nil`. A dedicated batch API stays in research
until a representative dual-stack benchmark demonstrates a benefit over this
caller loop.

## Milestone 0.7 — Support Server-Side Swift

Expand Down Expand Up @@ -136,7 +99,7 @@ command-line applications, not only Apple-platform apps.
Goal: publish a narrow, durable API and compatibility policy suitable for
long-term adoption.

- [ ] Finalize the typed lookup API and complete announced deprecations.
- [ ] Confirm the lookup compatibility policy with a clean external consumer.
- [ ] Decide whether the legacy compressed format stays supported, moves to a
separate product, or is removed. Record the decision in the migration
guide and changelog.
Expand Down
11 changes: 10 additions & 1 deletion Sources/IP2ASNDataPrep/DatabaseBuildManifest.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import CryptoKit
import Foundation
@_spi(IP2ASNDataPrep) import SwiftIP2ASN

Expand Down Expand Up @@ -113,7 +114,15 @@ public struct DatabaseBuildManifest: Codable, Equatable, Sendable {
}

private static func artifact(at url: URL) throws -> Artifact {
artifact(for: try Data(contentsOf: url))
let handle = try FileHandle(forReadingFrom: url)
defer { try? handle.close() }
var hash = SHA256()
var byteCount = 0
while let chunk = try handle.read(upToCount: 64 * 1024), !chunk.isEmpty {
hash.update(data: chunk)
byteCount += chunk.count
}
return Artifact(byteCount: byteCount, sha256: hash.finalize().map { String(format: "%02x", $0) }.joined())
}

private static func artifact(for data: Data) -> Artifact {
Expand Down
Loading
Loading