build-binaries / build-binaries (push) Successful in 2m18s
Builds the code half of #60, and closes the CLI gap the #53 sweep found: PR #71 shipped #53's original surface rather than the one #56, #62 and #65 settled. ## What lands **`depot.KeyStore`** — `ProbeKey` / `PutReader` / `GetKey`, addressing the zone by object key rather than by depot sha. NWSync cannot use the sha-addressed path: a blob is named after the sha1 of its *uncompressed* bytes while the body uploaded is the compressed form, and Bunny's `Checksum` header is sha256 of the body. Per #55 this reuses `internal/depot`'s `httpBackend` — same IPv4-pinned transport, same retry, same tri-state probe — and the sha-addressed `Backend` is now rewritten on top of it. No second HTTP client, no per-instance hash-function fields: the caller passes the key and the checksum, which turned out simpler than #55 expected. **A sink in `internal/nwsync`** — the zone by default, a local tree under `--out DIR` as the conformance path. Blobs upload as they are produced and the index lands last, so the presence of an index is the publication marker. A blob already in the zone is skipped via #55's probe *without* paying for compression (the body is a thunk) — which matters for the backfill, where compression is the expensive part. **The settled CLI** ``` nwsync emit [--as NAME] [--out DIR] <artifact-key> <file> nwsync assemble --group-id N [--tlk-key KEY] [--out DIR] <artifact-key>... ``` Artifact keys are depot keys; an index lives beside its artifact with the extension replaced (#62), derived in exactly one place so `emit` and `assemble` cannot disagree. Flags may now follow positionals — Go's `flag` stops at the first non-flag argument, which cost a run during #59. **Fail-closed in two places** — an artifact key whose embedded digest does not match the file is refused (publishing an index under the wrong key silently pairs a manifest with the wrong artifact), and `assemble` refuses an artifact with no index rather than publishing a manifest missing a hak. ## Checks `make check` green. Six new tests run against a Bunny-shaped `httptest` zone that verifies the `Checksum` header the way Bunny does: blobs-then-index ordering, skip-if-present, no index after a failed upload, key/file mismatch, and assemble reading indexes back out of the zone. Conformance re-run through the new CLI against upstream `nwn_nwsync_write` 2.1.2 over `sow_vfxs_01.hak` (#59's oracle): the manifest is still **byte-identical**. ## Not in this PR - **Live upload against the real zone.** The nwsync zone and its credential are #61, still open. Everything here is proven against a fake zone only. - **Consumer wiring** — #65, in the three producer repos. - **The mid-hak failure *policy*.** The mechanism is here (fail closed, orphan blobs left, re-run resumes); whether a module release may proceed when an emit failed is a human call, still open on #60. 🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: #73 Co-authored-by: vickydotbat <vickydotbat@tutamail.com>
265 lines
8.7 KiB
Go
265 lines
8.7 KiB
Go
package nwsync
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha1"
|
|
"fmt"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"slices"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.westgate.pw/ShadowsOverWestgate/sow-tools/internal/buildinfo"
|
|
"git.westgate.pw/ShadowsOverWestgate/sow-tools/internal/erf"
|
|
)
|
|
|
|
// fileSizeLimit matches upstream's --limit-file-size default of 15 MB. A
|
|
// resource over it is a hard failure, not a skip: upstream quit(1)s and so do
|
|
// we. Our largest resource today is 13.66 MiB, so the headroom is thin.
|
|
const fileSizeLimit = 15 * 1024 * 1024
|
|
|
|
// skippedTypes are never published, matching upstream's GobalResTypeSkipList.
|
|
var skippedTypes = resTypes("nss", "ndb", "gic")
|
|
|
|
// emitterVersion identifies the blob/manifest byte format this package
|
|
// produces. assemble refuses to merge indexes that disagree on it, because two
|
|
// producers of blobs mean a skewed emitter can otherwise write blobs the merged
|
|
// manifest quietly disagrees with. Bump it only when emitted bytes change — it
|
|
// is deliberately not the build revision, which would invalidate every
|
|
// published index on every unrelated commit.
|
|
const emitterVersion = "1"
|
|
|
|
// serverTypes are loaded only server-side; a manifest holding nothing else
|
|
// has no client contents. Mirrors upstream's GlobalResTypeServerList, whose
|
|
// trailing 0 is RESTYPE_INVALID.
|
|
var serverTypes = append(resTypes(
|
|
"are", "dlg", "fac", "gic", "git", "ifo", "itp", "jrl", "ncs", "ndb",
|
|
"nss", "ptm", "utc", "utd", "ute", "uti", "utm", "utp", "uts", "utt", "utw",
|
|
), 0)
|
|
|
|
func resTypes(extensions ...string) []uint16 {
|
|
types := make([]uint16, 0, len(extensions))
|
|
for _, extension := range extensions {
|
|
restype, ok := erf.ResourceTypeForExtension(extension)
|
|
if !ok {
|
|
panic("nwsync: unknown restype " + extension)
|
|
}
|
|
types = append(types, restype)
|
|
}
|
|
return types
|
|
}
|
|
|
|
// EmitResult reports what one emit run produced.
|
|
type EmitResult struct {
|
|
Name string // artifact name, without extension
|
|
ManifestPath string
|
|
Entries int
|
|
BlobsWritten int
|
|
}
|
|
|
|
// EmitOptions describes one emit run.
|
|
type EmitOptions struct {
|
|
ArtifactKey string // depot key of the artifact; the NSYM key is derived from it
|
|
ArtifactPath string // the file on disk
|
|
As string // name override, for a TLK whose filename is not its published name
|
|
OutDir string // write locally instead of uploading — the conformance path
|
|
Sink sink // test seam; nil means OutDir or the zone
|
|
}
|
|
|
|
// Emit explodes one artifact — a .hak/.erf or a loose file such as the TLK —
|
|
// into NWSync blobs plus a NSYM manifest describing only that artifact.
|
|
//
|
|
// Blobs go up as they are produced and the index lands last, so the presence of
|
|
// an index is the publication marker: an artifact whose emit died halfway has
|
|
// real blobs in the zone and no index, which is unambiguous. Blob names are
|
|
// content hashes, so re-running skips whatever already landed.
|
|
func Emit(options EmitOptions) (EmitResult, error) {
|
|
artifact, err := os.ReadFile(options.ArtifactPath)
|
|
if err != nil {
|
|
return EmitResult{}, fmt.Errorf("read artifact: %w", err)
|
|
}
|
|
if err := checkArtifactKey(options.ArtifactKey, artifact); err != nil {
|
|
return EmitResult{}, err
|
|
}
|
|
name := options.As
|
|
if name == "" {
|
|
name = path.Base(options.ArtifactKey)
|
|
}
|
|
extension := path.Ext(name)
|
|
name = strings.TrimSuffix(name, extension)
|
|
|
|
key, err := resolveIndexKey(options.ArtifactKey, options.OutDir)
|
|
if err != nil {
|
|
return EmitResult{}, err
|
|
}
|
|
|
|
resources, err := readArtifact(options.ArtifactPath, artifact, name)
|
|
if err != nil {
|
|
return EmitResult{}, err
|
|
}
|
|
|
|
target, err := openSink(options.OutDir, options.Sink)
|
|
if err != nil {
|
|
return EmitResult{}, err
|
|
}
|
|
|
|
entries, blobs, onDiskBytes, err := emitResources(resources, target)
|
|
if err != nil {
|
|
return EmitResult{}, err
|
|
}
|
|
if len(entries) == 0 {
|
|
return EmitResult{}, fmt.Errorf("%s: nothing to index (no publishable resources)", options.ArtifactPath)
|
|
}
|
|
|
|
data, err := writeManifest(entries)
|
|
if err != nil {
|
|
return EmitResult{}, err
|
|
}
|
|
if err := putManifestPair(target, key, data, entries, onDiskBytes, Sidecar{ModuleName: name}); err != nil {
|
|
return EmitResult{}, err
|
|
}
|
|
return EmitResult{Name: name, ManifestPath: target.describe(key), Entries: len(entries), BlobsWritten: blobs}, nil
|
|
}
|
|
|
|
// openSink returns the zone sink, or a local directory when outDir is set.
|
|
func openSink(outDir string, injected sink) (sink, error) {
|
|
if injected != nil {
|
|
return injected, nil
|
|
}
|
|
if outDir != "" {
|
|
return dirSink{root: outDir}, nil
|
|
}
|
|
return newZoneSink(context.Background(), os.Getenv)
|
|
}
|
|
|
|
// readArtifact returns the resources of an ERF/HAK/MOD, or the single resource
|
|
// a loose file represents. Upstream's resman does the same dispatch on the
|
|
// file's first three bytes. name is the artifact's published name, which for a
|
|
// loose file is also its resref.
|
|
func readArtifact(path string, data []byte, name string) ([]erf.Resource, error) {
|
|
if len(data) >= 3 {
|
|
switch string(data[:3]) {
|
|
case "ERF", "HAK":
|
|
archive, err := erf.Read(bytes.NewReader(data))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s: %w", path, err)
|
|
}
|
|
return archive.Resources, nil
|
|
case "MOD":
|
|
// A persistent world never publishes module contents, so the .mod
|
|
// contributes no bytes to a manifest — it only says which haks and
|
|
// which TLK the manifest covers.
|
|
return nil, fmt.Errorf("%s: a module is never emitted; a manifest is haks plus the TLK", path)
|
|
}
|
|
}
|
|
extension := filepath.Ext(filepath.Base(path))
|
|
restype, ok := erf.ResourceTypeForExtension(extension)
|
|
if !ok {
|
|
return nil, fmt.Errorf("%s: unknown resource type %q", path, extension)
|
|
}
|
|
return []erf.Resource{{
|
|
Name: name,
|
|
Type: restype,
|
|
Data: data,
|
|
}}, nil
|
|
}
|
|
|
|
func emitResources(resources []erf.Resource, target sink) ([]Entry, int, int64, error) {
|
|
// A resref appearing twice inside one artifact resolves to the last one,
|
|
// the way resman lets the last container added win.
|
|
order := make([]Identity, 0, len(resources))
|
|
latest := make(map[Identity]erf.Resource, len(resources))
|
|
var tooBig []string
|
|
for _, resource := range resources {
|
|
if _, ok := erf.ExtensionForResourceType(resource.Type); !ok {
|
|
return nil, 0, 0, fmt.Errorf("resref %s is not resolvable (unknown restype %d)", resource.Name, resource.Type)
|
|
}
|
|
if slices.Contains(skippedTypes, resource.Type) {
|
|
continue
|
|
}
|
|
if len(resource.Data) > fileSizeLimit {
|
|
tooBig = append(tooBig, fmt.Sprintf("%s: %d bytes > %d", resource.Name, len(resource.Data), fileSizeLimit))
|
|
continue
|
|
}
|
|
identity := Identity{ResRef: strings.ToLower(resource.Name), ResType: resource.Type}
|
|
if _, seen := latest[identity]; !seen {
|
|
order = append(order, identity)
|
|
}
|
|
latest[identity] = resource
|
|
}
|
|
if len(tooBig) > 0 {
|
|
sort.Strings(tooBig)
|
|
return nil, 0, 0, fmt.Errorf("resources exceed the file size limit:\n %s", strings.Join(tooBig, "\n "))
|
|
}
|
|
|
|
entries := make([]Entry, 0, len(order))
|
|
var blobs int
|
|
var onDiskBytes int64
|
|
for _, identity := range order {
|
|
resource := latest[identity]
|
|
sum := sha1.Sum(resource.Data)
|
|
entries = append(entries, Entry{
|
|
SHA1: sum,
|
|
Size: uint32(len(resource.Data)),
|
|
ResRef: identity.ResRef,
|
|
ResType: identity.ResType,
|
|
})
|
|
written, err := target.putBlob(fmt.Sprintf("%x", sum), func() []byte { return compressBlob(resource.Data) })
|
|
if err != nil {
|
|
return nil, 0, 0, err
|
|
}
|
|
if written > 0 {
|
|
blobs++
|
|
onDiskBytes += written
|
|
}
|
|
}
|
|
return entries, blobs, onDiskBytes, nil
|
|
}
|
|
|
|
// created is the sidecar timestamp. SOURCE_DATE_EPOCH pins it so a build can
|
|
// be reproduced byte for byte; the manifest itself is deterministic already.
|
|
func created() int64 {
|
|
if raw := os.Getenv("SOURCE_DATE_EPOCH"); raw != "" {
|
|
if seconds, err := strconv.ParseInt(raw, 10, 64); err == nil {
|
|
return seconds
|
|
}
|
|
}
|
|
return time.Now().Unix()
|
|
}
|
|
|
|
// putManifestPair stores a NSYM manifest and its .json sidecar at key. The
|
|
// caller supplies the sidecar fields it knows; the rest are derived from the
|
|
// entries. data must be the serialised form of entries.
|
|
func putManifestPair(target sink, key string, data []byte, entries []Entry, onDiskBytes int64, sidecar Sidecar) error {
|
|
var totalBytes int64
|
|
clientContents := false
|
|
for _, entry := range entries {
|
|
totalBytes += int64(entry.Size)
|
|
if !slices.Contains(serverTypes, entry.ResType) {
|
|
clientContents = true
|
|
}
|
|
}
|
|
sidecar.Version = manifestVersion
|
|
sidecar.SHA1 = fmt.Sprintf("%x", sha1.Sum(data))
|
|
sidecar.HashTreeDepth = hashTreeDepth
|
|
sidecar.IncludesModuleContents = false
|
|
sidecar.IncludesClientContents = clientContents
|
|
sidecar.TotalFiles = len(entries)
|
|
sidecar.TotalBytes = totalBytes
|
|
sidecar.OnDiskBytes = onDiskBytes
|
|
sidecar.Created = created()
|
|
sidecar.CreatedWith = buildinfo.String()
|
|
sidecar.EmitterVersion = emitterVersion
|
|
|
|
body, err := marshalSidecar(sidecar)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return target.putIndex(key, data, body)
|
|
}
|