forked from rlerdorf/mod_socket_handoff
-
Notifications
You must be signed in to change notification settings - Fork 0
Add noop-monitor backend for convos connection monitoring #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
qeggleston
wants to merge
1
commit into
main
Choose a base branch
from
noop-monitor-daemon
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| package backends | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "log/slog" | ||
| "net" | ||
| "time" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/prometheus/client_golang/prometheus/promauto" | ||
|
|
||
| "examples/config" | ||
| ) | ||
|
|
||
| // Backend-owned metrics for the connection monitor. Kept low-cardinality: | ||
| // source is clamped to {detail, message_list, other} and reason to a fixed | ||
| // set, so these are safe to expose per-label. | ||
| var ( | ||
| monitorActive = promauto.NewGaugeVec(prometheus.GaugeOpts{ | ||
| Name: "noop_monitor_active", | ||
| Help: "Currently held monitor connections, by originating surface", | ||
| }, []string{"source"}) | ||
|
|
||
| monitorClosed = promauto.NewCounterVec(prometheus.CounterOpts{ | ||
| Name: "noop_monitor_closed_total", | ||
| Help: "Monitor connections closed, by surface and reason", | ||
| }, []string{"source", "reason"}) | ||
| ) | ||
|
|
||
| // NoopMonitor holds a handed-off client connection open, sending only periodic | ||
| // SSE keepalive comments, so connection volume/concurrency/duration can be read | ||
| // straight from this daemon's Prometheus metrics. It never streams message data. | ||
| type NoopMonitor struct { | ||
| pingInterval time.Duration | ||
| } | ||
|
|
||
| func init() { | ||
| Register(&NoopMonitor{}) | ||
| } | ||
|
|
||
| func (n *NoopMonitor) Name() string { | ||
| return "noop-monitor" | ||
| } | ||
|
|
||
| func (n *NoopMonitor) Description() string { | ||
| return "Holds the connection open, sends nothing (convos connection monitor)" | ||
| } | ||
|
|
||
| func (n *NoopMonitor) Init(cfg *config.BackendConfig) error { | ||
| n.pingInterval = 25 * time.Second | ||
| if cfg != nil && cfg.NoopMonitor.PingIntervalMs > 0 { | ||
| n.pingInterval = time.Duration(cfg.NoopMonitor.PingIntervalMs) * time.Millisecond | ||
| } | ||
| slog.Info("noop-monitor backend initialized", "ping_interval", n.pingInterval) | ||
| return nil | ||
| } | ||
|
|
||
| // Stream holds the connection open, writing a `: ping` keepalive every | ||
| // pingInterval. A write-only stream over SOCK_SEQPACKET only learns the client | ||
| // left when a write fails, so the keepalive doubles as disconnect detection. | ||
| // A client disconnect is normal, not an error, so it returns (0, nil). | ||
| func (n *NoopMonitor) Stream(ctx context.Context, conn net.Conn, handoff HandoffData) (int64, error) { | ||
| source := normalizeSource(handoff.Source) | ||
|
|
||
| RecordBackendRequest("noop-monitor") | ||
| monitorActive.WithLabelValues(source).Inc() | ||
| defer monitorActive.WithLabelValues(source).Dec() | ||
|
|
||
| start := time.Now() | ||
| reason := "shutdown" | ||
| ticker := time.NewTicker(n.pingInterval) | ||
| defer ticker.Stop() | ||
|
|
||
| loop: | ||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| if errors.Is(context.Cause(ctx), context.DeadlineExceeded) { | ||
| reason = "max_lifetime" | ||
| } | ||
| break loop | ||
| case <-ticker.C: | ||
| _ = conn.SetWriteDeadline(time.Now().Add(WriteTimeout)) | ||
| if _, err := conn.Write(pingMsg); err != nil { | ||
| reason = "client_disconnect" | ||
| break loop | ||
| } | ||
| } | ||
| } | ||
|
|
||
| RecordBackendDuration("noop-monitor", time.Since(start).Seconds()) | ||
| monitorClosed.WithLabelValues(source, reason).Inc() | ||
| return 0, nil | ||
| } | ||
|
|
||
| // pingMsg is an SSE comment line; clients ignore it, but the write attempt is | ||
| // how a write-only stream detects that the client has gone away. | ||
| var pingMsg = []byte(": ping\n\n") | ||
|
|
||
| // normalizeSource clamps the client-influenced source label to a known set so a | ||
| // malformed or unexpected value can't blow up Prometheus label cardinality. | ||
| func normalizeSource(source string) string { | ||
| switch source { | ||
| case "detail", "message_list": | ||
| return source | ||
| default: | ||
| return "other" | ||
| } | ||
| } | ||
124 changes: 124 additions & 0 deletions
124
examples/streaming-daemon-go/backends/noop_monitor_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| package backends | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "io" | ||
| "net" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus/testutil" | ||
| ) | ||
|
|
||
| // runMonitor runs Stream against a net.Pipe and returns once it exits. | ||
| // The drain callback receives the client end so a test can either read the | ||
| // pings or close the connection to simulate a disconnect. | ||
| func runMonitor(t *testing.T, ctx context.Context, n *NoopMonitor, h HandoffData, drain func(client net.Conn)) { | ||
| t.Helper() | ||
| client, server := net.Pipe() | ||
| defer client.Close() | ||
| defer server.Close() | ||
|
|
||
| drain(client) | ||
|
|
||
| done := make(chan struct{}) | ||
| go func() { | ||
| n.Stream(ctx, server, h) | ||
| close(done) | ||
| }() | ||
|
|
||
| select { | ||
| case <-done: | ||
| case <-time.After(2 * time.Second): | ||
| t.Fatal("Stream did not return within timeout") | ||
| } | ||
| } | ||
|
|
||
| func TestNoopMonitorClientDisconnect(t *testing.T) { | ||
| before := testutil.ToFloat64(monitorClosed.WithLabelValues("detail", "client_disconnect")) | ||
| activeBefore := testutil.ToFloat64(monitorActive.WithLabelValues("detail")) | ||
|
|
||
| n := &NoopMonitor{pingInterval: 5 * time.Millisecond} | ||
| runMonitor(t, context.Background(), n, HandoffData{Source: "detail"}, func(client net.Conn) { | ||
| client.Close() // client is gone; the first ping write fails | ||
| }) | ||
|
|
||
| if got := testutil.ToFloat64(monitorClosed.WithLabelValues("detail", "client_disconnect")); got != before+1 { | ||
| t.Errorf("client_disconnect counter = %v, want %v", got, before+1) | ||
| } | ||
| if got := testutil.ToFloat64(monitorActive.WithLabelValues("detail")); got != activeBefore { | ||
| t.Errorf("active gauge = %v, want %v (should return to baseline)", got, activeBefore) | ||
| } | ||
| } | ||
|
|
||
| func TestNoopMonitorShutdown(t *testing.T) { | ||
| before := testutil.ToFloat64(monitorClosed.WithLabelValues("detail", "shutdown")) | ||
|
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| // Long ping interval so no write happens before the cancel is observed. | ||
| n := &NoopMonitor{pingInterval: 10 * time.Second} | ||
| go func() { | ||
| time.Sleep(10 * time.Millisecond) | ||
| cancel() | ||
| }() | ||
| runMonitor(t, ctx, n, HandoffData{Source: "detail"}, func(client net.Conn) { | ||
| go io.Copy(io.Discard, client) | ||
| }) | ||
| cancel() | ||
|
|
||
| if got := testutil.ToFloat64(monitorClosed.WithLabelValues("detail", "shutdown")); got != before+1 { | ||
| t.Errorf("shutdown counter = %v, want %v", got, before+1) | ||
| } | ||
| } | ||
|
|
||
| func TestNoopMonitorMaxLifetime(t *testing.T) { | ||
| before := testutil.ToFloat64(monitorClosed.WithLabelValues("detail", "max_lifetime")) | ||
|
|
||
| ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) | ||
| defer cancel() | ||
| n := &NoopMonitor{pingInterval: 10 * time.Second} | ||
| runMonitor(t, ctx, n, HandoffData{Source: "detail"}, func(client net.Conn) { | ||
| go io.Copy(io.Discard, client) | ||
| }) | ||
|
|
||
| if got := testutil.ToFloat64(monitorClosed.WithLabelValues("detail", "max_lifetime")); got != before+1 { | ||
| t.Errorf("max_lifetime counter = %v, want %v", got, before+1) | ||
| } | ||
| } | ||
|
|
||
| func TestNoopMonitorWritesPing(t *testing.T) { | ||
| n := &NoopMonitor{pingInterval: 5 * time.Millisecond} | ||
| client, server := net.Pipe() | ||
| defer client.Close() | ||
| defer server.Close() | ||
|
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| go func() { | ||
| n.Stream(ctx, server, HandoffData{Source: "message_list"}) | ||
| }() | ||
|
|
||
| got := make([]byte, len(pingMsg)) | ||
| _ = client.SetReadDeadline(time.Now().Add(2 * time.Second)) | ||
| if _, err := io.ReadFull(client, got); err != nil { | ||
| t.Fatalf("reading ping: %v", err) | ||
| } | ||
| if !bytes.Equal(got, pingMsg) { | ||
| t.Errorf("first write = %q, want %q", got, pingMsg) | ||
| } | ||
| cancel() | ||
| } | ||
|
|
||
| func TestNormalizeSource(t *testing.T) { | ||
| tests := map[string]string{ | ||
| "detail": "detail", | ||
| "message_list": "message_list", | ||
| "": "other", | ||
| "bogus": "other", | ||
| } | ||
| for in, want := range tests { | ||
| if got := normalizeSource(in); got != want { | ||
| t.Errorf("normalizeSource(%q) = %q, want %q", in, got, want) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This doesnt look like golang. Missing comment?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's a label, on lines 82 and 87 it's used to specify what to break out of when we reach max connection lifetime or client disconnect. It's because if we just did normal "break" we'd just break out of
selectThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fwiw,
make buildpasses without any issues