Skip to content

Alerts, FanOut & Concurrent Webhooks

This program debounces rapid state transitions, broadcasts each settled alert concurrently to an audit writer and an alert channel via FanOut, and dispatches webhook deliveries concurrently using ParEach.

What It Exercises

  • Trailing-edge burst suppression with Debounce
  • Concurrent multi-sink broadcast via FanOut
  • Writer and channel sinks (ToWriter, ToChan, CloseOnDone)
  • Bounded concurrent terminal execution with ParEach

Complete Program

package main

import (
    "context"
    "fmt"
    "os"
    "strings"
    "sync"
    "time"

    "github.com/vladimirvivien/automi"
)

type ServiceState struct {
    Service string
    Status  string
}

func main() {
    ctx := context.Background()
    rawStates := make(chan ServiceState)

    // Simulate rapid flapping before settling cleanly.
    go func() {
        defer close(rawStates)
        events := []ServiceState{
            {Service: "payments", Status: "degraded"},
            {Service: "payments", Status: "down"},
            {Service: "payments", Status: "healthy"},
        }
        for _, ev := range events {
            rawStates <- ev
            time.Sleep(10 * time.Millisecond)
        }
        // Pause longer than debounce window so "healthy" flushes separately.
        time.Sleep(60 * time.Millisecond)
        rawStates <- ServiceState{Service: "checkout", Status: "degraded"}
    }()

    settled := automi.FromChan(rawStates).
        Debounce(35 * time.Millisecond)

    var auditLog strings.Builder
    alertCh := make(chan string, 8)
    var dispatchWG sync.WaitGroup
    var delivered []string
    var deliveredMu sync.Mutex

    // Consume alertCh concurrently with ParEach across 3 workers.
    dispatchWG.Add(1)
    var dispatchErr error
    go func() {
        defer dispatchWG.Done()
        dispatchErr = automi.FromChan(alertCh).
            ParEach(ctx, 3, func(_ context.Context, msg string) error {
                deliveredMu.Lock()
                delivered = append(delivered, "webhook sent -> "+strings.TrimSpace(msg))
                deliveredMu.Unlock()
                return nil
            })
    }()

    formatted := settled.Map(func(s ServiceState) string {
        return fmt.Sprintf("%s=%s\n", s.Service, s.Status)
    })

    err := automi.FanOut(ctx, formatted,
        automi.ToWriter[string](&auditLog),
        automi.ToChan(alertCh, automi.CloseOnDone()),
    )
    dispatchWG.Wait()

    if err != nil || dispatchErr != nil {
        fmt.Fprintf(os.Stderr, "fanout=%v dispatch=%v\n", err, dispatchErr)
        os.Exit(1)
    }

    fmt.Println("=== Audit Writer ===")
    fmt.Print(auditLog.String())
    fmt.Println("=== Webhook Deliveries ===")
    for _, line := range delivered {
        fmt.Println(line)
    }
}

Expected Output

=== Audit Writer ===
payments=healthy
checkout=degraded
=== Webhook Deliveries ===
webhook sent -> payments=healthy
webhook sent -> checkout=degraded

The first two intermediate flaps (degraded → down) collapsed inside the 35ms debounce window, emitting only the settled state transitions to both downstream destinations.