From 38766fdcd5d6f5f173b4a009dd98b52f1393ec7e Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 23 Jun 2026 01:26:04 -0500 Subject: [PATCH] =?UTF-8?q?feat(M7):=20SSE=20reconnect=20backoff=20+=20sha?= =?UTF-8?q?re-name=20validation=20=F0=9F=9B=A1=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - daemon: exponential backoff (1s→30s) + ±25% jitter on SSE reconnect so a fleet that drops together doesn't reconnect in lockstep; a long-lived stream resets it - hub: ValidateShareName rejects path separators, traversal, control/non-ASCII chars, reserved Windows device names (CON/NUL/COM1…), and case-clashes with an existing share (Foo vs foo would collide on case-insensitive filesystems) - tests for both --- internal/daemon/backoff.go | 34 +++++++++++++++++++++ internal/daemon/backoff_test.go | 39 ++++++++++++++++++++++++ internal/daemon/daemon.go | 15 +++++++-- internal/hub/server.go | 9 ++++++ internal/hub/sharename.go | 54 +++++++++++++++++++++++++++++++++ internal/hub/sharename_test.go | 38 +++++++++++++++++++++++ scripts/build-release.sh | 44 +++++++++++++++++++++++++++ 7 files changed, 230 insertions(+), 3 deletions(-) create mode 100644 internal/daemon/backoff.go create mode 100644 internal/daemon/backoff_test.go create mode 100644 internal/hub/sharename.go create mode 100644 internal/hub/sharename_test.go create mode 100755 scripts/build-release.sh diff --git a/internal/daemon/backoff.go b/internal/daemon/backoff.go new file mode 100644 index 0000000..cf5136e --- /dev/null +++ b/internal/daemon/backoff.go @@ -0,0 +1,34 @@ +package daemon + +import ( + "math/rand" + "time" +) + +// Reconnect backoff bounds: start at 1s, double to a 30s ceiling. +const ( + backoffBase = 1 * time.Second + backoffMax = 30 * time.Second +) + +// nextBackoff returns the next clean (un-jittered) backoff: base, then doubling +// up to backoffMax. Pass the previous clean value; pass <=0 to (re)start at base. +func nextBackoff(prev time.Duration) time.Duration { + switch { + case prev <= 0: + return backoffBase + case prev*2 >= backoffMax: + return backoffMax + default: + return prev * 2 + } +} + +// jittered spreads a backoff by ±25% so a fleet that all lost the hub at once +// doesn't reconnect in lockstep (thundering herd). Returns 0 unchanged. +func jittered(d time.Duration) time.Duration { + if d <= 0 { + return 0 + } + return d + time.Duration(rand.Int63n(int64(d/2))) - d/4 +} diff --git a/internal/daemon/backoff_test.go b/internal/daemon/backoff_test.go new file mode 100644 index 0000000..d538251 --- /dev/null +++ b/internal/daemon/backoff_test.go @@ -0,0 +1,39 @@ +package daemon + +import ( + "testing" + "time" +) + +func TestNextBackoffDoublesAndCaps(t *testing.T) { + // Starts at base, doubles, then saturates at the ceiling. + want := []time.Duration{ + 1 * time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, + 16 * time.Second, 30 * time.Second, 30 * time.Second, + } + got := time.Duration(0) + for i, w := range want { + got = nextBackoff(got) + if got != w { + t.Fatalf("step %d: nextBackoff = %s, want %s", i, got, w) + } + } + // A non-positive input restarts at base (used to reset after a healthy stream). + if d := nextBackoff(0); d != backoffBase { + t.Fatalf("reset: nextBackoff(0) = %s, want %s", d, backoffBase) + } +} + +func TestJitteredStaysWithinBand(t *testing.T) { + const d = 8 * time.Second + lo, hi := d-d/4, d+d/4 // ±25% + for i := 0; i < 1000; i++ { + j := jittered(d) + if j < lo || j >= hi { + t.Fatalf("jittered(%s) = %s, want in [%s,%s)", d, j, lo, hi) + } + } + if jittered(0) != 0 { + t.Fatal("jittered(0) should be 0") + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index f706099..4657e9c 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -127,18 +127,27 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) { }() } - // Hub change events -> sync (reconnect with backoff). + // Hub change events -> sync (reconnect with exponential backoff + jitter). go func() { + backoff := time.Duration(0) for ctx.Err() == nil { + start := time.Now() err := c.Events(ctx, m.Share, func(proto.Event) { nudge() }) if ctx.Err() != nil { return } - d.logf("events %s reconnecting: %v", m.Share, err) + // A stream that lived a while is a transient drop, not a hard failure: + // reset so the retry is prompt instead of inheriting a grown delay. + if time.Since(start) > backoffMax { + backoff = 0 + } + backoff = nextBackoff(backoff) + wait := jittered(backoff) + d.logf("events %s reconnecting in ~%s: %v", m.Share, wait.Round(time.Millisecond), err) select { case <-ctx.Done(): return - case <-time.After(2 * time.Second): + case <-time.After(wait): } } }() diff --git a/internal/hub/server.go b/internal/hub/server.go index c9660c7..5f84aaf 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -127,6 +127,15 @@ func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, deviceID if !decode(w, r, &req) { return } + existing, err := s.db.ShareNames() + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + if err := ValidateShareName(req.Share, existing); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } if err := s.db.CreateShare(req.Share, deviceID, time.Now().Unix()); err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return diff --git a/internal/hub/sharename.go b/internal/hub/sharename.go new file mode 100644 index 0000000..05fa1f7 --- /dev/null +++ b/internal/hub/sharename.go @@ -0,0 +1,54 @@ +package hub + +import ( + "fmt" + "strings" +) + +// reservedNames are Windows device names a share must not use (case-insensitive): +// a share name can become a directory on a Windows client, where these are magic. +var reservedNames = func() map[string]bool { + m := map[string]bool{"con": true, "prn": true, "aux": true, "nul": true} + for i := 1; i <= 9; i++ { + m[fmt.Sprintf("com%d", i)] = true + m[fmt.Sprintf("lpt%d", i)] = true + } + return m +}() + +// ValidateShareName rejects share names that are unsafe as a path component or +// would collide with an existing share on a case-insensitive filesystem (macOS, +// Windows). existing is the set of names already on the hub; an exact match is +// allowed (publish is idempotent) — only a different-case clash is rejected. +func ValidateShareName(name string, existing []string) error { + switch { + case name == "": + return fmt.Errorf("share name is empty") + case strings.TrimSpace(name) != name: + return fmt.Errorf("share name %q has leading/trailing whitespace", name) + case len(name) > 128: + return fmt.Errorf("share name %q is too long (max 128 bytes)", name) + case name == "." || name == "..": + return fmt.Errorf("share name %q is reserved", name) + case strings.HasPrefix(name, ".") || strings.HasPrefix(name, "-"): + return fmt.Errorf("share name %q must not start with '.' or '-'", name) + } + for _, r := range name { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': + case r == '.', r == '_', r == '-': + default: + return fmt.Errorf("share name %q has invalid character %q (allowed: letters, digits, . _ -)", name, r) + } + } + if reservedNames[strings.ToLower(name)] { + return fmt.Errorf("share name %q is a reserved device name", name) + } + lower := strings.ToLower(name) + for _, e := range existing { + if e != name && strings.ToLower(e) == lower { + return fmt.Errorf("share name %q case-clashes with existing share %q (collides on case-insensitive filesystems)", name, e) + } + } + return nil +} diff --git a/internal/hub/sharename_test.go b/internal/hub/sharename_test.go new file mode 100644 index 0000000..ff0816a --- /dev/null +++ b/internal/hub/sharename_test.go @@ -0,0 +1,38 @@ +package hub + +import "testing" + +func TestValidateShareName(t *testing.T) { + existing := []string{"projects", "Repos"} + cases := []struct { + name string + ok bool + }{ + {"projects", true}, // exact match of an existing share is fine (idempotent publish) + {"my-app_2", true}, // letters, digits, dash, underscore + {"web.staging", true}, + {"", false}, // empty + {" lead", false}, // whitespace + {"trail ", false}, + {"a/b", false}, // path separator (sub-paths are mount-side, not in the name) + {"a\\b", false}, // backslash + {"..", false}, // traversal + {".hidden", false}, // leading dot + {"-flag", false}, // leading dash + {"sp ace", false}, // interior space + {"emoji🎉", false}, // non-ASCII + {"CON", false}, // reserved Windows device name + {"lpt3", false}, // reserved (case-insensitive) + {"repos", false}, // case-clashes with existing "Repos" + {"REPOS", false}, // case-clash + } + for _, c := range cases { + err := ValidateShareName(c.name, existing) + if c.ok && err != nil { + t.Errorf("ValidateShareName(%q) = %v, want ok", c.name, err) + } + if !c.ok && err == nil { + t.Errorf("ValidateShareName(%q) = ok, want error", c.name) + } + } +} diff --git a/scripts/build-release.sh b/scripts/build-release.sh new file mode 100755 index 0000000..412ad01 --- /dev/null +++ b/scripts/build-release.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Cross-compile both devbox binaries for all release targets. +# Override version: VERSION=v1.2.3 ./scripts/build-release.sh + +cd "$(dirname "$0")/.." + +VERSION="${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo dev)}" +LDFLAGS="-s -w -X main.version=$VERSION" + +BINS=(devbox devbox-hub) +TARGETS=(linux/amd64 darwin/arm64 darwin/amd64 windows/amd64) + +rm -rf dist && mkdir -p dist + +echo "Building version: $VERSION" + +for bin in "${BINS[@]}"; do + for target in "${TARGETS[@]}"; do + os="${target%/*}" + arch="${target#*/}" + out="dist/${bin}_${VERSION}_${os}_${arch}" + [ "$os" = "windows" ] && out="${out}.exe" + echo " -> $out" + CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" \ + go build -ldflags "$LDFLAGS" -o "$out" "./cmd/${bin}" + done +done + +# Generate checksums. +echo "Generating dist/SHA256SUMS" +( + cd dist + if command -v shasum >/dev/null 2>&1; then + shasum -a 256 * > SHA256SUMS + else + sha256sum * > SHA256SUMS + fi +) + +echo +echo "Done. Artifacts in dist/:" +ls -lh dist/