detached 8d24bba

#2 feat: library packages and CDN source

state
merged · 7ab9936 · merge commit
branch
feat/library → main
opened
bnema ·
updated

Turn forever-db into a library and add a CDN source, so a server can build the data without a game install.

Changes

  • Module path bnema.dev/forever-db; public packages under pkg/ (blte, casc, casc/cdn, dataset, db2, dbd, defs, hotfix, install, sources, tactkeys, wdc5); fsutil, salsa20, export, schema stay internal.
  • pkg/casc/cdn: build list over HTTPS from <region>.version.battle.net, archive index scan, HTTP range reads, cache of indexes and loose files. Every downloaded file is checked (BLTE header and block MD5s vs its encoding key) before caching; bounded responses; next-server retry on bad bodies.
  • pkg/dataset: shared table loader (Load, streaming OnTable or Result.Tables), used by export and by other callers.
  • pkg/defs.Generate works on any storage.
  • CLI: export --cdn (writes wowf-<version>-cdn.sqlite, leaves current.sqlite on the local export) and --hotfixes FILE; _meta.source.
  • internal/export and pkg/dataset stay network-free (TestNoNetworkDeps).

Checks

  • gofmt, go vet, staticcheck, go test -race ./..., fuzz smoke runs.
  • Real data: local export identical to before (full-database identity diff); CDN export identical to the local one (1161 tables); real CDN test: 308 MB, ~14 s cold, peak 541 MiB.
  • Wrap-up review (2 reviewers) + 2 targeted re-reviews: all findings fixed.
CommitSubjectAuthorDateSignatureStatus
8d24bbarefactor(export): rename TableFailure.Err to Errorbrice GPG Verified
003e90dfix(cdn): verify blocks, retry bad bodies on the next server, HTTPS build list onlybrice GPG Verified
e3d31a9feat(blte): verify a file against its encoding key and block checksumsbrice GPG Verified
27e4365feat(export): name CDN exports apart and keep current.sqlite localbrice GPG Verified
9209293refactor: move fsutil and salsa20 back to internalbrice GPG Verified
90f9c32refactor(dataset): validate Load options, type statuses, share casc.FileReaderbrice GPG Verified
936850ftest(cdn): fuzz index and table parsers, sync the cancel testbrice GPG Verified
08d8688fix(cdn): read the build list from the HTTPS version serverbrice GPG Verified
d959c6efix(cdn): cache only verified files and prune the cache on closebrice GPG Verified
3168717fix(cdn): bound responses, check ranges, configs and 4xx answersbrice GPG Verified
29efc29feat(export): export from the CDN with optional hotfixesbrice GPG Verified
3cdd847refactor(defs): generate definitions from any storagebrice GPG Verified
1ed0312refactor(dataset): share table loading between export and other callersbrice GPG Verified
771902ctest(cdn): compare CDN and local storage on real databrice GPG Verified
bd944f1feat(cdn): open game storage from the CDNbrice GPG Verified
09a2c47feat(cdn): scan archive indexes for wanted keysbrice GPG Verified
09b6ef8feat(casc): resolve the latest build from the patch serverbrice GPG Verified
6061917refactor(casc): read encoded files through a reader interfacebrice GPG Verified
1e7d40frefactor: move library packages to pkg/brice GPG Verified
f526036refactor: rename the module to bnema.dev/forever-dbbrice GPG Verified

Checks 0

no checks

