feat(transfer): opt-in gzip blob compression for WAN sync 🌐🗜️
The "changed my mind" feature: deferred as YAGNI on a LAN, but the hub is now WAN-reachable (port-forwarded), so over-the-internet sync is a real path and compression earns its keep. - client (settings.transfer.compress, default off): gzip a blob upload only when it actually shrinks — incompressible chunks (media, encrypted) go raw so we never inflate the wire. Sets Content-Encoding: gzip. Wired into the daemon sync loop and the initial `publish` upload. - hub: decompresses gzip uploads before hashing, so dedup + content-address integrity are unchanged. Bomb-safe — caps BOTH the compressed stream (MaxBytesReader) and the decompressed size (LimitReader), rejecting a gzip header over a non-gzip body. Tests: client gzip-when-smaller / raw-when-not, hub decompress round-trip + bad-gzip rejection. go test ./... -race clean, go vet clean.
This commit is contained in:
parent
8c5d576a72
commit
11fe999ca2
6 changed files with 165 additions and 6 deletions
|
|
@ -154,6 +154,9 @@ func publishCmd() *cobra.Command {
|
|||
|
||||
c := transport.New(d.Hub)
|
||||
c.SetBearer(d.Bearer)
|
||||
if s, err := config.LoadSettings(dir); err == nil {
|
||||
c.SetCompress(s.Transfer.Compress) // big initial upload — honor compress over WAN
|
||||
}
|
||||
if err := c.Publish(share); err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -131,6 +131,7 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) {
|
|||
}
|
||||
c := transport.New(m.Hub)
|
||||
c.SetBearer(d.cfg.Bearer)
|
||||
c.SetCompress(d.compress)
|
||||
if d.maxBytesPerSec > 0 {
|
||||
c.SetRateLimit(d.maxBytesPerSec)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
package hub
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
|
|
@ -396,13 +397,29 @@ func (s *Server) handleGetBlob(w http.ResponseWriter, r *http.Request, _ string)
|
|||
|
||||
func (s *Server) handleBlob(w http.ResponseWriter, r *http.Request, _ string) {
|
||||
hash := r.PathValue("hash")
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBlobBytes)
|
||||
body, err := io.ReadAll(r.Body)
|
||||
// MaxBytesReader caps the COMPRESSED stream (wire DoS bound).
|
||||
var src io.Reader = http.MaxBytesReader(w, r.Body, maxBlobBytes)
|
||||
if r.Header.Get("Content-Encoding") == "gzip" {
|
||||
gz, err := gzip.NewReader(src)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "bad gzip body")
|
||||
return
|
||||
}
|
||||
defer gz.Close()
|
||||
// Also cap the DECOMPRESSED size (+1 to detect overflow) so a gzip bomb
|
||||
// can't OOM the hub; a blob is ≤ maxBlobBytes uncompressed by definition.
|
||||
src = io.LimitReader(gz, maxBlobBytes+1)
|
||||
}
|
||||
body, err := io.ReadAll(src)
|
||||
if err != nil {
|
||||
// MaxBytesReader trips here when the body exceeds maxBlobBytes.
|
||||
writeErr(w, http.StatusRequestEntityTooLarge, err.Error())
|
||||
return
|
||||
}
|
||||
if len(body) > maxBlobBytes {
|
||||
writeErr(w, http.StatusRequestEntityTooLarge, "decompressed blob too large")
|
||||
return
|
||||
}
|
||||
if chunk.Hash(body) != hash {
|
||||
writeErr(w, http.StatusBadRequest, "body does not match hash")
|
||||
return
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package hub
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
|
|
@ -272,6 +273,56 @@ func TestPushWriteGate(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestBlobGzipUpload is the hub side of opt-in transport compression: a blob
|
||||
// PUT with Content-Encoding: gzip must be decompressed before hashing/storing
|
||||
// (so dedup + integrity are unchanged), round-trip back identical, and a gzip
|
||||
// header over a non-gzip body must be rejected (bomb-safe ingest).
|
||||
func TestBlobGzipUpload(t *testing.T) {
|
||||
base, db := testHub(t)
|
||||
if err := db.CreateToken(HashToken("tok"), time.Now().Unix()+3600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bearer := joinWith(t, base, "tok").Bearer
|
||||
|
||||
original := bytes.Repeat([]byte("devbox compresses well over WAN! "), 2048)
|
||||
hash := chunk.Hash(original)
|
||||
var gz bytes.Buffer
|
||||
zw := gzip.NewWriter(&gz)
|
||||
if _, err := zw.Write(original); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zw.Close()
|
||||
if gz.Len() >= len(original) {
|
||||
t.Fatalf("test data must compress: gz=%d orig=%d", gz.Len(), len(original))
|
||||
}
|
||||
|
||||
put := func(h string, body []byte, enc string) int {
|
||||
req, _ := http.NewRequest("PUT", base+proto.PathBlob+h, bytes.NewReader(body))
|
||||
req.Header.Set(proto.AuthHeader, "Bearer "+bearer)
|
||||
if enc != "" {
|
||||
req.Header.Set("Content-Encoding", enc)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
if st := put(hash, gz.Bytes(), "gzip"); st != http.StatusOK {
|
||||
t.Fatalf("gzip PUT status = %d, want 200", st)
|
||||
}
|
||||
// Hub stored the DECOMPRESSED bytes — GET returns the original.
|
||||
if st, got := do(t, "GET", base+proto.PathBlob+hash, bearer, nil); st != http.StatusOK || !bytes.Equal(got, original) {
|
||||
t.Fatalf("round-trip: status=%d, %d bytes (want 200, %d)", st, len(got), len(original))
|
||||
}
|
||||
// A gzip header over a non-gzip body is rejected, not stored.
|
||||
if st := put(chunk.Hash([]byte("x")), []byte("not gzip at all"), "gzip"); st != http.StatusBadRequest {
|
||||
t.Fatalf("non-gzip body with gzip header: status = %d, want 400", st)
|
||||
}
|
||||
}
|
||||
|
||||
// joinWith enrolls a fresh device using token and returns its JoinResponse.
|
||||
func joinWith(t *testing.T, base, token string) proto.JoinResponse {
|
||||
t.Helper()
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ package transport
|
|||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"encoding/json"
|
||||
|
|
@ -31,6 +32,7 @@ type Client struct {
|
|||
bearer string // device bearer token; empty until Join
|
||||
hc *http.Client
|
||||
limiter *rate.Limiter // optional blob-transfer rate cap; nil = unlimited
|
||||
compress bool // gzip blob uploads when it shrinks them (settings.transfer.compress)
|
||||
}
|
||||
|
||||
// New returns a Client for the hub at base (e.g. "http://host:8080").
|
||||
|
|
@ -44,6 +46,25 @@ func New(base string) *Client {
|
|||
// SetBearer sets the device bearer token used for authenticated requests.
|
||||
func (c *Client) SetBearer(b string) { c.bearer = b }
|
||||
|
||||
// SetCompress enables gzip on blob uploads (used when settings.transfer.compress
|
||||
// is on — e.g. syncing over a WAN link). Off by default.
|
||||
func (c *Client) SetCompress(on bool) { c.compress = on }
|
||||
|
||||
// gzipBytes returns the gzip-compressed form of data. Errors are impossible for
|
||||
// an in-memory writer; on the off chance, returns data so the caller's "shrank?"
|
||||
// check falls through to sending it uncompressed.
|
||||
func gzipBytes(data []byte) []byte {
|
||||
var buf bytes.Buffer
|
||||
zw := gzip.NewWriter(&buf)
|
||||
if _, err := zw.Write(data); err != nil {
|
||||
return data
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
return data
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// Bearer returns the current device bearer token.
|
||||
func (c *Client) Bearer() string { return c.bearer }
|
||||
|
||||
|
|
@ -238,12 +259,24 @@ func (c *Client) do(method, path string, auth bool, body, out any) error {
|
|||
|
||||
// raw sends raw bytes (used for blob uploads) with the bearer header set.
|
||||
func (c *Client) raw(method, path string, data []byte) error {
|
||||
enc := ""
|
||||
// gzip the body when compression is on AND it actually shrinks — incompressible
|
||||
// chunks (already-compressed media, encrypted blobs) go raw so we never inflate
|
||||
// the wire. The hub hashes the DECOMPRESSED body, so dedup/integrity are intact.
|
||||
if c.compress {
|
||||
if gz := gzipBytes(data); len(gz) < len(data) {
|
||||
data, enc = gz, "gzip"
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequest(method, c.base+path, c.limit(bytes.NewReader(data)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.ContentLength = int64(len(data)) // body is a custom reader; set length explicitly
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
if enc != "" {
|
||||
req.Header.Set("Content-Encoding", enc)
|
||||
}
|
||||
req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer)
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package transport
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
|
|
@ -149,6 +150,59 @@ func TestPutBlob(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestPutBlobCompress proves SetCompress gzips a compressible body (with the
|
||||
// Content-Encoding header, decompressing back to the original) but sends an
|
||||
// incompressible body raw — never inflating the wire.
|
||||
func TestPutBlobCompress(t *testing.T) {
|
||||
var gotEnc string
|
||||
var gotBody []byte
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotEnc = r.Header.Get("Content-Encoding")
|
||||
gotBody, _ = io.ReadAll(r.Body)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL)
|
||||
c.SetBearer("secret")
|
||||
c.SetCompress(true)
|
||||
|
||||
// Compressible payload → gzip, and it must decode back to the original.
|
||||
original := bytes.Repeat([]byte("compress me over the WAN "), 1024)
|
||||
if err := c.PutBlob("h1", original); err != nil {
|
||||
t.Fatalf("PutBlob: %v", err)
|
||||
}
|
||||
if gotEnc != "gzip" {
|
||||
t.Fatalf("compressible blob: Content-Encoding = %q, want gzip", gotEnc)
|
||||
}
|
||||
zr, err := gzip.NewReader(bytes.NewReader(gotBody))
|
||||
if err != nil {
|
||||
t.Fatalf("server body not gzip: %v", err)
|
||||
}
|
||||
dec, _ := io.ReadAll(zr)
|
||||
if !bytes.Equal(dec, original) {
|
||||
t.Fatal("decompressed body != original")
|
||||
}
|
||||
if len(gotBody) >= len(original) {
|
||||
t.Fatalf("gzip body (%d) not smaller than original (%d)", len(gotBody), len(original))
|
||||
}
|
||||
|
||||
// Incompressible payload (random) → sent raw, no Content-Encoding.
|
||||
rnd := make([]byte, 4096)
|
||||
if _, err := rand.Read(rnd); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.PutBlob("h2", rnd); err != nil {
|
||||
t.Fatalf("PutBlob random: %v", err)
|
||||
}
|
||||
if gotEnc != "" {
|
||||
t.Fatalf("incompressible blob should send raw, got Content-Encoding %q", gotEnc)
|
||||
}
|
||||
if !bytes.Equal(gotBody, rnd) {
|
||||
t.Fatal("raw body mismatch for incompressible payload")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPush(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != proto.PathPush {
|
||||
|
|
|
|||
Loading…
Reference in a new issue