From fa76e28f3cddb510d1115aefd2e61de56df79e8d Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Sun, 22 Nov 2026 08:28:09 -0800 Subject: [PATCH] Release SwiftIP2ASN 0.6.0 --- .github/workflows/ci.yml | 3 +- .github/workflows/update-database.yml | 51 +++++-- CHANGELOG.md | 26 +++- CONTRIBUTING.md | 15 +- README.md | 32 ++++- ROADMAP.md | 71 +++------- .../DatabaseBuildManifest.swift | 11 +- Sources/IP2ASNDataPrep/TSVInput.swift | 50 +++++++ .../IP2ASNDataPrep/UltraCompactBuilder.swift | 134 +++++++++++------- Sources/SwiftIP2ASN/EmbeddedDatabase.swift | 6 +- Sources/SwiftIP2ASN/IPAddress.swift | 10 +- .../SwiftIP2ASN.docc/SwiftIP2ASN.md | 5 +- Sources/SwiftIP2ASN/UltraCompactFormat.swift | 37 +++-- Sources/ip2asn-tools/main.swift | 62 ++++---- .../DatabaseArtifactDiagnosticsTests.swift | 23 +++ .../EmbeddedDatabaseTests.swift | 6 + Tests/SwiftIP2ASNTests/IPAddressTests.swift | 17 +++ .../UltraCompactBuilderTests.swift | 49 +++++++ 18 files changed, 423 insertions(+), 185 deletions(-) create mode 100644 Sources/IP2ASNDataPrep/TSVInput.swift diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 32044ea..7b6c58e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: diff --git a/.github/workflows/update-database.yml b/.github/workflows/update-database.yml index 4c824f0..d7a7bd1 100644 --- a/.github/workflows/update-database.yml +++ b/.github/workflows/update-database.yml @@ -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: @@ -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 \ @@ -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 \ @@ -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: | @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 58ac5e0..23fca77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4d61f64..6176be7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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 @@ -204,6 +211,10 @@ and `R2_ENDPOINT` (`https://.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: diff --git a/README.md b/README.md index d113cd8..be62fb1 100644 --- a/README.md +++ b/README.md @@ -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") ] ``` @@ -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()`, @@ -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 @@ -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 @@ -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) diff --git a/ROADMAP.md b/ROADMAP.md index 78875bf..6c6e28e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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; @@ -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 @@ -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 @@ -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. diff --git a/Sources/IP2ASNDataPrep/DatabaseBuildManifest.swift b/Sources/IP2ASNDataPrep/DatabaseBuildManifest.swift index 5fcaff5..95e977a 100644 --- a/Sources/IP2ASNDataPrep/DatabaseBuildManifest.swift +++ b/Sources/IP2ASNDataPrep/DatabaseBuildManifest.swift @@ -1,3 +1,4 @@ +import CryptoKit import Foundation @_spi(IP2ASNDataPrep) import SwiftIP2ASN @@ -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 { diff --git a/Sources/IP2ASNDataPrep/TSVInput.swift b/Sources/IP2ASNDataPrep/TSVInput.swift new file mode 100644 index 0000000..1946556 --- /dev/null +++ b/Sources/IP2ASNDataPrep/TSVInput.swift @@ -0,0 +1,50 @@ +import Foundation + +struct TSVInputError: Error, CustomStringConvertible { + let description: String + + init(_ description: String) { + self.description = description + } +} + +/// Split bytes before decoding so a read boundary can fall inside a UTF-8 scalar or CRLF. +func forEachTSVLine(path: String, _ body: (String, Int) throws -> Void) throws { + let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path)) + defer { try? handle.close() } + var number = 1 + var pending = Data() + + func emit(_ bytes: Data) throws { + let content = bytes.last == 13 ? bytes.dropLast() : bytes + guard let line = String(data: content, encoding: .utf8) else { + throw TSVInputError("\(path):\(number): invalid UTF-8") + } + try body(line, number) + number += 1 + } + + while let chunk = try handle.read(upToCount: 64 * 1024), !chunk.isEmpty { + var remaining = chunk[...] + while !remaining.isEmpty { + let end = remaining.firstIndex(of: 10) ?? remaining.endIndex + let segment = remaining[..= 5, - let s = ipv4ToUInt32(f[0]), - let e = ipv4ToUInt32(f[1]) - else { continue } - let asnString = f[2].replacingOccurrences(of: "AS", with: "") - guard let a = UInt32(asnString), a != 0 else { continue } - v4Ranges.append((s, e, a)) - if asnNames[a] == nil { asnNames[a] = f[4] } - } - v4Ranges.sort { $0.start < $1.start } + package static func build( + ipv4TSV: String?, ipv6TSV: String?, to outputPath: String, + metadata: UltraCompactBuildMetadata? + ) throws -> RowCounts { + guard ipv4TSV != nil || ipv6TSV != nil else { + throw TSVInputError("Provide at least one IPv4 or IPv6 TSV input") } - if let v6Path = ipv6TSV { - let lines = try String(contentsOfFile: v6Path).split(separator: "\n") - for line in lines { - let f = line.split(separator: "\t").map(String.init) - guard f.count >= 5, - let s = parseIPv6ToPair(f[0]), - let e = parseIPv6ToPair(f[1]) - else { continue } - let asnString = f[2].replacingOccurrences(of: "AS", with: "") - guard let a = UInt32(asnString), a != 0 else { continue } - v6Ranges.append((s.hi, s.lo, e.hi, e.lo, a)) - if asnNames[a] == nil { asnNames[a] = f[4] } - } - v6Ranges.sort { - if $0.startHi != $1.startHi { return $0.startHi < $1.startHi } - return $0.startLo < $1.startLo - } - } + var counts = RowCounts() + var asnNames: [UInt32: String] = [:] + let v4Ranges = try readRanges( + path: ipv4TSV, family: "IPv4", parse: parseIPv4ToUInt32, less: (<), + names: &asnNames, counts: &counts + ) + let v6Ranges = try readRanges( + path: ipv6TSV, family: "IPv6", parse: parseIPv6ToPair, less: (<), + names: &asnNames, counts: &counts + ) + guard let v4Count = UInt32(exactly: v4Ranges.count), + let v6Count = UInt32(exactly: v6Ranges.count), + let nameCount = UInt32(exactly: asnNames.count) + else { throw TSVInputError("Range or name count exceeds the ULT2 format limit") } var data = Data() data.append(contentsOf: "ULT2".utf8) data.append(UltraCompactFormat.currentFormatVersion) // 1B format version data.append(metadata == nil ? 0 : UltraCompactFormat.metadataFlag) - data.append(uint32LE(UInt32(v4Ranges.count))) - data.append(uint32LE(UInt32(v6Ranges.count))) - data.append(uint32LE(UInt32(asnNames.count))) + data.append(uint32LE(v4Count)) + data.append(uint32LE(v6Count)) + data.append(uint32LE(nameCount)) for r in v4Ranges { data.append(uint32BE(r.start)) - data.append(encodeVarint(r.end &- r.start)) + data.append(encodeVarint(r.end - r.start)) data.append(encodeVarint(r.asn)) } for r in v6Ranges { - data.append(uint64BE(r.startHi)) - data.append(uint64BE(r.startLo)) - data.append(uint64BE(r.endHi)) - data.append(uint64BE(r.endLo)) + data.append(uint64BE(r.start.hi)) + data.append(uint64BE(r.start.lo)) + data.append(uint64BE(r.end.hi)) + data.append(uint64BE(r.end.lo)) data.append(encodeVarint(r.asn)) } @@ -128,15 +119,60 @@ public enum UltraCompactBuilder { } let compressed = try zlibCompress(data) - try compressed.write(to: URL(fileURLWithPath: outputPath)) + let limit = try UltraCompactFormat.decodedSizeLimit(compressedBytes: compressed.count) + guard data.count <= limit else { + throw TSVInputError("Encoded database exceeds the reader's decoded size limit of \(limit) bytes") + } + try compressed.write(to: URL(fileURLWithPath: outputPath), options: .atomic) + return counts } // MARK: helpers - private static func ipv4ToUInt32(_ ip: String) -> UInt32? { - let p = ip.split(separator: ".").compactMap { UInt32($0) } - guard p.count == 4 else { return nil } - return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3] + private struct RangeRecord
{ + let start: Address + let end: Address + let asn: UInt32 + let line: Int + } + + private static func readRanges
( + path: String?, family: String, parse: (String) -> Address?, less: (Address, Address) -> Bool, + names: inout [UInt32: String], counts: inout RowCounts + ) throws -> [RangeRecord
] { + guard let path else { return [] } + var ranges: [RangeRecord
] = [] + try forEachTSVLine(path: path) { line, number in + counts.total += 1 + if line.isEmpty { + counts.blank += 1 + return + } + let fields = line.split(separator: "\t", omittingEmptySubsequences: false) + guard fields.count >= 5 else { throw TSVInputError("\(path):\(number): expected five TSV columns") } + guard let start = parse(String(fields[0])), let end = parse(String(fields[1])) else { + throw TSVInputError("\(path):\(number): invalid \(family) range endpoint") + } + guard !less(end, start) else { + throw TSVInputError("\(path):\(number): \(family) range ends before it starts") + } + let digits = fields[2].hasPrefix("AS") ? fields[2].dropFirst(2) : fields[2] + guard digits.utf8.allSatisfy({ (48...57).contains($0) }), let asn = UInt32(digits) else { + throw TSVInputError("\(path):\(number): invalid ASN") + } + if asn == 0 { + counts.unrouted += 1 + return + } + ranges.append(RangeRecord(start: start, end: end, asn: asn, line: number)) + if names[asn] == nil { names[asn] = String(fields[4]) } + } + + ranges.sort { less($0.start, $1.start) } + for (previous, next) in zip(ranges, ranges.dropFirst()) where !less(previous.end, next.start) { + throw TSVInputError("\(path):\(next.line): \(family) range overlaps line \(previous.line)") + } + return ranges } private static func uint32LE(_ v: UInt32) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } } diff --git a/Sources/SwiftIP2ASN/EmbeddedDatabase.swift b/Sources/SwiftIP2ASN/EmbeddedDatabase.swift index cfa0511..967b878 100644 --- a/Sources/SwiftIP2ASN/EmbeddedDatabase.swift +++ b/Sources/SwiftIP2ASN/EmbeddedDatabase.swift @@ -520,7 +520,9 @@ public actor RemoteDatabase { } let storedMetadata = loadMetadata() - var request = URLRequest(url: remoteURL) + // These validators describe our database on disk. Consult the CDN + // even if URLSession has a separately cached response for this URL. + var request = URLRequest(url: remoteURL, cachePolicy: .reloadIgnoringLocalCacheData) request.httpMethod = "GET" if let etag = storedMetadata?.etag { request.setValue(etag, forHTTPHeaderField: "If-None-Match") @@ -631,7 +633,7 @@ public actor RemoteDatabase { try FileManager.default.createDirectory(at: cacheDir, withIntermediateDirectories: true) // Download - var request = URLRequest(url: remoteURL) + var request = URLRequest(url: remoteURL, cachePolicy: .reloadIgnoringLocalCacheData) request.httpMethod = "GET" let (data, response) = try await performRequest(request, operation: "Download") diff --git a/Sources/SwiftIP2ASN/IPAddress.swift b/Sources/SwiftIP2ASN/IPAddress.swift index d02cfd6..4cd46b0 100644 --- a/Sources/SwiftIP2ASN/IPAddress.swift +++ b/Sources/SwiftIP2ASN/IPAddress.swift @@ -42,14 +42,14 @@ public enum IPAddress: Sendable, Hashable { public func getBit(at index: Int) -> Bool { switch self { case .v4(let addr): - guard index < 32 else { return false } + guard (0..<32).contains(index) else { return false } let data = addr.rawValue let byteIndex = index >> 3 // index / 8 let bitIndex = 7 - (index & 7) // 7 - (index % 8) return (data[byteIndex] & (1 << bitIndex)) != 0 case .v6(let addr): - guard index < 128 else { return false } + guard (0..<128).contains(index) else { return false } let data = addr.rawValue let byteIndex = index >> 3 let bitIndex = 7 - (index & 7) @@ -102,7 +102,7 @@ public struct IPRange: Sendable { } public init?(cidr: String) { - let parts = cidr.split(separator: "/") + let parts = cidr.split(separator: "/", omittingEmptySubsequences: false) guard parts.count == 2, let address = IPAddress(string: String(parts[0])), let prefix = Int(parts[1]) @@ -122,6 +122,8 @@ public struct IPRange: Sendable { /// Check if address is within this range using efficient prefix comparison. @inlinable public func contains(_ address: IPAddress) -> Bool { + guard (0...start.bitCount).contains(prefixLength) else { return false } + // Check if address types match switch (start, address) { case (.v4, .v4), (.v6, .v6): @@ -145,7 +147,7 @@ public struct IPRange: Sendable { // Compare remaining bits let remainingBits = prefixLength & 7 if remainingBits > 0 { - let mask = UInt8(0xFF << (8 - remainingBits)) + let mask = UInt8.max << (8 - remainingBits) if (startBytes[fullBytes] & mask) != (addrBytes[fullBytes] & mask) { return false } diff --git a/Sources/SwiftIP2ASN/SwiftIP2ASN.docc/SwiftIP2ASN.md b/Sources/SwiftIP2ASN/SwiftIP2ASN.docc/SwiftIP2ASN.md index 440040a..4b09a8e 100644 --- a/Sources/SwiftIP2ASN/SwiftIP2ASN.docc/SwiftIP2ASN.md +++ b/Sources/SwiftIP2ASN/SwiftIP2ASN.docc/SwiftIP2ASN.md @@ -106,7 +106,10 @@ if let result = db.lookupResult(address) { ``ASNLookupResult`` reports only the BGP-origin ASN and source-provided name. It does not represent IP geolocation, legal ownership, or a canonical CIDR prefix. -Existing tuple-returning lookup methods remain available during the 0.x line. +The tuple-returning lookup methods remain supported through 1.0. To migrate a +call site, change `lookup` to `lookupResult` and read the same `asn` and `name` +fields. For several addresses, use `addresses.map { db.lookupResult($0) }` to +keep input order, duplicates, and a `nil` at each miss. ## Topics diff --git a/Sources/SwiftIP2ASN/UltraCompactFormat.swift b/Sources/SwiftIP2ASN/UltraCompactFormat.swift index fb7183e..c604f55 100644 --- a/Sources/SwiftIP2ASN/UltraCompactFormat.swift +++ b/Sources/SwiftIP2ASN/UltraCompactFormat.swift @@ -40,6 +40,14 @@ public enum UltraCompactFormat { /// Bump (and update the magic) when the layout changes. public static let currentFormatVersion: UInt8 = 2 + // Bound expansion of downloaded artifacts. Allow small, highly repetitive + // custom databases and scale the limit with production database size. + package static func decodedSizeLimit(compressedBytes: Int) throws -> Int { + let (limit, overflow) = compressedBytes.multipliedReportingOverflow(by: 32) + guard !overflow else { throw UltraCompactError.decompressionFailed } + return max(8 * 1024 * 1024, limit) + } + /// Header flag indicating that a version-1 metadata trailer follows the /// ASN name table. Released readers ignore this bit and trailing bytes. public static let metadataFlag: UInt8 = 1 << 0 @@ -683,16 +691,11 @@ public struct UltraCompactDatabase: Sendable { guard !data.isEmpty else { throw UltraCompactError.decompressionFailed } - let (initialBufferSize, initialSizeOverflow) = data.count.multipliedReportingOverflow(by: 8) - guard !initialSizeOverflow else { - throw UltraCompactError.decompressionFailed - } + // One extra byte distinguishes an exact fit from a truncated prefix. + let limit = try UltraCompactFormat.decodedSizeLimit(compressedBytes: data.count) + 1 + var bufferSize = data.count * 8 - var bufferSize = initialBufferSize - var attempts = 0 - let maxAttempts = 3 - - while attempts < maxAttempts { + while true { let buffer = UnsafeMutablePointer.allocate(capacity: bufferSize) defer { buffer.deallocate() } @@ -705,21 +708,13 @@ public struct UltraCompactDatabase: Sendable { ) } - if decompressedSize > 0 { + guard decompressedSize > 0 else { throw UltraCompactError.decompressionFailed } + if decompressedSize < bufferSize { return Data(bytes: buffer, count: decompressedSize) } - - attempts += 1 - if attempts < maxAttempts { - let (nextBufferSize, sizeOverflow) = bufferSize.multipliedReportingOverflow(by: 2) - guard !sizeOverflow else { - throw UltraCompactError.decompressionFailed - } - bufferSize = nextBufferSize - } + guard bufferSize < limit else { throw UltraCompactError.decompressionFailed } + bufferSize = bufferSize <= limit / 2 ? bufferSize * 2 : limit } - - throw UltraCompactError.decompressionFailed } } diff --git a/Sources/ip2asn-tools/main.swift b/Sources/ip2asn-tools/main.swift index d5d21cf..7b6cc70 100644 --- a/Sources/ip2asn-tools/main.swift +++ b/Sources/ip2asn-tools/main.swift @@ -37,7 +37,7 @@ func usage(exitCode: Int32 = 2) -> Never { lookup-ultra bench-ultra [iterations] """ - print(msg) + if exitCode == 0 { print(msg) } else { fputs(msg + "\n", stderr) } exit(exitCode) } @@ -148,21 +148,9 @@ case .lookupCompressed: } case .benchCompressed: - guard args.count >= 2 else { usage() } - let dbPath = String(args.dropFirst().first!) - let iters = Int(args.dropFirst(2).first ?? "5") ?? 5 - if iters <= 0 { - print("iterations must be > 0") - exit(2) - } - _ = try? CompressedDatabaseFormat.loadCompressed(from: dbPath) // warmup - var timesC: [Double] = [] - for _ in 0..= 2 else { usage() } - let dbPath = String(args.dropFirst().first!) - let iters = Int(args.dropFirst(2).first ?? "5") ?? 5 - if iters <= 0 { - print("iterations must be > 0") - exit(2) - } - _ = try? UltraCompactDatabase(path: dbPath) // warmup - var timesU: [Double] = [] - for _ in 0.. Never { exit(1) } +func benchmark(arguments: [String], label: String, load: (String) throws -> Void) { + guard (1...2).contains(arguments.count) else { usage() } + let iterations = arguments.count == 2 ? Int(arguments[1]) : 5 + guard let iterations, iterations > 0 else { + fputs("Error: iterations must be a positive integer\n", stderr) + exit(2) + } + do { + try load(arguments[0]) + var times: [Double] = [] + for _ in 0.. [URLRequest.CachePolicy] { + requests.map(\.cachePolicy) + } + func requestedMethods() -> [String] { requests.map { $0.httpMethod ?? "GET" } } @@ -517,6 +521,8 @@ final class RemoteDatabaseTests: XCTestCase { } let requestedMethods = await transport.requestedMethods() XCTAssertEqual(requestedMethods, ["GET", "GET"]) + let policies = await transport.requestedCachePolicies() + XCTAssertEqual(policies, [.reloadIgnoringLocalCacheData, .reloadIgnoringLocalCacheData]) let etags = await transport.requestedHeaderValues(for: "If-None-Match") let modifiedDates = await transport.requestedHeaderValues(for: "If-Modified-Since") XCTAssertEqual(etags, [nil, "\"fixture-v1\""]) diff --git a/Tests/SwiftIP2ASNTests/IPAddressTests.swift b/Tests/SwiftIP2ASNTests/IPAddressTests.swift index 2861c4c..bf3349f 100644 --- a/Tests/SwiftIP2ASNTests/IPAddressTests.swift +++ b/Tests/SwiftIP2ASNTests/IPAddressTests.swift @@ -98,6 +98,23 @@ final class IPAddressTests: XCTestCase { XCTAssertFalse(range.contains(ip4)) } + func testPartialBytePrefixesAndOutOfBoundsInputs() throws { + for (cidr, last, outside) in [ + ("192.0.2.0/25", "192.0.2.127", "192.0.2.128"), + ("2001:db8::/127", "2001:db8::1", "2001:db8::2") + ] { + let range = try XCTUnwrap(IPRange(cidr: cidr)) + let address = try XCTUnwrap(IPAddress(string: last)) + XCTAssertTrue(range.contains(address)) + XCTAssertFalse(range.contains(try XCTUnwrap(IPAddress(string: outside)))) + XCTAssertFalse(address.getBit(at: -1)) + XCTAssertFalse(address.getBit(at: address.bitCount)) + XCTAssertFalse(IPRange(start: address, prefixLength: -1).contains(address)) + XCTAssertFalse(IPRange(start: address, prefixLength: address.bitCount + 1).contains(address)) + } + XCTAssertNil(IPRange(cidr: "192.0.2.0//25")) + } + func testMixedTypeRangeContains() { guard let ipv4Range = IPRange(cidr: "192.168.0.0/16") else { return } guard let ipv6Address = IPAddress(string: "2001:db8::1") else { return } diff --git a/Tests/SwiftIP2ASNTests/UltraCompactBuilderTests.swift b/Tests/SwiftIP2ASNTests/UltraCompactBuilderTests.swift index f249300..dc925e1 100644 --- a/Tests/SwiftIP2ASNTests/UltraCompactBuilderTests.swift +++ b/Tests/SwiftIP2ASNTests/UltraCompactBuilderTests.swift @@ -190,6 +190,55 @@ struct UltraCompactBuilderTests { } } + @Test("Streaming reads preserve split UTF-8, CRLF, blank rows, and the final unterminated row") + func streamingRows() throws { + let directory = try makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let input = directory.appendingPathComponent("ranges.tsv") + let output = directory.appendingPathComponent("out.ultra") + let prefix = "1.1.1.1\t1.1.1.1\tAS42\t\t" + let name = String(repeating: "x", count: 65_535 - prefix.utf8.count) + "é" + try (prefix + name + "\r\n\r\n1.1.1.2\t1.1.1.2\t0\tZZ\tUnrouted") + .write(to: input, atomically: true, encoding: .utf8) + let rows = try UltraCompactBuilder.build(ipv4TSV: input.path, ipv6TSV: nil, to: output.path, metadata: nil) + #expect(rows.total == 3) + #expect(rows.blank == 1) + #expect(rows.unrouted == 1) + let database = try UltraCompactDatabase(path: output.path) + #expect(database.lookupResult("1.1.1.1") == ASNLookupResult(asn: 42, name: name)) + } + + @Test("A failed build identifies the source row and preserves an existing output") + func rejectsInvalidSource() throws { + let directory = try makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let input = directory.appendingPathComponent("ranges.tsv") + let output = directory.appendingPathComponent("out.ultra") + let original = Data("previous output".utf8) + try original.write(to: output) + for (row, reason) in [ + ("1.0.0.256\t1.0.1.0\t42\tZZ\tExample", "endpoint"), + ("1.0.0.2\t1.0.0.1\t42\tZZ\tExample", "ends before"), + ("1.0.0.1\t1.0.0.2\t4AS2\tZZ\tExample", "invalid ASN"), + ("1.0.0.1\t1.0.0.2\t42\tZZ\tExample", "overlaps"), + ("1.0.0.1\t1.0.0.2", "columns"), + (String(repeating: "x", count: 1024 * 1024 + 1), "exceeds") + ] { + try ("1.0.0.0\t1.0.0.1\t17\tZZ\tFirst\n" + row) + .write(to: input, atomically: true, encoding: .utf8) + #expect { + try UltraCompactBuilder.createUltraCompact(from: input.path, to: output.path) + } throws: { error in + String(describing: error).contains("\(input.path):2:") + && String(describing: error).contains(reason) + } + #expect(try Data(contentsOf: output) == original) + } + #expect(throws: TSVInputError.self) { + try UltraCompactBuilder.createUltraCompact(ipv4TSV: nil, ipv6TSV: nil, to: output.path) + } + } + private func makeTemporaryDirectory() throws -> URL { let url = FileManager.default.temporaryDirectory .appendingPathComponent(