An open-source, faster Devin alternative
TypeScript
feat(webhooks): CP-origin lifecycle outbox relay (replaces materializer/dispatcher/ingress)
Igor Zalutski0a8c6ce98f35
diff --git a/cmd/server/main.go b/cmd/server/main.goindex aff803b8..a075bbf3 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -287,24 +287,16 @@ func main() {defer cr.Stop()}- // Worker-origin webhook ingress — consumes the events:{cell_id} stream- // and records canonical lifecycle events (created/ready/migrated) for- // sandbox webhooks. CP-origin events (stopped/hibernated) are recorded- // in-tx and don't need this. (.agents/work/sandbox-lifecycle-webhooks.md §5)+ // CP-origin lifecycle outbox relay — drains sandbox_lifecycle_events+ // (written in-tx by CP transitions) to the events:{cell} stream, where it+ // reaches the edge → Svix like worker-origin events. Worker-origin events+ // already flow to the edge directly, so no CP ingestion is needed.+ // (.agents/work/sandbox-webhooks-rearchitecture.md)if opts.Store != nil && cfg.CellID != "" {- ingress, err := controlplane.NewLifecycleIngress(redisRegistry.RedisClient(), opts.Store, cfg.CellID)- if err != nil {- log.Fatalf("lifecycle_ingress: %v", err)- }- if err := ingress.Start(context.Background()); err != nil {- log.Fatalf("lifecycle_ingress start: %v", err)- }- defer func() {- stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)- defer stopCancel()- _ = ingress.Stop(stopCtx)- }()- log.Printf("opensandbox: webhook lifecycle ingress started (cell=%s)", cfg.CellID)+ relay := controlplane.NewLifecycleOutboxRelay(opts.Store, redisRegistry.RedisClient(), cfg.CellID)+ relay.Start()+ defer relay.Stop()+ log.Printf("opensandbox: webhook lifecycle outbox relay started (cell=%s)", cfg.CellID)}}@@ -879,20 +871,10 @@ func main() {senderOpts.Interval, senderOpts.Batch)}- // Sandbox webhooks — the materializer (canonical events → delivery rows) and- // the dispatcher (send/retry/dead-letter) need only Postgres, so they run in- // any mode; the worker-origin ingress (started above, server mode) feeds them- // the worker events. Dormant until a destination exists.- // (.agents/work/sandbox-lifecycle-webhooks.md)- if opts.Store != nil {- mat := controlplane.NewWebhookMaterializer(opts.Store)- mat.Start()- defer mat.Stop()- disp := controlplane.NewWebhookDispatcher(opts.Store, cfg.CellID)- disp.Start()- defer disp.Stop()- log.Printf("opensandbox: sandbox webhook materializer + dispatcher started")- }+ // Sandbox webhooks: delivery is owned by Svix (managed). OC only relays+ // CP-origin lifecycle events to the cell stream (the outbox relay, started+ // above in the server-mode block) → edge → Svix. No CP fan-out/dispatcher.+ // (.agents/work/sandbox-webhooks-rearchitecture.md)// Start NATS sync consumer if both PG and NATS are configuredif opts.Store != nil && cfg.NATSURL != "" {diff --git a/internal/controlplane/lifecycle_ingress.go b/internal/controlplane/lifecycle_ingress.godeleted file mode 100644index 7c67add5..00000000--- a/internal/controlplane/lifecycle_ingress.go+++ /dev/null@@ -1,313 +0,0 @@-package controlplane--import (- "context"- "encoding/json"- "errors"- "fmt"- "log"- "os"- "sync"- "time"-- "github.com/google/uuid"- "github.com/redis/go-redis/v9"-- "github.com/opensandbox/opensandbox/internal/db"- "github.com/opensandbox/opensandbox/pkg/types"-)--// LifecycleIngress is the worker-origin half of the webhook pipeline: it consumes-// the events:{cell_id} Redis stream with its own consumer group and materializes-// the webhook-eligible worker events into the canonical sandbox_lifecycle_events-// table (via the single recordLifecycleEvent primitive). CP-origin events-// (stopped/hibernated/resumed) are recorded in-tx and are intentionally NOT-// handled here — this consumer maps only the worker-origin types below.-//-// Independent of EventForwarder's consumer group (each group gets its own copy of-// the stream). Reclaim mirrors event_forwarder: plain XPENDING + XCLAIM JUSTID-// (Azure Redis 6.0 lacks XAUTOCLAIM). See §5 / §12 of the design doc.-type LifecycleIngress struct {- rdb *redis.Client- store *db.Store- streamKey string- groupName string- consumer string- batchSize int64- blockDur time.Duration-- stopCh chan struct{}- doneCh chan struct{}- wg sync.WaitGroup- once sync.Once-}--// ingressTypeMap maps the internal worker event strings to public lifecycle-// types. Only these worker-origin events become webhooks via the ingress; every-// other stream entry is acked and ignored by this consumer group.-//-// Notes:-// - No "running" entry: the worker emits no post-boot stream event (sessions-// are created directly as running), so sandbox.ready is recorded CP-side.-// - No "migrated" entry: the worker never emits "migrated"; it's recorded-// CP-side in CompleteMigration (the migration-completion funnel).-// - "woke" is the worker's wake signal (grpc_server.go WakeSandbox) → resumed.-var ingressTypeMap = map[string]string{- "created": types.WebhookEventCreated,- "woke": types.WebhookEventResumed,-}--// normalizeIngressData maps an internal worker payload to the PUBLIC event.data-// contract (the worker logs include internal fields like sandbox_id; the public-// data is clean camelCase per docs). created → {template}; everything else → {}.-func normalizeIngressData(publicType string, payload json.RawMessage) json.RawMessage {- if publicType == types.WebhookEventCreated {- var p struct {- Template string `json:"template"`- }- _ = json.Unmarshal(payload, &p)- b, _ := json.Marshal(map[string]string{"template": p.Template})- return b- }- return json.RawMessage("{}")-}--// streamLifecycleEnvelope is the subset of the stream "event" payload we need.-// Both the worker publisher and the CP PublishLifecycle helper share these keys.-type streamLifecycleEnvelope struct {- ID string `json:"id"`- Type string `json:"type"`- SandboxID string `json:"sandbox_id"`- OrgID string `json:"org_id"`- Payload json.RawMessage `json:"payload"`- Timestamp string `json:"timestamp"`-}--// NewLifecycleIngress constructs the ingress. Caller must Start it. Requires a-// Redis client (server mode) and the cell id (the stream is events:{cellID}).-func NewLifecycleIngress(rdb *redis.Client, store *db.Store, cellID string) (*LifecycleIngress, error) {- if rdb == nil {- return nil, errors.New("lifecycle_ingress: Redis client required")- }- if store == nil {- return nil, errors.New("lifecycle_ingress: store required")- }- if cellID == "" {- return nil, errors.New("lifecycle_ingress: cellID required")- }- host, _ := os.Hostname()- return &LifecycleIngress{- rdb: rdb,- store: store,- streamKey: "events:" + cellID,- groupName: "webhook-ingress",- consumer: fmt.Sprintf("%s-%d", host, os.Getpid()),- batchSize: 200,- blockDur: 5 * time.Second,- stopCh: make(chan struct{}),- doneCh: make(chan struct{}),- }, nil-}--func (g *LifecycleIngress) Start(ctx context.Context) error {- if err := g.rdb.XGroupCreateMkStream(ctx, g.streamKey, g.groupName, "$").Err(); err != nil {- if !isBusyGroup(err) {- return fmt.Errorf("lifecycle_ingress: create consumer group: %w", err)- }- }- g.wg.Add(2)- go g.readLoop(ctx)- go g.reclaimLoop(ctx)- go func() {- g.wg.Wait()- close(g.doneCh)- }()- log.Printf("lifecycle_ingress: started (stream=%s group=%s consumer=%s)", g.streamKey, g.groupName, g.consumer)- return nil-}--func (g *LifecycleIngress) Stop(ctx context.Context) error {- g.once.Do(func() { close(g.stopCh) })- select {- case <-g.doneCh:- case <-ctx.Done():- return ctx.Err()- }- return nil-}--func (g *LifecycleIngress) readLoop(ctx context.Context) {- defer g.wg.Done()- for {- select {- case <-ctx.Done():- return- case <-g.stopCh:- return- default:- }- streams, err := g.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{- Group: g.groupName,- Consumer: g.consumer,- Streams: []string{g.streamKey, ">"},- Count: g.batchSize,- Block: g.blockDur,- }).Result()- if err != nil {- if errors.Is(err, redis.Nil) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {- continue- }- log.Printf("lifecycle_ingress: XREADGROUP error: %v", err)- select {- case <-time.After(2 * time.Second):- case <-ctx.Done():- return- case <-g.stopCh:- return- }- continue- }- for _, s := range streams {- for _, m := range s.Messages {- g.process(ctx, m)- }- }- }-}--func (g *LifecycleIngress) reclaimLoop(ctx context.Context) {- defer g.wg.Done()- ticker := time.NewTicker(30 * time.Second)- defer ticker.Stop()- for {- select {- case <-ctx.Done():- return- case <-g.stopCh:- return- case <-ticker.C:- g.reclaimOnce(ctx)- }- }-}--// reclaimOnce recovers entries whose owning consumer died. Plain XPENDING + XCLAIM-// JUSTID with MinIdle (Azure Redis 6.0 compatible — no XAUTOCLAIM/IDLE filter).-func (g *LifecycleIngress) reclaimOnce(ctx context.Context) {- start := "-"- const batch = 100- for {- pending, err := g.rdb.XPendingExt(ctx, &redis.XPendingExtArgs{- Stream: g.streamKey,- Group: g.groupName,- Start: start,- End: "+",- Count: batch,- }).Result()- if err != nil {- log.Printf("lifecycle_ingress: XPENDING error: %v", err)- return- }- if len(pending) == 0 {- return- }- ids := make([]string, 0, len(pending))- for _, p := range pending {- ids = append(ids, p.ID)- }- claimed, err := g.rdb.XClaimJustID(ctx, &redis.XClaimArgs{- Stream: g.streamKey,- Group: g.groupName,- Consumer: g.consumer,- MinIdle: 60 * time.Second,- Messages: ids,- }).Result()- if err != nil {- log.Printf("lifecycle_ingress: XCLAIM error (%d ids): %v", len(ids), err)- return- }- for _, id := range claimed {- entries, rerr := g.rdb.XRange(ctx, g.streamKey, id, id).Result()- if rerr != nil {- log.Printf("lifecycle_ingress: XRANGE %s error: %v", id, rerr)- continue- }- if len(entries) == 0 {- g.ack(ctx, id) // trimmed away — clear the orphaned PEL entry- continue- }- g.process(ctx, entries[0])- }- if len(pending) < batch {- return- }- start = bumpStreamID(pending[len(pending)-1].ID)- if start == "" {- return- }- }-}--// process handles one stream entry: map to a public lifecycle type, record the-// canonical event, and ack. Irrelevant/malformed entries are acked and dropped;-// a transient store error leaves the entry in the PEL for reclaim.-func (g *LifecycleIngress) process(ctx context.Context, m redis.XMessage) {- raw, ok := m.Values["event"].(string)- if !ok || !json.Valid([]byte(raw)) {- g.ack(ctx, m.ID)- return- }- var env streamLifecycleEnvelope- if err := json.Unmarshal([]byte(raw), &env); err != nil {- g.ack(ctx, m.ID)- return- }- publicType, eligible := ingressTypeMap[env.Type]- if !eligible {- g.ack(ctx, m.ID) // not a webhook-eligible worker event- return- }- if env.OrgID == "" || env.SandboxID == "" {- log.Printf("lifecycle_ingress: %s (%s) missing org/sandbox — dropping", m.ID, env.Type)- g.ack(ctx, m.ID)- return- }- orgID, err := uuid.Parse(env.OrgID)- if err != nil {- g.ack(ctx, m.ID)- return- }- ts := time.Now().UTC()- if env.Timestamp != "" {- if t, perr := time.Parse(time.RFC3339Nano, env.Timestamp); perr == nil {- ts = t- }- }- id := env.ID- if id == "" {- id = fmt.Sprintf("%s:%s:%s", env.SandboxID, env.Type, m.ID)- }- // Map the internal worker payload to the public event.data contract.- data := normalizeIngressData(publicType, env.Payload)- if err := g.store.RecordLifecycleEvent(ctx, db.LifecycleEvent{- ID: id,- OrgID: orgID,- SandboxID: env.SandboxID,- Type: publicType,- Data: data,- Ts: ts,- }); err != nil {- log.Printf("lifecycle_ingress: record %s: %v — leaving in PEL", id, err)- return // do not ack; reclaim retries- }- g.ack(ctx, m.ID)-}--func (g *LifecycleIngress) ack(ctx context.Context, ids ...string) {- if len(ids) == 0 {- return- }- if err := g.rdb.XAck(ctx, g.streamKey, g.groupName, ids...).Err(); err != nil {- log.Printf("lifecycle_ingress: XACK error: %v", err)- }-}diff --git a/internal/controlplane/lifecycle_outbox_relay.go b/internal/controlplane/lifecycle_outbox_relay.gonew file mode 100644index 00000000..d889b63d--- /dev/null+++ b/internal/controlplane/lifecycle_outbox_relay.go@@ -0,0 +1,112 @@+package controlplane++import (+ "context"+ "encoding/json"+ "log"+ "time"++ "github.com/redis/go-redis/v9"++ "github.com/opensandbox/opensandbox/internal/cellevents"+ "github.com/opensandbox/opensandbox/internal/db"+)++// LifecycleOutboxRelay drains the in-tx lifecycle outbox (sandbox_lifecycle_events,+// written transactionally by CP-origin transitions) and publishes each event to+// the cell's events:{cell} stream, where it reaches the edge → Svix exactly like+// worker-origin events. Only events that successfully publish are marked relayed,+// so a Redis hiccup is retried on the next tick (durability preserved); a stable+// event id makes the at-least-once re-publish idempotent at the edge and at Svix.+//+// Replaces the old WebhookMaterializer + WebhookDispatcher: OC no longer fans out+// or tracks delivery state — Svix owns that.+// See .agents/work/sandbox-webhooks-rearchitecture.md.+type LifecycleOutboxRelay struct {+ store *db.Store+ rdb *redis.Client+ cellID string+ interval time.Duration+ batch int+ stop chan struct{}+ stopped chan struct{}+}++func NewLifecycleOutboxRelay(store *db.Store, rdb *redis.Client, cellID string) *LifecycleOutboxRelay {+ return &LifecycleOutboxRelay{+ store: store,+ rdb: rdb,+ cellID: cellID,+ interval: 1 * time.Second,+ batch: 100,+ stop: make(chan struct{}),+ stopped: make(chan struct{}),+ }+}++func (r *LifecycleOutboxRelay) Start() { go r.loop() }++func (r *LifecycleOutboxRelay) Stop() {+ close(r.stop)+ <-r.stopped+}++func (r *LifecycleOutboxRelay) loop() {+ defer close(r.stopped)+ tick := time.NewTicker(r.interval)+ defer tick.Stop()+ for {+ select {+ case <-r.stop:+ return+ case <-tick.C:+ r.drainSafe()+ }+ }+}++func (r *LifecycleOutboxRelay) drainSafe() {+ defer func() {+ if rec := recover(); rec != nil {+ log.Printf("lifecycle_outbox_relay: recovered from panic: %v", rec)+ }+ }()+ ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)+ defer cancel()+ for {+ rows, err := r.store.DrainLifecycleOutbox(ctx, r.batch)+ if err != nil {+ log.Printf("lifecycle_outbox_relay: drain: %v", err)+ return+ }+ if len(rows) == 0 {+ return+ }+ sent := make([]string, 0, len(rows))+ for _, row := range rows {+ var data map[string]any+ if len(row.Data) > 0 {+ _ = json.Unmarshal(row.Data, &data)+ }+ if cellevents.PublishLifecycleEvent(ctx, r.rdb, r.cellID, cellevents.LifecycleEvent{+ ID: row.ID,+ Type: row.Type,+ SandboxID: row.SandboxID,+ OrgID: row.OrgID,+ Data: data,+ Ts: row.Ts,+ }) {+ sent = append(sent, row.ID)+ }+ }+ if len(sent) > 0 {+ if err := r.store.MarkLifecycleOutboxSent(ctx, sent); err != nil {+ log.Printf("lifecycle_outbox_relay: mark sent (%d): %v", len(sent), err)+ return // retry next tick; the re-publish is idempotent via the stable id+ }+ }+ if len(rows) < r.batch {+ return+ }+ }+}diff --git a/internal/controlplane/webhook_materializer.go b/internal/controlplane/webhook_materializer.godeleted file mode 100644index 003740ee..00000000--- a/internal/controlplane/webhook_materializer.go+++ /dev/null@@ -1,75 +0,0 @@-package controlplane--import (- "context"- "log"- "time"-- "github.com/opensandbox/opensandbox/internal/db"-)--// WebhookMaterializer turns canonical sandbox_lifecycle_events into-// webhook_deliveries rows — the single place delivery rows are created (the-// match / filter / watermark / metadata logic lives in the store). It runs on a-// short tick and drains the backlog each pass. Needs only Postgres, so it runs-// in combined mode too (CP-origin events still flow without Redis).-//-// See .agents/work/sandbox-lifecycle-webhooks.md §5.-type WebhookMaterializer struct {- store *db.Store- interval time.Duration- batch int- stop chan struct{}- stopped chan struct{}-}--func NewWebhookMaterializer(store *db.Store) *WebhookMaterializer {- return &WebhookMaterializer{- store: store,- interval: 1 * time.Second,- batch: 100,- stop: make(chan struct{}),- stopped: make(chan struct{}),- }-}--func (m *WebhookMaterializer) Start() { go m.loop() }--func (m *WebhookMaterializer) Stop() {- close(m.stop)- <-m.stopped-}--func (m *WebhookMaterializer) loop() {- defer close(m.stopped)- tick := time.NewTicker(m.interval)- defer tick.Stop()- for {- select {- case <-m.stop:- return- case <-tick.C:- m.drainSafe()- }- }-}--func (m *WebhookMaterializer) drainSafe() {- defer func() {- if r := recover(); r != nil {- log.Printf("webhook_materializer: recovered from panic: %v", r)- }- }()- ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)- defer cancel()- for {- n, err := m.store.MaterializePendingLifecycleEvents(ctx, m.batch)- if err != nil {- log.Printf("webhook_materializer: materialize: %v", err)- return- }- if n < m.batch {- return // backlog drained for now- }- }-}diff --git a/internal/db/webhooks.go b/internal/db/webhooks.goindex bf7b7c61..e122169b 100644--- a/internal/db/webhooks.go+++ b/internal/db/webhooks.go@@ -137,6 +137,58 @@ func (s *Store) CurrentLifecycleSeq(ctx context.Context) (int64, error) {return seq, err}+// LifecycleOutboxRow is an unrelayed lifecycle event drained from the in-tx+// outbox (sandbox_lifecycle_events) for publishing to the cell stream.+type LifecycleOutboxRow struct {+ ID string+ OrgID uuid.UUID+ SandboxID string+ Type string+ Data json.RawMessage+ Ts time.Time+}++// DrainLifecycleOutbox returns up to `batch` unrelayed lifecycle events (oldest+// first by seq). The webhook re-architecture relays these to the events:{cell}+// stream; MarkLifecycleOutboxSent then stamps them relayed. (Reuses the+// sandbox_lifecycle_events.materialized_at column as the relayed marker.)+// See .agents/work/sandbox-webhooks-rearchitecture.md.+func (s *Store) DrainLifecycleOutbox(ctx context.Context, batch int) ([]LifecycleOutboxRow, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT id, org_id, sandbox_id, type, data, ts+ FROM sandbox_lifecycle_events+ WHERE materialized_at IS NULL+ ORDER BY seq+ LIMIT $1`, batch)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var out []LifecycleOutboxRow+ for rows.Next() {+ var r LifecycleOutboxRow+ var data []byte+ if err := rows.Scan(&r.ID, &r.OrgID, &r.SandboxID, &r.Type, &data, &r.Ts); err != nil {+ return nil, err+ }+ r.Data = json.RawMessage(data)+ out = append(out, r)+ }+ return out, rows.Err()+}++// MarkLifecycleOutboxSent stamps the given events relayed (materialized_at=now()).+// Idempotent: a re-publish of an already-relayed event is harmless (the edge and+// Svix both dedupe on the stable event id).+func (s *Store) MarkLifecycleOutboxSent(ctx context.Context, ids []string) error {+ if len(ids) == 0 {+ return nil+ }+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_lifecycle_events SET materialized_at = now() WHERE id = ANY($1)`, ids)+ return err+}+// ---------------------------------------------------------------------------// Destinations// ---------------------------------------------------------------------------