85 files · +3613 -413
no checks
M Makefile +1 -1
@@ -1,6 +1,6 @@
11 VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
22 COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
3-LDFLAGS := -ldflags "-s -w -X github.com/bnema/forever-db/cmd.version=$(VERSION) -X github.com/bnema/forever-db/cmd.commit=$(COMMIT)"
3+LDFLAGS := -ldflags "-s -w -X bnema.dev/forever-db/cmd.version=$(VERSION) -X bnema.dev/forever-db/cmd.commit=$(COMMIT)"
44
55 .PHONY: build install fmt vet test tidy clean
66
@@ -1,6 +1,6 @@
1 VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")1 VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
2 COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")2 COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
3-LDFLAGS := -ldflags "-s -w -X github.com/bnema/forever-db/cmd.version=$(VERSION) -X github.com/bnema/forever-db/cmd.commit=$(COMMIT)"3+LDFLAGS := -ldflags "-s -w -X bnema.dev/forever-db/cmd.version=$(VERSION) -X bnema.dev/forever-db/cmd.commit=$(COMMIT)"
4 4
5 .PHONY: build install fmt vet test tidy clean5 .PHONY: build install fmt vet test tidy clean
6 6
M NOTICE +2 -2
@@ -61,7 +61,7 @@ SOFTWARE.
6161 Data
6262 ------------------------------------------------------------------------
6363
64-The embedded definitions snapshot (internal/defs/data/forever.json.gz) is
64+The embedded definitions snapshot (pkg/defs/data/forever.json.gz) is
6565 derived from WoWDBDefs (https://github.com/wowdev/WoWDBDefs) by the
6666 WoWDBDefs contributors, CC BY-SA 4.0, and TACTKeys
67-(https://github.com/wowdev/TACTKeys). See internal/defs/data/README.md.
67+(https://github.com/wowdev/TACTKeys). See pkg/defs/data/README.md.
@@ -61,7 +61,7 @@ SOFTWARE.
61 Data61 Data
62 ------------------------------------------------------------------------62 ------------------------------------------------------------------------
63 63
64-The embedded definitions snapshot (internal/defs/data/forever.json.gz) is64+The embedded definitions snapshot (pkg/defs/data/forever.json.gz) is
65 derived from WoWDBDefs (https://github.com/wowdev/WoWDBDefs) by the65 derived from WoWDBDefs (https://github.com/wowdev/WoWDBDefs) by the
66 WoWDBDefs contributors, CC BY-SA 4.0, and TACTKeys66 WoWDBDefs contributors, CC BY-SA 4.0, and TACTKeys
67-(https://github.com/wowdev/TACTKeys). See internal/defs/data/README.md.67+(https://github.com/wowdev/TACTKeys). See pkg/defs/data/README.md.
M README.md +19 -10
@@ -5,7 +5,7 @@ forever-db exports the game data of a local World of Warcraft: Forever client in
55 ## Install
66
77 ```sh
8-go install github.com/bnema/forever-db@latest
8+go install bnema.dev/forever-db@latest
99 ```
1010
1111 Or from a checkout:
@@ -17,7 +17,8 @@ make build # produces build/forever-db
1717 ## Usage
1818
1919 ```sh
20-forever-db export --dir "<WoW dir>"
20+forever-db export --dir "<WoW dir>" [--hotfixes FILE]
21+forever-db export --cdn [--hotfixes FILE]
2122 forever-db status --dir "<WoW dir>" [--json]
2223 forever-db defs show [--json]
2324 forever-db defs update --dir "<WoW dir>" [--fresh] [--output FILE] [--offline]
@@ -28,31 +29,39 @@ forever-db defs update --dir "<WoW dir>" [--fresh] [--output FILE] [--offline]
2829
2930 | Flag / env | Meaning |
3031 |---|---|
31-| `--dir`, `FOREVER_DB_WOW_DIR` | Game directory (required by `export`, `status` and `defs update`) |
32+| `--dir`, `FOREVER_DB_WOW_DIR` | Game directory (required by `export` without `--cdn`, `status` and `defs update`) |
3233 | `--out`, `FOREVER_DB_DATA_DIR` | Output directory, default `$XDG_DATA_HOME/forever-db` (`~/.local/share/forever-db`) |
3334 | `--force` | Export even when the database is already up to date |
35+| `--cdn` | Export the latest build from the Blizzard CDN instead of a local install (`--dir` is ignored) |
36+| `--hotfixes FILE` | `DBCache.bin` to apply; default: the install's, none with `--cdn`. On a local export it implies `--force` |
3437 | `-v`, `--verbose` | Debug logging |
3538
3639 A flag always wins over its environment variable.
3740
38-Each export writes `wowf-<version>.sqlite` and points the `current.sqlite` symlink at it.
41+Each local export writes `wowf-<version>.sqlite` and points the `current.sqlite` symlink at it. A `--cdn` export writes `wowf-<version>-cdn.sqlite` and leaves `current.sqlite` alone: it always tracks the local install.
42+
43+### CDN source
44+
45+`export --cdn` needs no game install: it reads the latest `wowf` build from Blizzard's public CDN (build list over HTTPS from `<region>.version.battle.net`). The first run downloads about 300 MB (encoding, root, archive indexes, the DB2 files); indexes and loose files are cached in `$XDG_CACHE_HOME/forever-db/cdn`, so later runs of the same build download a few MB. Hotfixes are not on the CDN: without `--hotfixes FILE` the export has none (`dbcache_status` `missing`).
46+
47+`scripts/compare-exports.sh A B` compares the craft tables of two exports (row counts and `EXCEPT` both ways).
3948
4049 ### Definitions
4150
42-`export` never uses the network. The table definitions and encryption keys for the Forever client ship inside the binary as a small snapshot.
51+`export` uses the network only with `--cdn`. The table definitions and encryption keys for the Forever client ship inside the binary as a small snapshot.
4352
44-After a game patch, `export` may report tables without a definition (status `no_definition`) and suggests `forever-db defs update`. That command downloads WoWDBDefs and TACTKeys (cached and revalidated in `$XDG_CACHE_HOME/forever-db`), reads the installed client, and writes `<data dir>/defs.json.gz`, which overrides the embedded snapshot. By default the new definitions are merged with the current ones: the snapshot in use (`<data dir>/defs.json.gz`, else the embedded one), or, with `--output FILE` (written there instead), that file if it exists, else the embedded snapshot. `--fresh` starts from scratch, `--offline` uses the download cache only. `defs update` is the only command that uses the network.
53+After a game patch, `export` may report tables without a definition (status `no_definition`) and suggests `forever-db defs update`. That command downloads WoWDBDefs and TACTKeys (cached and revalidated in `$XDG_CACHE_HOME/forever-db`), reads the installed client, and writes `<data dir>/defs.json.gz`, which overrides the embedded snapshot. By default the new definitions are merged with the current ones: the snapshot in use (`<data dir>/defs.json.gz`, else the embedded one), or, with `--output FILE` (written there instead), that file if it exists, else the embedded snapshot. `--fresh` starts from scratch, `--offline` uses the download cache only. Apart from `export --cdn`, `defs update` is the only command that uses the network.
4554
4655 `forever-db defs show` prints which snapshot is in use (`embedded` or `local`), its builds, WoWDBDefs commit, generation time, table, layout and key counts, and an attribution line for the data sources (`attribution` object with `--json`).
4756
48-Hotfixes change after a patch or a game session. `forever-db status` reports `up to date`, `stale` (with the reasons: `build_changed`, `hotfixes_changed`, `schema_changed`, `defs_changed` when the definitions snapshot in use differs from the one of the export) or `never exported`; run `export` again when it is stale.
57+Hotfixes change after a patch or a game session. `forever-db status` reports `up to date`, `stale` (with the reasons: `build_changed`, `hotfixes_changed`, `schema_changed`, `defs_changed` when the definitions snapshot in use differs from the one of the export, `source_changed` if `current.sqlite` points at a non-local export) or `never exported`; run `export` again when it is stale.
4958
5059 Exit codes: 0 success (including per-table failures, listed in the summary and `_tables`), 1 fatal error. Use `status --json` (`state`) and `_tables.status` in scripts.
5160
5261 ## Database layout
5362
5463 - **One table per DB2 table**, named like the DB2 table (`SpellReagents`, `ItemSparse`, …). Columns follow the WoWDBDefs definition; arrays become `Name_0`, `Name_1`, … The record ID is the `INTEGER PRIMARY KEY`.
55-- **`_meta`**: key/value pairs: schema version, tool version, build version and key, locale, export time, DBCache hash and status (`applied`, `missing`, `invalid`, `build_mismatch`), definitions snapshot origin (`embedded` or `local`), its WoWDBDefs commit, generation time and SHA-256, table counts.
64+- **`_meta`**: key/value pairs: schema version, tool version, source (`local` or `cdn`), build version and key (the build config hash with `--cdn`), locale, export time, DBCache hash and status (`applied`, `missing`, `invalid`, `build_mismatch`), definitions snapshot origin (`embedded` or `local`), its WoWDBDefs commit, generation time and SHA-256, table counts.
5665 - **`_tables`**: one row per table: `status` (`ok`, `absent`, `no_definition`, `failed`), error message, base row count, hotfix counts (upserts, deletes, reverts, errors), skipped rows and sections.
5766 - **`_columns`**: one row per SQL column: type (`int`, `uint`, `float`, `string`), bit size, array index, and `ref_table` / `ref_column` for columns that reference another table. Use these to find joins.
5867 - **`_hotfixes`**: every hotfix entry of a known table with the action taken (`upsert`, `delete`, `revert`, `ignored`, `error`).
@@ -95,7 +104,7 @@ WHERE ie."TriggerType" = 6 AND ie."SpellID" = ?;
95104 | Variable | Points to |
96105 |---|---|
97106 | `FOREVER_DB_TEST_WOW_DIR` | A WoW Forever install (folder with `.build.info`) |
98-| `FOREVER_DB_TEST_DEFS` | A definitions snapshot (`defs.json.gz`), e.g. `internal/defs/data/forever.json.gz` |
107+| `FOREVER_DB_TEST_DEFS` | A definitions snapshot (`defs.json.gz`), e.g. `pkg/defs/data/forever.json.gz` |
99108 | `FOREVER_DB_TEST_DBD_DIR` | A WoWDBDefs `definitions/` folder |
100109 | `FOREVER_DB_TEST_MANIFEST` | A WoWDBDefs `manifest.json` |
101110 | `FOREVER_DB_TEST_TACTKEYS` | A TACTKeys `WoW.txt` file |
@@ -107,7 +116,7 @@ WHERE ie."TriggerType" = 6 AND ie."SpellID" = ?;
107116 - Table definitions: [WoWDBDefs](https://github.com/wowdev/WoWDBDefs) (CC BY-SA 4.0).
108117 - Encryption keys: [TACTKeys](https://github.com/wowdev/TACTKeys).
109118
110-The definitions snapshot (embedded, or written by `defs update`) is derived from these projects and is licensed under CC BY-SA 4.0; see `internal/defs/data/README.md`. The CASC, BLTE and WDC5 readers follow DBCD and TACTSharp (MIT); see `NOTICE`.
119+The definitions snapshot (embedded, or written by `defs update`) is derived from these projects and is licensed under CC BY-SA 4.0; see `pkg/defs/data/README.md`. The CASC, BLTE and WDC5 readers follow DBCD and TACTSharp (MIT); see `NOTICE`.
111120
112121 Copyright (C) 2026 bnema. SPDX-License-Identifier: AGPL-3.0-or-later. The project code is licensed under the GNU Affero General Public License v3.0 or later (see `LICENSE`).
113122
@@ -5,7 +5,7 @@ forever-db exports the game data of a local World of Warcraft: Forever client in
5 ## Install5 ## Install
6 6
7 ```sh7 ```sh
8-go install github.com/bnema/forever-db@latest8+go install bnema.dev/forever-db@latest
9 ```9 ```
10 10
11 Or from a checkout:11 Or from a checkout:
@@ -17,7 +17,8 @@ make build # produces build/forever-db
17 ## Usage17 ## Usage
18 18
19 ```sh19 ```sh
20-forever-db export --dir "<WoW dir>"20+forever-db export --dir "<WoW dir>" [--hotfixes FILE]
21+forever-db export --cdn [--hotfixes FILE]
21 forever-db status --dir "<WoW dir>" [--json]22 forever-db status --dir "<WoW dir>" [--json]
22 forever-db defs show [--json]23 forever-db defs show [--json]
23 forever-db defs update --dir "<WoW dir>" [--fresh] [--output FILE] [--offline]24 forever-db defs update --dir "<WoW dir>" [--fresh] [--output FILE] [--offline]
@@ -28,31 +29,39 @@ forever-db defs update --dir "<WoW dir>" [--fresh] [--output FILE] [--offline]
28 29
29 | Flag / env | Meaning |30 | Flag / env | Meaning |
30 |---|---|31 |---|---|
31-| `--dir`, `FOREVER_DB_WOW_DIR` | Game directory (required by `export`, `status` and `defs update`) |32+| `--dir`, `FOREVER_DB_WOW_DIR` | Game directory (required by `export` without `--cdn`, `status` and `defs update`) |
32 | `--out`, `FOREVER_DB_DATA_DIR` | Output directory, default `$XDG_DATA_HOME/forever-db` (`~/.local/share/forever-db`) |33 | `--out`, `FOREVER_DB_DATA_DIR` | Output directory, default `$XDG_DATA_HOME/forever-db` (`~/.local/share/forever-db`) |
33 | `--force` | Export even when the database is already up to date |34 | `--force` | Export even when the database is already up to date |
35+| `--cdn` | Export the latest build from the Blizzard CDN instead of a local install (`--dir` is ignored) |
36+| `--hotfixes FILE` | `DBCache.bin` to apply; default: the install's, none with `--cdn`. On a local export it implies `--force` |
34 | `-v`, `--verbose` | Debug logging |37 | `-v`, `--verbose` | Debug logging |
35 38
36 A flag always wins over its environment variable.39 A flag always wins over its environment variable.
37 40
38-Each export writes `wowf-<version>.sqlite` and points the `current.sqlite` symlink at it.41+Each local export writes `wowf-<version>.sqlite` and points the `current.sqlite` symlink at it. A `--cdn` export writes `wowf-<version>-cdn.sqlite` and leaves `current.sqlite` alone: it always tracks the local install.
42+
43+### CDN source
44+
45+`export --cdn` needs no game install: it reads the latest `wowf` build from Blizzard's public CDN (build list over HTTPS from `<region>.version.battle.net`). The first run downloads about 300 MB (encoding, root, archive indexes, the DB2 files); indexes and loose files are cached in `$XDG_CACHE_HOME/forever-db/cdn`, so later runs of the same build download a few MB. Hotfixes are not on the CDN: without `--hotfixes FILE` the export has none (`dbcache_status` `missing`).
46+
47+`scripts/compare-exports.sh A B` compares the craft tables of two exports (row counts and `EXCEPT` both ways).
39 48
40 ### Definitions49 ### Definitions
41 50
42-`export` never uses the network. The table definitions and encryption keys for the Forever client ship inside the binary as a small snapshot.51+`export` uses the network only with `--cdn`. The table definitions and encryption keys for the Forever client ship inside the binary as a small snapshot.
43 52
44-After a game patch, `export` may report tables without a definition (status `no_definition`) and suggests `forever-db defs update`. That command downloads WoWDBDefs and TACTKeys (cached and revalidated in `$XDG_CACHE_HOME/forever-db`), reads the installed client, and writes `<data dir>/defs.json.gz`, which overrides the embedded snapshot. By default the new definitions are merged with the current ones: the snapshot in use (`<data dir>/defs.json.gz`, else the embedded one), or, with `--output FILE` (written there instead), that file if it exists, else the embedded snapshot. `--fresh` starts from scratch, `--offline` uses the download cache only. `defs update` is the only command that uses the network.53+After a game patch, `export` may report tables without a definition (status `no_definition`) and suggests `forever-db defs update`. That command downloads WoWDBDefs and TACTKeys (cached and revalidated in `$XDG_CACHE_HOME/forever-db`), reads the installed client, and writes `<data dir>/defs.json.gz`, which overrides the embedded snapshot. By default the new definitions are merged with the current ones: the snapshot in use (`<data dir>/defs.json.gz`, else the embedded one), or, with `--output FILE` (written there instead), that file if it exists, else the embedded snapshot. `--fresh` starts from scratch, `--offline` uses the download cache only. Apart from `export --cdn`, `defs update` is the only command that uses the network.
45 54
46 `forever-db defs show` prints which snapshot is in use (`embedded` or `local`), its builds, WoWDBDefs commit, generation time, table, layout and key counts, and an attribution line for the data sources (`attribution` object with `--json`).55 `forever-db defs show` prints which snapshot is in use (`embedded` or `local`), its builds, WoWDBDefs commit, generation time, table, layout and key counts, and an attribution line for the data sources (`attribution` object with `--json`).
47 56
48-Hotfixes change after a patch or a game session. `forever-db status` reports `up to date`, `stale` (with the reasons: `build_changed`, `hotfixes_changed`, `schema_changed`, `defs_changed` when the definitions snapshot in use differs from the one of the export) or `never exported`; run `export` again when it is stale.57+Hotfixes change after a patch or a game session. `forever-db status` reports `up to date`, `stale` (with the reasons: `build_changed`, `hotfixes_changed`, `schema_changed`, `defs_changed` when the definitions snapshot in use differs from the one of the export, `source_changed` if `current.sqlite` points at a non-local export) or `never exported`; run `export` again when it is stale.
49 58
50 Exit codes: 0 success (including per-table failures, listed in the summary and `_tables`), 1 fatal error. Use `status --json` (`state`) and `_tables.status` in scripts.59 Exit codes: 0 success (including per-table failures, listed in the summary and `_tables`), 1 fatal error. Use `status --json` (`state`) and `_tables.status` in scripts.
51 60
52 ## Database layout61 ## Database layout
53 62
54 - **One table per DB2 table**, named like the DB2 table (`SpellReagents`, `ItemSparse`, …). Columns follow the WoWDBDefs definition; arrays become `Name_0`, `Name_1`, … The record ID is the `INTEGER PRIMARY KEY`.63 - **One table per DB2 table**, named like the DB2 table (`SpellReagents`, `ItemSparse`, …). Columns follow the WoWDBDefs definition; arrays become `Name_0`, `Name_1`, … The record ID is the `INTEGER PRIMARY KEY`.
55-- **`_meta`**: key/value pairs: schema version, tool version, build version and key, locale, export time, DBCache hash and status (`applied`, `missing`, `invalid`, `build_mismatch`), definitions snapshot origin (`embedded` or `local`), its WoWDBDefs commit, generation time and SHA-256, table counts.64+- **`_meta`**: key/value pairs: schema version, tool version, source (`local` or `cdn`), build version and key (the build config hash with `--cdn`), locale, export time, DBCache hash and status (`applied`, `missing`, `invalid`, `build_mismatch`), definitions snapshot origin (`embedded` or `local`), its WoWDBDefs commit, generation time and SHA-256, table counts.
56 - **`_tables`**: one row per table: `status` (`ok`, `absent`, `no_definition`, `failed`), error message, base row count, hotfix counts (upserts, deletes, reverts, errors), skipped rows and sections.65 - **`_tables`**: one row per table: `status` (`ok`, `absent`, `no_definition`, `failed`), error message, base row count, hotfix counts (upserts, deletes, reverts, errors), skipped rows and sections.
57 - **`_columns`**: one row per SQL column: type (`int`, `uint`, `float`, `string`), bit size, array index, and `ref_table` / `ref_column` for columns that reference another table. Use these to find joins.66 - **`_columns`**: one row per SQL column: type (`int`, `uint`, `float`, `string`), bit size, array index, and `ref_table` / `ref_column` for columns that reference another table. Use these to find joins.
58 - **`_hotfixes`**: every hotfix entry of a known table with the action taken (`upsert`, `delete`, `revert`, `ignored`, `error`).67 - **`_hotfixes`**: every hotfix entry of a known table with the action taken (`upsert`, `delete`, `revert`, `ignored`, `error`).
@@ -95,7 +104,7 @@ WHERE ie."TriggerType" = 6 AND ie."SpellID" = ?;
95 | Variable | Points to |104 | Variable | Points to |
96 |---|---|105 |---|---|
97 | `FOREVER_DB_TEST_WOW_DIR` | A WoW Forever install (folder with `.build.info`) |106 | `FOREVER_DB_TEST_WOW_DIR` | A WoW Forever install (folder with `.build.info`) |
98-| `FOREVER_DB_TEST_DEFS` | A definitions snapshot (`defs.json.gz`), e.g. `internal/defs/data/forever.json.gz` |107+| `FOREVER_DB_TEST_DEFS` | A definitions snapshot (`defs.json.gz`), e.g. `pkg/defs/data/forever.json.gz` |
99 | `FOREVER_DB_TEST_DBD_DIR` | A WoWDBDefs `definitions/` folder |108 | `FOREVER_DB_TEST_DBD_DIR` | A WoWDBDefs `definitions/` folder |
100 | `FOREVER_DB_TEST_MANIFEST` | A WoWDBDefs `manifest.json` |109 | `FOREVER_DB_TEST_MANIFEST` | A WoWDBDefs `manifest.json` |
101 | `FOREVER_DB_TEST_TACTKEYS` | A TACTKeys `WoW.txt` file |110 | `FOREVER_DB_TEST_TACTKEYS` | A TACTKeys `WoW.txt` file |
@@ -107,7 +116,7 @@ WHERE ie."TriggerType" = 6 AND ie."SpellID" = ?;
107 - Table definitions: [WoWDBDefs](https://github.com/wowdev/WoWDBDefs) (CC BY-SA 4.0).116 - Table definitions: [WoWDBDefs](https://github.com/wowdev/WoWDBDefs) (CC BY-SA 4.0).
108 - Encryption keys: [TACTKeys](https://github.com/wowdev/TACTKeys).117 - Encryption keys: [TACTKeys](https://github.com/wowdev/TACTKeys).
109 118
110-The definitions snapshot (embedded, or written by `defs update`) is derived from these projects and is licensed under CC BY-SA 4.0; see `internal/defs/data/README.md`. The CASC, BLTE and WDC5 readers follow DBCD and TACTSharp (MIT); see `NOTICE`.119+The definitions snapshot (embedded, or written by `defs update`) is derived from these projects and is licensed under CC BY-SA 4.0; see `pkg/defs/data/README.md`. The CASC, BLTE and WDC5 readers follow DBCD and TACTSharp (MIT); see `NOTICE`.
111 120
112 Copyright (C) 2026 bnema. SPDX-License-Identifier: AGPL-3.0-or-later. The project code is licensed under the GNU Affero General Public License v3.0 or later (see `LICENSE`).121 Copyright (C) 2026 bnema. SPDX-License-Identifier: AGPL-3.0-or-later. The project code is licensed under the GNU Affero General Public License v3.0 or later (see `LICENSE`).
113 122
A cdn.test +0 -0 binary file: no text diff

binary file: no text diff

M cmd/debug.go +4 -4
@@ -8,10 +8,10 @@ import (
88
99 "github.com/spf13/cobra"
1010
11- "github.com/bnema/forever-db/internal/casc"
12- "github.com/bnema/forever-db/internal/defs"
13- "github.com/bnema/forever-db/internal/install"
14- "github.com/bnema/forever-db/internal/tactkeys"
11+ "bnema.dev/forever-db/pkg/casc"
12+ "bnema.dev/forever-db/pkg/defs"
13+ "bnema.dev/forever-db/pkg/install"
14+ "bnema.dev/forever-db/pkg/tactkeys"
1515 )
1616
1717 var debugCmd = &cobra.Command{
@@ -8,10 +8,10 @@ import (
8 8
9 "github.com/spf13/cobra"9 "github.com/spf13/cobra"
10 10
11- "github.com/bnema/forever-db/internal/casc"11+ "bnema.dev/forever-db/pkg/casc"
12- "github.com/bnema/forever-db/internal/defs"12+ "bnema.dev/forever-db/pkg/defs"
13- "github.com/bnema/forever-db/internal/install"13+ "bnema.dev/forever-db/pkg/install"
14- "github.com/bnema/forever-db/internal/tactkeys"14+ "bnema.dev/forever-db/pkg/tactkeys"
15 )15 )
16 16
17 var debugCmd = &cobra.Command{17 var debugCmd = &cobra.Command{
M cmd/defs.go +15 -6
@@ -17,11 +17,13 @@ import (
1717
1818 "github.com/spf13/cobra"
1919
20- "github.com/bnema/forever-db/internal/defs"
21- "github.com/bnema/forever-db/internal/fsutil"
22- "github.com/bnema/forever-db/internal/install"
23- "github.com/bnema/forever-db/internal/sources"
24- "github.com/bnema/forever-db/internal/tactkeys"
20+ "bnema.dev/forever-db/internal/fsutil"
21+ "bnema.dev/forever-db/pkg/casc"
22+ "bnema.dev/forever-db/pkg/db2"
23+ "bnema.dev/forever-db/pkg/defs"
24+ "bnema.dev/forever-db/pkg/install"
25+ "bnema.dev/forever-db/pkg/sources"
26+ "bnema.dev/forever-db/pkg/tactkeys"
2527 )
2628
2729 // Test hooks for defs update.
@@ -83,7 +85,14 @@ var defsUpdateCmd = &cobra.Command{
8385 return err
8486 }
8587 fresh, stats, err := defs.Generate(ctx, defs.GenerateInput{
86- Install: inst, Manifest: manifestEntries(manifest), DBDPath: src.DBDPath, Keys: ring,
88+ Open: func(keys db2.KeyRing) (defs.FileSource, error) {
89+ st, err := casc.Open(inst, keys)
90+ if err != nil {
91+ return nil, err
92+ }
93+ return st, nil
94+ },
95+ Version: inst.Version, Manifest: manifestEntries(manifest), DBDPath: src.DBDPath, Keys: ring,
8796 Source: defs.Source{WoWDBDefsCommit: src.DBDCommit, TACTKeysSHA256: src.TACTKeysSHA256},
8897 })
8998 if err != nil {
@@ -17,11 +17,13 @@ import (
17 17
18 "github.com/spf13/cobra"18 "github.com/spf13/cobra"
19 19
20- "github.com/bnema/forever-db/internal/defs"20+ "bnema.dev/forever-db/internal/fsutil"
21- "github.com/bnema/forever-db/internal/fsutil"21+ "bnema.dev/forever-db/pkg/casc"
22- "github.com/bnema/forever-db/internal/install"22+ "bnema.dev/forever-db/pkg/db2"
23- "github.com/bnema/forever-db/internal/sources"23+ "bnema.dev/forever-db/pkg/defs"
24- "github.com/bnema/forever-db/internal/tactkeys"24+ "bnema.dev/forever-db/pkg/install"
25+ "bnema.dev/forever-db/pkg/sources"
26+ "bnema.dev/forever-db/pkg/tactkeys"
25 )27 )
26 28
27 // Test hooks for defs update.29 // Test hooks for defs update.
@@ -83,7 +85,14 @@ var defsUpdateCmd = &cobra.Command{
83 return err85 return err
84 }86 }
85 fresh, stats, err := defs.Generate(ctx, defs.GenerateInput{87 fresh, stats, err := defs.Generate(ctx, defs.GenerateInput{
86- Install: inst, Manifest: manifestEntries(manifest), DBDPath: src.DBDPath, Keys: ring,88+ Open: func(keys db2.KeyRing) (defs.FileSource, error) {
89+ st, err := casc.Open(inst, keys)
90+ if err != nil {
91+ return nil, err
92+ }
93+ return st, nil
94+ },
95+ Version: inst.Version, Manifest: manifestEntries(manifest), DBDPath: src.DBDPath, Keys: ring,
87 Source: defs.Source{WoWDBDefsCommit: src.DBDCommit, TACTKeysSHA256: src.TACTKeysSHA256},96 Source: defs.Source{WoWDBDefsCommit: src.DBDCommit, TACTKeysSHA256: src.TACTKeysSHA256},
88 })97 })
89 if err != nil {98 if err != nil {
M cmd/defs_test.go +4 -4
@@ -13,9 +13,9 @@ import (
1313 "strings"
1414 "testing"
1515
16- "github.com/bnema/forever-db/internal/defs"
17- "github.com/bnema/forever-db/internal/sources"
18- "github.com/bnema/forever-db/internal/testutil"
16+ "bnema.dev/forever-db/internal/testutil"
17+ "bnema.dev/forever-db/pkg/defs"
18+ "bnema.dev/forever-db/pkg/sources"
1919 )
2020
2121 const defsTestSHA = "0123456789abcdef0123456789abcdef01234567"
@@ -171,7 +171,7 @@ func TestDefsShow(t *testing.T) {
171171 t.Fatal(err)
172172 }
173173 if !strings.Contains(out, "origin: local") || !strings.Contains(out, "tables: 1, layouts: 1, keys: 0") || !strings.Contains(out, defsTestSHA) ||
174- !strings.HasSuffix(out, "attribution: table definitions from WoWDBDefs contributors (CC BY-SA 4.0, https://github.com/wowdev/WoWDBDefs); see internal/defs/data/README.md\n") {
174+ !strings.HasSuffix(out, "attribution: table definitions from WoWDBDefs contributors (CC BY-SA 4.0, https://github.com/wowdev/WoWDBDefs); see pkg/defs/data/README.md\n") {
175175 t.Fatalf("out = %s", out)
176176 }
177177 }
@@ -13,9 +13,9 @@ import (
13 "strings"13 "strings"
14 "testing"14 "testing"
15 15
16- "github.com/bnema/forever-db/internal/defs"16+ "bnema.dev/forever-db/internal/testutil"
17- "github.com/bnema/forever-db/internal/sources"17+ "bnema.dev/forever-db/pkg/defs"
18- "github.com/bnema/forever-db/internal/testutil"18+ "bnema.dev/forever-db/pkg/sources"
19 )19 )
20 20
21 const defsTestSHA = "0123456789abcdef0123456789abcdef01234567"21 const defsTestSHA = "0123456789abcdef0123456789abcdef01234567"
@@ -171,7 +171,7 @@ func TestDefsShow(t *testing.T) {
171 t.Fatal(err)171 t.Fatal(err)
172 }172 }
173 if !strings.Contains(out, "origin: local") || !strings.Contains(out, "tables: 1, layouts: 1, keys: 0") || !strings.Contains(out, defsTestSHA) ||173 if !strings.Contains(out, "origin: local") || !strings.Contains(out, "tables: 1, layouts: 1, keys: 0") || !strings.Contains(out, defsTestSHA) ||
174- !strings.HasSuffix(out, "attribution: table definitions from WoWDBDefs contributors (CC BY-SA 4.0, https://github.com/wowdev/WoWDBDefs); see internal/defs/data/README.md\n") {174+ !strings.HasSuffix(out, "attribution: table definitions from WoWDBDefs contributors (CC BY-SA 4.0, https://github.com/wowdev/WoWDBDefs); see pkg/defs/data/README.md\n") {
175 t.Fatalf("out = %s", out)175 t.Fatalf("out = %s", out)
176 }176 }
177 }177 }
M cmd/export.go +73 -17
@@ -1,30 +1,43 @@
11 package cmd
22
33 import (
4+ "context"
45 "fmt"
56 "io"
7+ "log/slog"
68 "os"
79 "os/signal"
10+ "path/filepath"
811 "syscall"
912
1013 "github.com/spf13/cobra"
1114
12- "github.com/bnema/forever-db/internal/export"
13- "github.com/bnema/forever-db/internal/install"
15+ "bnema.dev/forever-db/internal/export"
16+ "bnema.dev/forever-db/pkg/casc/cdn"
17+ "bnema.dev/forever-db/pkg/dataset"
18+ "bnema.dev/forever-db/pkg/db2"
19+ "bnema.dev/forever-db/pkg/install"
1420 )
1521
16-var exportForce bool
22+var (
23+ exportForce bool
24+ exportCDN bool
25+ exportHotfixes string
26+)
1727
1828 var exportCmd = &cobra.Command{
1929 Use: "export",
2030 Short: "Export every client table to a SQLite database",
2131 Args: cobra.NoArgs,
2232 RunE: func(cmd *cobra.Command, args []string) error {
23- dir, err := resolveDir(dirFlag, os.Getenv)
33+ out, err := resolveOut(outFlag, os.Getenv)
2434 if err != nil {
2535 return err
2636 }
27- out, err := resolveOut(outFlag, os.Getenv)
37+ if exportCDN {
38+ return exportFromCDN(cmd, out)
39+ }
40+ dir, err := resolveDir(dirFlag, os.Getenv)
2841 if err != nil {
2942 return err
3043 }
@@ -33,7 +46,7 @@ var exportCmd = &cobra.Command{
3346 return err
3447 }
3548 w := cmd.OutOrStdout()
36- if !exportForce {
49+ if !exportForce && exportHotfixes == "" {
3750 r, err := export.Status(inst, out)
3851 if err != nil {
3952 return err
@@ -43,14 +56,9 @@ var exportCmd = &cobra.Command{
4356 return err
4457 }
4558 }
46- ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
59+ ctx, stop := signalContext(cmd)
4760 defer stop()
48- // After the first signal, restore default handling so a second one kills.
49- go func() {
50- <-ctx.Done()
51- stop()
52- }()
53- sum, err := export.Run(ctx, export.Options{Dir: dir, OutDir: out, ToolVersion: version})
61+ sum, err := export.Run(ctx, export.Options{Dir: dir, OutDir: out, ToolVersion: version, HotfixesPath: exportHotfixes})
5462 if err != nil {
5563 return err
5664 }
@@ -59,12 +67,58 @@ var exportCmd = &cobra.Command{
5967 },
6068 }
6169
70+// signalContext cancels on SIGINT/SIGTERM; after the first signal, default
71+// handling is restored so a second one kills.
72+func signalContext(cmd *cobra.Command) (context.Context, context.CancelFunc) {
73+ ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
74+ go func() {
75+ <-ctx.Done()
76+ stop()
77+ }()
78+ return ctx, stop
79+}
80+
81+// exportFromCDN exports the latest CDN build. It always exports: status
82+// only compares local exports with the install.
83+func exportFromCDN(cmd *cobra.Command, out string) error {
84+ if dirFlag != "" {
85+ slog.Warn("--cdn: --dir is ignored")
86+ }
87+ cache, err := cacheDir(os.Getenv)
88+ if err != nil {
89+ return err
90+ }
91+ ctx, stop := signalContext(cmd)
92+ defer stop()
93+ cfg := cdn.Config{CacheDir: filepath.Join(cache, "cdn"), Locale: cdn.DefaultLocale}
94+ b, err := cdn.LatestBuild(ctx, cfg)
95+ if err != nil {
96+ return err
97+ }
98+ slog.Info("CDN build", "version", b.Version)
99+ sum, err := export.Run(ctx, export.Options{OutDir: out, ToolVersion: version, HotfixesPath: exportHotfixes,
100+ Remote: &export.Remote{Source: export.SourceCDN, Version: b.Version, BuildNumber: b.BuildNumber,
101+ BuildKey: b.BuildConfig, Locale: cfg.Locale,
102+ Open: func(keys db2.KeyRing) (dataset.FileSource, error) {
103+ st, err := cdn.Open(ctx, cfg, b, keys)
104+ if err != nil {
105+ return nil, err
106+ }
107+ return st, nil
108+ }}})
109+ if err != nil {
110+ return err
111+ }
112+ printSummary(cmd.OutOrStdout(), sum)
113+ return nil
114+}
115+
62116 func printSummary(w io.Writer, s *export.Summary) {
63- fmt.Fprintf(w, "exported %s to %s in %s\n", s.Version, s.OutputPath, s.Duration.Round(1e7))
117+ fmt.Fprintf(w, "exported %s (%s) to %s in %s\n", s.Version, s.Source, s.OutputPath, s.Duration.Round(1e7))
64118 fmt.Fprintf(w, "tables: %d ok, %d absent, %d no_definition, %d failed\n",
65- s.Counts[export.StatusOK], s.Counts[export.StatusAbsent], s.Counts[export.StatusNoDefinition], s.Counts[export.StatusFailed])
119+ s.Counts[dataset.StatusOK], s.Counts[dataset.StatusAbsent], s.Counts[dataset.StatusNoDefinition], s.Counts[dataset.StatusFailed])
66120 for _, f := range s.Failed {
67- fmt.Fprintf(w, " failed %s: %s\n", f.Name, f.Err)
121+ fmt.Fprintf(w, " failed %s: %s\n", f.Name, f.Error)
68122 }
69123 fmt.Fprintf(w, "hotfixes (%s): %d upserts, %d deletes, %d reverts, %d errors\n",
70124 s.DBCacheStatus, s.Hotfix.Upserts, s.Hotfix.Deletes, s.Hotfix.Reverts, s.Hotfix.Errors)
@@ -85,12 +139,14 @@ func printSummary(w io.Writer, s *export.Summary) {
85139 generated = "unknown"
86140 }
87141 fmt.Fprintf(w, "definitions: %s (WoWDBDefs %s, generated %s)\n", s.DefsOrigin, commit, generated)
88- if n := s.Counts[export.StatusNoDefinition]; n > 0 {
142+ if n := s.Counts[dataset.StatusNoDefinition]; n > 0 {
89143 fmt.Fprintf(w, "hint: %d tables have no definition — run \"forever-db defs update\"\n", n)
90144 }
91145 }
92146
93147 func init() {
94148 exportCmd.Flags().BoolVar(&exportForce, "force", false, "export even when the last export is up to date")
149+ exportCmd.Flags().BoolVar(&exportCDN, "cdn", false, "read the latest build from the Blizzard CDN instead of the install (uses the network)")
150+ exportCmd.Flags().StringVar(&exportHotfixes, "hotfixes", "", "DBCache.bin to apply (default: the install's; none with --cdn)")
95151 rootCmd.AddCommand(exportCmd)
96152 }
@@ -1,30 +1,43 @@
1 package cmd1 package cmd
2 2
3 import (3 import (
4+ "context"
4 "fmt"5 "fmt"
5 "io"6 "io"
7+ "log/slog"
6 "os"8 "os"
7 "os/signal"9 "os/signal"
10+ "path/filepath"
8 "syscall"11 "syscall"
9 12
10 "github.com/spf13/cobra"13 "github.com/spf13/cobra"
11 14
12- "github.com/bnema/forever-db/internal/export"15+ "bnema.dev/forever-db/internal/export"
13- "github.com/bnema/forever-db/internal/install"16+ "bnema.dev/forever-db/pkg/casc/cdn"
17+ "bnema.dev/forever-db/pkg/dataset"
18+ "bnema.dev/forever-db/pkg/db2"
19+ "bnema.dev/forever-db/pkg/install"
14 )20 )
15 21
16-var exportForce bool22+var (
23+ exportForce bool
24+ exportCDN bool
25+ exportHotfixes string
26+)
17 27
18 var exportCmd = &cobra.Command{28 var exportCmd = &cobra.Command{
19 Use: "export",29 Use: "export",
20 Short: "Export every client table to a SQLite database",30 Short: "Export every client table to a SQLite database",
21 Args: cobra.NoArgs,31 Args: cobra.NoArgs,
22 RunE: func(cmd *cobra.Command, args []string) error {32 RunE: func(cmd *cobra.Command, args []string) error {
23- dir, err := resolveDir(dirFlag, os.Getenv)33+ out, err := resolveOut(outFlag, os.Getenv)
24 if err != nil {34 if err != nil {
25 return err35 return err
26 }36 }
27- out, err := resolveOut(outFlag, os.Getenv)37+ if exportCDN {
38+ return exportFromCDN(cmd, out)
39+ }
40+ dir, err := resolveDir(dirFlag, os.Getenv)
28 if err != nil {41 if err != nil {
29 return err42 return err
30 }43 }
@@ -33,7 +46,7 @@ var exportCmd = &cobra.Command{
33 return err46 return err
34 }47 }
35 w := cmd.OutOrStdout()48 w := cmd.OutOrStdout()
36- if !exportForce {49+ if !exportForce && exportHotfixes == "" {
37 r, err := export.Status(inst, out)50 r, err := export.Status(inst, out)
38 if err != nil {51 if err != nil {
39 return err52 return err
@@ -43,14 +56,9 @@ var exportCmd = &cobra.Command{
43 return err56 return err
44 }57 }
45 }58 }
46- ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)59+ ctx, stop := signalContext(cmd)
47 defer stop()60 defer stop()
48- // After the first signal, restore default handling so a second one kills.61+ sum, err := export.Run(ctx, export.Options{Dir: dir, OutDir: out, ToolVersion: version, HotfixesPath: exportHotfixes})
49- go func() {
50- <-ctx.Done()
51- stop()
52- }()
53- sum, err := export.Run(ctx, export.Options{Dir: dir, OutDir: out, ToolVersion: version})
54 if err != nil {62 if err != nil {
55 return err63 return err
56 }64 }
@@ -59,12 +67,58 @@ var exportCmd = &cobra.Command{
59 },67 },
60 }68 }
61 69
70+// signalContext cancels on SIGINT/SIGTERM; after the first signal, default
71+// handling is restored so a second one kills.
72+func signalContext(cmd *cobra.Command) (context.Context, context.CancelFunc) {
73+ ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
74+ go func() {
75+ <-ctx.Done()
76+ stop()
77+ }()
78+ return ctx, stop
79+}
80+
81+// exportFromCDN exports the latest CDN build. It always exports: status
82+// only compares local exports with the install.
83+func exportFromCDN(cmd *cobra.Command, out string) error {
84+ if dirFlag != "" {
85+ slog.Warn("--cdn: --dir is ignored")
86+ }
87+ cache, err := cacheDir(os.Getenv)
88+ if err != nil {
89+ return err
90+ }
91+ ctx, stop := signalContext(cmd)
92+ defer stop()
93+ cfg := cdn.Config{CacheDir: filepath.Join(cache, "cdn"), Locale: cdn.DefaultLocale}
94+ b, err := cdn.LatestBuild(ctx, cfg)
95+ if err != nil {
96+ return err
97+ }
98+ slog.Info("CDN build", "version", b.Version)
99+ sum, err := export.Run(ctx, export.Options{OutDir: out, ToolVersion: version, HotfixesPath: exportHotfixes,
100+ Remote: &export.Remote{Source: export.SourceCDN, Version: b.Version, BuildNumber: b.BuildNumber,
101+ BuildKey: b.BuildConfig, Locale: cfg.Locale,
102+ Open: func(keys db2.KeyRing) (dataset.FileSource, error) {
103+ st, err := cdn.Open(ctx, cfg, b, keys)
104+ if err != nil {
105+ return nil, err
106+ }
107+ return st, nil
108+ }}})
109+ if err != nil {
110+ return err
111+ }
112+ printSummary(cmd.OutOrStdout(), sum)
113+ return nil
114+}
115+
62 func printSummary(w io.Writer, s *export.Summary) {116 func printSummary(w io.Writer, s *export.Summary) {
63- fmt.Fprintf(w, "exported %s to %s in %s\n", s.Version, s.OutputPath, s.Duration.Round(1e7))117+ fmt.Fprintf(w, "exported %s (%s) to %s in %s\n", s.Version, s.Source, s.OutputPath, s.Duration.Round(1e7))
64 fmt.Fprintf(w, "tables: %d ok, %d absent, %d no_definition, %d failed\n",118 fmt.Fprintf(w, "tables: %d ok, %d absent, %d no_definition, %d failed\n",
65- s.Counts[export.StatusOK], s.Counts[export.StatusAbsent], s.Counts[export.StatusNoDefinition], s.Counts[export.StatusFailed])119+ s.Counts[dataset.StatusOK], s.Counts[dataset.StatusAbsent], s.Counts[dataset.StatusNoDefinition], s.Counts[dataset.StatusFailed])
66 for _, f := range s.Failed {120 for _, f := range s.Failed {
67- fmt.Fprintf(w, " failed %s: %s\n", f.Name, f.Err)121+ fmt.Fprintf(w, " failed %s: %s\n", f.Name, f.Error)
68 }122 }
69 fmt.Fprintf(w, "hotfixes (%s): %d upserts, %d deletes, %d reverts, %d errors\n",123 fmt.Fprintf(w, "hotfixes (%s): %d upserts, %d deletes, %d reverts, %d errors\n",
70 s.DBCacheStatus, s.Hotfix.Upserts, s.Hotfix.Deletes, s.Hotfix.Reverts, s.Hotfix.Errors)124 s.DBCacheStatus, s.Hotfix.Upserts, s.Hotfix.Deletes, s.Hotfix.Reverts, s.Hotfix.Errors)
@@ -85,12 +139,14 @@ func printSummary(w io.Writer, s *export.Summary) {
85 generated = "unknown"139 generated = "unknown"
86 }140 }
87 fmt.Fprintf(w, "definitions: %s (WoWDBDefs %s, generated %s)\n", s.DefsOrigin, commit, generated)141 fmt.Fprintf(w, "definitions: %s (WoWDBDefs %s, generated %s)\n", s.DefsOrigin, commit, generated)
88- if n := s.Counts[export.StatusNoDefinition]; n > 0 {142+ if n := s.Counts[dataset.StatusNoDefinition]; n > 0 {
89 fmt.Fprintf(w, "hint: %d tables have no definition — run \"forever-db defs update\"\n", n)143 fmt.Fprintf(w, "hint: %d tables have no definition — run \"forever-db defs update\"\n", n)
90 }144 }
91 }145 }
92 146
93 func init() {147 func init() {
94 exportCmd.Flags().BoolVar(&exportForce, "force", false, "export even when the last export is up to date")148 exportCmd.Flags().BoolVar(&exportForce, "force", false, "export even when the last export is up to date")
149+ exportCmd.Flags().BoolVar(&exportCDN, "cdn", false, "read the latest build from the Blizzard CDN instead of the install (uses the network)")
150+ exportCmd.Flags().StringVar(&exportHotfixes, "hotfixes", "", "DBCache.bin to apply (default: the install's; none with --cdn)")
95 rootCmd.AddCommand(exportCmd)151 rootCmd.AddCommand(exportCmd)
96 }152 }
M cmd/export_test.go +5 -4
@@ -7,8 +7,9 @@ import (
77 "strings"
88 "testing"
99
10- "github.com/bnema/forever-db/internal/export"
11- "github.com/bnema/forever-db/internal/testutil"
10+ "bnema.dev/forever-db/internal/export"
11+ "bnema.dev/forever-db/internal/testutil"
12+ "bnema.dev/forever-db/pkg/dataset"
1213 )
1314
1415 func runCLI(t *testing.T, args ...string) (string, error) {
@@ -63,7 +64,7 @@ func TestOfflineFlagRemoved(t *testing.T) {
6364
6465 func TestPrintSummaryHint(t *testing.T) {
6566 var b bytes.Buffer
66- printSummary(&b, &export.Summary{Counts: map[string]int{export.StatusNoDefinition: 3}, DefsOrigin: "local",
67+ printSummary(&b, &export.Summary{Counts: map[dataset.TableStatus]int{dataset.StatusNoDefinition: 3}, DefsOrigin: "local",
6768 DefsCommit: "0123456789abcdef0123", DefsGeneratedAt: "2026-11-20T10:00:00Z"})
6869 out := b.String()
6970 if !strings.Contains(out, "definitions: local (WoWDBDefs 0123456789ab, generated 2026-11-20)\n") ||
@@ -71,7 +72,7 @@ func TestPrintSummaryHint(t *testing.T) {
7172 t.Fatalf("out = %s", out)
7273 }
7374 b.Reset()
74- printSummary(&b, &export.Summary{Counts: map[string]int{}})
75+ printSummary(&b, &export.Summary{Counts: map[dataset.TableStatus]int{}})
7576 if strings.Contains(b.String(), "hint:") {
7677 t.Fatalf("unexpected hint: %s", b.String())
7778 }
@@ -7,8 +7,9 @@ import (
7 "strings"7 "strings"
8 "testing"8 "testing"
9 9
10- "github.com/bnema/forever-db/internal/export"10+ "bnema.dev/forever-db/internal/export"
11- "github.com/bnema/forever-db/internal/testutil"11+ "bnema.dev/forever-db/internal/testutil"
12+ "bnema.dev/forever-db/pkg/dataset"
12 )13 )
13 14
14 func runCLI(t *testing.T, args ...string) (string, error) {15 func runCLI(t *testing.T, args ...string) (string, error) {
@@ -63,7 +64,7 @@ func TestOfflineFlagRemoved(t *testing.T) {
63 64
64 func TestPrintSummaryHint(t *testing.T) {65 func TestPrintSummaryHint(t *testing.T) {
65 var b bytes.Buffer66 var b bytes.Buffer
66- printSummary(&b, &export.Summary{Counts: map[string]int{export.StatusNoDefinition: 3}, DefsOrigin: "local",67+ printSummary(&b, &export.Summary{Counts: map[dataset.TableStatus]int{dataset.StatusNoDefinition: 3}, DefsOrigin: "local",
67 DefsCommit: "0123456789abcdef0123", DefsGeneratedAt: "2026-11-20T10:00:00Z"})68 DefsCommit: "0123456789abcdef0123", DefsGeneratedAt: "2026-11-20T10:00:00Z"})
68 out := b.String()69 out := b.String()
69 if !strings.Contains(out, "definitions: local (WoWDBDefs 0123456789ab, generated 2026-11-20)\n") ||70 if !strings.Contains(out, "definitions: local (WoWDBDefs 0123456789ab, generated 2026-11-20)\n") ||
@@ -71,7 +72,7 @@ func TestPrintSummaryHint(t *testing.T) {
71 t.Fatalf("out = %s", out)72 t.Fatalf("out = %s", out)
72 }73 }
73 b.Reset()74 b.Reset()
74- printSummary(&b, &export.Summary{Counts: map[string]int{}})75+ printSummary(&b, &export.Summary{Counts: map[dataset.TableStatus]int{}})
75 if strings.Contains(b.String(), "hint:") {76 if strings.Contains(b.String(), "hint:") {
76 t.Fatalf("unexpected hint: %s", b.String())77 t.Fatalf("unexpected hint: %s", b.String())
77 }78 }
M cmd/status.go +2 -2
@@ -9,8 +9,8 @@ import (
99
1010 "github.com/spf13/cobra"
1111
12- "github.com/bnema/forever-db/internal/export"
13- "github.com/bnema/forever-db/internal/install"
12+ "bnema.dev/forever-db/internal/export"
13+ "bnema.dev/forever-db/pkg/install"
1414 )
1515
1616 var statusJSON bool
@@ -9,8 +9,8 @@ import (
9 9
10 "github.com/spf13/cobra"10 "github.com/spf13/cobra"
11 11
12- "github.com/bnema/forever-db/internal/export"12+ "bnema.dev/forever-db/internal/export"
13- "github.com/bnema/forever-db/internal/install"13+ "bnema.dev/forever-db/pkg/install"
14 )14 )
15 15
16 var statusJSON bool16 var statusJSON bool
M cmd/status_test.go +1 -1
@@ -5,7 +5,7 @@ import (
55 "strings"
66 "testing"
77
8- "github.com/bnema/forever-db/internal/export"
8+ "bnema.dev/forever-db/internal/export"
99 )
1010
1111 func TestPrintStatus(t *testing.T) {
@@ -5,7 +5,7 @@ import (
5 "strings"5 "strings"
6 "testing"6 "testing"
7 7
8- "github.com/bnema/forever-db/internal/export"8+ "bnema.dev/forever-db/internal/export"
9 )9 )
10 10
11 func TestPrintStatus(t *testing.T) {11 func TestPrintStatus(t *testing.T) {
M go.mod +1 -1
@@ -1,4 +1,4 @@
1-module github.com/bnema/forever-db
1+module bnema.dev/forever-db
22
33 go 1.26.0
44
@@ -1,4 +1,4 @@
1-module github.com/bnema/forever-db1+module bnema.dev/forever-db
2 2
3 go 1.26.03 go 1.26.0
4 4
M internal/export/export.go +191 -184
@@ -1,3 +1,4 @@
1+// Package export runs the DB2 → SQLite export pipeline.
12 package export
23
34 import (
@@ -6,6 +7,7 @@ import (
67 "encoding/hex"
78 "errors"
89 "fmt"
10+ "io"
911 "io/fs"
1012 "log/slog"
1113 "os"
@@ -13,24 +15,16 @@ import (
1315 "runtime"
1416 "sort"
1517 "strconv"
16- "sync"
1718 "syscall"
1819 "time"
1920
20- "github.com/bnema/forever-db/internal/casc"
21- "github.com/bnema/forever-db/internal/db2"
22- "github.com/bnema/forever-db/internal/defs"
23- "github.com/bnema/forever-db/internal/hotfix"
24- "github.com/bnema/forever-db/internal/install"
25- "github.com/bnema/forever-db/internal/schema"
26-)
27-
28-// DBCache statuses.
29-const (
30- DBCacheApplied = "applied"
31- DBCacheMissing = "missing"
32- DBCacheInvalid = "invalid"
33- DBCacheBuildMismatch = "build_mismatch"
21+ "bnema.dev/forever-db/internal/schema"
22+ "bnema.dev/forever-db/pkg/casc"
23+ "bnema.dev/forever-db/pkg/dataset"
24+ "bnema.dev/forever-db/pkg/db2"
25+ "bnema.dev/forever-db/pkg/defs"
26+ "bnema.dev/forever-db/pkg/hotfix"
27+ "bnema.dev/forever-db/pkg/install"
3428 )
3529
3630 // CurrentName is the symlink pointing at the latest export.
@@ -38,30 +32,54 @@ const CurrentName = "current.sqlite"
3832
3933 // Options configures Run.
4034 type Options struct {
41- Dir, OutDir string // OutDir also holds the optional defs.json.gz override
42- ToolVersion string
43- Workers int // 0 → runtime.NumCPU()
44- Now func() time.Time
35+ Dir, OutDir string // OutDir also holds the optional defs.json.gz override; Dir is unused with Remote
36+ Remote *Remote // nil = read the local install in Dir
37+ // HotfixesPath overrides the DBCache.bin to apply. Empty: the install's
38+ // DBCache.bin for a local export, no hotfixes for a remote one.
39+ HotfixesPath string
40+ ToolVersion string
41+ Workers int // 0 → runtime.NumCPU()
42+ Now func() time.Time
4543
4644 // Test hooks.
4745 afterResult func(w *Writer) // after each table result is written
4846 beforeRename func() // after the database is closed, before the install re-check
4947 }
5048
49+// Source values (_meta.source).
50+const (
51+ SourceLocal = "local"
52+ SourceCDN = "cdn"
53+)
54+
55+// Remote is a game build read from somewhere other than a local install.
56+// export never opens network storage itself: the caller provides Open.
57+type Remote struct {
58+ Source string // e.g. SourceCDN
59+ Version string
60+ BuildNumber uint32
61+ BuildKey string // build config hash
62+ Locale string
63+ // Open opens the storage with the snapshot's key ring. Run closes the
64+ // returned source when it implements io.Closer.
65+ Open func(keys db2.KeyRing) (dataset.FileSource, error)
66+}
67+
5168 // TableFailure names a table that failed to export.
5269 type TableFailure struct {
53- Name, Err string
70+ Name, Error string
5471 }
5572
5673 // Summary reports an export.
5774 type Summary struct {
5875 Version, OutputPath string
59- Counts map[string]int // by table status
76+ Source string // SourceLocal or SourceCDN
77+ Counts map[dataset.TableStatus]int
6078 Failed []TableFailure
6179 Hotfix hotfix.Stats
6280 SkippedRows int
6381 MissingKeys map[uint64]int
64- DBCacheStatus string
82+ DBCacheStatus dataset.HotfixStatus
6583 ClientKeysAdded int
6684 Duration time.Duration
6785 DefsOrigin string // defs.OriginEmbedded or defs.OriginLocal
@@ -69,46 +87,49 @@ type Summary struct {
6987 DefsGeneratedAt string
7088 }
7189
72-// FileName returns the export file name for version.
90+// FileName returns the file name of a local export of version.
7391 func FileName(version string) string { return "wowf-" + version + ".sqlite" }
7492
93+// RemoteFileName returns the file name of an export of version read from
94+// source (e.g. wowf-1.60.1.71037-cdn.sqlite).
95+func RemoteFileName(version, source string) string {
96+ return "wowf-" + version + "-" + source + ".sqlite"
97+}
98+
99+// dbcache is the raw hotfix cache: nil data with status invalid when the
100+// file exists but cannot be read (e.g. the game writing it).
75101 type dbcache struct {
76- cache *hotfix.Cache
77- status string
102+ data []byte
103+ status dataset.HotfixStatus // "" = decided by dataset.Load
78104 sha string
79105 }
80106
81-// loadDBCache reads the hotfix cache. An unsupported DBCache version is
82-// fatal; other read or parse errors (e.g. the game writing the file) give
83-// status invalid and no hotfixes.
84-func loadDBCache(inst *install.Install) (dbcache, error) {
85- raw, err := os.ReadFile(inst.HotfixPath())
107+// readDBCache reads path; a missing file means no hotfixes unless the path
108+// was given explicitly (required), which is an error.
109+func readDBCache(path string, required bool) (dbcache, error) {
110+ if path == "" {
111+ return dbcache{}, nil
112+ }
113+ raw, err := os.ReadFile(path)
86114 if errors.Is(err, fs.ErrNotExist) {
87- return dbcache{status: DBCacheMissing}, nil
115+ if required {
116+ return dbcache{}, err
117+ }
118+ return dbcache{}, nil
88119 }
89120 if err != nil {
90121 slog.Warn("DBCache unreadable, hotfixes not applied", "err", err)
91- return dbcache{status: DBCacheInvalid}, nil
122+ return dbcache{status: dataset.HotfixInvalid}, nil
92123 }
93124 h := sha256.Sum256(raw)
94- d := dbcache{sha: hex.EncodeToString(h[:])}
95- c, err := hotfix.Parse(raw)
96- switch {
97- case errors.Is(err, hotfix.ErrUnsupportedHotfix):
98- return d, fmt.Errorf("%s: %w", inst.HotfixPath(), err)
99- case err != nil:
100- slog.Warn("DBCache invalid, hotfixes not applied", "err", err)
101- d.status = DBCacheInvalid
102- case c.Build != inst.BuildNumber:
103- d.status = DBCacheBuildMismatch
104- default:
105- d.cache, d.status = c, DBCacheApplied
106- }
107- return d, nil
125+ return dbcache{data: raw, sha: hex.EncodeToString(h[:])}, nil
108126 }
109127
110-// Run exports every manifest table of the install in opts.Dir into
111-// <OutDir>/wowf-<version>.sqlite and points current.sqlite at it.
128+// Run exports every snapshot table. By default it reads the install in
129+// opts.Dir, writes <OutDir>/wowf-<version>.sqlite and points current.sqlite
130+// at it. With opts.Remote it reads that build instead, writes
131+// <OutDir>/wowf-<version>-<source>.sqlite and leaves current.sqlite alone:
132+// current always tracks the local install.
112133 func Run(ctx context.Context, opts Options) (*Summary, error) {
113134 start := time.Now()
114135 now := opts.Now
@@ -120,7 +141,7 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
120141 workers = runtime.NumCPU()
121142 }
122143
123- inst, err := install.Detect(opts.Dir)
144+ b, err := resolveBuild(opts)
124145 if err != nil {
125146 return nil, err
126147 }
@@ -140,45 +161,29 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
140161 if err != nil {
141162 return nil, err
142163 }
143- tables := snap.TableEntries()
144164 ring := snap.Ring()
145- st, err := casc.Open(inst, ring)
165+ st, err := b.open(ring)
146166 if err != nil {
147167 return nil, err
148168 }
149- defer st.Close()
150- fdids := make([]uint32, len(tables))
151- byName := make(map[string]defs.TableEntry, len(tables))
152- for i, e := range tables {
153- fdids[i] = e.FDID
154- byName[e.Name] = e
155- }
156- if _, err := st.Resolve(fdids); err != nil {
157- return nil, err
169+ if c, ok := st.(io.Closer); ok {
170+ defer c.Close()
158171 }
159- st.ReleaseRoot()
160172 if err := ctx.Err(); err != nil {
161173 return nil, err
162174 }
163-
164- if err := ctx.Err(); err != nil {
165- return nil, err
166- }
167- dc, err := loadDBCache(inst)
175+ dc, err := readDBCache(b.hotfixPath, opts.HotfixesPath != "")
168176 if err != nil {
169177 return nil, err
170178 }
171- sum := &Summary{Version: inst.Version, Counts: map[string]int{}, MissingKeys: map[uint64]int{}, DBCacheStatus: dc.status,
179+ sum := &Summary{Version: b.version, Source: b.source, Counts: map[dataset.TableStatus]int{}, MissingKeys: map[uint64]int{},
172180 DefsOrigin: origin, DefsCommit: snap.Source.WoWDBDefsCommit, DefsGeneratedAt: snap.GeneratedAt}
173- sum.ClientKeysAdded, err = loadClientKeys(st, byName, snap.Definition, ring, dc.cache)
174- if err != nil {
175- return nil, err
176- }
177181
178- if err := ctx.Err(); err != nil {
179- return nil, err
182+ name := FileName(b.version)
183+ if opts.Remote != nil {
184+ name = RemoteFileName(b.version, b.source)
180185 }
181- final := filepath.Join(opts.OutDir, FileName(inst.Version))
186+ final := filepath.Join(opts.OutDir, name)
182187 tmp := final + ".tmp"
183188 if err := os.Remove(tmp); err != nil && !errors.Is(err, fs.ErrNotExist) {
184189 return nil, err
@@ -195,32 +200,57 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
195200 os.Remove(tmp) // no-op after a successful rename
196201 }()
197202
198- defs, err := writeTables(ctx, w, st, snap.Definition, tables, ring, dc.cache, workers, sum, opts.afterResult)
203+ var written []*db2.Definition
204+ res, err := dataset.Load(ctx, dataset.Options{
205+ Source: st, Snapshot: snap, Ring: ring, Hotfixes: dc.data, BuildNumber: b.buildNumber, Workers: workers,
206+ OnTable: func(r dataset.TableReport, t *db2.Table) error {
207+ status, err := writeResult(w, r, t, sum)
208+ if err != nil {
209+ return err
210+ }
211+ if opts.afterResult != nil {
212+ opts.afterResult(w)
213+ }
214+ if status == dataset.StatusOK {
215+ written = append(written, t.Def)
216+ }
217+ return nil
218+ },
219+ })
220+ if errors.Is(err, hotfix.ErrUnsupportedHotfix) {
221+ return nil, fmt.Errorf("%s: %w", b.hotfixPath, err)
222+ }
199223 if err != nil {
200224 return nil, err
201225 }
226+ sum.ClientKeysAdded = res.ClientKeys
227+ sum.DBCacheStatus = res.HotfixStatus
228+ if dc.status != "" {
229+ sum.DBCacheStatus = dc.status
230+ }
202231 if err := ctx.Err(); err != nil {
203232 return nil, err
204233 }
205- if err := w.CreateIndexes(defs); err != nil {
234+ if err := w.CreateIndexes(written); err != nil {
206235 return nil, err
207236 }
208237 meta := map[string]string{
209238 schema.MetaSchemaVersion: strconv.Itoa(schema.Version),
210239 schema.MetaToolVersion: opts.ToolVersion,
211240 schema.MetaProduct: "wowf",
212- schema.MetaBuildVersion: inst.Version,
213- schema.MetaBuildKey: inst.BuildKey,
214- schema.MetaLocale: inst.Locale,
241+ schema.MetaBuildVersion: b.version,
242+ schema.MetaBuildKey: b.buildKey,
243+ schema.MetaLocale: b.locale,
244+ schema.MetaSource: b.source,
215245 schema.MetaExportedAt: now().UTC().Format(time.RFC3339),
216246 schema.MetaDBCacheSHA256: dc.sha,
217- schema.MetaDBCacheStatus: dc.status,
247+ schema.MetaDBCacheStatus: string(sum.DBCacheStatus),
218248 schema.MetaDefsOrigin: origin,
219249 schema.MetaDefsCommit: snap.Source.WoWDBDefsCommit,
220250 schema.MetaDefsGenerated: snap.GeneratedAt,
221251 schema.MetaDefsSHA256: defsSum,
222- schema.MetaTablesOK: strconv.Itoa(sum.Counts[StatusOK]),
223- schema.MetaTablesFailed: strconv.Itoa(sum.Counts[StatusFailed]),
252+ schema.MetaTablesOK: strconv.Itoa(sum.Counts[dataset.StatusOK]),
253+ schema.MetaTablesFailed: strconv.Itoa(sum.Counts[dataset.StatusFailed]),
224254 }
225255 if err := w.WriteMeta(meta); err != nil {
226256 return nil, err
@@ -232,12 +262,14 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
232262 if opts.beforeRename != nil {
233263 opts.beforeRename()
234264 }
235- again, err := install.Detect(opts.Dir)
236- if err != nil {
237- return nil, fmt.Errorf("install changed during export: %w", err)
238- }
239- if again.Version != inst.Version || again.BuildKey != inst.BuildKey {
240- return nil, errors.New("install changed during export")
265+ if opts.Remote == nil {
266+ again, err := install.Detect(opts.Dir)
267+ if err != nil {
268+ return nil, fmt.Errorf("install changed during export: %w", err)
269+ }
270+ if again.Version != b.version || again.BuildKey != b.buildKey {
271+ return nil, errors.New("install changed during export")
272+ }
241273 }
242274 if err := ctx.Err(); err != nil {
243275 return nil, err
@@ -245,16 +277,10 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
245277 if err := os.Rename(tmp, final); err != nil {
246278 return nil, err
247279 }
248- link := filepath.Join(opts.OutDir, CurrentName)
249- if err := os.Remove(link + ".tmp"); err != nil && !errors.Is(err, fs.ErrNotExist) {
250- return nil, err
251- }
252- if err := os.Symlink(FileName(inst.Version), link+".tmp"); err != nil {
253- return nil, err
254- }
255- if err := os.Rename(link+".tmp", link); err != nil {
256- os.Remove(link + ".tmp")
257- return nil, err
280+ if opts.Remote == nil {
281+ if err := pointCurrent(opts.OutDir, name); err != nil {
282+ return nil, err
283+ }
258284 }
259285 if err := syncDir(opts.OutDir); err != nil {
260286 return nil, err
@@ -296,123 +322,104 @@ func syncDir(dir string) error {
296322 return d.Sync()
297323 }
298324
299-// writeTables decodes tables in a worker pool and writes them from the
300-// calling goroutine. It returns the definitions of the written tables.
301-func writeTables(ctx context.Context, w *Writer, st *casc.Storage, lookup defLookup, tables []defs.TableEntry,
302- ring db2.KeyRing, hf *hotfix.Cache, workers int, sum *Summary, afterResult func(*Writer)) ([]*db2.Definition, error) {
303- ctx, cancel := context.WithCancel(ctx)
304- defer cancel()
305- jobs := make(chan defs.TableEntry)
306- results := make(chan TableResult)
307- var wg sync.WaitGroup
308- for i := 0; i < workers; i++ {
309- wg.Add(1)
310- go func() {
311- defer wg.Done()
312- for e := range jobs {
313- r := decodeTable(st, e, lookup, ring, hf)
314- select {
315- case results <- r:
316- case <-ctx.Done():
317- return
318- }
319- }
320- }()
321- }
322- go func() {
323- defer close(jobs)
324- for _, e := range tables {
325- select {
326- case jobs <- e:
327- case <-ctx.Done():
328- return
329- }
330- }
331- }()
332- go func() {
333- wg.Wait()
334- close(results)
335- }()
336-
337- var defs []*db2.Definition
338- var werr error
339- for r := range results {
340- if werr != nil {
341- continue // drain
342- }
343- status, err := writeResult(w, r, sum)
344- if err != nil {
345- werr = err
346- cancel()
347- continue
348- }
349- if afterResult != nil {
350- afterResult(w)
351- }
352- if status == StatusOK {
353- defs = append(defs, r.Def)
354- }
355- }
356- if werr != nil {
357- return nil, werr
358- }
359- if err := ctx.Err(); err != nil {
360- return nil, err
361- }
362- return defs, nil
363-}
364-
365325 // writeResult writes one decoded table and its status row. A table that
366326 // cannot be written is recorded as failed; only fatal writer errors are
367327 // returned. It returns the final table status.
368-func writeResult(w *Writer, r TableResult, sum *Summary) (string, error) {
369- if r.Status == StatusOK {
370- if err := w.WriteTable(r.Table); err != nil {
328+func writeResult(w *Writer, r dataset.TableReport, t *db2.Table, sum *Summary) (dataset.TableStatus, error) {
329+ if r.Status == dataset.StatusOK {
330+ if err := w.WriteTable(t); err != nil {
371331 if IsFatal(err) {
372332 return "", err
373333 }
374- slog.Warn("table write failed", "table", r.Entry.Name, "err", err)
375- r.Status, r.Err = StatusFailed, err
334+ slog.Warn("table write failed", "table", r.Name, "err", err)
335+ r.Status, r.Err = dataset.StatusFailed, err
376336 }
377337 }
378338 row := TableStatusRow{
379- TableName: r.Entry.Name, FDID: r.Entry.FDID, Status: r.Status,
339+ TableName: r.Name, FDID: r.FDID, Status: string(r.Status), MatchedBy: r.MatchedBy,
380340 BaseRows: r.BaseRows, HotfixUpserts: r.Hotfix.Upserts, HotfixDeletes: r.Hotfix.Deletes,
381341 HotfixReverts: r.Hotfix.Reverts, HotfixErrors: r.Hotfix.Errors,
382- SkippedRows: r.Info.SkippedRows, SkippedSections: r.Info.SkippedSections,
342+ SkippedRows: r.SkippedRows, SkippedSections: r.SkippedSections,
383343 }
384- if r.Entry.Hash != 0 {
385- row.TableHash = fmt.Sprintf("%08X", r.Entry.Hash)
344+ if r.Err != nil {
345+ row.Error = r.Err.Error()
346+ }
347+ if r.Hash != 0 {
348+ row.TableHash = fmt.Sprintf("%08X", r.Hash)
386349 }
387350 if r.Layout != 0 {
388351 row.LayoutHash = fmt.Sprintf("%08X", r.Layout)
389352 }
390- if r.Def != nil {
391- row.MatchedBy = r.Def.MatchedBy
392- }
393- if r.Err != nil {
394- row.Error = r.Err.Error()
395- }
396353 if err := w.WriteTableStatus(row); err != nil {
397354 return "", err
398355 }
399- if len(r.HotfixLog) > 0 {
400- if err := w.WriteHotfixLog(r.Entry.Name, r.HotfixLog); err != nil {
356+ if len(r.Log) > 0 {
357+ if err := w.WriteHotfixLog(r.Name, r.Log); err != nil {
401358 return "", err
402359 }
403360 }
404361 sum.Counts[r.Status]++
405- if r.Status == StatusFailed {
406- sum.Failed = append(sum.Failed, TableFailure{Name: r.Entry.Name, Err: row.Error})
362+ if r.Status == dataset.StatusFailed {
363+ sum.Failed = append(sum.Failed, TableFailure{Name: r.Name, Error: row.Error})
407364 }
408365 sum.Hotfix.Upserts += r.Hotfix.Upserts
409366 sum.Hotfix.Deletes += r.Hotfix.Deletes
410367 sum.Hotfix.Reverts += r.Hotfix.Reverts
411368 sum.Hotfix.Errors += r.Hotfix.Errors
412369 sum.Hotfix.Ignored += r.Hotfix.Ignored
413- sum.SkippedRows += r.Info.SkippedRows
370+ sum.SkippedRows += r.SkippedRows
414371 for k, n := range r.MissingKeys {
415372 sum.MissingKeys[k] += n
416373 }
417374 return r.Status, nil
418375 }
376+
377+// build is the game build an export reads.
378+type build struct {
379+ source, version, buildKey, locale, hotfixPath string
380+ buildNumber uint32
381+ open func(db2.KeyRing) (dataset.FileSource, error)
382+}
383+
384+func resolveBuild(opts Options) (build, error) {
385+ if r := opts.Remote; r != nil {
386+ if r.Open == nil || r.Version == "" || r.Source == "" {
387+ return build{}, errors.New("export: Remote needs Source, Version and Open")
388+ }
389+ return build{source: r.Source, version: r.Version, buildKey: r.BuildKey, locale: r.Locale,
390+ buildNumber: r.BuildNumber, hotfixPath: opts.HotfixesPath, open: r.Open}, nil
391+ }
392+ inst, err := install.Detect(opts.Dir)
393+ if err != nil {
394+ return build{}, err
395+ }
396+ hp := inst.HotfixPath()
397+ if opts.HotfixesPath != "" {
398+ hp = opts.HotfixesPath
399+ }
400+ return build{source: SourceLocal, version: inst.Version, buildKey: inst.BuildKey, locale: inst.Locale,
401+ buildNumber: inst.BuildNumber, hotfixPath: hp,
402+ open: func(keys db2.KeyRing) (dataset.FileSource, error) {
403+ st, err := casc.Open(inst, keys)
404+ if err != nil {
405+ return nil, err
406+ }
407+ return st, nil
408+ }}, nil
409+}
410+
411+// pointCurrent atomically points <dir>/current.sqlite at name.
412+func pointCurrent(dir, name string) error {
413+ link := filepath.Join(dir, CurrentName)
414+ if err := os.Remove(link + ".tmp"); err != nil && !errors.Is(err, fs.ErrNotExist) {
415+ return err
416+ }
417+ if err := os.Symlink(name, link+".tmp"); err != nil {
418+ return err
419+ }
420+ if err := os.Rename(link+".tmp", link); err != nil {
421+ os.Remove(link + ".tmp")
422+ return err
423+ }
424+ return nil
425+}
@@ -1,3 +1,4 @@
1+// Package export runs the DB2 → SQLite export pipeline.
1 package export2 package export
2 3
3 import (4 import (
@@ -6,6 +7,7 @@ import (
6 "encoding/hex"7 "encoding/hex"
7 "errors"8 "errors"
8 "fmt"9 "fmt"
10+ "io"
9 "io/fs"11 "io/fs"
10 "log/slog"12 "log/slog"
11 "os"13 "os"
@@ -13,24 +15,16 @@ import (
13 "runtime"15 "runtime"
14 "sort"16 "sort"
15 "strconv"17 "strconv"
16- "sync"
17 "syscall"18 "syscall"
18 "time"19 "time"
19 20
20- "github.com/bnema/forever-db/internal/casc"21+ "bnema.dev/forever-db/internal/schema"
21- "github.com/bnema/forever-db/internal/db2"22+ "bnema.dev/forever-db/pkg/casc"
22- "github.com/bnema/forever-db/internal/defs"23+ "bnema.dev/forever-db/pkg/dataset"
23- "github.com/bnema/forever-db/internal/hotfix"24+ "bnema.dev/forever-db/pkg/db2"
24- "github.com/bnema/forever-db/internal/install"25+ "bnema.dev/forever-db/pkg/defs"
25- "github.com/bnema/forever-db/internal/schema"26+ "bnema.dev/forever-db/pkg/hotfix"
26-)27+ "bnema.dev/forever-db/pkg/install"
27-
28-// DBCache statuses.
29-const (
30- DBCacheApplied = "applied"
31- DBCacheMissing = "missing"
32- DBCacheInvalid = "invalid"
33- DBCacheBuildMismatch = "build_mismatch"
34 )28 )
35 29
36 // CurrentName is the symlink pointing at the latest export.30 // CurrentName is the symlink pointing at the latest export.
@@ -38,30 +32,54 @@ const CurrentName = "current.sqlite"
38 32
39 // Options configures Run.33 // Options configures Run.
40 type Options struct {34 type Options struct {
41- Dir, OutDir string // OutDir also holds the optional defs.json.gz override35+ Dir, OutDir string // OutDir also holds the optional defs.json.gz override; Dir is unused with Remote
42- ToolVersion string36+ Remote *Remote // nil = read the local install in Dir
43- Workers int // 0 → runtime.NumCPU()37+ // HotfixesPath overrides the DBCache.bin to apply. Empty: the install's
44- Now func() time.Time38+ // DBCache.bin for a local export, no hotfixes for a remote one.
39+ HotfixesPath string
40+ ToolVersion string
41+ Workers int // 0 → runtime.NumCPU()
42+ Now func() time.Time
45 43
46 // Test hooks.44 // Test hooks.
47 afterResult func(w *Writer) // after each table result is written45 afterResult func(w *Writer) // after each table result is written
48 beforeRename func() // after the database is closed, before the install re-check46 beforeRename func() // after the database is closed, before the install re-check
49 }47 }
50 48
49+// Source values (_meta.source).
50+const (
51+ SourceLocal = "local"
52+ SourceCDN = "cdn"
53+)
54+
55+// Remote is a game build read from somewhere other than a local install.
56+// export never opens network storage itself: the caller provides Open.
57+type Remote struct {
58+ Source string // e.g. SourceCDN
59+ Version string
60+ BuildNumber uint32
61+ BuildKey string // build config hash
62+ Locale string
63+ // Open opens the storage with the snapshot's key ring. Run closes the
64+ // returned source when it implements io.Closer.
65+ Open func(keys db2.KeyRing) (dataset.FileSource, error)
66+}
67+
51 // TableFailure names a table that failed to export.68 // TableFailure names a table that failed to export.
52 type TableFailure struct {69 type TableFailure struct {
53- Name, Err string70+ Name, Error string
54 }71 }
55 72
56 // Summary reports an export.73 // Summary reports an export.
57 type Summary struct {74 type Summary struct {
58 Version, OutputPath string75 Version, OutputPath string
59- Counts map[string]int // by table status76+ Source string // SourceLocal or SourceCDN
77+ Counts map[dataset.TableStatus]int
60 Failed []TableFailure78 Failed []TableFailure
61 Hotfix hotfix.Stats79 Hotfix hotfix.Stats
62 SkippedRows int80 SkippedRows int
63 MissingKeys map[uint64]int81 MissingKeys map[uint64]int
64- DBCacheStatus string82+ DBCacheStatus dataset.HotfixStatus
65 ClientKeysAdded int83 ClientKeysAdded int
66 Duration time.Duration84 Duration time.Duration
67 DefsOrigin string // defs.OriginEmbedded or defs.OriginLocal85 DefsOrigin string // defs.OriginEmbedded or defs.OriginLocal
@@ -69,46 +87,49 @@ type Summary struct {
69 DefsGeneratedAt string87 DefsGeneratedAt string
70 }88 }
71 89
72-// FileName returns the export file name for version.90+// FileName returns the file name of a local export of version.
73 func FileName(version string) string { return "wowf-" + version + ".sqlite" }91 func FileName(version string) string { return "wowf-" + version + ".sqlite" }
74 92
93+// RemoteFileName returns the file name of an export of version read from
94+// source (e.g. wowf-1.60.1.71037-cdn.sqlite).
95+func RemoteFileName(version, source string) string {
96+ return "wowf-" + version + "-" + source + ".sqlite"
97+}
98+
99+// dbcache is the raw hotfix cache: nil data with status invalid when the
100+// file exists but cannot be read (e.g. the game writing it).
75 type dbcache struct {101 type dbcache struct {
76- cache *hotfix.Cache102+ data []byte
77- status string103+ status dataset.HotfixStatus // "" = decided by dataset.Load
78 sha string104 sha string
79 }105 }
80 106
81-// loadDBCache reads the hotfix cache. An unsupported DBCache version is107+// readDBCache reads path; a missing file means no hotfixes unless the path
82-// fatal; other read or parse errors (e.g. the game writing the file) give108+// was given explicitly (required), which is an error.
83-// status invalid and no hotfixes.109+func readDBCache(path string, required bool) (dbcache, error) {
84-func loadDBCache(inst *install.Install) (dbcache, error) {110+ if path == "" {
85- raw, err := os.ReadFile(inst.HotfixPath())111+ return dbcache{}, nil
112+ }
113+ raw, err := os.ReadFile(path)
86 if errors.Is(err, fs.ErrNotExist) {114 if errors.Is(err, fs.ErrNotExist) {
87- return dbcache{status: DBCacheMissing}, nil115+ if required {
116+ return dbcache{}, err
117+ }
118+ return dbcache{}, nil
88 }119 }
89 if err != nil {120 if err != nil {
90 slog.Warn("DBCache unreadable, hotfixes not applied", "err", err)121 slog.Warn("DBCache unreadable, hotfixes not applied", "err", err)
91- return dbcache{status: DBCacheInvalid}, nil122+ return dbcache{status: dataset.HotfixInvalid}, nil
92 }123 }
93 h := sha256.Sum256(raw)124 h := sha256.Sum256(raw)
94- d := dbcache{sha: hex.EncodeToString(h[:])}125+ return dbcache{data: raw, sha: hex.EncodeToString(h[:])}, nil
95- c, err := hotfix.Parse(raw)
96- switch {
97- case errors.Is(err, hotfix.ErrUnsupportedHotfix):
98- return d, fmt.Errorf("%s: %w", inst.HotfixPath(), err)
99- case err != nil:
100- slog.Warn("DBCache invalid, hotfixes not applied", "err", err)
101- d.status = DBCacheInvalid
102- case c.Build != inst.BuildNumber:
103- d.status = DBCacheBuildMismatch
104- default:
105- d.cache, d.status = c, DBCacheApplied
106- }
107- return d, nil
108 }126 }
109 127
110-// Run exports every manifest table of the install in opts.Dir into128+// Run exports every snapshot table. By default it reads the install in
111-// <OutDir>/wowf-<version>.sqlite and points current.sqlite at it.129+// opts.Dir, writes <OutDir>/wowf-<version>.sqlite and points current.sqlite
130+// at it. With opts.Remote it reads that build instead, writes
131+// <OutDir>/wowf-<version>-<source>.sqlite and leaves current.sqlite alone:
132+// current always tracks the local install.
112 func Run(ctx context.Context, opts Options) (*Summary, error) {133 func Run(ctx context.Context, opts Options) (*Summary, error) {
113 start := time.Now()134 start := time.Now()
114 now := opts.Now135 now := opts.Now
@@ -120,7 +141,7 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
120 workers = runtime.NumCPU()141 workers = runtime.NumCPU()
121 }142 }
122 143
123- inst, err := install.Detect(opts.Dir)144+ b, err := resolveBuild(opts)
124 if err != nil {145 if err != nil {
125 return nil, err146 return nil, err
126 }147 }
@@ -140,45 +161,29 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
140 if err != nil {161 if err != nil {
141 return nil, err162 return nil, err
142 }163 }
143- tables := snap.TableEntries()
144 ring := snap.Ring()164 ring := snap.Ring()
145- st, err := casc.Open(inst, ring)165+ st, err := b.open(ring)
146 if err != nil {166 if err != nil {
147 return nil, err167 return nil, err
148 }168 }
149- defer st.Close()169+ if c, ok := st.(io.Closer); ok {
150- fdids := make([]uint32, len(tables))170+ defer c.Close()
151- byName := make(map[string]defs.TableEntry, len(tables))
152- for i, e := range tables {
153- fdids[i] = e.FDID
154- byName[e.Name] = e
155- }
156- if _, err := st.Resolve(fdids); err != nil {
157- return nil, err
158 }171 }
159- st.ReleaseRoot()
160 if err := ctx.Err(); err != nil {172 if err := ctx.Err(); err != nil {
161 return nil, err173 return nil, err
162 }174 }
163-175+ dc, err := readDBCache(b.hotfixPath, opts.HotfixesPath != "")
164- if err := ctx.Err(); err != nil {
165- return nil, err
166- }
167- dc, err := loadDBCache(inst)
168 if err != nil {176 if err != nil {
169 return nil, err177 return nil, err
170 }178 }
171- sum := &Summary{Version: inst.Version, Counts: map[string]int{}, MissingKeys: map[uint64]int{}, DBCacheStatus: dc.status,179+ sum := &Summary{Version: b.version, Source: b.source, Counts: map[dataset.TableStatus]int{}, MissingKeys: map[uint64]int{},
172 DefsOrigin: origin, DefsCommit: snap.Source.WoWDBDefsCommit, DefsGeneratedAt: snap.GeneratedAt}180 DefsOrigin: origin, DefsCommit: snap.Source.WoWDBDefsCommit, DefsGeneratedAt: snap.GeneratedAt}
173- sum.ClientKeysAdded, err = loadClientKeys(st, byName, snap.Definition, ring, dc.cache)
174- if err != nil {
175- return nil, err
176- }
177 181
178- if err := ctx.Err(); err != nil {182+ name := FileName(b.version)
179- return nil, err183+ if opts.Remote != nil {
184+ name = RemoteFileName(b.version, b.source)
180 }185 }
181- final := filepath.Join(opts.OutDir, FileName(inst.Version))186+ final := filepath.Join(opts.OutDir, name)
182 tmp := final + ".tmp"187 tmp := final + ".tmp"
183 if err := os.Remove(tmp); err != nil && !errors.Is(err, fs.ErrNotExist) {188 if err := os.Remove(tmp); err != nil && !errors.Is(err, fs.ErrNotExist) {
184 return nil, err189 return nil, err
@@ -195,32 +200,57 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
195 os.Remove(tmp) // no-op after a successful rename200 os.Remove(tmp) // no-op after a successful rename
196 }()201 }()
197 202
198- defs, err := writeTables(ctx, w, st, snap.Definition, tables, ring, dc.cache, workers, sum, opts.afterResult)203+ var written []*db2.Definition
204+ res, err := dataset.Load(ctx, dataset.Options{
205+ Source: st, Snapshot: snap, Ring: ring, Hotfixes: dc.data, BuildNumber: b.buildNumber, Workers: workers,
206+ OnTable: func(r dataset.TableReport, t *db2.Table) error {
207+ status, err := writeResult(w, r, t, sum)
208+ if err != nil {
209+ return err
210+ }
211+ if opts.afterResult != nil {
212+ opts.afterResult(w)
213+ }
214+ if status == dataset.StatusOK {
215+ written = append(written, t.Def)
216+ }
217+ return nil
218+ },
219+ })
220+ if errors.Is(err, hotfix.ErrUnsupportedHotfix) {
221+ return nil, fmt.Errorf("%s: %w", b.hotfixPath, err)
222+ }
199 if err != nil {223 if err != nil {
200 return nil, err224 return nil, err
201 }225 }
226+ sum.ClientKeysAdded = res.ClientKeys
227+ sum.DBCacheStatus = res.HotfixStatus
228+ if dc.status != "" {
229+ sum.DBCacheStatus = dc.status
230+ }
202 if err := ctx.Err(); err != nil {231 if err := ctx.Err(); err != nil {
203 return nil, err232 return nil, err
204 }233 }
205- if err := w.CreateIndexes(defs); err != nil {234+ if err := w.CreateIndexes(written); err != nil {
206 return nil, err235 return nil, err
207 }236 }
208 meta := map[string]string{237 meta := map[string]string{
209 schema.MetaSchemaVersion: strconv.Itoa(schema.Version),238 schema.MetaSchemaVersion: strconv.Itoa(schema.Version),
210 schema.MetaToolVersion: opts.ToolVersion,239 schema.MetaToolVersion: opts.ToolVersion,
211 schema.MetaProduct: "wowf",240 schema.MetaProduct: "wowf",
212- schema.MetaBuildVersion: inst.Version,241+ schema.MetaBuildVersion: b.version,
213- schema.MetaBuildKey: inst.BuildKey,242+ schema.MetaBuildKey: b.buildKey,
214- schema.MetaLocale: inst.Locale,243+ schema.MetaLocale: b.locale,
244+ schema.MetaSource: b.source,
215 schema.MetaExportedAt: now().UTC().Format(time.RFC3339),245 schema.MetaExportedAt: now().UTC().Format(time.RFC3339),
216 schema.MetaDBCacheSHA256: dc.sha,246 schema.MetaDBCacheSHA256: dc.sha,
217- schema.MetaDBCacheStatus: dc.status,247+ schema.MetaDBCacheStatus: string(sum.DBCacheStatus),
218 schema.MetaDefsOrigin: origin,248 schema.MetaDefsOrigin: origin,
219 schema.MetaDefsCommit: snap.Source.WoWDBDefsCommit,249 schema.MetaDefsCommit: snap.Source.WoWDBDefsCommit,
220 schema.MetaDefsGenerated: snap.GeneratedAt,250 schema.MetaDefsGenerated: snap.GeneratedAt,
221 schema.MetaDefsSHA256: defsSum,251 schema.MetaDefsSHA256: defsSum,
222- schema.MetaTablesOK: strconv.Itoa(sum.Counts[StatusOK]),252+ schema.MetaTablesOK: strconv.Itoa(sum.Counts[dataset.StatusOK]),
223- schema.MetaTablesFailed: strconv.Itoa(sum.Counts[StatusFailed]),253+ schema.MetaTablesFailed: strconv.Itoa(sum.Counts[dataset.StatusFailed]),
224 }254 }
225 if err := w.WriteMeta(meta); err != nil {255 if err := w.WriteMeta(meta); err != nil {
226 return nil, err256 return nil, err
@@ -232,12 +262,14 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
232 if opts.beforeRename != nil {262 if opts.beforeRename != nil {
233 opts.beforeRename()263 opts.beforeRename()
234 }264 }
235- again, err := install.Detect(opts.Dir)265+ if opts.Remote == nil {
236- if err != nil {266+ again, err := install.Detect(opts.Dir)
237- return nil, fmt.Errorf("install changed during export: %w", err)267+ if err != nil {
238- }268+ return nil, fmt.Errorf("install changed during export: %w", err)
239- if again.Version != inst.Version || again.BuildKey != inst.BuildKey {269+ }
240- return nil, errors.New("install changed during export")270+ if again.Version != b.version || again.BuildKey != b.buildKey {
271+ return nil, errors.New("install changed during export")
272+ }
241 }273 }
242 if err := ctx.Err(); err != nil {274 if err := ctx.Err(); err != nil {
243 return nil, err275 return nil, err
@@ -245,16 +277,10 @@ func Run(ctx context.Context, opts Options) (*Summary, error) {
245 if err := os.Rename(tmp, final); err != nil {277 if err := os.Rename(tmp, final); err != nil {
246 return nil, err278 return nil, err
247 }279 }
248- link := filepath.Join(opts.OutDir, CurrentName)280+ if opts.Remote == nil {
249- if err := os.Remove(link + ".tmp"); err != nil && !errors.Is(err, fs.ErrNotExist) {281+ if err := pointCurrent(opts.OutDir, name); err != nil {
250- return nil, err282+ return nil, err
251- }283+ }
252- if err := os.Symlink(FileName(inst.Version), link+".tmp"); err != nil {
253- return nil, err
254- }
255- if err := os.Rename(link+".tmp", link); err != nil {
256- os.Remove(link + ".tmp")
257- return nil, err
258 }284 }
259 if err := syncDir(opts.OutDir); err != nil {285 if err := syncDir(opts.OutDir); err != nil {
260 return nil, err286 return nil, err
@@ -296,123 +322,104 @@ func syncDir(dir string) error {
296 return d.Sync()322 return d.Sync()
297 }323 }
298 324
299-// writeTables decodes tables in a worker pool and writes them from the
300-// calling goroutine. It returns the definitions of the written tables.
301-func writeTables(ctx context.Context, w *Writer, st *casc.Storage, lookup defLookup, tables []defs.TableEntry,
302- ring db2.KeyRing, hf *hotfix.Cache, workers int, sum *Summary, afterResult func(*Writer)) ([]*db2.Definition, error) {
303- ctx, cancel := context.WithCancel(ctx)
304- defer cancel()
305- jobs := make(chan defs.TableEntry)
306- results := make(chan TableResult)
307- var wg sync.WaitGroup
308- for i := 0; i < workers; i++ {
309- wg.Add(1)
310- go func() {
311- defer wg.Done()
312- for e := range jobs {
313- r := decodeTable(st, e, lookup, ring, hf)
314- select {
315- case results <- r:
316- case <-ctx.Done():
317- return
318- }
319- }
320- }()
321- }
322- go func() {
323- defer close(jobs)
324- for _, e := range tables {
325- select {
326- case jobs <- e:
327- case <-ctx.Done():
328- return
329- }
330- }
331- }()
332- go func() {
333- wg.Wait()
334- close(results)
335- }()
336-
337- var defs []*db2.Definition
338- var werr error
339- for r := range results {
340- if werr != nil {
341- continue // drain
342- }
343- status, err := writeResult(w, r, sum)
344- if err != nil {
345- werr = err
346- cancel()
347- continue
348- }
349- if afterResult != nil {
350- afterResult(w)
351- }
352- if status == StatusOK {
353- defs = append(defs, r.Def)
354- }
355- }
356- if werr != nil {
357- return nil, werr
358- }
359- if err := ctx.Err(); err != nil {
360- return nil, err
361- }
362- return defs, nil
363-}
364-
365 // writeResult writes one decoded table and its status row. A table that325 // writeResult writes one decoded table and its status row. A table that
366 // cannot be written is recorded as failed; only fatal writer errors are326 // cannot be written is recorded as failed; only fatal writer errors are
367 // returned. It returns the final table status.327 // returned. It returns the final table status.
368-func writeResult(w *Writer, r TableResult, sum *Summary) (string, error) {328+func writeResult(w *Writer, r dataset.TableReport, t *db2.Table, sum *Summary) (dataset.TableStatus, error) {
369- if r.Status == StatusOK {329+ if r.Status == dataset.StatusOK {
370- if err := w.WriteTable(r.Table); err != nil {330+ if err := w.WriteTable(t); err != nil {
371 if IsFatal(err) {331 if IsFatal(err) {
372 return "", err332 return "", err
373 }333 }
374- slog.Warn("table write failed", "table", r.Entry.Name, "err", err)334+ slog.Warn("table write failed", "table", r.Name, "err", err)
375- r.Status, r.Err = StatusFailed, err335+ r.Status, r.Err = dataset.StatusFailed, err
376 }336 }
377 }337 }
378 row := TableStatusRow{338 row := TableStatusRow{
379- TableName: r.Entry.Name, FDID: r.Entry.FDID, Status: r.Status,339+ TableName: r.Name, FDID: r.FDID, Status: string(r.Status), MatchedBy: r.MatchedBy,
380 BaseRows: r.BaseRows, HotfixUpserts: r.Hotfix.Upserts, HotfixDeletes: r.Hotfix.Deletes,340 BaseRows: r.BaseRows, HotfixUpserts: r.Hotfix.Upserts, HotfixDeletes: r.Hotfix.Deletes,
381 HotfixReverts: r.Hotfix.Reverts, HotfixErrors: r.Hotfix.Errors,341 HotfixReverts: r.Hotfix.Reverts, HotfixErrors: r.Hotfix.Errors,
382- SkippedRows: r.Info.SkippedRows, SkippedSections: r.Info.SkippedSections,342+ SkippedRows: r.SkippedRows, SkippedSections: r.SkippedSections,
383 }343 }
384- if r.Entry.Hash != 0 {344+ if r.Err != nil {
385- row.TableHash = fmt.Sprintf("%08X", r.Entry.Hash)345+ row.Error = r.Err.Error()
346+ }
347+ if r.Hash != 0 {
348+ row.TableHash = fmt.Sprintf("%08X", r.Hash)
386 }349 }
387 if r.Layout != 0 {350 if r.Layout != 0 {
388 row.LayoutHash = fmt.Sprintf("%08X", r.Layout)351 row.LayoutHash = fmt.Sprintf("%08X", r.Layout)
389 }352 }
390- if r.Def != nil {
391- row.MatchedBy = r.Def.MatchedBy
392- }
393- if r.Err != nil {
394- row.Error = r.Err.Error()
395- }
396 if err := w.WriteTableStatus(row); err != nil {353 if err := w.WriteTableStatus(row); err != nil {
397 return "", err354 return "", err
398 }355 }
399- if len(r.HotfixLog) > 0 {356+ if len(r.Log) > 0 {
400- if err := w.WriteHotfixLog(r.Entry.Name, r.HotfixLog); err != nil {357+ if err := w.WriteHotfixLog(r.Name, r.Log); err != nil {
401 return "", err358 return "", err
402 }359 }
403 }360 }
404 sum.Counts[r.Status]++361 sum.Counts[r.Status]++
405- if r.Status == StatusFailed {362+ if r.Status == dataset.StatusFailed {
406- sum.Failed = append(sum.Failed, TableFailure{Name: r.Entry.Name, Err: row.Error})363+ sum.Failed = append(sum.Failed, TableFailure{Name: r.Name, Error: row.Error})
407 }364 }
408 sum.Hotfix.Upserts += r.Hotfix.Upserts365 sum.Hotfix.Upserts += r.Hotfix.Upserts
409 sum.Hotfix.Deletes += r.Hotfix.Deletes366 sum.Hotfix.Deletes += r.Hotfix.Deletes
410 sum.Hotfix.Reverts += r.Hotfix.Reverts367 sum.Hotfix.Reverts += r.Hotfix.Reverts
411 sum.Hotfix.Errors += r.Hotfix.Errors368 sum.Hotfix.Errors += r.Hotfix.Errors
412 sum.Hotfix.Ignored += r.Hotfix.Ignored369 sum.Hotfix.Ignored += r.Hotfix.Ignored
413- sum.SkippedRows += r.Info.SkippedRows370+ sum.SkippedRows += r.SkippedRows
414 for k, n := range r.MissingKeys {371 for k, n := range r.MissingKeys {
415 sum.MissingKeys[k] += n372 sum.MissingKeys[k] += n
416 }373 }
417 return r.Status, nil374 return r.Status, nil
418 }375 }
376+
377+// build is the game build an export reads.
378+type build struct {
379+ source, version, buildKey, locale, hotfixPath string
380+ buildNumber uint32
381+ open func(db2.KeyRing) (dataset.FileSource, error)
382+}
383+
384+func resolveBuild(opts Options) (build, error) {
385+ if r := opts.Remote; r != nil {
386+ if r.Open == nil || r.Version == "" || r.Source == "" {
387+ return build{}, errors.New("export: Remote needs Source, Version and Open")
388+ }
389+ return build{source: r.Source, version: r.Version, buildKey: r.BuildKey, locale: r.Locale,
390+ buildNumber: r.BuildNumber, hotfixPath: opts.HotfixesPath, open: r.Open}, nil
391+ }
392+ inst, err := install.Detect(opts.Dir)
393+ if err != nil {
394+ return build{}, err
395+ }
396+ hp := inst.HotfixPath()
397+ if opts.HotfixesPath != "" {
398+ hp = opts.HotfixesPath
399+ }
400+ return build{source: SourceLocal, version: inst.Version, buildKey: inst.BuildKey, locale: inst.Locale,
401+ buildNumber: inst.BuildNumber, hotfixPath: hp,
402+ open: func(keys db2.KeyRing) (dataset.FileSource, error) {
403+ st, err := casc.Open(inst, keys)
404+ if err != nil {
405+ return nil, err
406+ }
407+ return st, nil
408+ }}, nil
409+}
410+
411+// pointCurrent atomically points <dir>/current.sqlite at name.
412+func pointCurrent(dir, name string) error {
413+ link := filepath.Join(dir, CurrentName)
414+ if err := os.Remove(link + ".tmp"); err != nil && !errors.Is(err, fs.ErrNotExist) {
415+ return err
416+ }
417+ if err := os.Symlink(name, link+".tmp"); err != nil {
418+ return err
419+ }
420+ if err := os.Rename(link+".tmp", link); err != nil {
421+ os.Remove(link + ".tmp")
422+ return err
423+ }
424+ return nil
425+}
M internal/export/export_test.go +104 -23
@@ -4,20 +4,24 @@ import (
44 "context"
55 "database/sql"
66 "errors"
7+ gobuild "go/build"
8+ "io/fs"
79 "net/http"
810 "os"
911 "os/exec"
1012 "path/filepath"
11- "runtime"
1213 "slices"
1314 "strings"
1415 "testing"
1516 "time"
1617
17- "github.com/bnema/forever-db/internal/defs"
18- "github.com/bnema/forever-db/internal/hotfix"
19- "github.com/bnema/forever-db/internal/install"
20- "github.com/bnema/forever-db/internal/testutil"
18+ "bnema.dev/forever-db/internal/testutil"
19+ "bnema.dev/forever-db/pkg/casc"
20+ "bnema.dev/forever-db/pkg/dataset"
21+ "bnema.dev/forever-db/pkg/db2"
22+ "bnema.dev/forever-db/pkg/defs"
23+ "bnema.dev/forever-db/pkg/hotfix"
24+ "bnema.dev/forever-db/pkg/install"
2125 )
2226
2327 const testSHA = "0123456789abcdef0123456789abcdef01234567"
@@ -122,10 +126,10 @@ func TestRun(t *testing.T) {
122126 if err != nil {
123127 t.Fatal(err)
124128 }
125- if sum.Counts[StatusOK] != 2 || sum.Counts[StatusAbsent] != 1 || sum.Counts[StatusNoDefinition] != 1 || len(sum.Failed) != 0 {
129+ if sum.Counts[dataset.StatusOK] != 2 || sum.Counts[dataset.StatusAbsent] != 1 || sum.Counts[dataset.StatusNoDefinition] != 1 || len(sum.Failed) != 0 {
126130 t.Errorf("counts = %v failed %v", sum.Counts, sum.Failed)
127131 }
128- if sum.DBCacheStatus != DBCacheApplied || sum.Hotfix.Upserts != 1 || sum.Version != "1.60.1.71037" {
132+ if sum.DBCacheStatus != dataset.HotfixApplied || sum.Hotfix.Upserts != 1 || sum.Version != "1.60.1.71037" {
129133 t.Errorf("summary = %+v", sum)
130134 }
131135 if target, err := os.Readlink(filepath.Join(f.out, CurrentName)); err != nil || target != "wowf-1.60.1.71037.sqlite" {
@@ -162,12 +166,12 @@ func TestRun(t *testing.T) {
162166 for k, want := range map[string]string{"tool_version": "test", "product": "wowf", "build_version": "1.60.1.71037",
163167 "build_key": testutil.InstallBuildKey, "locale": "enUS", "exported_at": "2026-11-21T12:00:00Z", "dbcache_status": "applied",
164168 "defs_origin": "local", "defs_wowdbdefs_commit": testSHA, "defs_generated_at": "2026-11-20T10:00:00Z",
165- "schema_version": "2", "tables_ok": "2", "tables_failed": "0"} {
169+ "schema_version": "2", "tables_ok": "2", "tables_failed": "0", "source": "local"} {
166170 if meta[k] != want {
167171 t.Errorf("_meta %s = %q, want %q", k, meta[k], want)
168172 }
169173 }
170- if len(meta["dbcache_sha256"]) != 64 || len(meta["defs_sha256"]) != 64 || len(meta) != 15 {
174+ if len(meta["dbcache_sha256"]) != 64 || len(meta["defs_sha256"]) != 64 || len(meta) != 16 {
171175 t.Errorf("_meta = %v", meta)
172176 }
173177 }
@@ -245,8 +249,8 @@ func TestRunDuplicateColumnFails(t *testing.T) {
245249 if err != nil {
246250 t.Fatal(err)
247251 }
248- if sum.Counts[StatusOK] != 1 || sum.Counts[StatusFailed] != 1 || len(sum.Failed) != 1 ||
249- sum.Failed[0].Name != "Alpha" || sum.Failed[0].Err != "duplicate column v" {
252+ if sum.Counts[dataset.StatusOK] != 1 || sum.Counts[dataset.StatusFailed] != 1 || len(sum.Failed) != 1 ||
253+ sum.Failed[0].Name != "Alpha" || sum.Failed[0].Error != "duplicate column v" {
250254 t.Fatalf("counts %v failed %v", sum.Counts, sum.Failed)
251255 }
252256 db, _ := sql.Open("sqlite", filepath.Join(f.out, CurrentName))
@@ -300,7 +304,7 @@ func TestRunDBCacheInvalid(t *testing.T) {
300304 inst, _ := install.Detect(f.wow)
301305 os.WriteFile(inst.HotfixPath(), []byte("garbage"), 0o644)
302306 sum, err := Run(context.Background(), f.opts())
303- if err != nil || sum.DBCacheStatus != DBCacheInvalid || sum.Hotfix.Upserts != 0 {
307+ if err != nil || sum.DBCacheStatus != dataset.HotfixInvalid || sum.Hotfix.Upserts != 0 {
304308 t.Fatalf("%+v, %v", sum, err)
305309 }
306310 }
@@ -327,12 +331,12 @@ func TestRunUnknownLayout(t *testing.T) {
327331 if err != nil {
328332 t.Fatal(err)
329333 }
330- if sum.Counts[StatusNoDefinition] != 1 || sum.DefsOrigin != defs.OriginLocal || sum.DefsCommit != testSHA {
334+ if sum.Counts[dataset.StatusNoDefinition] != 1 || sum.DefsOrigin != defs.OriginLocal || sum.DefsCommit != testSHA {
331335 t.Fatalf("summary = %+v", sum)
332336 }
333337 db, _ := sql.Open("sqlite", filepath.Join(f.out, CurrentName))
334338 defer db.Close()
335- if g := flat(query(t, db, `SELECT error FROM _tables WHERE table_name='NoDef'`)); g != "layout 00000003 not in definitions snapshot (run forever-db defs update)" {
339+ if g := flat(query(t, db, `SELECT error FROM _tables WHERE table_name='NoDef'`)); g != "layout 00000003 not in the definitions snapshot" {
336340 t.Fatalf("error = %q", g)
337341 }
338342 }
@@ -387,20 +391,97 @@ func TestStatusDefsChanged(t *testing.T) {
387391 }
388392 }
389393
394+// TestRunRemote exports through Options.Remote (here a local storage
395+// standing in for the CDN) and checks hotfix selection and status.
396+func TestRunRemote(t *testing.T) {
397+ f := newFixture(t)
398+ inst, err := install.Detect(f.wow)
399+ if err != nil {
400+ t.Fatal(err)
401+ }
402+ opened := 0
403+ remote := func() *Remote {
404+ return &Remote{Source: SourceCDN, Version: inst.Version, BuildNumber: inst.BuildNumber, BuildKey: "bc", Locale: "enUS",
405+ Open: func(keys db2.KeyRing) (dataset.FileSource, error) {
406+ opened++
407+ return casc.Open(inst, keys)
408+ }}
409+ }
410+ if _, err := Run(context.Background(), f.opts()); err != nil { // local export first
411+ t.Fatal(err)
412+ }
413+ o := f.opts()
414+ o.Dir, o.Remote = "", remote()
415+ sum, err := Run(context.Background(), o)
416+ if err != nil {
417+ t.Fatal(err)
418+ }
419+ if sum.DBCacheStatus != dataset.HotfixMissing || sum.Source != SourceCDN || sum.Counts[dataset.StatusOK] != 2 || opened != 1 {
420+ t.Fatalf("summary = %+v, opened %d", sum, opened)
421+ }
422+ if want := filepath.Join(f.out, "wowf-1.60.1.71037-cdn.sqlite"); sum.OutputPath != want {
423+ t.Errorf("output %s, want %s", sum.OutputPath, want)
424+ }
425+ db, err := sql.Open("sqlite", sum.OutputPath)
426+ if err != nil {
427+ t.Fatal(err)
428+ }
429+ if g := flat(query(t, db, `SELECT key,value FROM _meta WHERE key IN ('source','build_key','dbcache_status') ORDER BY 1`)); g != "build_key,bc;dbcache_status,missing;source,cdn" {
430+ t.Errorf("_meta = %s", g)
431+ }
432+ db.Close()
433+ // current.sqlite still points at the local export, which stays up to date.
434+ if target, err := os.Readlink(filepath.Join(f.out, CurrentName)); err != nil || target != "wowf-1.60.1.71037.sqlite" {
435+ t.Errorf("current = %q, %v", target, err)
436+ }
437+ if r, err := Status(inst, f.out); err != nil || r.State != StateUpToDate {
438+ t.Fatalf("status after cdn export: %+v, %v", r, err)
439+ }
440+
441+ o.Remote, o.HotfixesPath = remote(), inst.HotfixPath()
442+ if sum, err = Run(context.Background(), o); err != nil || sum.DBCacheStatus != dataset.HotfixApplied || sum.Hotfix.Upserts != 1 {
443+ t.Fatalf("cdn + hotfixes: %+v, %v", sum, err)
444+ }
445+ o.HotfixesPath = filepath.Join(t.TempDir(), "nope.bin")
446+ if _, err := Run(context.Background(), o); !errors.Is(err, fs.ErrNotExist) {
447+ t.Fatalf("missing --hotfixes file: %v", err)
448+ }
449+ o.Remote = &Remote{Source: SourceCDN}
450+ if _, err := Run(context.Background(), o); err == nil {
451+ t.Fatal("incomplete Remote: no error")
452+ }
453+}
454+
455+// TestRunHotfixesPathLocal overrides the install's DBCache.bin.
456+func TestRunHotfixesPathLocal(t *testing.T) {
457+ f := newFixture(t)
458+ o := f.opts()
459+ o.HotfixesPath = filepath.Join(t.TempDir(), "empty.bin")
460+ os.WriteFile(o.HotfixesPath, []byte("garbage"), 0o644)
461+ sum, err := Run(context.Background(), o)
462+ if err != nil || sum.DBCacheStatus != dataset.HotfixInvalid || sum.Source != SourceLocal {
463+ t.Fatalf("%+v, %v", sum, err)
464+ }
465+}
466+
390467 // TestNoNetworkDeps checks that the export package cannot reach the network:
391-// it must not link net/http or the sources downloader.
468+// it must not link net/http, the sources downloader or the CDN reader.
392469 func TestNoNetworkDeps(t *testing.T) {
393- gobin := filepath.Join(runtime.GOROOT(), "bin", "go")
470+ gobin := filepath.Join(gobuild.Default.GOROOT, "bin", "go")
394471 if _, err := os.Stat(gobin); err != nil {
395472 t.Fatalf("go tool not found: %v", err)
396473 }
397- out, err := exec.Command(gobin, "list", "-deps", ".").CombinedOutput()
398- if err != nil {
399- t.Fatalf("go list: %v\n%s", err, out)
400- }
401- for _, dep := range strings.Fields(string(out)) {
402- if dep == "net/http" || strings.HasSuffix(dep, "/internal/sources") {
403- t.Errorf("export depends on %s", dep)
474+ for _, pkg := range []string{".", "bnema.dev/forever-db/pkg/dataset"} {
475+ out, err := exec.Command(gobin, "list", "-deps", pkg).CombinedOutput()
476+ if err != nil {
477+ t.Fatalf("go list %s: %v\n%s", pkg, err, out)
478+ }
479+ for _, dep := range strings.Fields(string(out)) {
480+ if dep == "net/http" || strings.HasSuffix(dep, "/pkg/sources") || strings.HasSuffix(dep, "/pkg/casc/cdn") {
481+ t.Errorf("%s depends on %s", pkg, dep)
482+ }
404483 }
405484 }
406485 }
486+
487+func u32(v uint32) []byte { return []byte{byte(v), byte(v >> 8), byte(v >> 16), byte(v >> 24)} }
@@ -4,20 +4,24 @@ import (
4 "context"4 "context"
5 "database/sql"5 "database/sql"
6 "errors"6 "errors"
7+ gobuild "go/build"
8+ "io/fs"
7 "net/http"9 "net/http"
8 "os"10 "os"
9 "os/exec"11 "os/exec"
10 "path/filepath"12 "path/filepath"
11- "runtime"
12 "slices"13 "slices"
13 "strings"14 "strings"
14 "testing"15 "testing"
15 "time"16 "time"
16 17
17- "github.com/bnema/forever-db/internal/defs"18+ "bnema.dev/forever-db/internal/testutil"
18- "github.com/bnema/forever-db/internal/hotfix"19+ "bnema.dev/forever-db/pkg/casc"
19- "github.com/bnema/forever-db/internal/install"20+ "bnema.dev/forever-db/pkg/dataset"
20- "github.com/bnema/forever-db/internal/testutil"21+ "bnema.dev/forever-db/pkg/db2"
22+ "bnema.dev/forever-db/pkg/defs"
23+ "bnema.dev/forever-db/pkg/hotfix"
24+ "bnema.dev/forever-db/pkg/install"
21 )25 )
22 26
23 const testSHA = "0123456789abcdef0123456789abcdef01234567"27 const testSHA = "0123456789abcdef0123456789abcdef01234567"
@@ -122,10 +126,10 @@ func TestRun(t *testing.T) {
122 if err != nil {126 if err != nil {
123 t.Fatal(err)127 t.Fatal(err)
124 }128 }
125- if sum.Counts[StatusOK] != 2 || sum.Counts[StatusAbsent] != 1 || sum.Counts[StatusNoDefinition] != 1 || len(sum.Failed) != 0 {129+ if sum.Counts[dataset.StatusOK] != 2 || sum.Counts[dataset.StatusAbsent] != 1 || sum.Counts[dataset.StatusNoDefinition] != 1 || len(sum.Failed) != 0 {
126 t.Errorf("counts = %v failed %v", sum.Counts, sum.Failed)130 t.Errorf("counts = %v failed %v", sum.Counts, sum.Failed)
127 }131 }
128- if sum.DBCacheStatus != DBCacheApplied || sum.Hotfix.Upserts != 1 || sum.Version != "1.60.1.71037" {132+ if sum.DBCacheStatus != dataset.HotfixApplied || sum.Hotfix.Upserts != 1 || sum.Version != "1.60.1.71037" {
129 t.Errorf("summary = %+v", sum)133 t.Errorf("summary = %+v", sum)
130 }134 }
131 if target, err := os.Readlink(filepath.Join(f.out, CurrentName)); err != nil || target != "wowf-1.60.1.71037.sqlite" {135 if target, err := os.Readlink(filepath.Join(f.out, CurrentName)); err != nil || target != "wowf-1.60.1.71037.sqlite" {
@@ -162,12 +166,12 @@ func TestRun(t *testing.T) {
162 for k, want := range map[string]string{"tool_version": "test", "product": "wowf", "build_version": "1.60.1.71037",166 for k, want := range map[string]string{"tool_version": "test", "product": "wowf", "build_version": "1.60.1.71037",
163 "build_key": testutil.InstallBuildKey, "locale": "enUS", "exported_at": "2026-11-21T12:00:00Z", "dbcache_status": "applied",167 "build_key": testutil.InstallBuildKey, "locale": "enUS", "exported_at": "2026-11-21T12:00:00Z", "dbcache_status": "applied",
164 "defs_origin": "local", "defs_wowdbdefs_commit": testSHA, "defs_generated_at": "2026-11-20T10:00:00Z",168 "defs_origin": "local", "defs_wowdbdefs_commit": testSHA, "defs_generated_at": "2026-11-20T10:00:00Z",
165- "schema_version": "2", "tables_ok": "2", "tables_failed": "0"} {169+ "schema_version": "2", "tables_ok": "2", "tables_failed": "0", "source": "local"} {
166 if meta[k] != want {170 if meta[k] != want {
167 t.Errorf("_meta %s = %q, want %q", k, meta[k], want)171 t.Errorf("_meta %s = %q, want %q", k, meta[k], want)
168 }172 }
169 }173 }
170- if len(meta["dbcache_sha256"]) != 64 || len(meta["defs_sha256"]) != 64 || len(meta) != 15 {174+ if len(meta["dbcache_sha256"]) != 64 || len(meta["defs_sha256"]) != 64 || len(meta) != 16 {
171 t.Errorf("_meta = %v", meta)175 t.Errorf("_meta = %v", meta)
172 }176 }
173 }177 }
@@ -245,8 +249,8 @@ func TestRunDuplicateColumnFails(t *testing.T) {
245 if err != nil {249 if err != nil {
246 t.Fatal(err)250 t.Fatal(err)
247 }251 }
248- if sum.Counts[StatusOK] != 1 || sum.Counts[StatusFailed] != 1 || len(sum.Failed) != 1 ||252+ if sum.Counts[dataset.StatusOK] != 1 || sum.Counts[dataset.StatusFailed] != 1 || len(sum.Failed) != 1 ||
249- sum.Failed[0].Name != "Alpha" || sum.Failed[0].Err != "duplicate column v" {253+ sum.Failed[0].Name != "Alpha" || sum.Failed[0].Error != "duplicate column v" {
250 t.Fatalf("counts %v failed %v", sum.Counts, sum.Failed)254 t.Fatalf("counts %v failed %v", sum.Counts, sum.Failed)
251 }255 }
252 db, _ := sql.Open("sqlite", filepath.Join(f.out, CurrentName))256 db, _ := sql.Open("sqlite", filepath.Join(f.out, CurrentName))
@@ -300,7 +304,7 @@ func TestRunDBCacheInvalid(t *testing.T) {
300 inst, _ := install.Detect(f.wow)304 inst, _ := install.Detect(f.wow)
301 os.WriteFile(inst.HotfixPath(), []byte("garbage"), 0o644)305 os.WriteFile(inst.HotfixPath(), []byte("garbage"), 0o644)
302 sum, err := Run(context.Background(), f.opts())306 sum, err := Run(context.Background(), f.opts())
303- if err != nil || sum.DBCacheStatus != DBCacheInvalid || sum.Hotfix.Upserts != 0 {307+ if err != nil || sum.DBCacheStatus != dataset.HotfixInvalid || sum.Hotfix.Upserts != 0 {
304 t.Fatalf("%+v, %v", sum, err)308 t.Fatalf("%+v, %v", sum, err)
305 }309 }
306 }310 }
@@ -327,12 +331,12 @@ func TestRunUnknownLayout(t *testing.T) {
327 if err != nil {331 if err != nil {
328 t.Fatal(err)332 t.Fatal(err)
329 }333 }
330- if sum.Counts[StatusNoDefinition] != 1 || sum.DefsOrigin != defs.OriginLocal || sum.DefsCommit != testSHA {334+ if sum.Counts[dataset.StatusNoDefinition] != 1 || sum.DefsOrigin != defs.OriginLocal || sum.DefsCommit != testSHA {
331 t.Fatalf("summary = %+v", sum)335 t.Fatalf("summary = %+v", sum)
332 }336 }
333 db, _ := sql.Open("sqlite", filepath.Join(f.out, CurrentName))337 db, _ := sql.Open("sqlite", filepath.Join(f.out, CurrentName))
334 defer db.Close()338 defer db.Close()
335- if g := flat(query(t, db, `SELECT error FROM _tables WHERE table_name='NoDef'`)); g != "layout 00000003 not in definitions snapshot (run forever-db defs update)" {339+ if g := flat(query(t, db, `SELECT error FROM _tables WHERE table_name='NoDef'`)); g != "layout 00000003 not in the definitions snapshot" {
336 t.Fatalf("error = %q", g)340 t.Fatalf("error = %q", g)
337 }341 }
338 }342 }
@@ -387,20 +391,97 @@ func TestStatusDefsChanged(t *testing.T) {
387 }391 }
388 }392 }
389 393
394+// TestRunRemote exports through Options.Remote (here a local storage
395+// standing in for the CDN) and checks hotfix selection and status.
396+func TestRunRemote(t *testing.T) {
397+ f := newFixture(t)
398+ inst, err := install.Detect(f.wow)
399+ if err != nil {
400+ t.Fatal(err)
401+ }
402+ opened := 0
403+ remote := func() *Remote {
404+ return &Remote{Source: SourceCDN, Version: inst.Version, BuildNumber: inst.BuildNumber, BuildKey: "bc", Locale: "enUS",
405+ Open: func(keys db2.KeyRing) (dataset.FileSource, error) {
406+ opened++
407+ return casc.Open(inst, keys)
408+ }}
409+ }
410+ if _, err := Run(context.Background(), f.opts()); err != nil { // local export first
411+ t.Fatal(err)
412+ }
413+ o := f.opts()
414+ o.Dir, o.Remote = "", remote()
415+ sum, err := Run(context.Background(), o)
416+ if err != nil {
417+ t.Fatal(err)
418+ }
419+ if sum.DBCacheStatus != dataset.HotfixMissing || sum.Source != SourceCDN || sum.Counts[dataset.StatusOK] != 2 || opened != 1 {
420+ t.Fatalf("summary = %+v, opened %d", sum, opened)
421+ }
422+ if want := filepath.Join(f.out, "wowf-1.60.1.71037-cdn.sqlite"); sum.OutputPath != want {
423+ t.Errorf("output %s, want %s", sum.OutputPath, want)
424+ }
425+ db, err := sql.Open("sqlite", sum.OutputPath)
426+ if err != nil {
427+ t.Fatal(err)
428+ }
429+ if g := flat(query(t, db, `SELECT key,value FROM _meta WHERE key IN ('source','build_key','dbcache_status') ORDER BY 1`)); g != "build_key,bc;dbcache_status,missing;source,cdn" {
430+ t.Errorf("_meta = %s", g)
431+ }
432+ db.Close()
433+ // current.sqlite still points at the local export, which stays up to date.
434+ if target, err := os.Readlink(filepath.Join(f.out, CurrentName)); err != nil || target != "wowf-1.60.1.71037.sqlite" {
435+ t.Errorf("current = %q, %v", target, err)
436+ }
437+ if r, err := Status(inst, f.out); err != nil || r.State != StateUpToDate {
438+ t.Fatalf("status after cdn export: %+v, %v", r, err)
439+ }
440+
441+ o.Remote, o.HotfixesPath = remote(), inst.HotfixPath()
442+ if sum, err = Run(context.Background(), o); err != nil || sum.DBCacheStatus != dataset.HotfixApplied || sum.Hotfix.Upserts != 1 {
443+ t.Fatalf("cdn + hotfixes: %+v, %v", sum, err)
444+ }
445+ o.HotfixesPath = filepath.Join(t.TempDir(), "nope.bin")
446+ if _, err := Run(context.Background(), o); !errors.Is(err, fs.ErrNotExist) {
447+ t.Fatalf("missing --hotfixes file: %v", err)
448+ }
449+ o.Remote = &Remote{Source: SourceCDN}
450+ if _, err := Run(context.Background(), o); err == nil {
451+ t.Fatal("incomplete Remote: no error")
452+ }
453+}
454+
455+// TestRunHotfixesPathLocal overrides the install's DBCache.bin.
456+func TestRunHotfixesPathLocal(t *testing.T) {
457+ f := newFixture(t)
458+ o := f.opts()
459+ o.HotfixesPath = filepath.Join(t.TempDir(), "empty.bin")
460+ os.WriteFile(o.HotfixesPath, []byte("garbage"), 0o644)
461+ sum, err := Run(context.Background(), o)
462+ if err != nil || sum.DBCacheStatus != dataset.HotfixInvalid || sum.Source != SourceLocal {
463+ t.Fatalf("%+v, %v", sum, err)
464+ }
465+}
466+
390 // TestNoNetworkDeps checks that the export package cannot reach the network:467 // TestNoNetworkDeps checks that the export package cannot reach the network:
391-// it must not link net/http or the sources downloader.468+// it must not link net/http, the sources downloader or the CDN reader.
392 func TestNoNetworkDeps(t *testing.T) {469 func TestNoNetworkDeps(t *testing.T) {
393- gobin := filepath.Join(runtime.GOROOT(), "bin", "go")470+ gobin := filepath.Join(gobuild.Default.GOROOT, "bin", "go")
394 if _, err := os.Stat(gobin); err != nil {471 if _, err := os.Stat(gobin); err != nil {
395 t.Fatalf("go tool not found: %v", err)472 t.Fatalf("go tool not found: %v", err)
396 }473 }
397- out, err := exec.Command(gobin, "list", "-deps", ".").CombinedOutput()474+ for _, pkg := range []string{".", "bnema.dev/forever-db/pkg/dataset"} {
398- if err != nil {475+ out, err := exec.Command(gobin, "list", "-deps", pkg).CombinedOutput()
399- t.Fatalf("go list: %v\n%s", err, out)476+ if err != nil {
400- }477+ t.Fatalf("go list %s: %v\n%s", pkg, err, out)
401- for _, dep := range strings.Fields(string(out)) {478+ }
402- if dep == "net/http" || strings.HasSuffix(dep, "/internal/sources") {479+ for _, dep := range strings.Fields(string(out)) {
403- t.Errorf("export depends on %s", dep)480+ if dep == "net/http" || strings.HasSuffix(dep, "/pkg/sources") || strings.HasSuffix(dep, "/pkg/casc/cdn") {
481+ t.Errorf("%s depends on %s", pkg, dep)
482+ }
404 }483 }
405 }484 }
406 }485 }
486+
487+func u32(v uint32) []byte { return []byte{byte(v), byte(v >> 8), byte(v >> 16), byte(v >> 24)} }
M internal/export/integration_test.go +4 -3
@@ -8,8 +8,9 @@ import (
88 "strings"
99 "testing"
1010
11- "github.com/bnema/forever-db/internal/defs"
12- "github.com/bnema/forever-db/internal/install"
11+ "bnema.dev/forever-db/pkg/dataset"
12+ "bnema.dev/forever-db/pkg/defs"
13+ "bnema.dev/forever-db/pkg/install"
1314 )
1415
1516 // TestRealExport runs the full export on a real install (V3). It needs
@@ -54,7 +55,7 @@ func TestRealExport(t *testing.T) {
5455 if target, err := os.Readlink(filepath.Join(out, CurrentName)); err != nil || target != FileName(build) {
5556 t.Errorf("current.sqlite → %q (%v)", target, err)
5657 }
57- if l, s := meta("locale"), meta("dbcache_status"); l != "enUS" || s != DBCacheApplied {
58+ if l, s := meta("locale"), meta("dbcache_status"); l != "enUS" || s != string(dataset.HotfixApplied) {
5859 t.Errorf("locale %q dbcache_status %q", l, s)
5960 }
6061 if n := one(`SELECT COUNT(*) FROM _tables WHERE status='ok'`); n != "1161" {
@@ -8,8 +8,9 @@ import (
8 "strings"8 "strings"
9 "testing"9 "testing"
10 10
11- "github.com/bnema/forever-db/internal/defs"11+ "bnema.dev/forever-db/pkg/dataset"
12- "github.com/bnema/forever-db/internal/install"12+ "bnema.dev/forever-db/pkg/defs"
13+ "bnema.dev/forever-db/pkg/install"
13 )14 )
14 15
15 // TestRealExport runs the full export on a real install (V3). It needs16 // TestRealExport runs the full export on a real install (V3). It needs
@@ -54,7 +55,7 @@ func TestRealExport(t *testing.T) {
54 if target, err := os.Readlink(filepath.Join(out, CurrentName)); err != nil || target != FileName(build) {55 if target, err := os.Readlink(filepath.Join(out, CurrentName)); err != nil || target != FileName(build) {
55 t.Errorf("current.sqlite → %q (%v)", target, err)56 t.Errorf("current.sqlite → %q (%v)", target, err)
56 }57 }
57- if l, s := meta("locale"), meta("dbcache_status"); l != "enUS" || s != DBCacheApplied {58+ if l, s := meta("locale"), meta("dbcache_status"); l != "enUS" || s != string(dataset.HotfixApplied) {
58 t.Errorf("locale %q dbcache_status %q", l, s)59 t.Errorf("locale %q dbcache_status %q", l, s)
59 }60 }
60 if n := one(`SELECT COUNT(*) FROM _tables WHERE status='ok'`); n != "1161" {61 if n := one(`SELECT COUNT(*) FROM _tables WHERE status='ok'`); n != "1161" {
M internal/export/snapshot_test.go +3 -3
@@ -8,9 +8,9 @@ import (
88 "strings"
99 "testing"
1010
11- "github.com/bnema/forever-db/internal/dbd"
12- "github.com/bnema/forever-db/internal/defs"
13- "github.com/bnema/forever-db/internal/schema"
11+ "bnema.dev/forever-db/internal/schema"
12+ "bnema.dev/forever-db/pkg/dbd"
13+ "bnema.dev/forever-db/pkg/defs"
1414 )
1515
1616 var schemaVersion = strconv.Itoa(schema.Version)
@@ -8,9 +8,9 @@ import (
8 "strings"8 "strings"
9 "testing"9 "testing"
10 10
11- "github.com/bnema/forever-db/internal/dbd"11+ "bnema.dev/forever-db/internal/schema"
12- "github.com/bnema/forever-db/internal/defs"12+ "bnema.dev/forever-db/pkg/dbd"
13- "github.com/bnema/forever-db/internal/schema"13+ "bnema.dev/forever-db/pkg/defs"
14 )14 )
15 15
16 var schemaVersion = strconv.Itoa(schema.Version)16 var schemaVersion = strconv.Itoa(schema.Version)
M internal/export/status.go +9 -3
@@ -11,9 +11,9 @@ import (
1111 "path/filepath"
1212 "strconv"
1313
14- "github.com/bnema/forever-db/internal/defs"
15- "github.com/bnema/forever-db/internal/install"
16- "github.com/bnema/forever-db/internal/schema"
14+ "bnema.dev/forever-db/internal/schema"
15+ "bnema.dev/forever-db/pkg/defs"
16+ "bnema.dev/forever-db/pkg/install"
1717 )
1818
1919 // Status states and reasons.
@@ -26,6 +26,7 @@ const (
2626 ReasonHotfixesChanged = "hotfixes_changed"
2727 ReasonSchemaChanged = "schema_changed"
2828 ReasonDefsChanged = "defs_changed"
29+ ReasonSourceChanged = "source_changed"
2930 )
3031
3132 // StatusReport describes how the last export compares to the install.
@@ -117,6 +118,11 @@ func Status(inst *install.Install, outDir string) (*StatusReport, error) {
117118 } else if v != hotfix {
118119 add(ReasonHotfixesChanged)
119120 }
121+ // Only a local export can be up to date with the install; exports made
122+ // before _meta.source existed are local.
123+ if v, ok := meta[schema.MetaSource]; ok && v != SourceLocal {
124+ add(ReasonSourceChanged)
125+ }
120126 if v, ok := meta[schema.MetaSchemaVersion]; !ok || v != strconv.Itoa(schema.Version) {
121127 add(ReasonSchemaChanged)
122128 }
@@ -11,9 +11,9 @@ import (
11 "path/filepath"11 "path/filepath"
12 "strconv"12 "strconv"
13 13
14- "github.com/bnema/forever-db/internal/defs"14+ "bnema.dev/forever-db/internal/schema"
15- "github.com/bnema/forever-db/internal/install"15+ "bnema.dev/forever-db/pkg/defs"
16- "github.com/bnema/forever-db/internal/schema"16+ "bnema.dev/forever-db/pkg/install"
17 )17 )
18 18
19 // Status states and reasons.19 // Status states and reasons.
@@ -26,6 +26,7 @@ const (
26 ReasonHotfixesChanged = "hotfixes_changed"26 ReasonHotfixesChanged = "hotfixes_changed"
27 ReasonSchemaChanged = "schema_changed"27 ReasonSchemaChanged = "schema_changed"
28 ReasonDefsChanged = "defs_changed"28 ReasonDefsChanged = "defs_changed"
29+ ReasonSourceChanged = "source_changed"
29 )30 )
30 31
31 // StatusReport describes how the last export compares to the install.32 // StatusReport describes how the last export compares to the install.
@@ -117,6 +118,11 @@ func Status(inst *install.Install, outDir string) (*StatusReport, error) {
117 } else if v != hotfix {118 } else if v != hotfix {
118 add(ReasonHotfixesChanged)119 add(ReasonHotfixesChanged)
119 }120 }
121+ // Only a local export can be up to date with the install; exports made
122+ // before _meta.source existed are local.
123+ if v, ok := meta[schema.MetaSource]; ok && v != SourceLocal {
124+ add(ReasonSourceChanged)
125+ }
120 if v, ok := meta[schema.MetaSchemaVersion]; !ok || v != strconv.Itoa(schema.Version) {126 if v, ok := meta[schema.MetaSchemaVersion]; !ok || v != strconv.Itoa(schema.Version) {
121 add(ReasonSchemaChanged)127 add(ReasonSchemaChanged)
122 }128 }
M internal/export/status_test.go +1 -1
@@ -8,7 +8,7 @@ import (
88 "slices"
99 "testing"
1010
11- "github.com/bnema/forever-db/internal/install"
11+ "bnema.dev/forever-db/pkg/install"
1212 )
1313
1414 func statusInstall(t *testing.T, dbcache []byte) *install.Install {
@@ -8,7 +8,7 @@ import (
8 "slices"8 "slices"
9 "testing"9 "testing"
10 10
11- "github.com/bnema/forever-db/internal/install"11+ "bnema.dev/forever-db/pkg/install"
12 )12 )
13 13
14 func statusInstall(t *testing.T, dbcache []byte) *install.Install {14 func statusInstall(t *testing.T, dbcache []byte) *install.Install {
M internal/export/writer.go +3 -3
@@ -13,9 +13,9 @@ import (
1313 "modernc.org/sqlite" // driver "sqlite"
1414 sqlite3 "modernc.org/sqlite/lib"
1515
16- "github.com/bnema/forever-db/internal/db2"
17- "github.com/bnema/forever-db/internal/hotfix"
18- "github.com/bnema/forever-db/internal/schema"
16+ "bnema.dev/forever-db/internal/schema"
17+ "bnema.dev/forever-db/pkg/db2"
18+ "bnema.dev/forever-db/pkg/hotfix"
1919 )
2020
2121 // Writer writes an export database. It is not safe for concurrent use:
@@ -13,9 +13,9 @@ import (
13 "modernc.org/sqlite" // driver "sqlite"13 "modernc.org/sqlite" // driver "sqlite"
14 sqlite3 "modernc.org/sqlite/lib"14 sqlite3 "modernc.org/sqlite/lib"
15 15
16- "github.com/bnema/forever-db/internal/db2"16+ "bnema.dev/forever-db/internal/schema"
17- "github.com/bnema/forever-db/internal/hotfix"17+ "bnema.dev/forever-db/pkg/db2"
18- "github.com/bnema/forever-db/internal/schema"18+ "bnema.dev/forever-db/pkg/hotfix"
19 )19 )
20 20
21 // Writer writes an export database. It is not safe for concurrent use:21 // Writer writes an export database. It is not safe for concurrent use:
M internal/export/writer_test.go +3 -3
@@ -7,9 +7,9 @@ import (
77 "testing"
88 "time"
99
10- "github.com/bnema/forever-db/internal/db2"
11- "github.com/bnema/forever-db/internal/hotfix"
12- "github.com/bnema/forever-db/internal/install"
10+ "bnema.dev/forever-db/pkg/db2"
11+ "bnema.dev/forever-db/pkg/hotfix"
12+ "bnema.dev/forever-db/pkg/install"
1313 )
1414
1515 func writerDef() *db2.Definition {
@@ -7,9 +7,9 @@ import (
7 "testing"7 "testing"
8 "time"8 "time"
9 9
10- "github.com/bnema/forever-db/internal/db2"10+ "bnema.dev/forever-db/pkg/db2"
11- "github.com/bnema/forever-db/internal/hotfix"11+ "bnema.dev/forever-db/pkg/hotfix"
12- "github.com/bnema/forever-db/internal/install"12+ "bnema.dev/forever-db/pkg/install"
13 )13 )
14 14
15 func writerDef() *db2.Definition {15 func writerDef() *db2.Definition {
M internal/schema/schema.go +2 -1
@@ -6,7 +6,7 @@ import (
66 "strconv"
77 "strings"
88
9- "github.com/bnema/forever-db/internal/db2"
9+ "bnema.dev/forever-db/pkg/db2"
1010 )
1111
1212 // Version is the export schema version stored in _meta.
@@ -29,6 +29,7 @@ const (
2929 MetaDefsSHA256 = "defs_sha256"
3030 MetaTablesOK = "tables_ok"
3131 MetaTablesFailed = "tables_failed"
32+ MetaSource = "source" // local or cdn
3233 )
3334
3435 // SQLColumn is one SQL column of a data table.
@@ -6,7 +6,7 @@ import (
6 "strconv"6 "strconv"
7 "strings"7 "strings"
8 8
9- "github.com/bnema/forever-db/internal/db2"9+ "bnema.dev/forever-db/pkg/db2"
10 )10 )
11 11
12 // Version is the export schema version stored in _meta.12 // Version is the export schema version stored in _meta.
@@ -29,6 +29,7 @@ const (
29 MetaDefsSHA256 = "defs_sha256"29 MetaDefsSHA256 = "defs_sha256"
30 MetaTablesOK = "tables_ok"30 MetaTablesOK = "tables_ok"
31 MetaTablesFailed = "tables_failed"31 MetaTablesFailed = "tables_failed"
32+ MetaSource = "source" // local or cdn
32 )33 )
33 34
34 // SQLColumn is one SQL column of a data table.35 // SQLColumn is one SQL column of a data table.
M internal/schema/schema_test.go +1 -1
@@ -5,7 +5,7 @@ import (
55 "strings"
66 "testing"
77
8- "github.com/bnema/forever-db/internal/db2"
8+ "bnema.dev/forever-db/pkg/db2"
99 )
1010
1111 func spellReagents() *db2.Definition {
@@ -5,7 +5,7 @@ import (
5 "strings"5 "strings"
6 "testing"6 "testing"
7 7
8- "github.com/bnema/forever-db/internal/db2"8+ "bnema.dev/forever-db/pkg/db2"
9 )9 )
10 10
11 func spellReagents() *db2.Definition {11 func spellReagents() *db2.Definition {
M internal/testutil/blte.go +5 -2
@@ -4,9 +4,10 @@ package testutil
44 import (
55 "bytes"
66 "compress/zlib"
7+ "crypto/md5"
78 "encoding/binary"
89
9- "github.com/bnema/forever-db/internal/salsa20"
10+ "bnema.dev/forever-db/internal/salsa20"
1011 )
1112
1213 // BLTEBlock describes one block. Mode is 'N', 'Z' or 'E'. For 'E', Data is
@@ -27,7 +28,7 @@ func BLTERaw(data []byte) []byte {
2728 }
2829
2930 // BLTETable returns a table-form BLTE from already encoded blocks and their
30-// logical sizes.
31+// logical sizes, with each block's MD5 in the table.
3132 func BLTETable(blocks [][]byte, logical []int) []byte {
3233 hsize := 12 + 24*len(blocks)
3334 out := make([]byte, hsize)
@@ -40,6 +41,8 @@ func BLTETable(blocks [][]byte, logical []int) []byte {
4041 e := out[12+i*24:]
4142 binary.BigEndian.PutUint32(e[0:], uint32(len(b)))
4243 binary.BigEndian.PutUint32(e[4:], uint32(logical[i]))
44+ sum := md5.Sum(b)
45+ copy(e[8:24], sum[:])
4346 }
4447 for _, b := range blocks {
4548 out = append(out, b...)
@@ -4,9 +4,10 @@ package testutil
4 import (4 import (
5 "bytes"5 "bytes"
6 "compress/zlib"6 "compress/zlib"
7+ "crypto/md5"
7 "encoding/binary"8 "encoding/binary"
8 9
9- "github.com/bnema/forever-db/internal/salsa20"10+ "bnema.dev/forever-db/internal/salsa20"
10 )11 )
11 12
12 // BLTEBlock describes one block. Mode is 'N', 'Z' or 'E'. For 'E', Data is13 // BLTEBlock describes one block. Mode is 'N', 'Z' or 'E'. For 'E', Data is
@@ -27,7 +28,7 @@ func BLTERaw(data []byte) []byte {
27 }28 }
28 29
29 // BLTETable returns a table-form BLTE from already encoded blocks and their30 // BLTETable returns a table-form BLTE from already encoded blocks and their
30-// logical sizes.31+// logical sizes, with each block's MD5 in the table.
31 func BLTETable(blocks [][]byte, logical []int) []byte {32 func BLTETable(blocks [][]byte, logical []int) []byte {
32 hsize := 12 + 24*len(blocks)33 hsize := 12 + 24*len(blocks)
33 out := make([]byte, hsize)34 out := make([]byte, hsize)
@@ -40,6 +41,8 @@ func BLTETable(blocks [][]byte, logical []int) []byte {
40 e := out[12+i*24:]41 e := out[12+i*24:]
41 binary.BigEndian.PutUint32(e[0:], uint32(len(b)))42 binary.BigEndian.PutUint32(e[0:], uint32(len(b)))
42 binary.BigEndian.PutUint32(e[4:], uint32(logical[i]))43 binary.BigEndian.PutUint32(e[4:], uint32(logical[i]))
44+ sum := md5.Sum(b)
45+ copy(e[8:24], sum[:])
43 }46 }
44 for _, b := range blocks {47 for _, b := range blocks {
45 out = append(out, b...)48 out = append(out, b...)
M main.go +1 -1
@@ -1,6 +1,6 @@
11 package main
22
3-import "github.com/bnema/forever-db/cmd"
3+import "bnema.dev/forever-db/cmd"
44
55 func main() {
66 cmd.Execute()
@@ -1,6 +1,6 @@
1 package main1 package main
2 2
3-import "github.com/bnema/forever-db/cmd"3+import "bnema.dev/forever-db/cmd"
4 4
5 func main() {5 func main() {
6 cmd.Execute()6 cmd.Execute()
R internal/blte/blte.go → pkg/blte/blte.go +43 -2 renamed, 81% similar
@@ -4,14 +4,15 @@ package blte
44 import (
55 "bytes"
66 "compress/zlib"
7+ "crypto/md5"
78 "encoding/binary"
89 "errors"
910 "fmt"
1011 "io"
1112 "slices"
1213
13- "github.com/bnema/forever-db/internal/db2"
14- "github.com/bnema/forever-db/internal/salsa20"
14+ "bnema.dev/forever-db/internal/salsa20"
15+ "bnema.dev/forever-db/pkg/db2"
1516 )
1617
1718 // Size bounds applied to values read from untrusted BLTE headers.
@@ -230,3 +231,43 @@ func decrypt(blk []byte, index, logical int, keys db2.KeyRing, out []byte, st *S
230231 }
231232 return nil, fmt.Errorf("encrypted: unsupported inner mode %q", plain[0])
232233 }
234+
235+// Verify checks that buf is the BLTE file named ekey, without decoding it.
236+// With a block table, ekey is the MD5 of the header (magic, size, table)
237+// and each block must match the MD5 in its table entry; with header size
238+// 0, ekey is the MD5 of the whole file.
239+func Verify(buf []byte, ekey [16]byte) error {
240+ if len(buf) < 8 || string(buf[:4]) != "BLTE" {
241+ return errors.New("blte: bad magic")
242+ }
243+ hsize := int64(binary.BigEndian.Uint32(buf[4:8]))
244+ if hsize == 0 {
245+ if md5.Sum(buf) != ekey {
246+ return errors.New("blte: file does not match its encoding key")
247+ }
248+ return nil
249+ }
250+ if hsize < 12 || hsize > int64(len(buf)) {
251+ return fmt.Errorf("blte: invalid header size %d", hsize)
252+ }
253+ if md5.Sum(buf[:hsize]) != ekey {
254+ return errors.New("blte: header does not match its encoding key")
255+ }
256+ n := int(buf[9])<<16 | int(buf[10])<<8 | int(buf[11])
257+ if buf[8] != 0x0F || n == 0 || 12+int64(n)*tableEntrySize > hsize {
258+ return errors.New("blte: invalid block table")
259+ }
260+ pos := hsize
261+ for i := 0; i < n; i++ {
262+ e := buf[12+i*tableEntrySize:]
263+ comp := int64(binary.BigEndian.Uint32(e[0:]))
264+ if comp < 1 || pos+comp > int64(len(buf)) {
265+ return fmt.Errorf("blte: block %d: truncated", i)
266+ }
267+ if md5.Sum(buf[pos:pos+comp]) != [16]byte(e[8:24]) {
268+ return fmt.Errorf("blte: block %d: content does not match its checksum", i)
269+ }
270+ pos += comp
271+ }
272+ return nil
273+}
@@ -4,14 +4,15 @@ package blte
4 import (4 import (
5 "bytes"5 "bytes"
6 "compress/zlib"6 "compress/zlib"
7+ "crypto/md5"
7 "encoding/binary"8 "encoding/binary"
8 "errors"9 "errors"
9 "fmt"10 "fmt"
10 "io"11 "io"
11 "slices"12 "slices"
12 13
13- "github.com/bnema/forever-db/internal/db2"14+ "bnema.dev/forever-db/internal/salsa20"
14- "github.com/bnema/forever-db/internal/salsa20"15+ "bnema.dev/forever-db/pkg/db2"
15 )16 )
16 17
17 // Size bounds applied to values read from untrusted BLTE headers.18 // Size bounds applied to values read from untrusted BLTE headers.
@@ -230,3 +231,43 @@ func decrypt(blk []byte, index, logical int, keys db2.KeyRing, out []byte, st *S
230 }231 }
231 return nil, fmt.Errorf("encrypted: unsupported inner mode %q", plain[0])232 return nil, fmt.Errorf("encrypted: unsupported inner mode %q", plain[0])
232 }233 }
234+
235+// Verify checks that buf is the BLTE file named ekey, without decoding it.
236+// With a block table, ekey is the MD5 of the header (magic, size, table)
237+// and each block must match the MD5 in its table entry; with header size
238+// 0, ekey is the MD5 of the whole file.
239+func Verify(buf []byte, ekey [16]byte) error {
240+ if len(buf) < 8 || string(buf[:4]) != "BLTE" {
241+ return errors.New("blte: bad magic")
242+ }
243+ hsize := int64(binary.BigEndian.Uint32(buf[4:8]))
244+ if hsize == 0 {
245+ if md5.Sum(buf) != ekey {
246+ return errors.New("blte: file does not match its encoding key")
247+ }
248+ return nil
249+ }
250+ if hsize < 12 || hsize > int64(len(buf)) {
251+ return fmt.Errorf("blte: invalid header size %d", hsize)
252+ }
253+ if md5.Sum(buf[:hsize]) != ekey {
254+ return errors.New("blte: header does not match its encoding key")
255+ }
256+ n := int(buf[9])<<16 | int(buf[10])<<8 | int(buf[11])
257+ if buf[8] != 0x0F || n == 0 || 12+int64(n)*tableEntrySize > hsize {
258+ return errors.New("blte: invalid block table")
259+ }
260+ pos := hsize
261+ for i := 0; i < n; i++ {
262+ e := buf[12+i*tableEntrySize:]
263+ comp := int64(binary.BigEndian.Uint32(e[0:]))
264+ if comp < 1 || pos+comp > int64(len(buf)) {
265+ return fmt.Errorf("blte: block %d: truncated", i)
266+ }
267+ if md5.Sum(buf[pos:pos+comp]) != [16]byte(e[8:24]) {
268+ return fmt.Errorf("blte: block %d: content does not match its checksum", i)
269+ }
270+ pos += comp
271+ }
272+ return nil
273+}
R internal/blte/blte_test.go → pkg/blte/blte_test.go +38 -2 renamed, 82% similar
R internal/casc/archive.go → pkg/casc/archive.go +2 -2 renamed, 96% similar
R internal/casc/archive_test.go → pkg/casc/archive_test.go +1 -1 renamed, 99% similar
A pkg/casc/cdn/cdn.go +123 -0
A pkg/casc/cdn/cdn_test.go +508 -0
A pkg/casc/cdn/export_test.go +96 -0
A pkg/casc/cdn/fuzz_test.go +22 -0
A pkg/casc/cdn/http.go +382 -0
A pkg/casc/cdn/http_test.go +286 -0
A pkg/casc/cdn/index.go +238 -0
A pkg/casc/cdn/index_test.go +236 -0
A pkg/casc/cdn/reader.go +263 -0
A pkg/casc/cdn/real_test.go +134 -0
R internal/casc/encoding.go → pkg/casc/encoding.go +0 -0 renamed, 100% similar
R internal/casc/encoding_test.go → pkg/casc/encoding_test.go +1 -1 renamed, 98% similar
R internal/casc/index.go → pkg/casc/index.go +0 -0 renamed, 100% similar
R internal/casc/root.go → pkg/casc/root.go +0 -0 renamed, 100% similar
R internal/casc/root_test.go → pkg/casc/root_test.go +1 -1 renamed, 98% similar
A pkg/casc/source.go +52 -0
R internal/casc/storage.go → pkg/casc/storage.go +21 -16 renamed, 83% similar
R internal/casc/storage_test.go → pkg/casc/storage_test.go +2 -2 renamed, 95% similar
A pkg/dataset/dataset.go +258 -0
A pkg/dataset/dataset_test.go +239 -0
A pkg/dataset/helpers_test.go +45 -0
R internal/export/keys.go → pkg/dataset/keys.go +10 -11 renamed, 71% similar
R internal/export/keys_test.go → pkg/dataset/keys_test.go +8 -8 renamed, 92% similar
R internal/export/table.go → pkg/dataset/table.go +18 -23 renamed, 64% similar
R internal/db2/db2.go → pkg/db2/db2.go +0 -0 renamed, 100% similar
R internal/db2/db2_test.go → pkg/db2/db2_test.go +0 -0 renamed, 100% similar
R internal/dbd/dbd.go → pkg/dbd/dbd.go +1 -1 renamed, 99% similar
R internal/dbd/dbd_test.go → pkg/dbd/dbd_test.go +1 -1 renamed, 99% similar
R internal/defs/data/README.md → pkg/defs/data/README.md +1 -1 renamed, 93% similar
R internal/defs/data/forever.json.gz → pkg/defs/data/forever.json.gz +0 -0 binary file: no text diff · renamed, 100% similar
R internal/defs/defs.go → pkg/defs/defs.go +3 -3 renamed, 99% similar
R internal/defs/defs_test.go → pkg/defs/defs_test.go +1 -1 renamed, 99% similar
R internal/defs/generate.go → pkg/defs/generate.go +22 -14 renamed, 83% similar
R internal/defs/generate_test.go → pkg/defs/generate_test.go +22 -8 renamed, 87% similar
R internal/hotfix/apply.go → pkg/hotfix/apply.go +1 -1 renamed, 98% similar
R internal/hotfix/apply_test.go → pkg/hotfix/apply_test.go +2 -2 renamed, 97% similar
R internal/hotfix/consistency_test.go → pkg/hotfix/consistency_test.go +4 -4 renamed, 88% similar
R internal/hotfix/integration_test.go → pkg/hotfix/integration_test.go +8 -8 renamed, 95% similar
R internal/hotfix/reader.go → pkg/hotfix/reader.go +0 -0 renamed, 100% similar
R internal/hotfix/reader_test.go → pkg/hotfix/reader_test.go +1 -1 renamed, 98% similar
R internal/install/install.go → pkg/install/install.go +7 -1 renamed, 94% similar
R internal/install/install_test.go → pkg/install/install_test.go +0 -0 renamed, 100% similar
R internal/sources/manifest.go → pkg/sources/manifest.go +0 -0 renamed, 100% similar
R internal/sources/manifest_test.go → pkg/sources/manifest_test.go +0 -0 renamed, 100% similar
R internal/sources/sources.go → pkg/sources/sources.go +2 -2 renamed, 99% similar
R internal/sources/sources_test.go → pkg/sources/sources_test.go +0 -0 renamed, 100% similar
R internal/tactkeys/tactkeys.go → pkg/tactkeys/tactkeys.go +1 -1 renamed, 97% similar
R internal/tactkeys/tactkeys_test.go → pkg/tactkeys/tactkeys_test.go +0 -0 renamed, 100% similar
R internal/wdc5/decode.go → pkg/wdc5/decode.go +1 -1 renamed, 95% similar
R internal/wdc5/dense.go → pkg/wdc5/dense.go +1 -1 renamed, 99% similar
R internal/wdc5/dense_test.go → pkg/wdc5/dense_test.go +2 -2 renamed, 99% similar
R internal/wdc5/header.go → pkg/wdc5/header.go +0 -0 renamed, 100% similar
R internal/wdc5/header_test.go → pkg/wdc5/header_test.go +1 -1 renamed, 99% similar
R internal/wdc5/integration_test.go → pkg/wdc5/integration_test.go +7 -7 renamed, 95% similar
R internal/wdc5/sparse.go → pkg/wdc5/sparse.go +1 -1 renamed, 98% similar
R internal/wdc5/sparse_test.go → pkg/wdc5/sparse_test.go +2 -2 renamed, 97% similar
A scripts/compare-exports.sh +40 -0

Comments00 unresolved

    no comments yet.

    Keyboard shortcuts

    Single-key shortcuts are on. ctrl k and esc work whatever this says.

    ctrl k :
    go to a section, branch, tag, file or repository
    ?
    this list
    j k
    move the row cursor down / up
    enter
    open the row under the cursor; on Files, a directory opens or closes in place
    ↑ ↓ ← → home end
    in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
    l h
    on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. On pages with a side panel: into the panel (on a merge request, its files) / back to the content; there j k move between its controls
    g g G
    first / last row
    /
    filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
    b
    switch branch or tag
    g s g f g c g b g m g i g r g a
    tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
    g h
    home
    w
    wide mode: use the whole width of the screen, or not (remembered)
    y
    copy a permalink pinned to the commit; in a file, click a line number to select it, shift-click for a range
    d u x
    diff: split / unified / collapse or expand all
    e E
    diff: the whole file in view / every file, with the lines the hunks hide
    n
    merge request: next note in the diff
    l
    merge request: the list of files (j k move, enter opens, esc back)
    M
    merge request: the merge menu; there 1–3 pick the mode, D deletes the branch, enter merges
    R
    merge request: mark the head read
    esc
    close a dialog, leave a field

    Branches 2

    Tags 1

    ↑↓ moveenter openesc close