feat(M3): live two-way sync — SSE fan-out + daemon + mount 🔄
- pkg/proto + internal/hub/events.go: SSE /v1/events with a broker; hub broadcasts on genuine head ADVANCE only (idempotent re-push doesn't broadcast -> no storm) - transport.Client.Events: SSE consumer (timeout-less, ctx-cancelled) - internal/daemon: per-mount loop funnels watcher + SSE triggers into a serialized Sync; read-only mounts pull-only; base snapshot persisted in state.json - cmd/devbox: 'mount <share> <dir> [--ro]' (clone+sync) and 'start' (foreground daemon) - fix: serialize chunk.Split — jotfs/fastcdc-go mutates a package global in NewChunker, racing under concurrent chunking (caught by -race) - test: two live daemons, an edit on one reaches the other automatically (race-clean)
This commit is contained in:
parent
a951d4ab2f
commit
dd0db590c7
9 changed files with 612 additions and 6 deletions
|
|
@ -2,12 +2,18 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/config"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/daemon"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/identity"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/secret"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/syncer"
|
||||
|
|
@ -27,10 +33,11 @@ func main() {
|
|||
root.AddCommand(
|
||||
joinCmd(),
|
||||
publishCmd(),
|
||||
mountCmd(),
|
||||
startCmd(),
|
||||
statusCmd(),
|
||||
versionCmd(),
|
||||
stub("start", "▶️ run the sync daemon", "M3"),
|
||||
stub("stop", "⏹️ stop the sync daemon", "M3"),
|
||||
stub("stop", "⏹️ stop the sync daemon", "M7"),
|
||||
)
|
||||
if err := root.Execute(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "error:", err)
|
||||
|
|
@ -145,6 +152,127 @@ func publishCmd() *cobra.Command {
|
|||
}
|
||||
}
|
||||
|
||||
func mountCmd() *cobra.Command {
|
||||
var ro bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "mount <share> <localdir>",
|
||||
Short: "🔗 mount a hub share into a local directory (clone + sync)",
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
share := args[0]
|
||||
local, err := filepath.Abs(args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dir, err := config.Dir()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := config.LoadDaemon(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Hub == "" || d.Bearer == "" {
|
||||
return fmt.Errorf("not joined — run: devbox join <hub> <token>")
|
||||
}
|
||||
if err := os.MkdirAll(local, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
d.Mounts = upsertMount(d.Mounts, config.Mount{Share: share, Local: local, Hub: d.Hub, ReadOnly: ro})
|
||||
if err := config.SaveDaemon(dir, d); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c := transport.New(d.Hub)
|
||||
c.SetBearer(d.Bearer)
|
||||
ig, err := syncer.LoadIgnore(local)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
guard, err := secret.New(nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
host, _ := os.Hostname()
|
||||
st, err := config.LoadState(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key := share + "\x00" + local
|
||||
|
||||
var pr syncer.PullResult
|
||||
var newBase string
|
||||
if ro {
|
||||
pr, err = syncer.Pull(c, local, share, st[key], host, time.Now().Unix(), ig, guard)
|
||||
newBase = pr.Base
|
||||
} else {
|
||||
newBase, pr, err = syncer.Sync(c, local, share, st[key], host, time.Now().Unix(), ig, guard)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st[key] = newBase
|
||||
if err := config.SaveState(dir, st); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
out := cmd.OutOrStdout()
|
||||
mode := "rw"
|
||||
if ro {
|
||||
mode = "ro"
|
||||
}
|
||||
fmt.Fprintf(out, "🔗 mounted %q -> %s [%s]\n", share, local, mode)
|
||||
fmt.Fprintf(out, "📥 %d files, %d conflicts\n", len(pr.Written), len(pr.Conflicts))
|
||||
fmt.Fprintln(out, "▶️ run 'devbox start' to keep it live-synced")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&ro, "ro", false, "mount read-only (pull only, never push)")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func upsertMount(mounts []config.Mount, m config.Mount) []config.Mount {
|
||||
for i, x := range mounts {
|
||||
if x.Share == m.Share && x.Local == m.Local {
|
||||
mounts[i] = m
|
||||
return mounts
|
||||
}
|
||||
}
|
||||
return append(mounts, m)
|
||||
}
|
||||
|
||||
func startCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "start",
|
||||
Short: "▶️ run the sync daemon (foreground)",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
dir, err := config.Dir()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := config.LoadDaemon(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.Hub == "" || cfg.Bearer == "" {
|
||||
return fmt.Errorf("not joined — run: devbox join <hub> <token>")
|
||||
}
|
||||
if len(cfg.Mounts) == 0 {
|
||||
return fmt.Errorf("no mounts — run: devbox mount <share> <dir>")
|
||||
}
|
||||
host, _ := os.Hostname()
|
||||
dmn, err := daemon.New(dir, cfg, host, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "▶️ devboxd watching %d mount(s); Ctrl-C to stop\n", len(cfg.Mounts))
|
||||
return dmn.Run(ctx)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func statusCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "status",
|
||||
|
|
|
|||
|
|
@ -9,11 +9,18 @@ import (
|
|||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
fastcdc "github.com/jotfs/fastcdc-go"
|
||||
"github.com/zeebo/blake3"
|
||||
)
|
||||
|
||||
// ponytail: jotfs/fastcdc-go mutates a package-global table inside NewChunker
|
||||
// (table[i] ^= Seed) on every call, so concurrent Split races even with Seed 0.
|
||||
// Serialize chunking per process. Upgrade path: vendor a FastCDC with a
|
||||
// per-chunker table if chunking throughput ever bottlenecks a single daemon.
|
||||
var splitMu sync.Mutex
|
||||
|
||||
// Chunk size targets. FastCDC keeps chunk lengths within [min, max] and aims
|
||||
// for the average via content-defined boundaries.
|
||||
const (
|
||||
|
|
@ -46,6 +53,8 @@ func Split(data []byte) ([]Chunk, error) {
|
|||
if len(data) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
splitMu.Lock()
|
||||
defer splitMu.Unlock()
|
||||
|
||||
chunker, err := fastcdc.NewChunker(bytes.NewReader(data), fastcdc.Options{
|
||||
MinSize: MinSize,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
|
@ -86,3 +87,34 @@ func SaveDaemon(dir string, d Daemon) error {
|
|||
}
|
||||
return os.Rename(tmp, daemonPath(dir))
|
||||
}
|
||||
|
||||
func statePath(dir string) string { return filepath.Join(dir, "state.json") }
|
||||
|
||||
// LoadState reads the per-mount last-applied snapshot map (mountKey -> snapshot).
|
||||
func LoadState(dir string) (map[string]string, error) {
|
||||
b, err := os.ReadFile(statePath(dir))
|
||||
if os.IsNotExist(err) {
|
||||
return map[string]string{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m := map[string]string{}
|
||||
return m, json.Unmarshal(b, &m)
|
||||
}
|
||||
|
||||
// SaveState writes the per-mount snapshot map atomically.
|
||||
func SaveState(dir string, m map[string]string) error {
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
b, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := statePath(dir) + ".tmp"
|
||||
if err := os.WriteFile(tmp, b, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, statePath(dir))
|
||||
}
|
||||
|
|
|
|||
175
internal/daemon/daemon.go
Normal file
175
internal/daemon/daemon.go
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
// Package daemon runs the live sync loop: for each mount it watches the local
|
||||
// tree (push on change) and subscribes to hub change events (pull on event),
|
||||
// funnelling both triggers into a serialized Sync that keeps the mount in
|
||||
// agreement with the hub.
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/config"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/secret"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/syncer"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/transport"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/watch"
|
||||
"git.shoemoney.ai/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
// Daemon syncs a device's mounts against their hub.
|
||||
type Daemon struct {
|
||||
dir string
|
||||
cfg config.Daemon
|
||||
host string
|
||||
guard *secret.Guard
|
||||
logf func(string, ...any)
|
||||
|
||||
mu sync.Mutex
|
||||
state map[string]string // mountKey -> last-applied snapshot
|
||||
}
|
||||
|
||||
// New builds a daemon from a loaded config. logf may be nil (defaults to log.Printf).
|
||||
func New(dir string, cfg config.Daemon, host string, logf func(string, ...any)) (*Daemon, error) {
|
||||
guard, err := secret.New(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state, err := config.LoadState(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if logf == nil {
|
||||
logf = log.Printf
|
||||
}
|
||||
return &Daemon{dir: dir, cfg: cfg, host: host, guard: guard, logf: logf, state: state}, nil
|
||||
}
|
||||
|
||||
// Run syncs every mount until ctx is cancelled.
|
||||
func (d *Daemon) Run(ctx context.Context) error {
|
||||
var wg sync.WaitGroup
|
||||
for _, m := range d.cfg.Mounts {
|
||||
wg.Add(1)
|
||||
go func(m config.Mount) {
|
||||
defer wg.Done()
|
||||
d.runMount(ctx, m)
|
||||
}(m)
|
||||
}
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
func mountKey(m config.Mount) string { return m.Share + "\x00" + m.Local }
|
||||
|
||||
func (d *Daemon) getBase(m config.Mount) string {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.state[mountKey(m)]
|
||||
}
|
||||
|
||||
func (d *Daemon) setBase(m config.Mount, base string) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if d.state[mountKey(m)] != base {
|
||||
d.state[mountKey(m)] = base
|
||||
if err := config.SaveState(d.dir, d.state); err != nil {
|
||||
d.logf("save state: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Daemon) runMount(ctx context.Context, m config.Mount) {
|
||||
c := transport.New(m.Hub)
|
||||
c.SetBearer(d.cfg.Bearer)
|
||||
|
||||
trigger := make(chan struct{}, 1)
|
||||
nudge := func() {
|
||||
select {
|
||||
case trigger <- struct{}{}:
|
||||
default: // a sync is already queued; coalesce
|
||||
}
|
||||
}
|
||||
|
||||
// Local filesystem changes -> sync.
|
||||
if w, err := watch.New(m.Local, 300*time.Millisecond); err != nil {
|
||||
d.logf("watch %s: %v", m.Local, err)
|
||||
} else {
|
||||
defer w.Close()
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-w.Events():
|
||||
nudge()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Hub change events -> sync (reconnect with backoff).
|
||||
go func() {
|
||||
for ctx.Err() == nil {
|
||||
err := c.Events(ctx, m.Share, func(proto.Event) { nudge() })
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
d.logf("events %s reconnecting: %v", m.Share, err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
nudge() // initial sync
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-trigger:
|
||||
d.syncMount(c, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Daemon) syncMount(c *transport.Client, m config.Mount) {
|
||||
ig, err := syncer.LoadIgnore(m.Local)
|
||||
if err != nil {
|
||||
d.logf("ignore %s: %v", m.Local, err)
|
||||
return
|
||||
}
|
||||
base := d.getBase(m)
|
||||
now := time.Now().Unix()
|
||||
|
||||
if m.ReadOnly {
|
||||
pr, err := syncer.Pull(c, m.Local, m.Share, base, d.host, now, ig, d.guard)
|
||||
if err != nil {
|
||||
d.logf("pull %s: %v", m.Share, err)
|
||||
return
|
||||
}
|
||||
d.setBase(m, pr.Base)
|
||||
d.report(m, pr)
|
||||
return
|
||||
}
|
||||
|
||||
newBase, pr, err := syncer.Sync(c, m.Local, m.Share, base, d.host, now, ig, d.guard)
|
||||
if err != nil {
|
||||
d.logf("sync %s: %v", m.Share, err)
|
||||
return
|
||||
}
|
||||
d.setBase(m, newBase)
|
||||
d.report(m, pr)
|
||||
}
|
||||
|
||||
func (d *Daemon) report(m config.Mount, pr syncer.PullResult) {
|
||||
if len(pr.Written)+len(pr.Deleted)+len(pr.Conflicts) == 0 {
|
||||
return
|
||||
}
|
||||
d.logf("📥 %s: %d written, %d deleted, %d conflicts", m.Share, len(pr.Written), len(pr.Deleted), len(pr.Conflicts))
|
||||
for _, cf := range pr.Conflicts {
|
||||
d.logf(" 💥 conflict copy: %s", cf)
|
||||
}
|
||||
}
|
||||
118
internal/daemon/daemon_test.go
Normal file
118
internal/daemon/daemon_test.go
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/config"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/meta"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/transport"
|
||||
)
|
||||
|
||||
func join(t *testing.T, db *meta.DB, url, name string) string {
|
||||
t.Helper()
|
||||
tok := name + "-tok"
|
||||
if err := db.CreateToken(hub.HashToken(tok), time.Now().Unix()+3600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := transport.New(url)
|
||||
pub, _, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Join(tok, name, pub); err != nil {
|
||||
t.Fatalf("join %s: %v", name, err)
|
||||
}
|
||||
return c.Bearer()
|
||||
}
|
||||
|
||||
func writeF(t *testing.T, root, rel, content string) {
|
||||
t.Helper()
|
||||
p := filepath.Join(root, filepath.FromSlash(rel))
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func waitFor(path, want string, d time.Duration) bool {
|
||||
deadline := time.Now().Add(d)
|
||||
for time.Now().Before(deadline) {
|
||||
if b, err := os.ReadFile(path); err == nil && string(b) == want {
|
||||
return true
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// TestLiveTwoWaySyncViaSSE runs two daemons against one hub and proves a change
|
||||
// on one machine reaches the other automatically (push -> SSE event -> pull).
|
||||
func TestLiveTwoWaySyncViaSSE(t *testing.T) {
|
||||
db, err := meta.Open(":memory:")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
store, err := blobstore.NewDisk(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(hub.NewServer(db, store).Handler())
|
||||
defer srv.Close()
|
||||
|
||||
bearerA := join(t, db, srv.URL, "alice")
|
||||
bearerB := join(t, db, srv.URL, "bob")
|
||||
|
||||
ca := transport.New(srv.URL)
|
||||
ca.SetBearer(bearerA)
|
||||
if err := ca.Publish("s"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rootA, rootB := t.TempDir(), t.TempDir()
|
||||
mount := func(hubURL, bearer, root string) (string, config.Daemon) {
|
||||
return t.TempDir(), config.Daemon{
|
||||
Hub: hubURL, Bearer: bearer,
|
||||
Mounts: []config.Mount{{Share: "s", Local: root, Hub: hubURL}},
|
||||
}
|
||||
}
|
||||
dirA, cfgA := mount(srv.URL, bearerA, rootA)
|
||||
dirB, cfgB := mount(srv.URL, bearerB, rootB)
|
||||
|
||||
dA, err := New(dirA, cfgA, "alice", t.Logf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dB, err := New(dirB, cfgB, "bob", t.Logf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go dA.Run(ctx)
|
||||
go dB.Run(ctx)
|
||||
time.Sleep(200 * time.Millisecond) // let both subscribe before the first edit
|
||||
|
||||
// Alice creates a file -> it should reach Bob automatically.
|
||||
writeF(t, rootA, "hello.txt", "from alice\n")
|
||||
if !waitFor(filepath.Join(rootB, "hello.txt"), "from alice\n", 10*time.Second) {
|
||||
t.Fatal("alice's file did not reach bob via live sync")
|
||||
}
|
||||
|
||||
// Bob creates a file -> it should reach Alice automatically.
|
||||
writeF(t, rootB, "reply.txt", "from bob\n")
|
||||
if !waitFor(filepath.Join(rootA, "reply.txt"), "from bob\n", 10*time.Second) {
|
||||
t.Fatal("bob's file did not reach alice via live sync")
|
||||
}
|
||||
}
|
||||
89
internal/hub/events.go
Normal file
89
internal/hub/events.go
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
package hub
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
// broker fans hub change events out to connected SSE subscribers. A slow
|
||||
// subscriber's events are dropped rather than blocking the push path — the
|
||||
// device re-syncs via Head() regardless, so a missed nudge is harmless.
|
||||
type broker struct {
|
||||
mu sync.Mutex
|
||||
subs map[chan proto.Event]string // channel -> share filter ("" = all shares)
|
||||
}
|
||||
|
||||
func newBroker() *broker { return &broker{subs: map[chan proto.Event]string{}} }
|
||||
|
||||
func (b *broker) sub(share string) chan proto.Event {
|
||||
ch := make(chan proto.Event, 16)
|
||||
b.mu.Lock()
|
||||
b.subs[ch] = share
|
||||
b.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (b *broker) unsub(ch chan proto.Event) {
|
||||
b.mu.Lock()
|
||||
if _, ok := b.subs[ch]; ok {
|
||||
delete(b.subs, ch)
|
||||
close(ch)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
// publish delivers ev to every subscriber whose filter matches. Held under the
|
||||
// same lock as unsub, so a channel is never sent-to after it is closed.
|
||||
func (b *broker) publish(ev proto.Event) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
for ch, filter := range b.subs {
|
||||
if filter != "" && filter != ev.Share {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case ch <- ev:
|
||||
default: // subscriber is slow; drop (it will re-sync via Head())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleEvents streams change events to a device as Server-Sent Events.
|
||||
func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request, _ string) {
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
writeErr(w, http.StatusInternalServerError, "streaming unsupported")
|
||||
return
|
||||
}
|
||||
ch := s.broker.sub(r.URL.Query().Get("share"))
|
||||
defer s.broker.unsub(ch)
|
||||
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/event-stream")
|
||||
h.Set("Cache-Control", "no-cache")
|
||||
h.Set("Connection", "keep-alive")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
flusher.Flush()
|
||||
|
||||
ping := time.NewTicker(25 * time.Second)
|
||||
defer ping.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-ping.C:
|
||||
fmt.Fprint(w, ": ping\n\n") // comment line keeps idle proxies from closing us
|
||||
flusher.Flush()
|
||||
case ev := <-ch:
|
||||
b, _ := json.Marshal(ev)
|
||||
fmt.Fprintf(w, "data: %s\n\n", b)
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -22,15 +22,17 @@ import (
|
|||
"git.shoemoney.ai/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
// Server is the devbox hub: metadata in db, blob bytes in store.
|
||||
// Server is the devbox hub: metadata in db, blob bytes in store, change events
|
||||
// fanned out via broker.
|
||||
type Server struct {
|
||||
db *meta.DB
|
||||
store blobstore.Store
|
||||
db *meta.DB
|
||||
store blobstore.Store
|
||||
broker *broker
|
||||
}
|
||||
|
||||
// NewServer builds a hub server over the given metadata store and blob store.
|
||||
func NewServer(db *meta.DB, store blobstore.Store) *Server {
|
||||
return &Server{db: db, store: store}
|
||||
return &Server{db: db, store: store, broker: newBroker()}
|
||||
}
|
||||
|
||||
// HashToken returns hex(sha256(token)); the token-mint CLI reuses it so the hub
|
||||
|
|
@ -57,6 +59,7 @@ func (s *Server) Handler() http.Handler {
|
|||
mux.HandleFunc("GET "+proto.PathBlob+"{hash}", s.auth(s.handleGetBlob))
|
||||
mux.HandleFunc("POST "+proto.PathPush, s.auth(s.handlePush))
|
||||
mux.HandleFunc("GET "+proto.PathHead, s.auth(s.handleHead))
|
||||
mux.HandleFunc("GET "+proto.PathEvents, s.auth(s.handleEvents))
|
||||
mux.HandleFunc("GET "+proto.PathMetrics, s.handleMetrics)
|
||||
return mux
|
||||
}
|
||||
|
|
@ -244,6 +247,12 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request, deviceID str
|
|||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
// Only announce a genuine head advance. An idempotent re-push (manifest ==
|
||||
// current head) must NOT broadcast, or daemons would storm: pull -> re-push
|
||||
// the same state -> broadcast -> pull -> ... forever.
|
||||
if req.ManifestHash != head {
|
||||
s.broker.publish(proto.Event{Share: req.Share, Snapshot: snapshotID})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, proto.PushResponse{Snapshot: snapshotID, Head: snapshotID, Conflict: false})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@
|
|||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
|
|
@ -73,6 +75,43 @@ func (c *Client) PutBlob(hash string, data []byte) error {
|
|||
return c.raw(http.MethodPut, proto.PathBlob+hash, data)
|
||||
}
|
||||
|
||||
// Events opens an SSE stream of hub change events (optionally filtered to one
|
||||
// share) and calls onEvent for each, until ctx is cancelled or the stream ends.
|
||||
// Uses a dedicated timeout-less client since the stream is long-lived.
|
||||
func (c *Client) Events(ctx context.Context, share string, onEvent func(proto.Event)) error {
|
||||
u := c.base + proto.PathEvents
|
||||
if share != "" {
|
||||
u += "?share=" + url.QueryEscape(share)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer)
|
||||
resp, err := (&http.Client{}).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return apiError(resp.StatusCode, b)
|
||||
}
|
||||
sc := bufio.NewScanner(resp.Body)
|
||||
sc.Buffer(make([]byte, 0, 64*1024), 1<<20)
|
||||
for sc.Scan() {
|
||||
data, ok := strings.CutPrefix(sc.Text(), "data: ")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var ev proto.Event
|
||||
if json.Unmarshal([]byte(data), &ev) == nil {
|
||||
onEvent(ev)
|
||||
}
|
||||
}
|
||||
return sc.Err()
|
||||
}
|
||||
|
||||
// GetBlob downloads one blob's raw bytes by content hash (used by pull).
|
||||
func (c *Client) GetBlob(hash string) ([]byte, error) {
|
||||
req, err := http.NewRequest(http.MethodGet, c.base+proto.PathBlob+hash, nil)
|
||||
|
|
|
|||
|
|
@ -11,9 +11,16 @@ const (
|
|||
PathBlob = "/v1/blob/" // PUT /v1/blob/{hash}, auth: upload one blob's bytes
|
||||
PathPush = "/v1/push" // POST, auth: commit a snapshot
|
||||
PathHead = "/v1/head" // GET ?share=, auth: current head snapshot id
|
||||
PathEvents = "/v1/events" // GET ?share=, auth: SSE stream of change events
|
||||
PathMetrics = "/metrics" // GET, no auth: Prometheus text exposition
|
||||
)
|
||||
|
||||
// Event is a hub change notification, delivered as one SSE "data:" line (JSON).
|
||||
type Event struct {
|
||||
Share string `json:"share"`
|
||||
Snapshot string `json:"snapshot"`
|
||||
}
|
||||
|
||||
// AuthHeader carries the device bearer token: "Authorization: Bearer <token>".
|
||||
const AuthHeader = "Authorization"
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue