From 435b6f37d2399a6fc10f2f50a97fee285a4ab367 Mon Sep 17 00:00:00 2001 From: jmbenlloch Date: Wed, 4 Nov 2026 15:44:51 +0100 Subject: [PATCH 1/2] Store GDC rate history and expose bounded counter-based rate queries --- api/README.md | 120 ++++ api/apiHandler.go | 2 + api/rateHistory.go | 354 ++++++++++++ api/rateHistory_test.go | 362 ++++++++++++ .../migrations/20261104_add_rate_samples.sql | 14 + database/queries/rates.sql | 6 + database/schema.sql | 15 + gui/src/gen/api_connect.ts | 13 +- gui/src/gen/api_pb.ts | 254 ++++++++- pkg/database/mocks/Querier.go | 18 + pkg/database/models.go | 15 + pkg/database/querier.go | 1 + pkg/database/rates.sql.go | 48 ++ rateReader/README.md | 392 +++---------- rateReader/main.go | 337 +++++++----- rateReader/main_test.go | 255 +++++++++ rpc/api/api.pb.go | 519 +++++++++++++++--- rpc/api/apiconnect/api.connect.go | 30 + rpc/proto/api/api.proto | 44 ++ 19 files changed, 2274 insertions(+), 525 deletions(-) create mode 100644 api/rateHistory.go create mode 100644 api/rateHistory_test.go create mode 100644 database/migrations/20261104_add_rate_samples.sql create mode 100644 database/queries/rates.sql create mode 100644 pkg/database/rates.sql.go create mode 100644 rateReader/main_test.go diff --git a/api/README.md b/api/README.md index 43b7f09..b44a347 100644 --- a/api/README.md +++ b/api/README.md @@ -323,3 +323,123 @@ go test -v ./api/ -run TestStartRun - **Non-blocking**: Async RPC calls to LDCs/GDCs - **Connection Pooling**: Database connection reuse - **Response Time**: <100ms for most operations + +## Historical trigger and byte rates + +`POST /apiService.DuckAPI/GetRateHistory` returns bounded, counter-derived rates +summed across the GDCs recorded for a single run. Apply the `rateSamples` +migration and deploy the history-enabled `rateReader` before collecting history. +This endpoint is read-only; it does not start acquisition or change TOPI. +The generated Go and TypeScript clients expose `getRateHistory`/`GetRateHistory`. + +### Request and browser modes + +Whole-run auto mode: + +```json +{"run": 16191, "maxPoints": 1000} +``` + +Fixed-window manual/zoom mode: + +```json +{ + "run": 16191, + "from": "2026-11-04T12:00:00Z", + "to": "2026-11-04T12:30:00Z", + "maxPoints": 1000 +} +``` + +Omitting `from` selects the run start (or earliest sample if start is unknown). +Omitting `to` selects the latest recorded sample, limited by the recorded stop +when present. Explicit bounds are clamped to that range, and windows entirely +outside it return no bins. `from` is inclusive and `to` is exclusive; a sample +at `to` can provide the counter endpoint for the preceding interval. + +`maxPoints=0` defaults to 1000; values from 1 through 2000 are accepted. The API +selects a bin width from 5, 10, 15, 30 seconds, 1, 2, 5, 10, 15, 30 minutes, +1, 2, 6, 12 hours, 1 day, then wider daily multiples as necessary. Bins are +anchored to the run start. Both clipped edge bins count against the point +budget, so an unaligned zoom does not produce an extra point. The minimum +resolution is five seconds; zooming further cannot recover finer measurements. + +The same RPC supports both browser modes; no persistent server-side mode is +needed. Auto mode can poll every five seconds, replacing the series and adapting +the time axis and bin width. Manual mode holds its selected window, cancels +superseded zoom requests and requests the same point budget over the smaller +window. A browser can return to auto by omitting the bounds again. The frontend +plot itself is not implemented by this API change. + +### Response and aggregation + +The response includes the selected `from`/`to`, `runStart`/`runStop` when known, +`latestSample`, `binWidthSeconds`, `gdcs`, `coverageBasis`, `hasData`, +`maxGapSeconds`, and at most `maxPoints` ordered `bins`. + +Each bin contains `start`, `end`, `coverage`, `complete`, `partial`, and optional +`triggerRateHz` and `byteRate` (bytes/second). `partial` means the selected window +clips the bin width; it is independent of missing telemetry. Rate fields are +present only when all the bin's GDC-time is covered. A true zero rate remains +present as zero; an incomplete bin has absent rate fields. Plot these as gaps, +not as zero and not as a line bridged through the gap. + +For each GDC, the API differences consecutive unsigned event/byte counters before +converting their deltas to floating point. It assumes a constant rate between +each pair of measurements and distributes the deltas to overlapping bins in +proportion to their time overlap. It then sums the GDC contributions and divides +by the actual bin duration. This produces time-weighted interval averages; +current sliding-window rate values and whole-run averages are not used. + +Zoom queries include one predecessor and one successor per GDC so window-edge +intervals can be calculated without snapping the requested window to samples. +Counter decreases and `counter_reset=true` invalidate the interval ending at the +reset sample; the next interval may recover normally. Intervals exceeding +`maxGapSeconds` are unknown, not interpolated. The default is 15 seconds for the +five-second writer; an explicit value from 1 to 3600 seconds supports different +collector periods or stricter gap policies. + +`coverage` is covered GDC-seconds divided by bin duration times roster size. +For now the roster consists of distinct GDCs recorded anywhere in the run, +including outside a manual window. `coverageBasis="observed_run_history"` +explicitly identifies this limitation: a GDC that never reported is unknown. +The endpoint does not substitute today's enabled-GDC configuration for a +historical configuration snapshot. Completed bins are complete relative to the +recorded roster, not a guarantee that every configured GDC reported. Persisting +an expected per-run roster can strengthen this in a later migration. + +### Database access and limits + +Queries use one repeatable-read, read-only transaction, so the roster, bounds and +counter streams share a snapshot while acquisition continues. The roster query +uses the `(run,gdc,sample_time)` primary key. Per-GDC window reads and the scalar +predecessor/successor lookups use the same key. The secondary `(run,sample_time)` +index remains available for other single-run time queries. + +Rows are streamed into at most 2000 in-memory bin accumulators, rather than +loading all raw samples into a Go slice or sending them to the browser. Memory +therefore does not grow with raw sample count. Work still scales with the +selected window's raw samples: indexing avoids other runs, but it does not make +a full long-run scan constant-time. A ten-second query deadline and a roster +limit of 256 bound each request. Measured demand can justify caching or stored +rollups without changing this contract. A corrupt/implausible span exceeding +100 years is rejected before bin arithmetic. + +An existing run with no history returns `hasData=false`, no bins and run metadata +when available. One sample can establish history bounds but cannot establish a +rate. Unknown runs return `not_found`; invalid arguments return +`invalid_argument`; a missing history table returns `failed_precondition`. +Canceling a request cancels its database work. + +### History API validation + +Run `go test -race ./api -run '^TestRateHistory' -timeout 60s`. +For the real MySQL/ConnectRPC test, set `RATE_HISTORY_TEST_DSN` to a disposable +schema and run the same command. The test creates and drops `runs` and +`rateSamples`; never point it at production. It verifies zoom boundary samples, +aggregate counter rates, gaps, reset recovery, run isolation, native resolution, +point limits and an indexed query plan. + +`go test ./api -run '^$' -bench '^BenchmarkRateHistoryRebin$' -benchtime=1x -benchmem` +measures only the Go aggregation step for seven GDCs with 120000 intervals each; +it is not a database or end-to-end latency measurement. diff --git a/api/apiHandler.go b/api/apiHandler.go index 1a9362c..fc541ab 100644 --- a/api/apiHandler.go +++ b/api/apiHandler.go @@ -10,6 +10,7 @@ import ( // DuckAPIServer implements DuckAPIHandler interface type DuckAPIServer struct { + historyDB *sql.DB queries database.Querier rpcClient RPCClient configFilename string @@ -25,6 +26,7 @@ func NewDuckAPIServer(db *sql.DB, configFilename string, centrifugalToken string queries := database.New(db) return &DuckAPIServer{ queries: queries, + historyDB: db, rpcClient: NewRealRPCClient(), configFilename: configFilename, centrifugalToken: centrifugalToken, diff --git a/api/rateHistory.go b/api/rateHistory.go new file mode 100644 index 0000000..c8fa656 --- /dev/null +++ b/api/rateHistory.go @@ -0,0 +1,354 @@ +package main + +import ( + "context" + "database/sql" + "errors" + "fmt" + "log" + "math" + "time" + + "connectrpc.com/connect" + "github.com/go-sql-driver/mysql" + pb "github.com/jmbenlloch/next_duck/rpc/api" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" +) + +const ( + defaultHistoryPoints = 1000 + maximumHistoryPoints = 2000 + defaultHistoryGap = 15 + maximumHistoryGap = 3600 + maximumHistoryGDCs = 256 +) + +type historySource struct { + name string + first, last time.Time +} + +type historySample struct { + at time.Time + events, bytes uint64 + reset bool +} + +type historyBin struct { + start, end time.Time + events, bytes, coveredSeconds float64 + partial bool +} + +func validateHistoryRequest(req *pb.GetRateHistoryRequest) (int, time.Duration, error) { + invalid := func(message string) (int, time.Duration, error) { + return 0, 0, connect.NewError(connect.CodeInvalidArgument, errors.New(message)) + } + if req.Run <= 0 { + return invalid("run must be positive") + } + for _, t := range []*timestamppb.Timestamp{req.From, req.To} { + if t != nil && t.CheckValid() != nil { + return invalid("invalid history timestamp") + } + } + if req.From != nil && req.To != nil && !req.From.AsTime().Before(req.To.AsTime()) { + return invalid("from must precede to") + } + points := int(req.MaxPoints) + if points == 0 { + points = defaultHistoryPoints + } + if req.MaxPoints > maximumHistoryPoints { + return invalid("max_points must be between 1 and 2000 (or 0 for default)") + } + gap := req.MaxGapSeconds + if gap == 0 { + gap = defaultHistoryGap + } + if gap > maximumHistoryGap { + return invalid("max_gap_seconds must not exceed 3600") + } + return points, time.Duration(gap) * time.Second, nil +} + +// Choose stable run-start-aligned bins; the two clipped edge bins count against +// the budget too. This avoids a max_points+1 response for unaligned zoom windows. +func historyBinWidth(origin, from, to time.Time, maxPoints int) time.Duration { + widths := []int64{5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 21600, 43200, 86400} + fits := func(width time.Duration) bool { + first := from.Sub(origin) / width + last := to.Sub(origin) / width + if to.Sub(origin)%width != 0 { + last++ + } + return last-first <= time.Duration(maxPoints) + } + for _, seconds := range widths { + width := time.Duration(seconds) * time.Second + if fits(width) { + return width + } + } + width := 24 * time.Hour + for !fits(width) { + width *= 2 + if width > time.Duration(math.MaxUint32)*time.Second { + return time.Duration(math.MaxUint32) * time.Second + } + } + return width +} + +func newHistoryBins(origin, from, to time.Time, width time.Duration) []historyBin { + bins := make([]historyBin, 0) + for start := origin.Add((from.Sub(origin) / width) * width); start.Before(to); start = start.Add(width) { + end := start.Add(width) + clippedStart, clippedEnd := start, end + if clippedStart.Before(from) { + clippedStart = from + } + if clippedEnd.After(to) { + clippedEnd = to + } + bins = append(bins, historyBin{start: clippedStart, end: clippedEnd, partial: !clippedStart.Equal(start) || !clippedEnd.Equal(end)}) + } + return bins +} + +func addHistoryInterval(bins []historyBin, previous, current historySample, gap time.Duration, width time.Duration) { + elapsed := current.at.Sub(previous.at) + if elapsed <= 0 || elapsed > gap || current.reset || current.events < previous.events || current.bytes < previous.bytes || len(bins) == 0 { + return + } + start, end := previous.at, current.at + if start.Before(bins[0].start) { + start = bins[0].start + } + if end.After(bins[len(bins)-1].end) { + end = bins[len(bins)-1].end + } + if !start.Before(end) { + return + } + // Account for a potentially clipped first bin. The loop visits only bins + // intersected by this interval, not all bins for every source sample. + i := 0 + if !start.Before(bins[0].end) { + i = 1 + int(start.Sub(bins[0].end)/width) + } + eventRate := float64(current.events-previous.events) / elapsed.Seconds() + byteRate := float64(current.bytes-previous.bytes) / elapsed.Seconds() + for ; i < len(bins) && bins[i].start.Before(end); i++ { + left, right := start, end + if left.Before(bins[i].start) { + left = bins[i].start + } + if right.After(bins[i].end) { + right = bins[i].end + } + seconds := right.Sub(left).Seconds() + if seconds <= 0 { + continue + } + bins[i].events += eventRate * seconds + bins[i].bytes += byteRate * seconds + bins[i].coveredSeconds += seconds + } +} + +func historyResponseBins(bins []historyBin, sources int) []*pb.RateHistoryBin { + result := make([]*pb.RateHistoryBin, 0, len(bins)) + for _, bin := range bins { + duration := bin.end.Sub(bin.start).Seconds() + coverage := math.Min(1, bin.coveredSeconds/(duration*float64(sources))) + complete := coverage >= 1-1e-9 + point := &pb.RateHistoryBin{Start: timestamppb.New(bin.start), End: timestamppb.New(bin.end), Coverage: coverage, Complete: complete, Partial: bin.partial} + if complete { + point.TriggerRateHz = proto.Float64(bin.events / duration) + point.ByteRate = proto.Float64(bin.bytes / duration) + } + result = append(result, point) + } + return result +} + +func historyError(err error) error { + if errors.Is(err, context.Canceled) { + return connect.NewError(connect.CodeCanceled, errors.New("history request canceled")) + } + if errors.Is(err, context.DeadlineExceeded) { + return connect.NewError(connect.CodeDeadlineExceeded, errors.New("history query timed out; select a smaller window")) + } + var mysqlErr *mysql.MySQLError + if errors.As(err, &mysqlErr) && mysqlErr.Number == 1146 { + return connect.NewError(connect.CodeFailedPrecondition, errors.New("rate history table unavailable; apply the rateSamples migration")) + } + log.Printf("rate history query failed: %v", err) + return connect.NewError(connect.CodeInternal, errors.New("could not read rate history")) +} + +// GetRateHistory serves both whole-run polling and fixed zoom windows. It never +// interpolates across a reset or a telemetry gap longer than max_gap_seconds. +func (s *DuckAPIServer) GetRateHistory(ctx context.Context, req *connect.Request[pb.GetRateHistoryRequest]) (*connect.Response[pb.GetRateHistoryResponse], error) { + maxPoints, maxGap, err := validateHistoryRequest(req.Msg) + if err != nil { + return nil, err + } + if s.historyDB == nil { + return nil, connect.NewError(connect.CodeUnavailable, errors.New("history database unavailable")) + } + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + // Metadata and source samples share a consistent snapshot while rateReader + // continues inserting data. Only the API process's memory is bounded here; + // query execution still scales with the selected run/window. + tx, err := s.historyDB.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true}) + if err != nil { + return nil, historyError(err) + } + defer tx.Rollback() + var start, stop sql.NullTime + if err := tx.QueryRowContext(ctx, "SELECT start, stop FROM runs WHERE id = ?", req.Msg.Run).Scan(&start, &stop); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, connect.NewError(connect.CodeNotFound, errors.New("run not found")) + } + return nil, historyError(err) + } + sources, err := loadHistorySources(ctx, tx, req.Msg.Run) + if err != nil { + return nil, historyError(err) + } + if len(sources) > maximumHistoryGDCs { + return nil, connect.NewError(connect.CodeResourceExhausted, errors.New("too many GDCs in rate history")) + } + response := &pb.GetRateHistoryResponse{Run: req.Msg.Run, CoverageBasis: "observed_run_history", MaxGapSeconds: uint32(maxGap / time.Second), Bins: []*pb.RateHistoryBin{}, Gdcs: []string{}} + if start.Valid { + response.RunStart = timestamppb.New(start.Time.UTC()) + } + if stop.Valid { + response.RunStop = timestamppb.New(stop.Time.UTC()) + } + if len(sources) == 0 { + if err := tx.Commit(); err != nil { + return nil, historyError(err) + } + return connect.NewResponse(response), nil + } + earliest, latest := sources[0].first, sources[0].last + for _, source := range sources { + response.Gdcs = append(response.Gdcs, source.name) + if source.first.Before(earliest) { + earliest = source.first + } + if source.last.After(latest) { + latest = source.last + } + } + response.HasData = true + response.LatestSample = timestamppb.New(latest) + origin := earliest + if start.Valid { + origin = start.Time.UTC() + } + end := latest + if stop.Valid && stop.Time.Before(end) { + end = stop.Time.UTC() + } + if end.Before(origin) { + end = origin + } + from, to := origin, end + clamp := func(t time.Time) time.Time { + if t.Before(origin) { + return origin + } + if t.After(end) { + return end + } + return t.UTC() + } + if req.Msg.From != nil { + from = clamp(req.Msg.From.AsTime()) + } + if req.Msg.To != nil { + to = clamp(req.Msg.To.AsTime()) + } + response.From, response.To = timestamppb.New(from), timestamppb.New(to) + if !from.Before(to) { + if err := tx.Commit(); err != nil { + return nil, historyError(err) + } + return connect.NewResponse(response), nil + } + // Reject corrupt/implausible timestamps before duration arithmetic can overflow. + if to.Sub(origin) > 100*365*24*time.Hour { + return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("rate history exceeds the supported 100-year span")) + } + width := historyBinWidth(origin, from, to, maxPoints) + bins := newHistoryBins(origin, from, to, width) + for _, source := range sources { + if err := accumulateHistorySource(ctx, tx, req.Msg.Run, source.name, from, to, maxGap, width, bins); err != nil { + return nil, historyError(err) + } + } + if err := tx.Commit(); err != nil { + return nil, historyError(err) + } + response.BinWidthSeconds = uint32(width / time.Second) + response.Bins = historyResponseBins(bins, len(sources)) + return connect.NewResponse(response), nil +} + +func loadHistorySources(ctx context.Context, tx *sql.Tx, run int32) ([]historySource, error) { + // The primary key (run,gdc,sample_time) supports this recorded-run roster. + rows, err := tx.QueryContext(ctx, `SELECT gdc, MIN(sample_time), MAX(sample_time) +FROM rateSamples WHERE run = ? GROUP BY gdc ORDER BY gdc LIMIT 257`, run) + if err != nil { + return nil, err + } + defer rows.Close() + sources := make([]historySource, 0) + for rows.Next() { + var source historySource + if err := rows.Scan(&source.name, &source.first, &source.last); err != nil { + return nil, err + } + source.first, source.last = source.first.UTC(), source.last.UTC() + sources = append(sources, source) + } + return sources, rows.Err() +} + +func accumulateHistorySource(ctx context.Context, tx *sql.Tx, run int32, gdc string, from, to time.Time, maxGap, width time.Duration, bins []historyBin) error { + // Include one predecessor and one successor. Both scalar boundary lookups and + // the ordered stream use the (run,gdc,sample_time) primary key. Samples outside + // the requested window never appear in the response; they define edge deltas. + rows, err := tx.QueryContext(ctx, `SELECT sample_time, events, bytes, counter_reset +FROM rateSamples WHERE run = ? AND gdc = ? +AND sample_time >= COALESCE((SELECT MAX(sample_time) FROM rateSamples WHERE run = ? AND gdc = ? AND sample_time <= ?), ?) +AND sample_time <= COALESCE((SELECT MIN(sample_time) FROM rateSamples WHERE run = ? AND gdc = ? AND sample_time >= ?), ?) +ORDER BY sample_time`, run, gdc, run, gdc, from, from, run, gdc, to, to) + if err != nil { + return err + } + defer rows.Close() + var previous historySample + havePrevious := false + for rows.Next() { + var current historySample + if err := rows.Scan(¤t.at, ¤t.events, ¤t.bytes, ¤t.reset); err != nil { + return err + } + current.at = current.at.UTC() + if havePrevious { + addHistoryInterval(bins, previous, current, maxGap, width) + } + previous, havePrevious = current, true + } + if err := rows.Err(); err != nil { + return fmt.Errorf("streaming GDC rate history: %w", err) + } + return nil +} diff --git a/api/rateHistory_test.go b/api/rateHistory_test.go new file mode 100644 index 0000000..5ec5b39 --- /dev/null +++ b/api/rateHistory_test.go @@ -0,0 +1,362 @@ +package main + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "math" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "connectrpc.com/connect" + "github.com/DATA-DOG/go-sqlmock" + "github.com/go-sql-driver/mysql" + pb "github.com/jmbenlloch/next_duck/rpc/api" + "github.com/jmbenlloch/next_duck/rpc/api/apiconnect" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func historyOrigin() time.Time { return time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) } +func closeRate(a, b float64) bool { return math.Abs(a-b) < 1e-8 } + +func TestRateHistoryWeightedCounterRebin(t *testing.T) { + origin := historyOrigin() + // A zoom cuts both a low-rate interval and a high-rate interval in half. + bins := newHistoryBins(origin, origin.Add(2*time.Second), origin.Add(8*time.Second), 10*time.Second) + addHistoryInterval(bins, historySample{at: origin, events: 100, bytes: 1000}, historySample{at: origin.Add(5 * time.Second), events: 150, bytes: 1500}, 15*time.Second, 10*time.Second) + addHistoryInterval(bins, historySample{at: origin.Add(5 * time.Second), events: 150, bytes: 1500}, historySample{at: origin.Add(10 * time.Second), events: 250, bytes: 2500}, 15*time.Second, 10*time.Second) + points := historyResponseBins(bins, 1) + if len(points) != 1 || !points[0].Complete || !points[0].Partial || !closeRate(points[0].GetTriggerRateHz(), 15) || !closeRate(points[0].GetByteRate(), 150) { + t.Fatalf("wrong weighted zoom result: %v", points) + } +} + +func TestRateHistoryGDCsumAndCoverage(t *testing.T) { + origin := historyOrigin() + bins := newHistoryBins(origin, origin, origin.Add(10*time.Second), 5*time.Second) + // Asynchronous GDC samples can cover the same bins without matching timestamps. + addHistoryInterval(bins, historySample{at: origin.Add(-time.Second), events: 100}, historySample{at: origin.Add(11 * time.Second), events: 340}, 15*time.Second, 5*time.Second) + addHistoryInterval(bins, historySample{at: origin, events: 100}, historySample{at: origin.Add(5 * time.Second), events: 250}, 15*time.Second, 5*time.Second) + points := historyResponseBins(bins, 2) + if !points[0].Complete || !closeRate(points[0].GetTriggerRateHz(), 50) { + t.Fatalf("GDCs not summed correctly: %v", points[0]) + } + if points[1].Complete || points[1].TriggerRateHz != nil || points[1].ByteRate != nil || !closeRate(points[1].Coverage, 0.5) { + t.Fatalf("missing host shown as a rate: %v", points[1]) + } +} + +func TestRateHistoryResetGapAndZero(t *testing.T) { + origin := historyOrigin() + for _, tc := range []struct { + name string + end historySample + gap time.Duration + valid bool + }{ + {"zero rate", historySample{at: origin.Add(5 * time.Second), events: 100, bytes: 1000}, 15 * time.Second, true}, + {"event reset", historySample{at: origin.Add(5 * time.Second), events: 1, bytes: 1000}, 15 * time.Second, false}, + {"byte reset", historySample{at: origin.Add(5 * time.Second), events: 110, bytes: 1}, 15 * time.Second, false}, + {"explicit reset", historySample{at: origin.Add(5 * time.Second), events: 110, bytes: 1100, reset: true}, 15 * time.Second, false}, + {"long telemetry gap", historySample{at: origin.Add(20 * time.Second), events: 110, bytes: 1100}, 15 * time.Second, false}, + } { + t.Run(tc.name, func(t *testing.T) { + bins := newHistoryBins(origin, origin, origin.Add(5*time.Second), 5*time.Second) + addHistoryInterval(bins, historySample{at: origin, events: 100, bytes: 1000}, tc.end, tc.gap, 5*time.Second) + point := historyResponseBins(bins, 1)[0] + if point.Complete != tc.valid { + t.Fatalf("wrong coverage: %v", point) + } + if tc.valid && (point.TriggerRateHz == nil || *point.TriggerRateHz != 0) { + t.Fatal("real zero must be present") + } + if !tc.valid && point.TriggerRateHz != nil { + t.Fatal("gap must have an absent rate") + } + }) + } + // Subtract integer counters before converting to float; large totals lose no delta. + bins := newHistoryBins(origin, origin, origin.Add(5*time.Second), 5*time.Second) + addHistoryInterval(bins, historySample{at: origin, events: 1 << 60}, historySample{at: origin.Add(5 * time.Second), events: (1 << 60) + 10}, 15*time.Second, 5*time.Second) + if !closeRate(historyResponseBins(bins, 1)[0].GetTriggerRateHz(), 2) { + t.Fatal("large counters lost precision") + } +} + +func TestRateHistoryBinBudgetAndAlignment(t *testing.T) { + origin := historyOrigin() + for _, duration := range []time.Duration{time.Second, 30 * time.Minute, 2 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour, 100 * 365 * 24 * time.Hour} { + for _, offset := range []time.Duration{0, 1234 * time.Millisecond, 61 * time.Second} { + for _, budget := range []int{1, 2, 10, 1000, 2000} { + from, to := origin.Add(offset), origin.Add(offset+duration) + width := historyBinWidth(origin, from, to, budget) + bins := newHistoryBins(origin, from, to, width) + if len(bins) > budget || len(bins) == 0 || !bins[0].start.Equal(from) || !bins[len(bins)-1].end.Equal(to) { + t.Fatalf("unbounded/misclipped bins: duration=%v offset=%v budget=%d width=%v count=%d", duration, offset, budget, width, len(bins)) + } + if width/time.Second > math.MaxUint32 { + t.Fatal("bin width exceeds wire format") + } + } + } + } + if width := historyBinWidth(origin, origin, origin.Add(30*time.Minute), 1000); width != 5*time.Second { + t.Fatalf("short run lost native resolution: %v", width) + } +} + +func TestRateHistoryRequestValidation(t *testing.T) { + for _, req := range []*pb.GetRateHistoryRequest{ + {}, {Run: -1}, {Run: 1, MaxPoints: 2001}, {Run: 1, MaxGapSeconds: 3601}, + {Run: 1, From: ×tamppb.Timestamp{Seconds: 253402300800}}, + {Run: 1, From: timestamppb.New(historyOrigin()), To: timestamppb.New(historyOrigin())}, + } { + _, _, err := validateHistoryRequest(req) + if connect.CodeOf(err) != connect.CodeInvalidArgument { + t.Fatalf("accepted invalid request %v: %v", req, err) + } + } + points, gap, err := validateHistoryRequest(&pb.GetRateHistoryRequest{Run: 1}) + if err != nil || points != 1000 || gap != 15*time.Second { + t.Fatal("bad defaults") + } +} + +func TestRateHistoryEmptyAndUnknownRun(t *testing.T) { + for _, exists := range []bool{true, false} { + db, mock, _ := sqlmock.New() + mock.ExpectBegin() + rows := sqlmock.NewRows([]string{"start", "stop"}) + if exists { + rows.AddRow(nil, nil) + } + mock.ExpectQuery("SELECT start, stop FROM runs").WithArgs(int32(123)).WillReturnRows(rows) + if exists { + mock.ExpectQuery("SELECT gdc, MIN").WithArgs(int32(123)).WillReturnRows(sqlmock.NewRows([]string{"gdc", "first", "last"})) + mock.ExpectCommit() + } else { + mock.ExpectRollback() + } + response, err := (&DuckAPIServer{historyDB: db}).GetRateHistory(context.Background(), connect.NewRequest(&pb.GetRateHistoryRequest{Run: 123})) + if exists { + if err != nil || response.Msg.HasData || len(response.Msg.Bins) != 0 { + t.Fatalf("bad empty history response: %v %v", response, err) + } + } else if connect.CodeOf(err) != connect.CodeNotFound { + t.Fatalf("wrong missing run error: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } + db.Close() + } +} + +// A disposable MySQL schema is required. This test creates/drops runs and rateSamples. +func TestRateHistoryMySQL(t *testing.T) { + dsn := os.Getenv("RATE_HISTORY_TEST_DSN") + if dsn == "" { + t.Skip("RATE_HISTORY_TEST_DSN not set") + } + db, err := sql.Open("mysql", dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + ddl, err := os.ReadFile("../database/migrations/20261104_add_rate_samples.sql") + if err != nil { + t.Fatal(err) + } + if _, err = db.Exec(string(ddl)); err != nil { + t.Fatal(err) + } + if _, err = db.Exec("CREATE TABLE runs (id INT PRIMARY KEY, start TIMESTAMP NULL, stop TIMESTAMP NULL)"); err != nil { + t.Fatal(err) + } + defer db.Exec("DROP TABLE runs, rateSamples") + origin := historyOrigin() + if _, err = db.Exec("INSERT INTO runs VALUES (1,?,NULL),(2,?,NULL)", origin, origin); err != nil { + t.Fatal(err) + } + for _, source := range []struct { + name string + offset time.Duration + eventsPerSample int + }{{"gdc1", 0, 50}, {"gdc2", time.Second, 100}} { + for i := 0; i <= 6; i++ { + at := origin.Add(time.Duration(i)*5*time.Second + source.offset) + // Current rates deliberately disagree with counters: history must ignore them. + _, err = db.Exec(`INSERT INTO rateSamples VALUES (1,?,?,?, ?,9999,9999,9999,9999,FALSE)`, source.name, at, 1000+i*source.eventsPerSample, 10000+i*source.eventsPerSample*10) + if err != nil { + t.Fatal(err) + } + } + } + // Noise from another run must never influence the roster, counters or bounds. + if _, err = db.Exec(`INSERT INTO rateSamples VALUES (2,'unrelated',?,0,0,0,0,0,0,FALSE)`, origin); err != nil { + t.Fatal(err) + } + server := NewDuckAPIServer(db, "", "", false) + path, handler := apiconnect.NewDuckAPIHandler(server) + _ = path + httpServer := httptest.NewServer(handler) + defer httpServer.Close() + client := apiconnect.NewDuckAPIClient(httpServer.Client(), httpServer.URL) + request := &pb.GetRateHistoryRequest{Run: 1, From: timestamppb.New(origin.Add(2 * time.Second)), To: timestamppb.New(origin.Add(28 * time.Second)), MaxPoints: 3} + response, err := client.GetRateHistory(context.Background(), connect.NewRequest(request)) + if err != nil { + t.Fatal(err) + } + result := response.Msg + if len(result.Bins) > 3 || len(result.Bins) == 0 || len(result.Gdcs) != 2 || result.CoverageBasis != "observed_run_history" { + t.Fatalf("wrong bounded response: %v", result) + } + for _, bin := range result.Bins { + if !bin.Complete || !closeRate(bin.GetTriggerRateHz(), 30) || !closeRate(bin.GetByteRate(), 300) { + t.Fatalf("edge predecessor/successor or aggregate wrong: %v", bin) + } + } + // Whole-run auto mode uses native resolution until the budget requires rebinning. + auto, err := client.GetRateHistory(context.Background(), connect.NewRequest(&pb.GetRateHistoryRequest{Run: 1})) + if err != nil || auto.Msg.BinWidthSeconds != 5 || len(auto.Msg.Bins) != 7 { + t.Fatalf("bad auto response: %v %v", auto, err) + } + if auto.Msg.Bins[0].TriggerRateHz != nil || auto.Msg.Bins[len(auto.Msg.Bins)-1].TriggerRateHz != nil { + t.Fatal("incomplete edge bins must not masquerade as zero") + } + // JSON optional rates distinguish a healthy zero from missing coverage. + encoded, err := protojson.Marshal(auto.Msg) + if err != nil { + t.Fatal(err) + } + var wire map[string]any + if err = json.Unmarshal(encoded, &wire); err != nil { + t.Fatal(err) + } + if strings.Contains(string(encoded), "9999") { + t.Fatal("used current rates instead of counters") + } + // Explicit windows wholly outside recorded data return no bins. + outside, err := client.GetRateHistory(context.Background(), connect.NewRequest(&pb.GetRateHistoryRequest{Run: 1, From: timestamppb.New(origin.Add(time.Hour)), To: timestamppb.New(origin.Add(2 * time.Hour))})) + if err != nil || len(outside.Msg.Bins) != 0 { + t.Fatal("outside window was extrapolated") + } + // A counter reset creates an internal hole, while following intervals recover. + if _, err = db.Exec("UPDATE rateSamples SET counter_reset=TRUE WHERE run=1 AND gdc='gdc1' AND sample_time=?", origin.Add(15*time.Second)); err != nil { + t.Fatal(err) + } + reset, err := client.GetRateHistory(context.Background(), connect.NewRequest(&pb.GetRateHistoryRequest{Run: 1})) + if err != nil || reset.Msg.Bins[2].Complete || reset.Msg.Bins[2].TriggerRateHz != nil || !reset.Msg.Bins[3].Complete { + t.Fatalf("reset handling failed: %v %v", reset, err) + } + // Check the range query's execution plan uses the per-run/GDC primary index. + rows, err := db.Query(`EXPLAIN FORMAT=TRADITIONAL SELECT sample_time,events,bytes,counter_reset FROM rateSamples WHERE run=1 AND gdc='gdc1' AND sample_time>=? AND sample_time<=? ORDER BY sample_time`, origin.Add(5*time.Second), origin.Add(15*time.Second)) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + columns, _ := rows.Columns() + values := make([]sql.RawBytes, len(columns)) + ptrs := make([]any, len(columns)) + for i := range ptrs { + ptrs[i] = &values[i] + } + if !rows.Next() { + t.Fatal("missing query plan") + } + if err := rows.Scan(ptrs...); err != nil { + t.Fatal(err) + } + indexed := false + for i, name := range columns { + if name == "key" && string(values[i]) == "PRIMARY" { + indexed = true + } + } + if !indexed { + t.Fatalf("history range read did not use primary key: %q", values) + } +} + +func BenchmarkRateHistoryRebin(b *testing.B) { + origin := historyOrigin() + const samples = 120000 + end := origin.Add(samples * 5 * time.Second) + width := historyBinWidth(origin, origin, end, 1000) + for i := 0; i < b.N; i++ { + bins := newHistoryBins(origin, origin, end, width) + for host := 0; host < 7; host++ { + for j := 0; j < samples; j++ { + previous := historySample{at: origin.Add(time.Duration(j) * 5 * time.Second), events: uint64(j * 100)} + current := historySample{at: previous.at.Add(5 * time.Second), events: uint64((j + 1) * 100)} + addHistoryInterval(bins, previous, current, 15*time.Second, width) + } + } + if len(historyResponseBins(bins, 7)) > 1000 { + b.Fatal(fmt.Errorf("point budget exceeded")) + } + } +} + +func TestRateHistoryDatabaseErrors(t *testing.T) { + for _, tc := range []struct { + name string + failure error + code connect.Code + }{ + {"missing migration", &mysql.MySQLError{Number: 1146, Message: "table missing"}, connect.CodeFailedPrecondition}, + {"deadline", context.DeadlineExceeded, connect.CodeDeadlineExceeded}, + {"canceled", context.Canceled, connect.CodeCanceled}, + } { + t.Run(tc.name, func(t *testing.T) { + db, mock, _ := sqlmock.New() + defer db.Close() + mock.ExpectBegin() + mock.ExpectQuery("SELECT start, stop FROM runs").WithArgs(int32(1)).WillReturnRows(sqlmock.NewRows([]string{"start", "stop"}).AddRow(nil, nil)) + mock.ExpectQuery("SELECT gdc, MIN").WithArgs(int32(1)).WillReturnError(tc.failure) + mock.ExpectRollback() + _, err := (&DuckAPIServer{historyDB: db}).GetRateHistory(context.Background(), connect.NewRequest(&pb.GetRateHistoryRequest{Run: 1})) + if connect.CodeOf(err) != tc.code { + t.Fatalf("wrong error code: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } + }) + } +} + +func TestRateHistoryOptionalZeroOnWire(t *testing.T) { + origin := historyOrigin() + bins := newHistoryBins(origin, origin, origin.Add(5*time.Second), 5*time.Second) + addHistoryInterval(bins, historySample{at: origin, events: 1}, historySample{at: origin.Add(5 * time.Second), events: 1}, 15*time.Second, 5*time.Second) + point := historyResponseBins(bins, 1)[0] + encoded, err := protojson.Marshal(point) + if err != nil { + t.Fatal(err) + } + var wire map[string]any + if err := json.Unmarshal(encoded, &wire); err != nil { + t.Fatal(err) + } + if value, present := wire["triggerRateHz"]; !present || value != float64(0) { + t.Fatalf("zero rate absent from JSON: %s", encoded) + } + point = historyResponseBins(bins, 2)[0] + encoded, err = protojson.Marshal(point) + if err != nil { + t.Fatal(err) + } + wire = make(map[string]any) + if err := json.Unmarshal(encoded, &wire); err != nil { + t.Fatal(err) + } + if _, present := wire["triggerRateHz"]; present { + t.Fatalf("incomplete rate present in JSON: %s", encoded) + } +} diff --git a/database/migrations/20261104_add_rate_samples.sql b/database/migrations/20261104_add_rate_samples.sql new file mode 100644 index 0000000..f238bd8 --- /dev/null +++ b/database/migrations/20261104_add_rate_samples.sql @@ -0,0 +1,14 @@ +CREATE TABLE IF NOT EXISTS rateSamples ( + run INT NOT NULL, + gdc VARCHAR(100) NOT NULL, + sample_time DATETIME(6) NOT NULL COMMENT 'UTC source message timestamp', + events BIGINT UNSIGNED NOT NULL, + bytes BIGINT UNSIGNED NOT NULL, + current_trigger_rate DOUBLE NOT NULL, + current_byte_rate DOUBLE NOT NULL, + avg_trigger_rate DOUBLE NOT NULL, + avg_byte_rate DOUBLE NOT NULL, + counter_reset BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (run, gdc, sample_time), + INDEX rateSamples_run_time (run, sample_time) +) ENGINE=InnoDB; diff --git a/database/queries/rates.sql b/database/queries/rates.sql new file mode 100644 index 0000000..f7a6b01 --- /dev/null +++ b/database/queries/rates.sql @@ -0,0 +1,6 @@ +-- name: InsertRateSample :exec +INSERT INTO rateSamples ( + run, gdc, sample_time, events, bytes, current_trigger_rate, + current_byte_rate, avg_trigger_rate, avg_byte_rate, counter_reset +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +ON DUPLICATE KEY UPDATE sample_time = rateSamples.sample_time; diff --git a/database/schema.sql b/database/schema.sql index 4c0e47e..80e795f 100644 --- a/database/schema.sql +++ b/database/schema.sql @@ -134,3 +134,18 @@ create table topiParams ( control_queue VARCHAR(255) not null default 'topi_daemon_control', selected_configuration VARCHAR(255) not null default '' ); + +CREATE TABLE IF NOT EXISTS rateSamples ( + run INT NOT NULL, + gdc VARCHAR(100) NOT NULL, + sample_time DATETIME(6) NOT NULL COMMENT 'UTC source message timestamp', + events BIGINT UNSIGNED NOT NULL, + bytes BIGINT UNSIGNED NOT NULL, + current_trigger_rate DOUBLE NOT NULL, + current_byte_rate DOUBLE NOT NULL, + avg_trigger_rate DOUBLE NOT NULL, + avg_byte_rate DOUBLE NOT NULL, + counter_reset BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (run, gdc, sample_time), + INDEX rateSamples_run_time (run, sample_time) +) ENGINE=InnoDB; diff --git a/gui/src/gen/api_connect.ts b/gui/src/gen/api_connect.ts index c6bcfa9..dee7537 100644 --- a/gui/src/gen/api_connect.ts +++ b/gui/src/gen/api_connect.ts @@ -3,7 +3,7 @@ /* eslint-disable */ // @ts-nocheck -import { CheckDisabledRequest, CheckDisabledResponse, CreateEquipmentRequest, CreateEquipmentResponse, CreateGDCRequest, CreateGDCResponse, CreateLDCRequest, CreateLDCResponse, DeleteEquipmentRequest, DeleteEquipmentResponse, DeleteGDCRequest, DeleteGDCResponse, DeleteLDCRequest, DeleteLDCResponse, ForceStopRunRequest, ForceStopRunResponse, GetDecoderConfigurationRequest, GetDecoderConfigurationResponse, GetEquipmentRequest, GetEquipmentResponse, GetEquipmentsRequest, GetEquipmentsResponse, GetGDCRequest, GetGDCResponse, GetGDCsRequest, GetGDCsResponse, GetLDCRequest, GetLDCResponse, GetLDCsRequest, GetLDCsResponse, GetProcessStatesRequest, GetProcessStatesResponse, GetRunNumberRequest, GetRunNumberResponse, GetRunTransitionStatusRequest, GetRunTransitionStatusResponse, GetTestDevicesStatesRequest, GetTestDevicesStatesResponse, GetTestDeviceStatisticsRequest, GetTestDeviceStatisticsResponse, GetTokenRequest, GetTokenResponse, GetTopiConfigurationRequest, GetTopiConfigurationResponse, ListTestDevicesRequest, ListTestDevicesResponse, ListTopiConfigurationsRequest, ListTopiConfigurationsResponse, RestartServicesRequest, RestartServicesResponse, StartRunRequest, StartRunResponse, StartTestDevicesRequest, StartTestDevicesResponse, StopRunRequest, StopRunResponse, StopTestDevicesRequest, StopTestDevicesResponse, UpdateDecoderConfigurationRequest, UpdateDecoderConfigurationResponse, UpdateEquipmentRequest, UpdateEquipmentResponse, UpdateGDCRequest, UpdateGDCResponse, UpdateLDCRequest, UpdateLDCResponse, UpdateTopiConfigurationRequest, UpdateTopiConfigurationResponse } from "./api_pb.js"; +import { CheckDisabledRequest, CheckDisabledResponse, CreateEquipmentRequest, CreateEquipmentResponse, CreateGDCRequest, CreateGDCResponse, CreateLDCRequest, CreateLDCResponse, DeleteEquipmentRequest, DeleteEquipmentResponse, DeleteGDCRequest, DeleteGDCResponse, DeleteLDCRequest, DeleteLDCResponse, ForceStopRunRequest, ForceStopRunResponse, GetDecoderConfigurationRequest, GetDecoderConfigurationResponse, GetEquipmentRequest, GetEquipmentResponse, GetEquipmentsRequest, GetEquipmentsResponse, GetGDCRequest, GetGDCResponse, GetGDCsRequest, GetGDCsResponse, GetLDCRequest, GetLDCResponse, GetLDCsRequest, GetLDCsResponse, GetProcessStatesRequest, GetProcessStatesResponse, GetRateHistoryRequest, GetRateHistoryResponse, GetRunNumberRequest, GetRunNumberResponse, GetRunTransitionStatusRequest, GetRunTransitionStatusResponse, GetTestDevicesStatesRequest, GetTestDevicesStatesResponse, GetTestDeviceStatisticsRequest, GetTestDeviceStatisticsResponse, GetTokenRequest, GetTokenResponse, GetTopiConfigurationRequest, GetTopiConfigurationResponse, ListTestDevicesRequest, ListTestDevicesResponse, ListTopiConfigurationsRequest, ListTopiConfigurationsResponse, RestartServicesRequest, RestartServicesResponse, StartRunRequest, StartRunResponse, StartTestDevicesRequest, StartTestDevicesResponse, StopRunRequest, StopRunResponse, StopTestDevicesRequest, StopTestDevicesResponse, UpdateDecoderConfigurationRequest, UpdateDecoderConfigurationResponse, UpdateEquipmentRequest, UpdateEquipmentResponse, UpdateGDCRequest, UpdateGDCResponse, UpdateLDCRequest, UpdateLDCResponse, UpdateTopiConfigurationRequest, UpdateTopiConfigurationResponse } from "./api_pb.js"; import { MethodKind } from "@bufbuild/protobuf"; /** @@ -260,6 +260,17 @@ export const DuckAPI = { O: ListTopiConfigurationsResponse, kind: MethodKind.Unary, }, + /** + * Counter-based, bounded historical detector rates. + * + * @generated from rpc apiService.DuckAPI.GetRateHistory + */ + getRateHistory: { + name: "GetRateHistory", + I: GetRateHistoryRequest, + O: GetRateHistoryResponse, + kind: MethodKind.Unary, + }, /** * Run Information * diff --git a/gui/src/gen/api_pb.ts b/gui/src/gen/api_pb.ts index 06aacae..bdd1c3b 100644 --- a/gui/src/gen/api_pb.ts +++ b/gui/src/gen/api_pb.ts @@ -4,7 +4,7 @@ // @ts-nocheck import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; +import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; /** * @generated from message apiService.SuccessResponse @@ -3609,3 +3609,255 @@ export class GetTestDeviceStatisticsResponse extends Message { + /** + * @generated from field: int32 run = 1; + */ + run = 0; + + /** + * @generated from field: google.protobuf.Timestamp from = 2; + */ + from?: Timestamp; + + /** + * @generated from field: google.protobuf.Timestamp to = 3; + */ + to?: Timestamp; + + /** + * 0 selects 1000. The server accepts 1..2000. + * + * @generated from field: uint32 max_points = 4; + */ + maxPoints = 0; + + /** + * 0 selects 15 seconds, suitable for the default five-second collector. + * Intervals longer than this are gaps, not interpolated measurements. + * + * @generated from field: uint32 max_gap_seconds = 5; + */ + maxGapSeconds = 0; + + constructor(data?: PartialMessage) { + super(); + proto3.util.initPartial(data, this); + } + + static readonly runtime: typeof proto3 = proto3; + static readonly typeName = "apiService.GetRateHistoryRequest"; + static readonly fields: FieldList = proto3.util.newFieldList(() => [ + { no: 1, name: "run", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, + { no: 2, name: "from", kind: "message", T: Timestamp }, + { no: 3, name: "to", kind: "message", T: Timestamp }, + { no: 4, name: "max_points", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, + { no: 5, name: "max_gap_seconds", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, + ]); + + static fromBinary(bytes: Uint8Array, options?: Partial): GetRateHistoryRequest { + return new GetRateHistoryRequest().fromBinary(bytes, options); + } + + static fromJson(jsonValue: JsonValue, options?: Partial): GetRateHistoryRequest { + return new GetRateHistoryRequest().fromJson(jsonValue, options); + } + + static fromJsonString(jsonString: string, options?: Partial): GetRateHistoryRequest { + return new GetRateHistoryRequest().fromJsonString(jsonString, options); + } + + static equals(a: GetRateHistoryRequest | PlainMessage | undefined, b: GetRateHistoryRequest | PlainMessage | undefined): boolean { + return proto3.util.equals(GetRateHistoryRequest, a, b); + } +} + +/** + * @generated from message apiService.RateHistoryBin + */ +export class RateHistoryBin extends Message { + /** + * @generated from field: google.protobuf.Timestamp start = 1; + */ + start?: Timestamp; + + /** + * @generated from field: google.protobuf.Timestamp end = 2; + */ + end?: Timestamp; + + /** + * Present only when the full bin is covered by every recorded GDC. + * + * @generated from field: optional double trigger_rate_hz = 3; + */ + triggerRateHz?: number; + + /** + * @generated from field: optional double byte_rate = 4; + */ + byteRate?: number; + + /** + * Fraction of GDC-time covered, relative to response.gdcs. + * + * @generated from field: double coverage = 5; + */ + coverage = 0; + + /** + * @generated from field: bool complete = 6; + */ + complete = false; + + /** + * Edge bin clipped by the selected window, rather than full bin width. + * + * @generated from field: bool partial = 7; + */ + partial = false; + + constructor(data?: PartialMessage) { + super(); + proto3.util.initPartial(data, this); + } + + static readonly runtime: typeof proto3 = proto3; + static readonly typeName = "apiService.RateHistoryBin"; + static readonly fields: FieldList = proto3.util.newFieldList(() => [ + { no: 1, name: "start", kind: "message", T: Timestamp }, + { no: 2, name: "end", kind: "message", T: Timestamp }, + { no: 3, name: "trigger_rate_hz", kind: "scalar", T: 1 /* ScalarType.DOUBLE */, opt: true }, + { no: 4, name: "byte_rate", kind: "scalar", T: 1 /* ScalarType.DOUBLE */, opt: true }, + { no: 5, name: "coverage", kind: "scalar", T: 1 /* ScalarType.DOUBLE */ }, + { no: 6, name: "complete", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, + { no: 7, name: "partial", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, + ]); + + static fromBinary(bytes: Uint8Array, options?: Partial): RateHistoryBin { + return new RateHistoryBin().fromBinary(bytes, options); + } + + static fromJson(jsonValue: JsonValue, options?: Partial): RateHistoryBin { + return new RateHistoryBin().fromJson(jsonValue, options); + } + + static fromJsonString(jsonString: string, options?: Partial): RateHistoryBin { + return new RateHistoryBin().fromJsonString(jsonString, options); + } + + static equals(a: RateHistoryBin | PlainMessage | undefined, b: RateHistoryBin | PlainMessage | undefined): boolean { + return proto3.util.equals(RateHistoryBin, a, b); + } +} + +/** + * @generated from message apiService.GetRateHistoryResponse + */ +export class GetRateHistoryResponse extends Message { + /** + * @generated from field: int32 run = 1; + */ + run = 0; + + /** + * @generated from field: google.protobuf.Timestamp run_start = 2; + */ + runStart?: Timestamp; + + /** + * @generated from field: google.protobuf.Timestamp run_stop = 3; + */ + runStop?: Timestamp; + + /** + * @generated from field: google.protobuf.Timestamp from = 4; + */ + from?: Timestamp; + + /** + * @generated from field: google.protobuf.Timestamp to = 5; + */ + to?: Timestamp; + + /** + * @generated from field: google.protobuf.Timestamp latest_sample = 6; + */ + latestSample?: Timestamp; + + /** + * @generated from field: uint32 bin_width_seconds = 7; + */ + binWidthSeconds = 0; + + /** + * @generated from field: repeated apiService.RateHistoryBin bins = 8; + */ + bins: RateHistoryBin[] = []; + + /** + * @generated from field: repeated string gdcs = 9; + */ + gdcs: string[] = []; + + /** + * Currently "observed_run_history"; not a configuration snapshot. + * + * @generated from field: string coverage_basis = 10; + */ + coverageBasis = ""; + + /** + * @generated from field: bool has_data = 11; + */ + hasData = false; + + /** + * @generated from field: uint32 max_gap_seconds = 12; + */ + maxGapSeconds = 0; + + constructor(data?: PartialMessage) { + super(); + proto3.util.initPartial(data, this); + } + + static readonly runtime: typeof proto3 = proto3; + static readonly typeName = "apiService.GetRateHistoryResponse"; + static readonly fields: FieldList = proto3.util.newFieldList(() => [ + { no: 1, name: "run", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, + { no: 2, name: "run_start", kind: "message", T: Timestamp }, + { no: 3, name: "run_stop", kind: "message", T: Timestamp }, + { no: 4, name: "from", kind: "message", T: Timestamp }, + { no: 5, name: "to", kind: "message", T: Timestamp }, + { no: 6, name: "latest_sample", kind: "message", T: Timestamp }, + { no: 7, name: "bin_width_seconds", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, + { no: 8, name: "bins", kind: "message", T: RateHistoryBin, repeated: true }, + { no: 9, name: "gdcs", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, + { no: 10, name: "coverage_basis", kind: "scalar", T: 9 /* ScalarType.STRING */ }, + { no: 11, name: "has_data", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, + { no: 12, name: "max_gap_seconds", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, + ]); + + static fromBinary(bytes: Uint8Array, options?: Partial): GetRateHistoryResponse { + return new GetRateHistoryResponse().fromBinary(bytes, options); + } + + static fromJson(jsonValue: JsonValue, options?: Partial): GetRateHistoryResponse { + return new GetRateHistoryResponse().fromJson(jsonValue, options); + } + + static fromJsonString(jsonString: string, options?: Partial): GetRateHistoryResponse { + return new GetRateHistoryResponse().fromJsonString(jsonString, options); + } + + static equals(a: GetRateHistoryResponse | PlainMessage | undefined, b: GetRateHistoryResponse | PlainMessage | undefined): boolean { + return proto3.util.equals(GetRateHistoryResponse, a, b); + } +} + diff --git a/pkg/database/mocks/Querier.go b/pkg/database/mocks/Querier.go index 364450d..bda9f4a 100644 --- a/pkg/database/mocks/Querier.go +++ b/pkg/database/mocks/Querier.go @@ -782,6 +782,24 @@ func (_m *Querier) InsertRate(ctx context.Context, arg database.InsertRateParams return r0 } +// InsertRateSample provides a mock function with given fields: ctx, arg +func (_m *Querier) InsertRateSample(ctx context.Context, arg database.InsertRateSampleParams) error { + ret := _m.Called(ctx, arg) + + if len(ret) == 0 { + panic("no return value specified for InsertRateSample") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, database.InsertRateSampleParams) error); ok { + r0 = rf(ctx, arg) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // ListEquipments provides a mock function with given fields: ctx func (_m *Querier) ListEquipments(ctx context.Context) ([]database.Equipment, error) { ret := _m.Called(ctx) diff --git a/pkg/database/models.go b/pkg/database/models.go index 3e27ae9..cf606f8 100644 --- a/pkg/database/models.go +++ b/pkg/database/models.go @@ -6,6 +6,7 @@ package database import ( "database/sql" + "time" ) type Datum struct { @@ -110,6 +111,20 @@ type Rate struct { Events sql.NullInt64 `db:"events" json:"events"` } +type Ratesample struct { + Run int32 `db:"run" json:"run"` + Gdc string `db:"gdc" json:"gdc"` + // UTC source message timestamp + SampleTime time.Time `db:"sample_time" json:"sample_time"` + Events uint64 `db:"events" json:"events"` + Bytes uint64 `db:"bytes" json:"bytes"` + CurrentTriggerRate float64 `db:"current_trigger_rate" json:"current_trigger_rate"` + CurrentByteRate float64 `db:"current_byte_rate" json:"current_byte_rate"` + AvgTriggerRate float64 `db:"avg_trigger_rate" json:"avg_trigger_rate"` + AvgByteRate float64 `db:"avg_byte_rate" json:"avg_byte_rate"` + CounterReset bool `db:"counter_reset" json:"counter_reset"` +} + type Run struct { ID int32 `db:"id" json:"id"` Start sql.NullTime `db:"start" json:"start"` diff --git a/pkg/database/querier.go b/pkg/database/querier.go index ceda40a..480e833 100644 --- a/pkg/database/querier.go +++ b/pkg/database/querier.go @@ -43,6 +43,7 @@ type Querier interface { InsertLDCEvents(ctx context.Context, arg InsertLDCEventsParams) error InsertNewRun(ctx context.Context) error InsertRate(ctx context.Context, arg InsertRateParams) error + InsertRateSample(ctx context.Context, arg InsertRateSampleParams) error ListEquipments(ctx context.Context) ([]Equipment, error) ListGDCs(ctx context.Context) ([]Gdc, error) ListLDCs(ctx context.Context) ([]Ldc, error) diff --git a/pkg/database/rates.sql.go b/pkg/database/rates.sql.go new file mode 100644 index 0000000..5935124 --- /dev/null +++ b/pkg/database/rates.sql.go @@ -0,0 +1,48 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.30.0 +// source: rates.sql + +package database + +import ( + "context" + "time" +) + +const insertRateSample = `-- name: InsertRateSample :exec +INSERT INTO rateSamples ( + run, gdc, sample_time, events, bytes, current_trigger_rate, + current_byte_rate, avg_trigger_rate, avg_byte_rate, counter_reset +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +ON DUPLICATE KEY UPDATE sample_time = rateSamples.sample_time +` + +type InsertRateSampleParams struct { + Run int32 `db:"run" json:"run"` + Gdc string `db:"gdc" json:"gdc"` + SampleTime time.Time `db:"sample_time" json:"sample_time"` + Events uint64 `db:"events" json:"events"` + Bytes uint64 `db:"bytes" json:"bytes"` + CurrentTriggerRate float64 `db:"current_trigger_rate" json:"current_trigger_rate"` + CurrentByteRate float64 `db:"current_byte_rate" json:"current_byte_rate"` + AvgTriggerRate float64 `db:"avg_trigger_rate" json:"avg_trigger_rate"` + AvgByteRate float64 `db:"avg_byte_rate" json:"avg_byte_rate"` + CounterReset bool `db:"counter_reset" json:"counter_reset"` +} + +func (q *Queries) InsertRateSample(ctx context.Context, arg InsertRateSampleParams) error { + _, err := q.db.ExecContext(ctx, insertRateSample, + arg.Run, + arg.Gdc, + arg.SampleTime, + arg.Events, + arg.Bytes, + arg.CurrentTriggerRate, + arg.CurrentByteRate, + arg.AvgTriggerRate, + arg.AvgByteRate, + arg.CounterReset, + ) + return err +} diff --git a/rateReader/README.md b/rateReader/README.md index 411ff3f..31f37d1 100644 --- a/rateReader/README.md +++ b/rateReader/README.md @@ -1,308 +1,94 @@ -# Rate Reader Service +# Rate history collection -Background service that aggregates metrics from all GDCs and writes rate monitoring data -to the database for real-time display in the web interface. - -## Overview - -The rate reader subscribes to the Centrifuge WebSocket to receive real-time metrics from -all running GDCs, aggregates the data, and periodically writes summary statistics to the -database `rates` table. - -## Architecture - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Rate Reader Service │ -│ │ -│ ┌────────────────────────────────────────────────────┐ │ -│ │ Centrifuge WebSocket Subscriber │ │ -│ │ - Subscribes to "duck" channel │ │ -│ │ - Receives METRICS messages from all GDCs │ │ -│ └───────────────────┬────────────────────────────────┘ │ -│ │ │ -│ v │ -│ ┌────────────────────────────────────────────────────┐ │ -│ │ Metrics Aggregator │ │ -│ │ - Sum total events across all GDCs │ │ -│ │ - Sum total bytes across all GDCs │ │ -│ │ - Calculate combined trigger rate (Hz) │ │ -│ │ - Calculate combined byte rate (MB/s) │ │ -│ └───────────────────┬────────────────────────────────┘ │ -│ │ │ -│ v │ -│ ┌────────────────────────────────────────────────────┐ │ -│ │ Periodic Database Writer │ │ -│ │ - Writes to 'rates' table every N seconds │ │ -│ │ - Configurable period (default: 5 seconds) │ │ -│ └───────────────────┬────────────────────────────────┘ │ -│ │ │ -└──────────────────────┼───────────────────────────────────────┘ - │ - v - ┌────────────────┐ - │ MySQL Database │ - │ rates table │ - └────────────────┘ -``` - -## Usage - -```bash -# Basic usage -./rateReader -config config.yaml - -# With custom update period -./rateReader -config config.yaml -period 10 - -# With verbose logging -./rateReader -config config.yaml -verbose -``` - -### Command-Line Flags - -| Flag | Default | Description | -|------|---------|-------------| -| `-config` | Required | Path to configuration YAML file | -| `-period` | 5 | Update period in seconds | -| `-verbose` | false | Enable verbose logging | - -## Configuration - -### YAML Configuration - -```yaml -dbHost: localhost -dbPort: 3306 -dbUser: root -dbPass: duck -dbName: duck - -centrifugo: - host: localhost - port: 8000 - apiKey: your-api-key - tokenHMACKey: your-hmac-key -``` - -### Environment Variables - -Alternatively, use environment variables: - -```bash -export DB_HOST=localhost -export DB_PORT=3306 -export DB_USER=root -export DB_PASS=duck -export DB_NAME=duck -export CENTRIFUGO_HOST=localhost -export CENTRIFUGO_PORT=8000 -export CENTRIFUGO_API_KEY=your-api-key -``` - -## Database Schema - -The service writes to the `rates` table: - -```sql -CREATE TABLE rates ( - timestamp TIMESTAMP PRIMARY KEY, - totalBytes BIGINT NOT NULL, - totalEvents BIGINT NOT NULL, - byteRate FLOAT NOT NULL, - triggerRate FLOAT NOT NULL -); -``` - -## Metrics Aggregation - -### Message Format - -GDCs publish METRICS messages to Centrifuge: - -```json -{ - "timestamp": 1709727296, - "host": "gdc1next", - "type": "METRICS", - "value": { - "events": 1234, - "bytes": 567890, - "errors": 0, - "avgRate": 12.5, - "currentRate": 13.2, - "avgByteRate": 0.57, - "currentByteRate": 0.61 - }, - "runNumber": 12345 -} -``` - -### Aggregation Logic - -The rate reader: - -1. **Subscribes** to Centrifuge "duck" channel -2. **Filters** METRICS messages from GDCs -3. **Aggregates** data from all GDCs: - - `totalEvents` = sum of all GDC event counts - - `totalBytes` = sum of all GDC byte counts - - `triggerRate` = sum of all GDC current rates - - `byteRate` = sum of all GDC byte rates -4. **Writes** aggregated data to database every N seconds - -## Example Output - -### Database Records - -```sql -SELECT * FROM rates ORDER BY timestamp DESC LIMIT 10; - -+---------------------+------------+-------------+-----------+-------------+ -| timestamp | totalBytes | totalEvents | byteRate | triggerRate | -+---------------------+------------+-------------+-----------+-------------+ -| 2025-03-06 12:34:55 | 125678900 | 245678 | 25.3 | 48.2 | -| 2025-03-06 12:34:50 | 125543200 | 245321 | 24.8 | 47.9 | -| 2025-03-06 12:34:45 | 125407500 | 244965 | 25.1 | 48.1 | -+---------------------+------------+-------------+-----------+-------------+ -``` - -### Log Output (Verbose Mode) - -``` -2025-03-06 12:34:50 [INFO] Connected to Centrifuge at ws://localhost:8000 -2025-03-06 12:34:50 [INFO] Subscribed to channel: duck -2025-03-06 12:34:55 [INFO] Aggregated metrics: events=245678, bytes=125678900 -2025-03-06 12:34:55 [INFO] Wrote rates to database: rate=48.2 Hz, byteRate=25.3 MB/s -``` - -## Monitoring - -The rate reader itself doesn't expose Prometheus metrics, but you can monitor: - -- **Database writes**: Check `rates` table for recent timestamps -- **Centrifuge connection**: Check logs for connection status -- **Update frequency**: Verify timestamps are ~5 seconds apart - -### SQL Queries - -```sql --- Check latest rates -SELECT * FROM rates ORDER BY timestamp DESC LIMIT 1; - --- Get average rate over last hour -SELECT - AVG(triggerRate) as avg_trigger_rate, - AVG(byteRate) as avg_byte_rate -FROM rates -WHERE timestamp > NOW() - INTERVAL 1 HOUR; - --- Get rate history for plotting -SELECT - timestamp, - triggerRate, - byteRate -FROM rates -WHERE timestamp > NOW() - INTERVAL 10 MINUTE -ORDER BY timestamp; -``` - -## Use Cases - -### Real-time Monitoring Dashboard - -The web GUI queries the `rates` table to display: -- Live trigger rate plot -- Data rate plot -- Total event count -- Total data volume - -### Performance Analysis - -```sql --- Peak rates during a run -SELECT MAX(triggerRate), MAX(byteRate) FROM rates -WHERE timestamp BETWEEN '2025-03-06 10:00:00' AND '2025-03-06 11:00:00'; -``` - -### System Health - -```sql --- Check if rate reader is active -SELECT COUNT(*) FROM rates WHERE timestamp > NOW() - INTERVAL 1 MINUTE; --- Should return 12+ rows (5-second intervals) -``` - -## Error Handling - -- **Centrifuge disconnect**: Automatically reconnects with exponential backoff -- **Database write failure**: Logs error and continues (doesn't crash) -- **Missing GDC metrics**: Aggregates available data, logs warning - -## Performance - -- **CPU**: <1% (minimal processing) -- **Memory**: ~10 MB (message buffering) -- **Network**: ~1 KB/s (WebSocket messages) -- **Database**: 1 write every 5 seconds - -## Building - -```bash -# Build binary -go build -o bin/rateReader ./rateReader - -# Or use project build system -task build:rateReader -``` +`rateReader` stores GDC counters and rates in the detector's acquisition database. +It continues updating the existing `rates` run summaries and appends history to +`rateSamples`. No GDC, API or frontend changes are required for collection. ## Deployment -### Docker - -```bash -docker run -d \ - --name rate-reader \ - -e DB_HOST=mysql \ - -e CENTRIFUGO_HOST=centrifugo \ - next-duck/rate-reader:latest \ - -period 5 -verbose -``` - -### Systemd +Apply `database/migrations/20261104_add_rate_samples.sql` to the configured +acquisition schema before starting the new binary. For the current deployments, +these schemas are `duck_v2` for NEXT100, `duck` for DEMO and `duck_v1` for HDDemo. +HDDemo uses one database and one collector for both GDCs. Run only one collector +per detector. The program checks that the history table exists at startup; it +does not automatically modify the production schema. + +Build with `go build -o bin/rateReader ./rateReader`, then use the existing +configuration and `-period 5` (the default). Deploy only the reader; do not restart +acquisition services. This change does not alter TOPI settings. + +## Stored values and timing + +Each history row contains the message's run number, GDC name, UTC timestamp with +microsecond precision, cumulative events/bytes, current trigger/byte rates, +whole-run average trigger/byte rates, and a counter-reset flag. Rates use Hz and +bytes/second. The current rate is preserved exactly as published by the GDC; it +is not recomputed into a five-second interval average. + +The first valid metric for a run/GDC is queued immediately. Later samples are +selected when their source timestamp is at least `-period` seconds after the +previous selected sample. A detected counter decrease forces an immediate +sample with `counter_reset=true`. Thus spacing follows actual incoming metrics, +not fixed wall-clock bins. No messages means no new history rows: missing +telemetry is not represented as zero or as a fresh copy of an old measurement. +GDC metrics without a positive run number or source timestamp, negative values, +and duplicate/out-of-order messages are rejected or ignored. A delayed message +from an older run cannot replace newer run state for that GDC. + +Counters allow a future history API to compute `delta(events)/delta(time)` within +a run/GDC and aggregate time bins. Never difference across a marked reset. +A restart that resets and catches up between messages cannot be detected without +additional source metadata. No historical data is backfilled. + +History writes and run-summary updates share a transaction. Source timestamps +and the `(run, gdc, sample_time)` primary key make retries idempotent. A bounded +in-memory queue retains up to 4096 pending samples across temporary DB failures; +new samples beyond this limit are dropped with an explicit log message. Pending +data is lost if the reader crashes or is killed. SIGINT/SIGTERM attempts a final +flush with a ten-second deadline. The queue is not a durable message broker. + +The reader preserves its existing summary definition: sums of GDC counters and +published run averages, grouped by each message's run. It skips summary updates +when a known member's measurement is older than three sampling periods. History +can still be saved for those source times. GDCs that have never reported are not +inferred to contribute zero; a future plot must evaluate expected-host coverage. + +The additive table can be left in place when rolling back the reader binary. +Keep recorded samples unless their removal is explicitly intended. + +## Single-run plots and indexes + +The first plot will show the aggregate rate across GDCs. Keep per-GDC rows as the +source data so missing hosts, resets and asynchronous sample times remain +visible to the aggregation logic. + +`rateSamples_run_time (run, sample_time)` supports reading one run and an +optional time range without scanning other runs, even after the table grows to +millions of rows. The `(run, gdc, sample_time)` primary key also supports +single-GDC history and idempotent insertion. The intended read shape is: -```ini -[Unit] -Description=NEXT-100 Rate Reader -After=network.target mysql.service - -[Service] -Type=simple -User=next -ExecStart=/opt/next/bin/rateReader -config /opt/next/config/rateReader.yaml -Restart=always -RestartSec=10 - -[Install] -WantedBy=multi-user.target -``` - -## Files - -| File | Purpose | -|------|---------| -| `main.go` | Main service implementation | - -## Dependencies - -- Go 1.24+ -- `github.com/centrifugal/centrifuge-go` - WebSocket client -- `github.com/go-sql-driver/mysql` - MySQL driver -- `pkg/` - Shared packages (config, centrifuge, logging) - -## Related - -- `gdcRPC/` - Publishes METRICS messages -- `api/` - Web API serves rate data -- `gui/` - Displays rate plots -- `database/` - Schema includes rates table +```sql +SELECT gdc, sample_time, events, bytes, current_trigger_rate, + current_byte_rate, avg_trigger_rate, avg_byte_rate, counter_reset +FROM rateSamples +WHERE run = ? AND sample_time >= ? AND sample_time < ? +ORDER BY sample_time; +``` + +A future API should group samples into common time bins, select at most one +current-rate sample per GDC/bin, and sum the selected GDC rates. Do not group by +exact message timestamps: different GDCs publish asynchronously. Return coverage +alongside the total and mark incomplete bins rather than treating absent GDCs +as zero. Counter-derived interval averages must be calculated per GDC before +combining them. Indexing isolates the requested run but does not bound the size +of a very long run; a future API should impose a point budget and aggregate +larger bins, with persisted rollups considered if measurements show a need. + +## Validation + +Run `go test -race ./rateReader ./pkg/database` and `go vet ./rateReader`. +Use `go test ./api -run '^$'` to check compatibility with API database mocks. +For the real MySQL test, set `RATE_READER_TEST_DSN` to an isolated, disposable +schema and run `go test -race ./rateReader -run TestMySQLHistoryAndRunSummaries`. +That test creates and drops `rates` and `rateSamples`; never point it at a +production schema. diff --git a/rateReader/main.go b/rateReader/main.go index 1ccdf34..7672529 100644 --- a/rateReader/main.go +++ b/rateReader/main.go @@ -6,184 +6,241 @@ import ( "encoding/json" "flag" "fmt" + "log" + "math" + "net" + "os" + "os/signal" "strings" + "sync" + "syscall" "time" - _ "github.com/go-sql-driver/mysql" + "github.com/go-sql-driver/mysql" duck "github.com/jmbenlloch/next_duck/pkg" "github.com/jmbenlloch/next_duck/pkg/database" ) -func connectToDatabase(dbConf duck.DatabaseConfiguration) (*sql.DB, error) { - dbURI := fmt.Sprintf("%s:%s@(%s:%s)/%s?parseTime=true", dbConf.Username, - dbConf.Password, dbConf.Hostname, dbConf.Port, dbConf.Database) - db, err := sql.Open("mysql", dbURI) - return db, err -} +const maxPendingSamples = 4096 -var ( - totalBytes int64 - totalEvents int64 - totalByteRate float64 - totalEventRate float64 -) +type sample struct { + run int32 + host string + timestamp time.Time + metric duck.Metrics + reset bool +} -type RunTimestamp struct { - Run int `db:"id"` - Timestamp time.Time `db:"start"` - Bytes int64 `db:"bytes"` - Events int64 `db:"events"` - AvgTriggerRate float64 `db:"avgTriggerRate"` - AvgByteRate float64 `db:"avgByteRate"` +// All mutable subscription state is protected; DB writes use immutable snapshots. +type sampleKey struct { + run int32 + host string } -func getRun(db *sql.DB) (int, error) { - queries := database.New(db) - run, err := queries.GetLatestRun(context.Background()) - return int(run), err +type collector struct { + mu sync.Mutex + period time.Duration + latest map[string]sample + selected map[sampleKey]sample + summaries map[sampleKey]sample + pending []sample } -func writeRateData(db *sql.DB) error { - queries := database.New(db) - ctx := context.Background() +func newCollector(period time.Duration) *collector { + return &collector{period: period, latest: make(map[string]sample), selected: make(map[sampleKey]sample), summaries: make(map[sampleKey]sample)} +} - run, err := getRun(db) - if err != nil { - fmt.Printf("Error getting run: %v\n", err) +func (c *collector) receive(message *duck.Message) error { + if message.Type != duck.MessageMetric || !strings.HasPrefix(message.Host, "gdc") { + return nil + } + if message.RunNumber <= 0 || message.Timestamp.IsZero() { + return fmt.Errorf("GDC metric lacks a valid run or source timestamp") + } + if int64(message.RunNumber) > math.MaxInt32 || len(message.Host) > 100 { + return fmt.Errorf("GDC metric identity exceeds database limits") + } + var metric duck.Metrics + if err := json.Unmarshal([]byte(message.Value), &metric); err != nil { return err } - - timestamp := time.Now() - - // Check if rate record exists for this run - _, err = queries.GetRateByRun(ctx, int32(run)) - if err != nil { - if err == sql.ErrNoRows { - // Insert new rate record - err = queries.InsertRate(ctx, database.InsertRateParams{ - Run: int32(run), - LastUpdate: sql.NullTime{Time: timestamp, Valid: true}, - Bytes: sql.NullInt64{Int64: totalBytes, Valid: true}, - Events: sql.NullInt64{Int64: totalEvents, Valid: true}, - Avgtriggerrate: sql.NullFloat64{Float64: totalEventRate, Valid: true}, - Avgbyterate: sql.NullFloat64{Float64: totalByteRate, Valid: true}, - }) - if err != nil { - fmt.Printf("Error inserting rate data: %v\n", err) - } - } else { - fmt.Printf("Error checking rate data: %v\n", err) + if metric.EventCounter < 0 || metric.ByteCounter < 0 { + return fmt.Errorf("negative GDC counter") + } + for _, rate := range []float64{metric.CurrentTrgRate, metric.CurrentDataRate, metric.AvgTrgRate, metric.AvgDataRate} { + if rate < 0 || math.IsNaN(rate) || math.IsInf(rate, 0) { + return fmt.Errorf("invalid GDC rate") } - return err } - - // Update existing rate record - err = queries.UpdateRate(ctx, database.UpdateRateParams{ - LastUpdate: sql.NullTime{Time: timestamp, Valid: true}, - Bytes: sql.NullInt64{Int64: totalBytes, Valid: true}, - Events: sql.NullInt64{Int64: totalEvents, Valid: true}, - Avgtriggerrate: sql.NullFloat64{Float64: totalEventRate, Valid: true}, - Avgbyterate: sql.NullFloat64{Float64: totalByteRate, Valid: true}, - Run: int32(run), - }) - if err != nil { - fmt.Printf("Error updating rate data: %v\n", err) + s := sample{run: int32(message.RunNumber), host: message.Host, timestamp: message.Timestamp.UTC().Truncate(time.Microsecond), metric: metric} + c.mu.Lock() + defer c.mu.Unlock() + previous, exists := c.latest[s.host] + if exists && (s.run < previous.run || !s.timestamp.After(previous.timestamp)) { + return nil + } + s.reset = exists && s.run == previous.run && (metric.EventCounter < previous.metric.EventCounter || metric.ByteCounter < previous.metric.ByteCounter) + c.latest[s.host] = s + key := sampleKey{s.run, s.host} + c.summaries[key] = s + last, selected := c.selected[key] + if selected && last.run == s.run && !s.reset && s.timestamp.Sub(last.timestamp) < c.period { + return nil } - return err + if len(c.pending) >= maxPendingSamples { + return fmt.Errorf("rate history queue full: dropping new sample for run %d GDC %s", s.run, s.host) + } + c.pending = append(c.pending, s) + c.selected[key] = s + return nil } -func updateDatabase(dbConfiguration duck.DatabaseConfiguration, period int, verbose bool) { - ticker := time.NewTicker(time.Duration(period) * time.Second) - defer ticker.Stop() +func connectToDatabase(conf duck.DatabaseConfiguration) (*sql.DB, error) { + cfg := mysql.NewConfig() + cfg.User, cfg.Passwd = conf.Username, conf.Password + cfg.Net, cfg.Addr, cfg.DBName = "tcp", net.JoinHostPort(conf.Hostname, conf.Port), conf.Database + cfg.ParseTime, cfg.Loc = true, time.UTC + cfg.Params = map[string]string{"time_zone": "'+00:00'"} + cfg.Timeout, cfg.ReadTimeout, cfg.WriteTimeout = 5*time.Second, 5*time.Second, 5*time.Second + return sql.Open("mysql", cfg.FormatDSN()) +} - dbConn, err := connectToDatabase(dbConfiguration) +func (c *collector) flush(ctx context.Context, db *sql.DB) error { + c.mu.Lock() + pending := append([]sample(nil), c.pending...) + latest := make([]sample, 0, len(c.summaries)) + for _, s := range c.summaries { + latest = append(latest, s) + } + c.mu.Unlock() + if len(pending) == 0 { + return nil + } + tx, err := db.BeginTx(ctx, nil) if err != nil { - fmt.Printf("Error connecting to database: %v\n", err) - return + return err } - defer dbConn.Close() - - for range ticker.C { - if verbose { - fmt.Printf("Updating database with totalBytes: %d, totalEvents: %d, totalByteRate: %.2f, totalEventRate: %.2f\n", - totalBytes, totalEvents, totalByteRate, totalEventRate) + defer tx.Rollback() + q := database.New(tx) + for _, s := range pending { + if err := q.InsertRateSample(ctx, database.InsertRateSampleParams{ + Run: s.run, Gdc: s.host, SampleTime: s.timestamp, + Events: uint64(s.metric.EventCounter), Bytes: uint64(s.metric.ByteCounter), + CurrentTriggerRate: s.metric.CurrentTrgRate, CurrentByteRate: s.metric.CurrentDataRate, + AvgTriggerRate: s.metric.AvgTrgRate, AvgByteRate: s.metric.AvgDataRate, CounterReset: s.reset, + }); err != nil { + return err + } + } + // Keep the existing run summaries, grouping hosts by their actual message run. + totals := make(map[int32]sample) + stale := make(map[int32]bool) + now := time.Now() + for _, s := range latest { + if now.Sub(s.timestamp) > 3*c.period { + stale[s.run] = true + } + t := totals[s.run] + if s.timestamp.After(t.timestamp) { + t.timestamp = s.timestamp + } + t.metric.EventCounter += s.metric.EventCounter + t.metric.ByteCounter += s.metric.ByteCounter + t.metric.AvgTrgRate += s.metric.AvgTrgRate + t.metric.AvgDataRate += s.metric.AvgDataRate + totals[s.run] = t + } + for run, t := range totals { + if stale[run] { + continue + } + _, err := q.GetRateByRun(ctx, run) + switch err { + case sql.ErrNoRows: + err = q.InsertRate(ctx, database.InsertRateParams{Run: run, LastUpdate: sql.NullTime{Time: t.timestamp, Valid: true}, Bytes: sql.NullInt64{Int64: int64(t.metric.ByteCounter), Valid: true}, Events: sql.NullInt64{Int64: int64(t.metric.EventCounter), Valid: true}, Avgtriggerrate: sql.NullFloat64{Float64: t.metric.AvgTrgRate, Valid: true}, Avgbyterate: sql.NullFloat64{Float64: t.metric.AvgDataRate, Valid: true}}) + case nil: + err = q.UpdateRate(ctx, database.UpdateRateParams{Run: run, LastUpdate: sql.NullTime{Time: t.timestamp, Valid: true}, Bytes: sql.NullInt64{Int64: int64(t.metric.ByteCounter), Valid: true}, Events: sql.NullInt64{Int64: int64(t.metric.EventCounter), Valid: true}, Avgtriggerrate: sql.NullFloat64{Float64: t.metric.AvgTrgRate, Valid: true}, Avgbyterate: sql.NullFloat64{Float64: t.metric.AvgDataRate, Valid: true}}) } - - // Add database update logic here - err = writeRateData(dbConn) if err != nil { - fmt.Printf("Reconnecting to database due to error: %v\n", err) - dbConn.Close() - dbConn, err = connectToDatabase(dbConfiguration) - if err != nil { - fmt.Printf("Error reconnecting to database: %v\n", err) - } + return err + } + } + if err := tx.Commit(); err != nil { + return err + } + c.mu.Lock() + c.pending = c.pending[len(pending):] + // Retire completed runs only after their final queued samples were committed. + activeRuns := make(map[int32]bool) + for _, s := range c.latest { + activeRuns[s.run] = true + } + for _, s := range c.pending { + activeRuns[s.run] = true + } + for key := range c.summaries { + if !activeRuns[key.run] { + delete(c.summaries, key) + delete(c.selected, key) } } + c.mu.Unlock() + return nil } func main() { configFilename := flag.String("config", "", "Configuration file path") - period := flag.Int("period", 5, "Period to update database in seconds") + period := flag.Int("period", 5, "Minimum source-time spacing between stored GDC samples, in seconds") verbose := flag.Bool("verbose", false, "Verbose output") flag.Parse() - + if *period <= 0 { + log.Fatal("period must be positive") + } configuration, err := duck.ReadConfigurationFile(*configFilename) if err != nil { - panic(err) + log.Fatal(err) } - - bytes := make(map[string]int64) - events := make(map[string]int64) - byteRate := make(map[string]float64) - eventRate := make(map[string]float64) - - userCentrifugal := "rateReader" - fn := func(message *duck.Message) { - if message.Type == duck.MessageMetric { - var metric duck.Metrics - err := json.Unmarshal([]byte(message.Value), &metric) - if err != nil { - fmt.Printf("Error unmarshalling message value: %v\n", err) - return - } - - // Use only GDC data - if !strings.HasPrefix(message.Host, "gdc") { - return - } - - bytes[message.Host] = int64(metric.ByteCounter) - events[message.Host] = int64(metric.EventCounter) - byteRate[message.Host] = metric.AvgDataRate - eventRate[message.Host] = metric.AvgTrgRate - - // Update total counters - totalBytes = 0 - for _, v := range bytes { - totalBytes += v - } - - totalEvents = 0 - for _, v := range events { - totalEvents += v - } - - totalByteRate = 0 - for _, v := range byteRate { - totalByteRate += v - } - - totalEventRate = 0 - for _, v := range eventRate { - totalEventRate += v - } - } + db, err := connectToDatabase(configuration.Database) + if err != nil { + log.Fatal(err) } - _, err = duck.CreateNewSubscriptionWithFnReadout(configuration.Centrifugal, userCentrifugal, fn) + defer db.Close() + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := db.PingContext(ctx); err != nil { + log.Fatal(err) + } + // Fail before subscribing if the additive history migration has not been applied. + if _, err := db.ExecContext(ctx, "SELECT run FROM rateSamples LIMIT 0"); err != nil { + log.Fatalf("rateSamples unavailable; apply database/migrations/20261104_add_rate_samples.sql: %v", err) + } + c := newCollector(time.Duration(*period) * time.Second) + _, err = duck.CreateNewSubscriptionWithFnReadout(configuration.Centrifugal, "rateReader", func(m *duck.Message) { + if err := c.receive(m); err != nil { + log.Printf("metric rejected: %v", err) + } + }) if err != nil { - panic(err) + log.Fatal(err) + } + ticker := time.NewTicker(c.period) + defer ticker.Stop() + flush := func() { + writeCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := c.flush(writeCtx, db); err != nil { + log.Printf("database write failed; retaining samples for retry: %v", err) + } else if *verbose { + log.Print("rate samples flushed") + } + } + for { + select { + case <-ticker.C: + flush() + case <-ctx.Done(): + flush() + return + } } - - updateDatabase(configuration.Database, *period, *verbose) } diff --git a/rateReader/main_test.go b/rateReader/main_test.go new file mode 100644 index 0000000..949d6ad --- /dev/null +++ b/rateReader/main_test.go @@ -0,0 +1,255 @@ +package main + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "os" + "sync" + "testing" + "time" + + "github.com/DATA-DOG/go-sqlmock" + duck "github.com/jmbenlloch/next_duck/pkg" +) + +func metricMessage(run int, host string, at time.Time, events int) *duck.Message { + data, _ := json.Marshal(duck.Metrics{EventCounter: events, ByteCounter: events * 100, CurrentTrgRate: 12, CurrentDataRate: 1200, AvgTrgRate: 10, AvgDataRate: 1000}) + return &duck.Message{Type: duck.MessageMetric, RunNumber: run, Host: host, Timestamp: at, Value: string(data)} +} + +func TestSamplingRunTransitionsAndReset(t *testing.T) { + c := newCollector(5 * time.Second) + at := time.Now().UTC().Truncate(time.Microsecond) + for _, m := range []*duck.Message{ + metricMessage(10, "gdc1", at, 100), + metricMessage(10, "gdc1", at.Add(time.Second), 110), // below sampling period + metricMessage(10, "gdc1", at, 100), // duplicate + metricMessage(10, "gdc1", at.Add(5*time.Second), 150), + metricMessage(10, "gdc1", at.Add(6*time.Second), 2), // reset must be captured immediately + metricMessage(11, "gdc1", at.Add(7*time.Second), 1), // new run does not wait five seconds + metricMessage(10, "gdc1", at.Add(8*time.Second), 200), // delayed old run + } { + if err := c.receive(m); err != nil { + t.Fatal(err) + } + } + if len(c.pending) != 4 { + t.Fatalf("samples: %+v", c.pending) + } + if !c.pending[2].reset || c.pending[3].reset { + t.Fatal("incorrect reset flags") + } + if c.pending[3].run != 11 { + t.Fatal("run attribution lost") + } + if c.pending[0].metric.CurrentTrgRate != 12 || c.pending[0].metric.CurrentDataRate != 1200 { + t.Fatal("current values lost") + } + if !c.pending[0].timestamp.Equal(at) { + t.Fatal("source timestamp lost") + } + if len(c.summaries) != 2 { + t.Fatal("previous run summary lost before flush") + } +} + +func TestMissingInvalidAndNonGDCMetrics(t *testing.T) { + at := time.Now() + for _, alter := range []func(*duck.Message){ + func(m *duck.Message) { m.RunNumber = 0 }, + func(m *duck.Message) { m.Timestamp = time.Time{} }, + func(m *duck.Message) { m.Value = `{"EventCounter":-1}` }, + func(m *duck.Message) { m.Value = `{"CurrentTrgRate":-1}` }, + func(m *duck.Message) { m.Value = `broken` }, + } { + c := newCollector(5 * time.Second) + m := metricMessage(1, "gdc1", at, 10) + alter(m) + if c.receive(m) == nil || len(c.pending) != 0 { + t.Fatal("accepted invalid metric") + } + } + c := newCollector(5 * time.Second) + if err := c.receive(metricMessage(1, "ldc1", at, 10)); err != nil || len(c.pending) != 0 { + t.Fatal("accepted LDC metric") + } +} + +func TestQueueBoundAndConcurrentSnapshots(t *testing.T) { + c := newCollector(time.Microsecond) + at := time.Now() + db, mock, err := sqlmock.New() + if err != nil { + t.Fatal(err) + } + defer db.Close() + for i := 0; i < 100; i++ { + mock.ExpectBegin().WillReturnError(fmt.Errorf("offline")) + } + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + _ = c.flush(context.Background(), db) + } + }() + for host := 0; host < 4; host++ { + wg.Add(1) + go func(host int) { + defer wg.Done() + for i := 0; i < 1100; i++ { + _ = c.receive(metricMessage(1, fmt.Sprintf("gdc%d", host), at.Add(time.Duration(i)*time.Millisecond), i)) + } + }(host) + } + wg.Wait() + if len(c.pending) != maxPendingSamples { + t.Fatalf("unbounded queue: %d", len(c.pending)) + } + if err := c.receive(metricMessage(1, "gdc-extra", at, 1)); err == nil { + t.Fatal("overflow must be reported") + } +} + +func expectHistory(mock sqlmock.Sqlmock) { + mock.ExpectExec("INSERT INTO rateSamples").WithArgs(int32(10), "gdc1", sqlmock.AnyArg(), uint64(100), uint64(10000), float64(12), float64(1200), float64(10), float64(1000), false).WillReturnResult(sqlmock.NewResult(0, 1)) +} + +func TestFlushRetryAndSummary(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatal(err) + } + defer db.Close() + c := newCollector(5 * time.Second) + if err := c.receive(metricMessage(10, "gdc1", time.Now(), 100)); err != nil { + t.Fatal(err) + } + mock.ExpectBegin() + mock.ExpectExec("INSERT INTO rateSamples").WillReturnError(fmt.Errorf("temporary database failure")) + mock.ExpectRollback() + if c.flush(context.Background(), db) == nil || len(c.pending) != 1 { + t.Fatal("failure discarded sample") + } + mock.ExpectBegin() + expectHistory(mock) + mock.ExpectQuery("SELECT run FROM rates").WithArgs(int32(10)).WillReturnRows(sqlmock.NewRows([]string{"run"})) + mock.ExpectExec("INSERT INTO rates").WithArgs(int32(10), sqlmock.AnyArg(), int64(10000), int64(100), float64(10), float64(1000)).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + if err := c.flush(context.Background(), db); err != nil { + t.Fatal(err) + } + if len(c.pending) != 0 { + t.Fatal("committed samples retained") + } + // No incoming metrics: do not create fresh-looking samples or rewrite summaries. + if err := c.flush(context.Background(), db); err != nil { + t.Fatal(err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} + +func TestStaleMetricHistoryDoesNotRewriteSummary(t *testing.T) { + db, mock, _ := sqlmock.New() + defer db.Close() + c := newCollector(5 * time.Second) + _ = c.receive(metricMessage(10, "gdc1", time.Now().Add(-time.Minute), 100)) + mock.ExpectBegin() + expectHistory(mock) + mock.ExpectCommit() + if err := c.flush(context.Background(), db); err != nil { + t.Fatal(err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} + +// Set RATE_READER_TEST_DSN to an isolated, disposable MySQL database. +func TestMySQLHistoryAndRunSummaries(t *testing.T) { + dsn := os.Getenv("RATE_READER_TEST_DSN") + if dsn == "" { + t.Skip("RATE_READER_TEST_DSN not set") + } + db, err := sql.Open("mysql", dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + ctx := context.Background() + migration, err := os.ReadFile("../database/migrations/20261104_add_rate_samples.sql") + if err != nil { + t.Fatal(err) + } + if _, err = db.Exec(string(migration)); err != nil { + t.Fatal(err) + } + if _, err = db.Exec(string(migration)); err != nil { + t.Fatalf("migration not idempotent: %v", err) + } + if _, err = db.Exec(`CREATE TABLE rates (run INT NOT NULL, last_update TIMESTAMP NULL, avgByteRate FLOAT NULL, avgTriggerRate FLOAT NULL, bytes BIGINT UNSIGNED NULL, events BIGINT UNSIGNED NULL)`); err != nil { + t.Fatal(err) + } + defer db.Exec("DROP TABLE rates, rateSamples") + at := time.Now().UTC().Truncate(time.Microsecond) + c := newCollector(5 * time.Second) + _ = c.receive(metricMessage(10, "gdc1", at, 100)) + _ = c.receive(metricMessage(10, "gdc2", at, 200)) + duplicate := c.pending[0] + if err := c.flush(ctx, db); err != nil { + t.Fatal(err) + } + c.pending = append(c.pending, duplicate) // model uncertain-commit retry + if err := c.flush(ctx, db); err != nil { + t.Fatal(err) + } + // A run/time index must exist in both the migration and fresh-schema path. + var indexedColumns string + if err := db.QueryRow(`SELECT GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX) FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='rateSamples' AND index_name='rateSamples_run_time'`).Scan(&indexedColumns); err != nil || indexedColumns != "run,sample_time" { + t.Fatalf("missing run/time index: %q %v", indexedColumns, err) + } + var count int + if err := db.QueryRow("SELECT COUNT(*) FROM rateSamples WHERE run=10").Scan(&count); err != nil || count != 2 { + t.Fatalf("duplicate history rows: %d %v", count, err) + } + _ = c.receive(metricMessage(11, "gdc1", at.Add(time.Second), 5)) + if err := c.flush(ctx, db); err != nil { + t.Fatal(err) + } + var events int + if err := db.QueryRow("SELECT events FROM rates WHERE run=10").Scan(&events); err != nil || events != 300 { + t.Fatalf("old run summary corrupted: %d %v", events, err) + } + if err := db.QueryRow("SELECT events FROM rates WHERE run=11").Scan(&events); err != nil || events != 5 { + t.Fatalf("new run summary wrong: %d %v", events, err) + } + var currentRate, avgRate float64 + var timestamp time.Time + if err := db.QueryRow("SELECT sample_time,current_trigger_rate,avg_trigger_rate FROM rateSamples WHERE run=10 AND gdc='gdc1'").Scan(×tamp, ¤tRate, &avgRate); err != nil { + t.Fatal(err) + } + if !timestamp.Equal(at) || currentRate != 12 || avgRate != 10 { + t.Fatalf("stored values differ: %v %v %v", timestamp, currentRate, avgRate) + } +} + +func TestCommitFailureRetainsSamples(t *testing.T) { + db, mock, _ := sqlmock.New() + defer db.Close() + c := newCollector(5 * time.Second) + _ = c.receive(metricMessage(10, "gdc1", time.Now().Add(-time.Minute), 100)) + mock.ExpectBegin() + expectHistory(mock) + mock.ExpectCommit().WillReturnError(fmt.Errorf("connection lost during commit")) + if c.flush(context.Background(), db) == nil || len(c.pending) != 1 { + t.Fatal("uncertain commit lost sample") + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} diff --git a/rpc/api/api.pb.go b/rpc/api/api.pb.go index dda6b82..6a5f683 100644 --- a/rpc/api/api.pb.go +++ b/rpc/api/api.pb.go @@ -9,6 +9,7 @@ package api import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" unsafe "unsafe" @@ -4407,12 +4408,320 @@ func (x *GetTestDeviceStatisticsResponse) GetStatistics() *TestDeviceStatistics return nil } +// Omit from/to for the full recorded run. Explicit bounds support browser zoom. +type GetRateHistoryRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Run int32 `protobuf:"varint,1,opt,name=run,proto3" json:"run,omitempty"` + From *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=from,proto3" json:"from,omitempty"` + To *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=to,proto3" json:"to,omitempty"` + // 0 selects 1000. The server accepts 1..2000. + MaxPoints uint32 `protobuf:"varint,4,opt,name=max_points,json=maxPoints,proto3" json:"max_points,omitempty"` + // 0 selects 15 seconds, suitable for the default five-second collector. + // Intervals longer than this are gaps, not interpolated measurements. + MaxGapSeconds uint32 `protobuf:"varint,5,opt,name=max_gap_seconds,json=maxGapSeconds,proto3" json:"max_gap_seconds,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetRateHistoryRequest) Reset() { + *x = GetRateHistoryRequest{} + mi := &file_api_proto_msgTypes[78] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetRateHistoryRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetRateHistoryRequest) ProtoMessage() {} + +func (x *GetRateHistoryRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_proto_msgTypes[78] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetRateHistoryRequest.ProtoReflect.Descriptor instead. +func (*GetRateHistoryRequest) Descriptor() ([]byte, []int) { + return file_api_proto_rawDescGZIP(), []int{78} +} + +func (x *GetRateHistoryRequest) GetRun() int32 { + if x != nil { + return x.Run + } + return 0 +} + +func (x *GetRateHistoryRequest) GetFrom() *timestamppb.Timestamp { + if x != nil { + return x.From + } + return nil +} + +func (x *GetRateHistoryRequest) GetTo() *timestamppb.Timestamp { + if x != nil { + return x.To + } + return nil +} + +func (x *GetRateHistoryRequest) GetMaxPoints() uint32 { + if x != nil { + return x.MaxPoints + } + return 0 +} + +func (x *GetRateHistoryRequest) GetMaxGapSeconds() uint32 { + if x != nil { + return x.MaxGapSeconds + } + return 0 +} + +type RateHistoryBin struct { + state protoimpl.MessageState `protogen:"open.v1"` + Start *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=start,proto3" json:"start,omitempty"` + End *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=end,proto3" json:"end,omitempty"` + // Present only when the full bin is covered by every recorded GDC. + TriggerRateHz *float64 `protobuf:"fixed64,3,opt,name=trigger_rate_hz,json=triggerRateHz,proto3,oneof" json:"trigger_rate_hz,omitempty"` + ByteRate *float64 `protobuf:"fixed64,4,opt,name=byte_rate,json=byteRate,proto3,oneof" json:"byte_rate,omitempty"` + // Fraction of GDC-time covered, relative to response.gdcs. + Coverage float64 `protobuf:"fixed64,5,opt,name=coverage,proto3" json:"coverage,omitempty"` + Complete bool `protobuf:"varint,6,opt,name=complete,proto3" json:"complete,omitempty"` + // Edge bin clipped by the selected window, rather than full bin width. + Partial bool `protobuf:"varint,7,opt,name=partial,proto3" json:"partial,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RateHistoryBin) Reset() { + *x = RateHistoryBin{} + mi := &file_api_proto_msgTypes[79] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RateHistoryBin) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RateHistoryBin) ProtoMessage() {} + +func (x *RateHistoryBin) ProtoReflect() protoreflect.Message { + mi := &file_api_proto_msgTypes[79] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RateHistoryBin.ProtoReflect.Descriptor instead. +func (*RateHistoryBin) Descriptor() ([]byte, []int) { + return file_api_proto_rawDescGZIP(), []int{79} +} + +func (x *RateHistoryBin) GetStart() *timestamppb.Timestamp { + if x != nil { + return x.Start + } + return nil +} + +func (x *RateHistoryBin) GetEnd() *timestamppb.Timestamp { + if x != nil { + return x.End + } + return nil +} + +func (x *RateHistoryBin) GetTriggerRateHz() float64 { + if x != nil && x.TriggerRateHz != nil { + return *x.TriggerRateHz + } + return 0 +} + +func (x *RateHistoryBin) GetByteRate() float64 { + if x != nil && x.ByteRate != nil { + return *x.ByteRate + } + return 0 +} + +func (x *RateHistoryBin) GetCoverage() float64 { + if x != nil { + return x.Coverage + } + return 0 +} + +func (x *RateHistoryBin) GetComplete() bool { + if x != nil { + return x.Complete + } + return false +} + +func (x *RateHistoryBin) GetPartial() bool { + if x != nil { + return x.Partial + } + return false +} + +type GetRateHistoryResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Run int32 `protobuf:"varint,1,opt,name=run,proto3" json:"run,omitempty"` + RunStart *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=run_start,json=runStart,proto3" json:"run_start,omitempty"` + RunStop *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=run_stop,json=runStop,proto3" json:"run_stop,omitempty"` + From *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=from,proto3" json:"from,omitempty"` + To *timestamppb.Timestamp `protobuf:"bytes,5,opt,name=to,proto3" json:"to,omitempty"` + LatestSample *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=latest_sample,json=latestSample,proto3" json:"latest_sample,omitempty"` + BinWidthSeconds uint32 `protobuf:"varint,7,opt,name=bin_width_seconds,json=binWidthSeconds,proto3" json:"bin_width_seconds,omitempty"` + Bins []*RateHistoryBin `protobuf:"bytes,8,rep,name=bins,proto3" json:"bins,omitempty"` + Gdcs []string `protobuf:"bytes,9,rep,name=gdcs,proto3" json:"gdcs,omitempty"` + // Currently "observed_run_history"; not a configuration snapshot. + CoverageBasis string `protobuf:"bytes,10,opt,name=coverage_basis,json=coverageBasis,proto3" json:"coverage_basis,omitempty"` + HasData bool `protobuf:"varint,11,opt,name=has_data,json=hasData,proto3" json:"has_data,omitempty"` + MaxGapSeconds uint32 `protobuf:"varint,12,opt,name=max_gap_seconds,json=maxGapSeconds,proto3" json:"max_gap_seconds,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetRateHistoryResponse) Reset() { + *x = GetRateHistoryResponse{} + mi := &file_api_proto_msgTypes[80] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetRateHistoryResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetRateHistoryResponse) ProtoMessage() {} + +func (x *GetRateHistoryResponse) ProtoReflect() protoreflect.Message { + mi := &file_api_proto_msgTypes[80] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetRateHistoryResponse.ProtoReflect.Descriptor instead. +func (*GetRateHistoryResponse) Descriptor() ([]byte, []int) { + return file_api_proto_rawDescGZIP(), []int{80} +} + +func (x *GetRateHistoryResponse) GetRun() int32 { + if x != nil { + return x.Run + } + return 0 +} + +func (x *GetRateHistoryResponse) GetRunStart() *timestamppb.Timestamp { + if x != nil { + return x.RunStart + } + return nil +} + +func (x *GetRateHistoryResponse) GetRunStop() *timestamppb.Timestamp { + if x != nil { + return x.RunStop + } + return nil +} + +func (x *GetRateHistoryResponse) GetFrom() *timestamppb.Timestamp { + if x != nil { + return x.From + } + return nil +} + +func (x *GetRateHistoryResponse) GetTo() *timestamppb.Timestamp { + if x != nil { + return x.To + } + return nil +} + +func (x *GetRateHistoryResponse) GetLatestSample() *timestamppb.Timestamp { + if x != nil { + return x.LatestSample + } + return nil +} + +func (x *GetRateHistoryResponse) GetBinWidthSeconds() uint32 { + if x != nil { + return x.BinWidthSeconds + } + return 0 +} + +func (x *GetRateHistoryResponse) GetBins() []*RateHistoryBin { + if x != nil { + return x.Bins + } + return nil +} + +func (x *GetRateHistoryResponse) GetGdcs() []string { + if x != nil { + return x.Gdcs + } + return nil +} + +func (x *GetRateHistoryResponse) GetCoverageBasis() string { + if x != nil { + return x.CoverageBasis + } + return "" +} + +func (x *GetRateHistoryResponse) GetHasData() bool { + if x != nil { + return x.HasData + } + return false +} + +func (x *GetRateHistoryResponse) GetMaxGapSeconds() uint32 { + if x != nil { + return x.MaxGapSeconds + } + return 0 +} + var File_api_proto protoreflect.FileDescriptor const file_api_proto_rawDesc = "" + "\n" + "\tapi.proto\x12\n" + - "apiService\"[\n" + + "apiService\x1a\x1fgoogle/protobuf/timestamp.proto\"[\n" + "\x0fSuccessResponse\x12\x18\n" + "\asuccess\x18\x01 \x01(\bR\asuccess\x12\x18\n" + "\amessage\x18\x02 \x01(\tR\amessage\x12\x14\n" + @@ -4722,7 +5031,39 @@ const file_api_proto_rawDesc = "" + "\x1fGetTestDeviceStatisticsResponse\x12@\n" + "\n" + "statistics\x18\x01 \x01(\v2 .apiService.TestDeviceStatisticsR\n" + - "statistics2\x81\x18\n" + + "statistics\"\xcc\x01\n" + + "\x15GetRateHistoryRequest\x12\x10\n" + + "\x03run\x18\x01 \x01(\x05R\x03run\x12.\n" + + "\x04from\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x04from\x12*\n" + + "\x02to\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\x02to\x12\x1d\n" + + "\n" + + "max_points\x18\x04 \x01(\rR\tmaxPoints\x12&\n" + + "\x0fmax_gap_seconds\x18\x05 \x01(\rR\rmaxGapSeconds\"\xb3\x02\n" + + "\x0eRateHistoryBin\x120\n" + + "\x05start\x18\x01 \x01(\v2\x1a.google.protobuf.TimestampR\x05start\x12,\n" + + "\x03end\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x03end\x12+\n" + + "\x0ftrigger_rate_hz\x18\x03 \x01(\x01H\x00R\rtriggerRateHz\x88\x01\x01\x12 \n" + + "\tbyte_rate\x18\x04 \x01(\x01H\x01R\bbyteRate\x88\x01\x01\x12\x1a\n" + + "\bcoverage\x18\x05 \x01(\x01R\bcoverage\x12\x1a\n" + + "\bcomplete\x18\x06 \x01(\bR\bcomplete\x12\x18\n" + + "\apartial\x18\a \x01(\bR\apartialB\x12\n" + + "\x10_trigger_rate_hzB\f\n" + + "\n" + + "_byte_rate\"\x91\x04\n" + + "\x16GetRateHistoryResponse\x12\x10\n" + + "\x03run\x18\x01 \x01(\x05R\x03run\x127\n" + + "\trun_start\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\brunStart\x125\n" + + "\brun_stop\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\arunStop\x12.\n" + + "\x04from\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\x04from\x12*\n" + + "\x02to\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\x02to\x12?\n" + + "\rlatest_sample\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\flatestSample\x12*\n" + + "\x11bin_width_seconds\x18\a \x01(\rR\x0fbinWidthSeconds\x12.\n" + + "\x04bins\x18\b \x03(\v2\x1a.apiService.RateHistoryBinR\x04bins\x12\x12\n" + + "\x04gdcs\x18\t \x03(\tR\x04gdcs\x12%\n" + + "\x0ecoverage_basis\x18\n" + + " \x01(\tR\rcoverageBasis\x12\x19\n" + + "\bhas_data\x18\v \x01(\bR\ahasData\x12&\n" + + "\x0fmax_gap_seconds\x18\f \x01(\rR\rmaxGapSeconds2\xdc\x18\n" + "\aDuckAPI\x12G\n" + "\bStartRun\x12\x1b.apiService.StartRunRequest\x1a\x1c.apiService.StartRunResponse\"\x00\x12D\n" + "\aStopRun\x12\x1a.apiService.StopRunRequest\x1a\x1b.apiService.StopRunResponse\"\x00\x12S\n" + @@ -4749,7 +5090,8 @@ const file_api_proto_rawDesc = "" + "\x1aUpdateDecoderConfiguration\x12-.apiService.UpdateDecoderConfigurationRequest\x1a..apiService.UpdateDecoderConfigurationResponse\"\x00\x12k\n" + "\x14GetTopiConfiguration\x12'.apiService.GetTopiConfigurationRequest\x1a(.apiService.GetTopiConfigurationResponse\"\x00\x12t\n" + "\x17UpdateTopiConfiguration\x12*.apiService.UpdateTopiConfigurationRequest\x1a+.apiService.UpdateTopiConfigurationResponse\"\x00\x12q\n" + - "\x16ListTopiConfigurations\x12).apiService.ListTopiConfigurationsRequest\x1a*.apiService.ListTopiConfigurationsResponse\"\x00\x12S\n" + + "\x16ListTopiConfigurations\x12).apiService.ListTopiConfigurationsRequest\x1a*.apiService.ListTopiConfigurationsResponse\"\x00\x12Y\n" + + "\x0eGetRateHistory\x12!.apiService.GetRateHistoryRequest\x1a\".apiService.GetRateHistoryResponse\"\x00\x12S\n" + "\fGetRunNumber\x12\x1f.apiService.GetRunNumberRequest\x1a .apiService.GetRunNumberResponse\"\x00\x12V\n" + "\rCheckDisabled\x12 .apiService.CheckDisabledRequest\x1a!.apiService.CheckDisabledResponse\"\x00\x12G\n" + "\bGetToken\x12\x1b.apiService.GetTokenRequest\x1a\x1c.apiService.GetTokenResponse\"\x00\x12_\n" + @@ -4771,7 +5113,7 @@ func file_api_proto_rawDescGZIP() []byte { return file_api_proto_rawDescData } -var file_api_proto_msgTypes = make([]protoimpl.MessageInfo, 79) +var file_api_proto_msgTypes = make([]protoimpl.MessageInfo, 82) var file_api_proto_goTypes = []any{ (*SuccessResponse)(nil), // 0: apiService.SuccessResponse (*StartRunRequest)(nil), // 1: apiService.StartRunRequest @@ -4851,7 +5193,11 @@ var file_api_proto_goTypes = []any{ (*ListTestDevicesResponse)(nil), // 75: apiService.ListTestDevicesResponse (*GetTestDeviceStatisticsRequest)(nil), // 76: apiService.GetTestDeviceStatisticsRequest (*GetTestDeviceStatisticsResponse)(nil), // 77: apiService.GetTestDeviceStatisticsResponse - nil, // 78: apiService.GetTestDevicesStatesResponse.StatesEntry + (*GetRateHistoryRequest)(nil), // 78: apiService.GetRateHistoryRequest + (*RateHistoryBin)(nil), // 79: apiService.RateHistoryBin + (*GetRateHistoryResponse)(nil), // 80: apiService.GetRateHistoryResponse + nil, // 81: apiService.GetTestDevicesStatesResponse.StatesEntry + (*timestamppb.Timestamp)(nil), // 82: google.protobuf.Timestamp } var file_api_proto_depIdxs = []int32{ 13, // 0: apiService.GetGDCsResponse.gdcs:type_name -> apiService.GDC @@ -4867,82 +5213,94 @@ var file_api_proto_depIdxs = []int32{ 51, // 10: apiService.UpdateTopiConfigurationRequest.configuration:type_name -> apiService.TopiConfiguration 56, // 11: apiService.ListTopiConfigurationsResponse.configurations:type_name -> apiService.TopiAvailableConfiguration 61, // 12: apiService.CheckDisabledResponse.warnings:type_name -> apiService.DisabledWarning - 78, // 13: apiService.GetTestDevicesStatesResponse.states:type_name -> apiService.GetTestDevicesStatesResponse.StatesEntry + 81, // 13: apiService.GetTestDevicesStatesResponse.states:type_name -> apiService.GetTestDevicesStatesResponse.StatesEntry 66, // 14: apiService.ListTestDevicesResponse.devices:type_name -> apiService.TestDevice 67, // 15: apiService.GetTestDeviceStatisticsResponse.statistics:type_name -> apiService.TestDeviceStatistics - 1, // 16: apiService.DuckAPI.StartRun:input_type -> apiService.StartRunRequest - 3, // 17: apiService.DuckAPI.StopRun:input_type -> apiService.StopRunRequest - 5, // 18: apiService.DuckAPI.ForceStopRun:input_type -> apiService.ForceStopRunRequest - 7, // 19: apiService.DuckAPI.GetProcessStates:input_type -> apiService.GetProcessStatesRequest - 9, // 20: apiService.DuckAPI.RestartServices:input_type -> apiService.RestartServicesRequest - 11, // 21: apiService.DuckAPI.GetRunTransitionStatus:input_type -> apiService.GetRunTransitionStatusRequest - 14, // 22: apiService.DuckAPI.CreateGDC:input_type -> apiService.CreateGDCRequest - 16, // 23: apiService.DuckAPI.GetGDCs:input_type -> apiService.GetGDCsRequest - 18, // 24: apiService.DuckAPI.GetGDC:input_type -> apiService.GetGDCRequest - 20, // 25: apiService.DuckAPI.UpdateGDC:input_type -> apiService.UpdateGDCRequest - 22, // 26: apiService.DuckAPI.DeleteGDC:input_type -> apiService.DeleteGDCRequest - 26, // 27: apiService.DuckAPI.CreateLDC:input_type -> apiService.CreateLDCRequest - 28, // 28: apiService.DuckAPI.GetLDCs:input_type -> apiService.GetLDCsRequest - 30, // 29: apiService.DuckAPI.GetLDC:input_type -> apiService.GetLDCRequest - 32, // 30: apiService.DuckAPI.UpdateLDC:input_type -> apiService.UpdateLDCRequest - 34, // 31: apiService.DuckAPI.DeleteLDC:input_type -> apiService.DeleteLDCRequest - 36, // 32: apiService.DuckAPI.CreateEquipment:input_type -> apiService.CreateEquipmentRequest - 38, // 33: apiService.DuckAPI.GetEquipments:input_type -> apiService.GetEquipmentsRequest - 40, // 34: apiService.DuckAPI.GetEquipment:input_type -> apiService.GetEquipmentRequest - 42, // 35: apiService.DuckAPI.UpdateEquipment:input_type -> apiService.UpdateEquipmentRequest - 44, // 36: apiService.DuckAPI.DeleteEquipment:input_type -> apiService.DeleteEquipmentRequest - 47, // 37: apiService.DuckAPI.GetDecoderConfiguration:input_type -> apiService.GetDecoderConfigurationRequest - 49, // 38: apiService.DuckAPI.UpdateDecoderConfiguration:input_type -> apiService.UpdateDecoderConfigurationRequest - 52, // 39: apiService.DuckAPI.GetTopiConfiguration:input_type -> apiService.GetTopiConfigurationRequest - 54, // 40: apiService.DuckAPI.UpdateTopiConfiguration:input_type -> apiService.UpdateTopiConfigurationRequest - 57, // 41: apiService.DuckAPI.ListTopiConfigurations:input_type -> apiService.ListTopiConfigurationsRequest - 59, // 42: apiService.DuckAPI.GetRunNumber:input_type -> apiService.GetRunNumberRequest - 62, // 43: apiService.DuckAPI.CheckDisabled:input_type -> apiService.CheckDisabledRequest - 64, // 44: apiService.DuckAPI.GetToken:input_type -> apiService.GetTokenRequest - 68, // 45: apiService.DuckAPI.StartTestDevices:input_type -> apiService.StartTestDevicesRequest - 70, // 46: apiService.DuckAPI.StopTestDevices:input_type -> apiService.StopTestDevicesRequest - 72, // 47: apiService.DuckAPI.GetTestDevicesStates:input_type -> apiService.GetTestDevicesStatesRequest - 74, // 48: apiService.DuckAPI.ListTestDevices:input_type -> apiService.ListTestDevicesRequest - 76, // 49: apiService.DuckAPI.GetTestDeviceStatistics:input_type -> apiService.GetTestDeviceStatisticsRequest - 2, // 50: apiService.DuckAPI.StartRun:output_type -> apiService.StartRunResponse - 4, // 51: apiService.DuckAPI.StopRun:output_type -> apiService.StopRunResponse - 6, // 52: apiService.DuckAPI.ForceStopRun:output_type -> apiService.ForceStopRunResponse - 8, // 53: apiService.DuckAPI.GetProcessStates:output_type -> apiService.GetProcessStatesResponse - 10, // 54: apiService.DuckAPI.RestartServices:output_type -> apiService.RestartServicesResponse - 12, // 55: apiService.DuckAPI.GetRunTransitionStatus:output_type -> apiService.GetRunTransitionStatusResponse - 15, // 56: apiService.DuckAPI.CreateGDC:output_type -> apiService.CreateGDCResponse - 17, // 57: apiService.DuckAPI.GetGDCs:output_type -> apiService.GetGDCsResponse - 19, // 58: apiService.DuckAPI.GetGDC:output_type -> apiService.GetGDCResponse - 21, // 59: apiService.DuckAPI.UpdateGDC:output_type -> apiService.UpdateGDCResponse - 23, // 60: apiService.DuckAPI.DeleteGDC:output_type -> apiService.DeleteGDCResponse - 27, // 61: apiService.DuckAPI.CreateLDC:output_type -> apiService.CreateLDCResponse - 29, // 62: apiService.DuckAPI.GetLDCs:output_type -> apiService.GetLDCsResponse - 31, // 63: apiService.DuckAPI.GetLDC:output_type -> apiService.GetLDCResponse - 33, // 64: apiService.DuckAPI.UpdateLDC:output_type -> apiService.UpdateLDCResponse - 35, // 65: apiService.DuckAPI.DeleteLDC:output_type -> apiService.DeleteLDCResponse - 37, // 66: apiService.DuckAPI.CreateEquipment:output_type -> apiService.CreateEquipmentResponse - 39, // 67: apiService.DuckAPI.GetEquipments:output_type -> apiService.GetEquipmentsResponse - 41, // 68: apiService.DuckAPI.GetEquipment:output_type -> apiService.GetEquipmentResponse - 43, // 69: apiService.DuckAPI.UpdateEquipment:output_type -> apiService.UpdateEquipmentResponse - 45, // 70: apiService.DuckAPI.DeleteEquipment:output_type -> apiService.DeleteEquipmentResponse - 48, // 71: apiService.DuckAPI.GetDecoderConfiguration:output_type -> apiService.GetDecoderConfigurationResponse - 50, // 72: apiService.DuckAPI.UpdateDecoderConfiguration:output_type -> apiService.UpdateDecoderConfigurationResponse - 53, // 73: apiService.DuckAPI.GetTopiConfiguration:output_type -> apiService.GetTopiConfigurationResponse - 55, // 74: apiService.DuckAPI.UpdateTopiConfiguration:output_type -> apiService.UpdateTopiConfigurationResponse - 58, // 75: apiService.DuckAPI.ListTopiConfigurations:output_type -> apiService.ListTopiConfigurationsResponse - 60, // 76: apiService.DuckAPI.GetRunNumber:output_type -> apiService.GetRunNumberResponse - 63, // 77: apiService.DuckAPI.CheckDisabled:output_type -> apiService.CheckDisabledResponse - 65, // 78: apiService.DuckAPI.GetToken:output_type -> apiService.GetTokenResponse - 69, // 79: apiService.DuckAPI.StartTestDevices:output_type -> apiService.StartTestDevicesResponse - 71, // 80: apiService.DuckAPI.StopTestDevices:output_type -> apiService.StopTestDevicesResponse - 73, // 81: apiService.DuckAPI.GetTestDevicesStates:output_type -> apiService.GetTestDevicesStatesResponse - 75, // 82: apiService.DuckAPI.ListTestDevices:output_type -> apiService.ListTestDevicesResponse - 77, // 83: apiService.DuckAPI.GetTestDeviceStatistics:output_type -> apiService.GetTestDeviceStatisticsResponse - 50, // [50:84] is the sub-list for method output_type - 16, // [16:50] is the sub-list for method input_type - 16, // [16:16] is the sub-list for extension type_name - 16, // [16:16] is the sub-list for extension extendee - 0, // [0:16] is the sub-list for field type_name + 82, // 16: apiService.GetRateHistoryRequest.from:type_name -> google.protobuf.Timestamp + 82, // 17: apiService.GetRateHistoryRequest.to:type_name -> google.protobuf.Timestamp + 82, // 18: apiService.RateHistoryBin.start:type_name -> google.protobuf.Timestamp + 82, // 19: apiService.RateHistoryBin.end:type_name -> google.protobuf.Timestamp + 82, // 20: apiService.GetRateHistoryResponse.run_start:type_name -> google.protobuf.Timestamp + 82, // 21: apiService.GetRateHistoryResponse.run_stop:type_name -> google.protobuf.Timestamp + 82, // 22: apiService.GetRateHistoryResponse.from:type_name -> google.protobuf.Timestamp + 82, // 23: apiService.GetRateHistoryResponse.to:type_name -> google.protobuf.Timestamp + 82, // 24: apiService.GetRateHistoryResponse.latest_sample:type_name -> google.protobuf.Timestamp + 79, // 25: apiService.GetRateHistoryResponse.bins:type_name -> apiService.RateHistoryBin + 1, // 26: apiService.DuckAPI.StartRun:input_type -> apiService.StartRunRequest + 3, // 27: apiService.DuckAPI.StopRun:input_type -> apiService.StopRunRequest + 5, // 28: apiService.DuckAPI.ForceStopRun:input_type -> apiService.ForceStopRunRequest + 7, // 29: apiService.DuckAPI.GetProcessStates:input_type -> apiService.GetProcessStatesRequest + 9, // 30: apiService.DuckAPI.RestartServices:input_type -> apiService.RestartServicesRequest + 11, // 31: apiService.DuckAPI.GetRunTransitionStatus:input_type -> apiService.GetRunTransitionStatusRequest + 14, // 32: apiService.DuckAPI.CreateGDC:input_type -> apiService.CreateGDCRequest + 16, // 33: apiService.DuckAPI.GetGDCs:input_type -> apiService.GetGDCsRequest + 18, // 34: apiService.DuckAPI.GetGDC:input_type -> apiService.GetGDCRequest + 20, // 35: apiService.DuckAPI.UpdateGDC:input_type -> apiService.UpdateGDCRequest + 22, // 36: apiService.DuckAPI.DeleteGDC:input_type -> apiService.DeleteGDCRequest + 26, // 37: apiService.DuckAPI.CreateLDC:input_type -> apiService.CreateLDCRequest + 28, // 38: apiService.DuckAPI.GetLDCs:input_type -> apiService.GetLDCsRequest + 30, // 39: apiService.DuckAPI.GetLDC:input_type -> apiService.GetLDCRequest + 32, // 40: apiService.DuckAPI.UpdateLDC:input_type -> apiService.UpdateLDCRequest + 34, // 41: apiService.DuckAPI.DeleteLDC:input_type -> apiService.DeleteLDCRequest + 36, // 42: apiService.DuckAPI.CreateEquipment:input_type -> apiService.CreateEquipmentRequest + 38, // 43: apiService.DuckAPI.GetEquipments:input_type -> apiService.GetEquipmentsRequest + 40, // 44: apiService.DuckAPI.GetEquipment:input_type -> apiService.GetEquipmentRequest + 42, // 45: apiService.DuckAPI.UpdateEquipment:input_type -> apiService.UpdateEquipmentRequest + 44, // 46: apiService.DuckAPI.DeleteEquipment:input_type -> apiService.DeleteEquipmentRequest + 47, // 47: apiService.DuckAPI.GetDecoderConfiguration:input_type -> apiService.GetDecoderConfigurationRequest + 49, // 48: apiService.DuckAPI.UpdateDecoderConfiguration:input_type -> apiService.UpdateDecoderConfigurationRequest + 52, // 49: apiService.DuckAPI.GetTopiConfiguration:input_type -> apiService.GetTopiConfigurationRequest + 54, // 50: apiService.DuckAPI.UpdateTopiConfiguration:input_type -> apiService.UpdateTopiConfigurationRequest + 57, // 51: apiService.DuckAPI.ListTopiConfigurations:input_type -> apiService.ListTopiConfigurationsRequest + 78, // 52: apiService.DuckAPI.GetRateHistory:input_type -> apiService.GetRateHistoryRequest + 59, // 53: apiService.DuckAPI.GetRunNumber:input_type -> apiService.GetRunNumberRequest + 62, // 54: apiService.DuckAPI.CheckDisabled:input_type -> apiService.CheckDisabledRequest + 64, // 55: apiService.DuckAPI.GetToken:input_type -> apiService.GetTokenRequest + 68, // 56: apiService.DuckAPI.StartTestDevices:input_type -> apiService.StartTestDevicesRequest + 70, // 57: apiService.DuckAPI.StopTestDevices:input_type -> apiService.StopTestDevicesRequest + 72, // 58: apiService.DuckAPI.GetTestDevicesStates:input_type -> apiService.GetTestDevicesStatesRequest + 74, // 59: apiService.DuckAPI.ListTestDevices:input_type -> apiService.ListTestDevicesRequest + 76, // 60: apiService.DuckAPI.GetTestDeviceStatistics:input_type -> apiService.GetTestDeviceStatisticsRequest + 2, // 61: apiService.DuckAPI.StartRun:output_type -> apiService.StartRunResponse + 4, // 62: apiService.DuckAPI.StopRun:output_type -> apiService.StopRunResponse + 6, // 63: apiService.DuckAPI.ForceStopRun:output_type -> apiService.ForceStopRunResponse + 8, // 64: apiService.DuckAPI.GetProcessStates:output_type -> apiService.GetProcessStatesResponse + 10, // 65: apiService.DuckAPI.RestartServices:output_type -> apiService.RestartServicesResponse + 12, // 66: apiService.DuckAPI.GetRunTransitionStatus:output_type -> apiService.GetRunTransitionStatusResponse + 15, // 67: apiService.DuckAPI.CreateGDC:output_type -> apiService.CreateGDCResponse + 17, // 68: apiService.DuckAPI.GetGDCs:output_type -> apiService.GetGDCsResponse + 19, // 69: apiService.DuckAPI.GetGDC:output_type -> apiService.GetGDCResponse + 21, // 70: apiService.DuckAPI.UpdateGDC:output_type -> apiService.UpdateGDCResponse + 23, // 71: apiService.DuckAPI.DeleteGDC:output_type -> apiService.DeleteGDCResponse + 27, // 72: apiService.DuckAPI.CreateLDC:output_type -> apiService.CreateLDCResponse + 29, // 73: apiService.DuckAPI.GetLDCs:output_type -> apiService.GetLDCsResponse + 31, // 74: apiService.DuckAPI.GetLDC:output_type -> apiService.GetLDCResponse + 33, // 75: apiService.DuckAPI.UpdateLDC:output_type -> apiService.UpdateLDCResponse + 35, // 76: apiService.DuckAPI.DeleteLDC:output_type -> apiService.DeleteLDCResponse + 37, // 77: apiService.DuckAPI.CreateEquipment:output_type -> apiService.CreateEquipmentResponse + 39, // 78: apiService.DuckAPI.GetEquipments:output_type -> apiService.GetEquipmentsResponse + 41, // 79: apiService.DuckAPI.GetEquipment:output_type -> apiService.GetEquipmentResponse + 43, // 80: apiService.DuckAPI.UpdateEquipment:output_type -> apiService.UpdateEquipmentResponse + 45, // 81: apiService.DuckAPI.DeleteEquipment:output_type -> apiService.DeleteEquipmentResponse + 48, // 82: apiService.DuckAPI.GetDecoderConfiguration:output_type -> apiService.GetDecoderConfigurationResponse + 50, // 83: apiService.DuckAPI.UpdateDecoderConfiguration:output_type -> apiService.UpdateDecoderConfigurationResponse + 53, // 84: apiService.DuckAPI.GetTopiConfiguration:output_type -> apiService.GetTopiConfigurationResponse + 55, // 85: apiService.DuckAPI.UpdateTopiConfiguration:output_type -> apiService.UpdateTopiConfigurationResponse + 58, // 86: apiService.DuckAPI.ListTopiConfigurations:output_type -> apiService.ListTopiConfigurationsResponse + 80, // 87: apiService.DuckAPI.GetRateHistory:output_type -> apiService.GetRateHistoryResponse + 60, // 88: apiService.DuckAPI.GetRunNumber:output_type -> apiService.GetRunNumberResponse + 63, // 89: apiService.DuckAPI.CheckDisabled:output_type -> apiService.CheckDisabledResponse + 65, // 90: apiService.DuckAPI.GetToken:output_type -> apiService.GetTokenResponse + 69, // 91: apiService.DuckAPI.StartTestDevices:output_type -> apiService.StartTestDevicesResponse + 71, // 92: apiService.DuckAPI.StopTestDevices:output_type -> apiService.StopTestDevicesResponse + 73, // 93: apiService.DuckAPI.GetTestDevicesStates:output_type -> apiService.GetTestDevicesStatesResponse + 75, // 94: apiService.DuckAPI.ListTestDevices:output_type -> apiService.ListTestDevicesResponse + 77, // 95: apiService.DuckAPI.GetTestDeviceStatistics:output_type -> apiService.GetTestDeviceStatisticsResponse + 61, // [61:96] is the sub-list for method output_type + 26, // [26:61] is the sub-list for method input_type + 26, // [26:26] is the sub-list for extension type_name + 26, // [26:26] is the sub-list for extension extendee + 0, // [0:26] is the sub-list for field type_name } func init() { file_api_proto_init() } @@ -4950,13 +5308,14 @@ func file_api_proto_init() { if File_api_proto != nil { return } + file_api_proto_msgTypes[79].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_proto_rawDesc), len(file_api_proto_rawDesc)), NumEnums: 0, - NumMessages: 79, + NumMessages: 82, NumExtensions: 0, NumServices: 1, }, diff --git a/rpc/api/apiconnect/api.connect.go b/rpc/api/apiconnect/api.connect.go index 3191988..bb0974c 100644 --- a/rpc/api/apiconnect/api.connect.go +++ b/rpc/api/apiconnect/api.connect.go @@ -92,6 +92,8 @@ const ( // DuckAPIListTopiConfigurationsProcedure is the fully-qualified name of the DuckAPI's // ListTopiConfigurations RPC. DuckAPIListTopiConfigurationsProcedure = "/apiService.DuckAPI/ListTopiConfigurations" + // DuckAPIGetRateHistoryProcedure is the fully-qualified name of the DuckAPI's GetRateHistory RPC. + DuckAPIGetRateHistoryProcedure = "/apiService.DuckAPI/GetRateHistory" // DuckAPIGetRunNumberProcedure is the fully-qualified name of the DuckAPI's GetRunNumber RPC. DuckAPIGetRunNumberProcedure = "/apiService.DuckAPI/GetRunNumber" // DuckAPICheckDisabledProcedure is the fully-qualified name of the DuckAPI's CheckDisabled RPC. @@ -147,6 +149,8 @@ type DuckAPIClient interface { GetTopiConfiguration(context.Context, *connect.Request[api.GetTopiConfigurationRequest]) (*connect.Response[api.GetTopiConfigurationResponse], error) UpdateTopiConfiguration(context.Context, *connect.Request[api.UpdateTopiConfigurationRequest]) (*connect.Response[api.UpdateTopiConfigurationResponse], error) ListTopiConfigurations(context.Context, *connect.Request[api.ListTopiConfigurationsRequest]) (*connect.Response[api.ListTopiConfigurationsResponse], error) + // Counter-based, bounded historical detector rates. + GetRateHistory(context.Context, *connect.Request[api.GetRateHistoryRequest]) (*connect.Response[api.GetRateHistoryResponse], error) // Run Information GetRunNumber(context.Context, *connect.Request[api.GetRunNumberRequest]) (*connect.Response[api.GetRunNumberResponse], error) CheckDisabled(context.Context, *connect.Request[api.CheckDisabledRequest]) (*connect.Response[api.CheckDisabledResponse], error) @@ -327,6 +331,12 @@ func NewDuckAPIClient(httpClient connect.HTTPClient, baseURL string, opts ...con connect.WithSchema(duckAPIMethods.ByName("ListTopiConfigurations")), connect.WithClientOptions(opts...), ), + getRateHistory: connect.NewClient[api.GetRateHistoryRequest, api.GetRateHistoryResponse]( + httpClient, + baseURL+DuckAPIGetRateHistoryProcedure, + connect.WithSchema(duckAPIMethods.ByName("GetRateHistory")), + connect.WithClientOptions(opts...), + ), getRunNumber: connect.NewClient[api.GetRunNumberRequest, api.GetRunNumberResponse]( httpClient, baseURL+DuckAPIGetRunNumberProcedure, @@ -406,6 +416,7 @@ type duckAPIClient struct { getTopiConfiguration *connect.Client[api.GetTopiConfigurationRequest, api.GetTopiConfigurationResponse] updateTopiConfiguration *connect.Client[api.UpdateTopiConfigurationRequest, api.UpdateTopiConfigurationResponse] listTopiConfigurations *connect.Client[api.ListTopiConfigurationsRequest, api.ListTopiConfigurationsResponse] + getRateHistory *connect.Client[api.GetRateHistoryRequest, api.GetRateHistoryResponse] getRunNumber *connect.Client[api.GetRunNumberRequest, api.GetRunNumberResponse] checkDisabled *connect.Client[api.CheckDisabledRequest, api.CheckDisabledResponse] getToken *connect.Client[api.GetTokenRequest, api.GetTokenResponse] @@ -546,6 +557,11 @@ func (c *duckAPIClient) ListTopiConfigurations(ctx context.Context, req *connect return c.listTopiConfigurations.CallUnary(ctx, req) } +// GetRateHistory calls apiService.DuckAPI.GetRateHistory. +func (c *duckAPIClient) GetRateHistory(ctx context.Context, req *connect.Request[api.GetRateHistoryRequest]) (*connect.Response[api.GetRateHistoryResponse], error) { + return c.getRateHistory.CallUnary(ctx, req) +} + // GetRunNumber calls apiService.DuckAPI.GetRunNumber. func (c *duckAPIClient) GetRunNumber(ctx context.Context, req *connect.Request[api.GetRunNumberRequest]) (*connect.Response[api.GetRunNumberResponse], error) { return c.getRunNumber.CallUnary(ctx, req) @@ -620,6 +636,8 @@ type DuckAPIHandler interface { GetTopiConfiguration(context.Context, *connect.Request[api.GetTopiConfigurationRequest]) (*connect.Response[api.GetTopiConfigurationResponse], error) UpdateTopiConfiguration(context.Context, *connect.Request[api.UpdateTopiConfigurationRequest]) (*connect.Response[api.UpdateTopiConfigurationResponse], error) ListTopiConfigurations(context.Context, *connect.Request[api.ListTopiConfigurationsRequest]) (*connect.Response[api.ListTopiConfigurationsResponse], error) + // Counter-based, bounded historical detector rates. + GetRateHistory(context.Context, *connect.Request[api.GetRateHistoryRequest]) (*connect.Response[api.GetRateHistoryResponse], error) // Run Information GetRunNumber(context.Context, *connect.Request[api.GetRunNumberRequest]) (*connect.Response[api.GetRunNumberResponse], error) CheckDisabled(context.Context, *connect.Request[api.CheckDisabledRequest]) (*connect.Response[api.CheckDisabledResponse], error) @@ -796,6 +814,12 @@ func NewDuckAPIHandler(svc DuckAPIHandler, opts ...connect.HandlerOption) (strin connect.WithSchema(duckAPIMethods.ByName("ListTopiConfigurations")), connect.WithHandlerOptions(opts...), ) + duckAPIGetRateHistoryHandler := connect.NewUnaryHandler( + DuckAPIGetRateHistoryProcedure, + svc.GetRateHistory, + connect.WithSchema(duckAPIMethods.ByName("GetRateHistory")), + connect.WithHandlerOptions(opts...), + ) duckAPIGetRunNumberHandler := connect.NewUnaryHandler( DuckAPIGetRunNumberProcedure, svc.GetRunNumber, @@ -898,6 +922,8 @@ func NewDuckAPIHandler(svc DuckAPIHandler, opts ...connect.HandlerOption) (strin duckAPIUpdateTopiConfigurationHandler.ServeHTTP(w, r) case DuckAPIListTopiConfigurationsProcedure: duckAPIListTopiConfigurationsHandler.ServeHTTP(w, r) + case DuckAPIGetRateHistoryProcedure: + duckAPIGetRateHistoryHandler.ServeHTTP(w, r) case DuckAPIGetRunNumberProcedure: duckAPIGetRunNumberHandler.ServeHTTP(w, r) case DuckAPICheckDisabledProcedure: @@ -1027,6 +1053,10 @@ func (UnimplementedDuckAPIHandler) ListTopiConfigurations(context.Context, *conn return nil, connect.NewError(connect.CodeUnimplemented, errors.New("apiService.DuckAPI.ListTopiConfigurations is not implemented")) } +func (UnimplementedDuckAPIHandler) GetRateHistory(context.Context, *connect.Request[api.GetRateHistoryRequest]) (*connect.Response[api.GetRateHistoryResponse], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("apiService.DuckAPI.GetRateHistory is not implemented")) +} + func (UnimplementedDuckAPIHandler) GetRunNumber(context.Context, *connect.Request[api.GetRunNumberRequest]) (*connect.Response[api.GetRunNumberResponse], error) { return nil, connect.NewError(connect.CodeUnimplemented, errors.New("apiService.DuckAPI.GetRunNumber is not implemented")) } diff --git a/rpc/proto/api/api.proto b/rpc/proto/api/api.proto index fd7fd70..c53e387 100644 --- a/rpc/proto/api/api.proto +++ b/rpc/proto/api/api.proto @@ -2,6 +2,8 @@ syntax = "proto3"; option go_package = "github.com/jmbenlloch/next_duck/rpc/api"; package apiService; +import "google/protobuf/timestamp.proto"; + // Web API Service for Duck Data Acquisition System service DuckAPI { // Run Control Operations @@ -42,6 +44,9 @@ service DuckAPI { rpc UpdateTopiConfiguration(UpdateTopiConfigurationRequest) returns (UpdateTopiConfigurationResponse) {} rpc ListTopiConfigurations(ListTopiConfigurationsRequest) returns (ListTopiConfigurationsResponse) {} + // Counter-based, bounded historical detector rates. + rpc GetRateHistory(GetRateHistoryRequest) returns (GetRateHistoryResponse) {} + // Run Information rpc GetRunNumber(GetRunNumberRequest) returns (GetRunNumberResponse) {} rpc CheckDisabled(CheckDisabledRequest) returns (CheckDisabledResponse) {} @@ -462,3 +467,42 @@ message GetTestDeviceStatisticsRequest { message GetTestDeviceStatisticsResponse { TestDeviceStatistics statistics = 1; } + +// Omit from/to for the full recorded run. Explicit bounds support browser zoom. +message GetRateHistoryRequest { + int32 run = 1; + google.protobuf.Timestamp from = 2; + google.protobuf.Timestamp to = 3; + // 0 selects 1000. The server accepts 1..2000. + uint32 max_points = 4; + // 0 selects 15 seconds, suitable for the default five-second collector. + // Intervals longer than this are gaps, not interpolated measurements. + uint32 max_gap_seconds = 5; +} +message RateHistoryBin { + google.protobuf.Timestamp start = 1; + google.protobuf.Timestamp end = 2; + // Present only when the full bin is covered by every recorded GDC. + optional double trigger_rate_hz = 3; + optional double byte_rate = 4; + // Fraction of GDC-time covered, relative to response.gdcs. + double coverage = 5; + bool complete = 6; + // Edge bin clipped by the selected window, rather than full bin width. + bool partial = 7; +} +message GetRateHistoryResponse { + int32 run = 1; + google.protobuf.Timestamp run_start = 2; + google.protobuf.Timestamp run_stop = 3; + google.protobuf.Timestamp from = 4; + google.protobuf.Timestamp to = 5; + google.protobuf.Timestamp latest_sample = 6; + uint32 bin_width_seconds = 7; + repeated RateHistoryBin bins = 8; + repeated string gdcs = 9; + // Currently "observed_run_history"; not a configuration snapshot. + string coverage_basis = 10; + bool has_data = 11; + uint32 max_gap_seconds = 12; +} From 172f9083d2e7b1df62311f20f6ce2c0152a92017 Mon Sep 17 00:00:00 2001 From: jmbenlloch Date: Wed, 4 Nov 2026 16:42:16 +0100 Subject: [PATCH 2/2] Add adaptive rate history viewer and resilient fluctuating test generator --- deviceSimulator/README.md | 17 ++ deviceSimulator/config.go | 1 + deviceSimulator/generator.go | 59 ++++++- deviceSimulator/generator_test.go | 68 ++++++++ deviceSimulator/main.go | 17 +- gui/.gitignore | 4 + gui/README.md | 49 ++++++ gui/e2e/rate-history.spec.ts | 105 ++++++++++++ gui/package-lock.json | 43 +++++ gui/package.json | 5 +- gui/playwright.rate-history.config.ts | 11 ++ gui/src/components/RateHistory.vue | 57 +++++++ gui/src/components/RateHistoryChart.vue | 107 ++++++++++++ gui/src/components/RunStatistics.vue | 15 +- .../__tests__/useRateHistory.spec.ts | 124 ++++++++++++++ gui/src/composables/useRateHistory.ts | 156 ++++++++++++++++++ gui/src/stores/__tests__/messages.spec.ts | 12 ++ gui/src/stores/messages.ts | 3 + gui/src/test/setup.ts | 1 + gui/src/views/HomeView.vue | 25 ++- 20 files changed, 862 insertions(+), 17 deletions(-) create mode 100644 deviceSimulator/generator_test.go create mode 100644 gui/e2e/rate-history.spec.ts create mode 100644 gui/playwright.rate-history.config.ts create mode 100644 gui/src/components/RateHistory.vue create mode 100644 gui/src/components/RateHistoryChart.vue create mode 100644 gui/src/composables/__tests__/useRateHistory.spec.ts create mode 100644 gui/src/composables/useRateHistory.ts diff --git a/deviceSimulator/README.md b/deviceSimulator/README.md index cd3323a..c970dbe 100644 --- a/deviceSimulator/README.md +++ b/deviceSimulator/README.md @@ -380,3 +380,20 @@ For issues or questions: 4. Check network connectivity to LDC 5. Review database configuration 6. Monitor Prometheus metrics + +### Fluctuating-rate generator profile + +For rate-history plotting tests, add `-mode generate -rate-profile fluctuating`. +`-rate` (or the database `event_rate_ms` value) remains the base rate. The profile +changes its target every two seconds, combining random steps, slower drift and +short bursts. Targets are bounded between 0.15 and 2.5 times the base rate. This +makes fine-bin fluctuations visible while coarser bins smooth them by averaging. +The default `-rate-profile constant` preserves fixed-rate generation. + +A generator now retries UDP connection-refused errors while a DAQ receiver is +stopped. It resumes sending when the receiver reopens for the next run, instead +of exiting silently while the control service still reports RUNNING. No real +hardware or production detector configuration is changed by this option. + +Run `go test -race ./deviceSimulator` to check profile bounds and recovery after +a UDP receiver restart. diff --git a/deviceSimulator/config.go b/deviceSimulator/config.go index cfe5895..9944d4f 100644 --- a/deviceSimulator/config.go +++ b/deviceSimulator/config.go @@ -21,6 +21,7 @@ type SimulatorParams struct { // GeneratorConfig holds configuration for generate mode type GeneratorConfig struct { + RateProfile string // "constant" (default) or "fluctuating" EquipmentID int Equipment duck.Equipment RateHz float64 // Absolute event rate in Hz (events per second) diff --git a/deviceSimulator/generator.go b/deviceSimulator/generator.go index 0222ceb..aaf9435 100644 --- a/deviceSimulator/generator.go +++ b/deviceSimulator/generator.go @@ -2,22 +2,25 @@ package main import ( "encoding/binary" + "errors" "fmt" "log" + "math" "math/rand/v2" "sync" + "syscall" "time" ) // Generator handles the generation of random test events type Generator struct { - config GeneratorConfig - sender *UDPSender - limiter *RateLimiter - state SourceState - stateMu sync.RWMutex - stopCh chan struct{} - doneCh chan struct{} + config GeneratorConfig + sender *UDPSender + limiter *RateLimiter + state SourceState + stateMu sync.RWMutex + stopCh chan struct{} + doneCh chan struct{} // Metrics eventsSent uint64 @@ -28,6 +31,9 @@ type Generator struct { // NewGenerator creates a new generator with the given configuration func NewGenerator(config GeneratorConfig) (*Generator, error) { + if config.RateProfile != "" && config.RateProfile != "constant" && config.RateProfile != "fluctuating" { + return nil, fmt.Errorf("unsupported rate profile %q", config.RateProfile) + } // Validate configuration if config.PacketsPerEvent <= 0 { config.PacketsPerEvent = 10 // Default @@ -79,14 +85,15 @@ func (g *Generator) Start() error { // Stop stops the event generation func (g *Generator) Stop() error { g.stateMu.Lock() - defer g.stateMu.Unlock() if g.state == SourceStateStopped { + g.stateMu.Unlock() return fmt.Errorf("generator is not running") } close(g.stopCh) g.state = SourceStateStopped + g.stateMu.Unlock() // Wait for generator to finish <-g.doneCh @@ -142,10 +149,16 @@ func (g *Generator) GetStatus() string { // generateLoop is the main generation loop func (g *Generator) generateLoop() { - defer close(g.doneCh) + defer func() { + g.stateMu.Lock() + g.state = SourceStateStopped + g.stateMu.Unlock() + close(g.doneCh) + }() g.startTime = time.Now() g.currentEventID = 1 + nextRateChange := g.startTime for { // Check for stop signal @@ -155,6 +168,12 @@ func (g *Generator) generateLoop() { default: } + if g.config.RateProfile == "fluctuating" && !time.Now().Before(nextRateChange) { + target := fluctuatingRate(g.config.RateHz, time.Since(g.startTime), 2*rand.Float64()-1) + g.limiter = NewRateLimiter(target) + nextRateChange = time.Now().Add(2 * time.Second) + log.Printf("Generator rate target: %.1f Hz", target) + } // Rate limiting g.limiter.Wait() @@ -164,6 +183,17 @@ func (g *Generator) generateLoop() { // Send event err := g.sendEvent(int(g.currentEventID), injectError) if err != nil { + if errors.Is(err, syscall.ECONNREFUSED) { + // A stopped DAQ closes its UDP listener. Keep the generator alive so + // reception resumes automatically when the next run opens that socket. + log.Printf("DAQ receiver unavailable; retrying event %d: %v", g.currentEventID, err) + select { + case <-g.stopCh: + return + case <-time.After(500 * time.Millisecond): + } + continue + } log.Printf("Error sending event %d: %v", g.currentEventID, err) return } @@ -234,3 +264,14 @@ func (g *Generator) sendEvent(eventID int, injectError bool) error { return nil } + +// fluctuatingRate combines short random steps, slower drift, and brief bursts. +// noise is in [-1,1]; bounded targets keep this useful for a lightweight demo. +func fluctuatingRate(base float64, elapsed time.Duration, noise float64) float64 { + seconds := elapsed.Seconds() + multiplier := 0.9 + 0.45*math.Sin(2*math.Pi*seconds/37) + 0.3*math.Sin(2*math.Pi*seconds/113) + 0.65*noise + if math.Mod(seconds, 29) < 3 { + multiplier += 0.6 + } + return base * math.Max(0.15, math.Min(2.5, multiplier)) +} diff --git a/deviceSimulator/generator_test.go b/deviceSimulator/generator_test.go new file mode 100644 index 0000000..7f8622c --- /dev/null +++ b/deviceSimulator/generator_test.go @@ -0,0 +1,68 @@ +package main + +import ( + "math" + "net" + "testing" + "time" + + duck "github.com/jmbenlloch/next_duck/pkg" +) + +func TestFluctuatingRateIsBoundedAndVariesAcrossTimeScales(t *testing.T) { + minRate, maxRate := math.Inf(1), 0.0 + values := make(map[int]bool) + for second := 0; second < 180; second++ { + for _, noise := range []float64{-1, 0, 1} { + rate := fluctuatingRate(50, time.Duration(second)*time.Second, noise) + if rate < 7.5 || rate > 125 { + t.Fatalf("unbounded target: %v", rate) + } + minRate = math.Min(minRate, rate) + maxRate = math.Max(maxRate, rate) + values[int(rate)] = true + } + } + if len(values) < 30 || maxRate-minRate < 60 { + t.Fatal("profile does not provide visible variation") + } + if _, err := NewGenerator(GeneratorConfig{RateProfile: "invalid"}); err == nil { + t.Fatal("invalid profile accepted") + } +} + +func TestGeneratorRecoversWhenUDPReceiverRestarts(t *testing.T) { + listener, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1")}) + if err != nil { + t.Fatal(err) + } + address := listener.LocalAddr().(*net.UDPAddr) + generator, err := NewGenerator(GeneratorConfig{Equipment: duck.Equipment{HostIP: "127.0.0.1", HostPort: address.Port}, RateHz: 200, PacketsPerEvent: 1, PacketSize: 64}) + if err != nil { + t.Fatal(err) + } + if err := generator.Start(); err != nil { + t.Fatal(err) + } + defer generator.Stop() + buffer := make([]byte, 512) + listener.SetReadDeadline(time.Now().Add(2 * time.Second)) + if _, _, err := listener.ReadFromUDP(buffer); err != nil { + t.Fatal(err) + } + listener.Close() + // Allow an ICMP port-unreachable to reach the connected sender. + time.Sleep(100 * time.Millisecond) + if generator.GetState() != SourceStateRunning { + t.Fatal("receiver stop terminated the generator") + } + listener, err = net.ListenUDP("udp", address) + if err != nil { + t.Fatal(err) + } + defer listener.Close() + listener.SetReadDeadline(time.Now().Add(2 * time.Second)) + if _, _, err := listener.ReadFromUDP(buffer); err != nil { + t.Fatalf("did not resume after receiver restart: %v", err) + } +} diff --git a/deviceSimulator/main.go b/deviceSimulator/main.go index 0545b31..3427ce5 100644 --- a/deviceSimulator/main.go +++ b/deviceSimulator/main.go @@ -27,7 +27,8 @@ var ( // server implements the RunControl service type server struct { - mode string // "replay" or "generate" + rateProfile string + mode string // "replay" or "generate" equipmentID int filePath string rate float64 @@ -66,6 +67,8 @@ func (s *server) StartRun(ctx context.Context, req *connect.Request[pb.DuckReque return connect.NewResponse(&pb.DuckReply{Message: fmt.Sprintf("Config error: %v", err)}), nil } + config.RateProfile = s.rateProfile + // Create generator generator, err := NewGenerator(config) if err != nil { @@ -190,6 +193,7 @@ func main() { configFilename := flag.String("config", "", "Configuration file path (YAML)") equipmentID := flag.Int("id", 0, "Equipment ID") filePath := flag.String("file", "", "Path to .rd dump file (replay mode)") + rateProfile := flag.String("rate-profile", "constant", "Generate-mode rate profile: constant or fluctuating") rate := flag.Float64("rate", 0, "Absolute event rate in Hz (0 = use database config)") loop := flag.Bool("loop", false, "Loop replay continuously (replay mode)") maxEvents := flag.Int("max-events", 0, "Maximum events to send (0 = unlimited)") @@ -215,6 +219,10 @@ func main() { os.Exit(1) } + if *rateProfile != "constant" && *rateProfile != "fluctuating" { + log.Fatal("rate-profile must be constant or fluctuating") + } + // Initialize logger deviceName := fmt.Sprintf("simulator-%d", *equipmentID) logger = duck.NewDuckLogger(deviceName, nil, slog.LevelInfo) @@ -247,7 +255,7 @@ func main() { // If not in server mode, run CLI mode if !*serverMode { - runCLI(*mode, *equipmentID, *filePath, *rate, *loop, *maxEvents, *fragmentSize, *packetsPerEvent, *errorInjection) + runCLI(*mode, *equipmentID, *filePath, *rate, *loop, *maxEvents, *fragmentSize, *packetsPerEvent, *errorInjection, *rateProfile) return } @@ -274,6 +282,7 @@ func main() { mux := http.NewServeMux() path, handler := pbconnect.NewRunControlHandler(&server{ mode: *mode, + rateProfile: *rateProfile, equipmentID: *equipmentID, filePath: *filePath, rate: *rate, @@ -311,7 +320,7 @@ func main() { } // runCLI runs in CLI-only mode without ConnectRPC server -func runCLI(mode string, equipmentID int, filePath string, rate float64, loop bool, maxEvents int, fragmentSize int, packetsPerEvent int, errorInjection float64) { +func runCLI(mode string, equipmentID int, filePath string, rate float64, loop bool, maxEvents int, fragmentSize int, packetsPerEvent int, errorInjection float64, rateProfile string) { // Get database connection db, err := GetDatabaseConnection() if err != nil { @@ -337,6 +346,8 @@ func runCLI(mode string, equipmentID int, filePath string, rate float64, loop bo log.Fatalf("Failed to build generator config: %v", err) } + config.RateProfile = rateProfile + // Create and start generator generator, err := NewGenerator(config) if err != nil { diff --git a/gui/.gitignore b/gui/.gitignore index 8ee54e8..36acdc9 100644 --- a/gui/.gitignore +++ b/gui/.gitignore @@ -28,3 +28,7 @@ coverage *.sw? *.tsbuildinfo + +# Browser test artifacts +/test-results/ +/playwright-report/ diff --git a/gui/README.md b/gui/README.md index 55ecf6f..a9032e0 100644 --- a/gui/README.md +++ b/gui/README.md @@ -481,3 +481,52 @@ npm run dev - [DaisyUI Components](https://daisyui.com/components/) - [Vitest](https://vitest.dev/) - [Playwright](https://playwright.dev/) + +## Trigger rate history + +The data-taking page includes a lazy-loaded ECharts plot below the run statistics. +Deploy the history-enabled Duck API, rateReader and `rateSamples` migration first. +The existing `VITE_API_SERVER` setting is used for history requests. + +- **Auto** shows the full selected run and requests updated, server-rebinned data + every five seconds after the previous request completes. The response budget + follows the chart width, up to 2000 bins. Polling pauses in background tabs. +- Zoom using the slider, **Select range**, or Ctrl + mouse wheel. This + switches to **Manual**, debounces the selected time range and requests finer + data from the API. The full-run navigation domain is retained, allowing zoom + back out beyond the currently loaded detail window. +- **Select range** lets you drag across the plot. **Back** restores the previous + view, including after detailed data has loaded. Zoom history is managed by the + query state, independently of chart updates. +- Manual mode also provides keyboard-accessible From/To inputs in UTC. **Auto** + restores the full-run view; **Refresh** reloads the selected window. +- The plot follows the current acquisition automatically; historical run selection + is not exposed. After Stop, the previous run remains visible; + polling allows final collector writes to arrive before ending once a stopped + run's latest timestamp has been unchanged for three polls. +- Horizontal segments show each bin's counter-derived interval average in Hz. + Missing coverage is a gap, not zero; a measured zero remains zero. Tooltip + intervals and coverage describe the API bins. Coverage is relative to the GDCs + recorded in that run, not an expected-configuration snapshot. +- Superseded requests are aborted and stale responses ignored. A refresh error + preserves the last successful result with a visible error message. Leaving the + page stops polling and disconnects observers. + +`src/composables/useRateHistory.ts` manages query state and polling; +`RateHistory.vue` owns controls and status; `RateHistoryChart.vue` renders the +series and emits zoom/resize events. Existing WebSocket statistics stay separate. + +Run `npm run type-check`, `npm run test:unit -- --run`, and +`npm run test:history:e2e`. The browser test mocks HTTP API responses, so it does +not require a detector or database. If Chromium is installed at a custom path, +set `PLAYWRIGHT_CHROMIUM_EXECUTABLE` when running the browser test. It verifies +actual zoom gestures, detailed time-window requests, Auto mode, UTC window +inputs, current-run display and mobile layout. + +For short local demonstrations, build with `VITE_RATE_HISTORY_MAX_POINTS=30` +to exercise automatic rebinning after a few minutes. The setting accepts limits +from 10 to 2000; omitting it retains the normal width-based point budget. + +At viewport widths of at least 1200 pixels, configurations with up to four +GDCs/LDCs in total show a combined statistics table beside a smaller plot. +Larger configurations and narrower screens keep the table above the plot. diff --git a/gui/e2e/rate-history.spec.ts b/gui/e2e/rate-history.spec.ts new file mode 100644 index 0000000..88db38e --- /dev/null +++ b/gui/e2e/rate-history.spec.ts @@ -0,0 +1,105 @@ +import { test, expect } from '@playwright/test' + +test('rate history renders, zooms with a detailed request, restores Auto and shows only the current run', async ({ page }) => { + let fleetSize = 1 + const requests: Record[] = [] + const errors: string[] = [] + page.on('pageerror', error => errors.push(error.message)) + const origin = Date.parse('2026-11-04T12:00:00Z') + const end = origin + 3600000 + await page.route('**/apiService.DuckAPI/*', async route => { + const method = route.request().url().split('/').pop() + let body: any = {} + if (method === 'GetRunNumber') body = { runNumber: 123 } + else if (method === 'GetGDCs') body = { gdcs: Array.from({ length: fleetSize }, (_, i) => ({ id: i + 1, name: `gdc${i + 1}`, enabled: true })) } + else if (method === 'GetLDCs') body = { ldcs: Array.from({ length: fleetSize }, (_, i) => ({ id: i + 1, name: `ldc${i + 1}`, enabled: true })) } + else if (method === 'GetToken') body = { token: '' } + else if (method === 'CheckDisabled') body = { warnings: {} } + else if (method === 'GetRateHistory') { + const request = route.request().postDataJSON() + requests.push(request) + if (request.run === 999) body = { run: 999, hasData: false, bins: [], gdcs: [] } + else { + const from = request.from ? Date.parse(request.from) : origin + const to = request.to ? Date.parse(request.to) : end + const width = Math.max(5, Math.ceil((to - from) / 1000 / Math.min(request.maxPoints ?? 1000, 300) / 5) * 5) + const bins = [] + for (let start = from, i = 0; start < to; start += width * 1000, i++) { + const complete = i !== 3 + bins.push({ start: new Date(start).toISOString(), end: new Date(Math.min(to, start + width * 1000)).toISOString(), ...(complete ? { triggerRateHz: i === 2 ? 0 : 120 + 20 * Math.sin(i / 10), byteRate: 50000 } : {}), complete, coverage: complete ? 1 : 0.5 }) + } + body = { run: 123, hasData: true, from: new Date(from).toISOString(), to: new Date(to).toISOString(), latestSample: new Date(end).toISOString(), runStart: new Date(origin).toISOString(), binWidthSeconds: width, gdcs: ['gdc1', 'gdc2'], coverageBasis: 'observed_run_history', bins } + } + } + await route.fulfill({ json: body, headers: { 'access-control-allow-origin': '*' } }) + }) + await page.goto('/daq/') + const panel = page.getByTestId('rate-history-panel') + await expect(panel.getByRole('heading', { name: 'Trigger rate history' })).toBeVisible() + await expect(panel.locator('canvas')).toBeVisible() + await expect(panel.getByText(/incomplete coverage/)).toBeVisible() + await expect.poll(() => requests.length).toBeGreaterThan(0) + await page.getByTestId('rate-history-chart').scrollIntoViewIfNeeded() + const statisticsBox = await page.getByTestId('run-statistics-container').boundingBox() + const historyBox = await panel.boundingBox() + expect(statisticsBox!.x + statisticsBox!.width).toBeLessThan(historyBox!.x) + expect(Math.abs(statisticsBox!.y - historyBox!.y)).toBeLessThan(16) + await expect(panel.getByRole('button', { name: 'Back', exact: true })).toBeDisabled() + await panel.getByRole('button', { name: 'Select range', exact: true }).click() + await expect(panel.getByRole('button', { name: 'Cancel selection', exact: true })).toHaveAttribute('aria-pressed', 'true') + const selectionBox = await page.getByTestId('rate-history-canvas').boundingBox() + if (!selectionBox) throw new Error('Selection canvas not visible') + await page.mouse.move(selectionBox.x + selectionBox.width * 0.25, selectionBox.y + 120) + await page.mouse.down() + await page.mouse.move(selectionBox.x + selectionBox.width * 0.65, selectionBox.y + 120, { steps: 12 }) + await page.mouse.up() + await expect(panel.getByRole('button', { name: 'Manual', exact: true })).toHaveAttribute('aria-pressed', 'true') + await expect.poll(() => requests.some(request => request.from && request.to)).toBe(true) + await panel.getByRole('button', { name: 'Back', exact: true }).click() + await expect(panel.getByRole('button', { name: 'Auto', exact: true })).toHaveAttribute('aria-pressed', 'true') + await expect(panel.getByRole('button', { name: 'Back', exact: true })).toBeDisabled() + await page.getByTestId('rate-history-canvas').scrollIntoViewIfNeeded() + const beforeZoom = requests.length + const box = await page.getByTestId('rate-history-chart').boundingBox() + if (!box) throw new Error('Chart not visible') + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2) + await page.keyboard.down('Control') + await page.mouse.wheel(0, -400) + await page.keyboard.up('Control') + await expect(panel.getByRole('button', { name: 'Manual', exact: true })).toHaveAttribute('aria-pressed', 'true') + await expect.poll(() => requests.slice(beforeZoom).some(request => request.from && request.to && Date.parse(request.to) - Date.parse(request.from) < end - origin)).toBe(true) + await panel.getByLabel('From (UTC)').fill('2026-11-04T12:15') + await panel.getByLabel('To (UTC)').fill('2026-11-04T12:30') + await panel.getByRole('button', { name: 'Apply window', exact: true }).click() + await expect.poll(() => requests.some(request => request.from === '2026-11-04T12:15:00Z' && request.to === '2026-11-04T12:30:00Z')).toBe(true) + await panel.getByRole('button', { name: 'Auto', exact: true }).click() + await expect.poll(() => requests[requests.length - 1]?.from).toBeUndefined() + await expect(panel.getByRole('button', { name: 'Auto', exact: true })).toHaveAttribute('aria-pressed', 'true') + await page.setViewportSize({ width: 390, height: 844 }) + await expect(panel.locator('canvas')).toBeVisible() + const mobileStatistics = await page.getByTestId('run-statistics-container').boundingBox() + const mobileHistory = await panel.boundingBox() + expect(mobileHistory!.y).toBeGreaterThanOrEqual(mobileStatistics!.y + mobileStatistics!.height) + expect((await panel.boundingBox())!.width).toBeLessThanOrEqual(390) + await page.screenshot({ path: '/tmp/duck-rate-history-mobile.png', fullPage: true }) + await page.setViewportSize({ width: 1440, height: 1000 }) + await expect(panel.getByRole('spinbutton')).toHaveCount(0) + await expect(panel.getByRole('button', { name: 'Load', exact: true })).toHaveCount(0) + await expect(panel.getByRole('button', { name: 'Live run', exact: true })).toHaveCount(0) + await expect(panel.getByText('Run 123', { exact: true })).toBeVisible() + await page.screenshot({ path: '/tmp/duck-rate-history-desktop.png', fullPage: true }) + fleetSize = 2 + await page.reload() + await expect(panel.locator('canvas')).toBeVisible() + const hdStatistics = await page.getByTestId('run-statistics-container').boundingBox() + const hdHistory = await panel.boundingBox() + expect(hdStatistics!.x + hdStatistics!.width).toBeLessThan(hdHistory!.x) + expect(hdHistory!.width).toBeGreaterThan(450) + fleetSize = 7 + await page.reload() + await expect(panel.locator('canvas')).toBeVisible() + const largeStatistics = await page.getByTestId('run-statistics-container').boundingBox() + const largeHistory = await panel.boundingBox() + expect(largeHistory!.y).toBeGreaterThanOrEqual(largeStatistics!.y + largeStatistics!.height) + expect(errors).toEqual([]) +}) diff --git a/gui/package-lock.json b/gui/package-lock.json index 596014c..9339ab5 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -18,12 +18,14 @@ "centrifuge": "^5.2.2", "daisyui": "^4.7.2", "dayjs": "^1.11.10", + "echarts": "^6.1.0", "pinia": "^2.1.7", "postcss": "^8.4.35", "tailwind": "^4.0.0", "tailwindcss": "^3.4.1", "vee-validate": "^4.12.6", "vue": "^3.4.15", + "vue-echarts": "^8.3.2", "vue-router": "^4.2.5", "ws": "^8.16.0", "yup": "^1.4.0" @@ -2777,6 +2779,22 @@ "safe-buffer": "^5.0.1" } }, + "node_modules/echarts": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/echarts/-/echarts-6.1.0.tgz", + "integrity": "sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "2.3.0", + "zrender": "6.1.0" + } + }, + "node_modules/echarts/node_modules/tslib": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", + "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==", + "license": "0BSD" + }, "node_modules/editorconfig": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/editorconfig/-/editorconfig-1.0.4.tgz", @@ -7340,6 +7358,16 @@ "integrity": "sha512-0vOfAtI67UjeO1G6UiX5Kd76CqaQ67wrRZiOe7UAb9Jm6GzlUr/fC7CV90XfwapJRjpCMaZFhv1V0ajWRmE9Dg==", "dev": true }, + "node_modules/vue-echarts": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/vue-echarts/-/vue-echarts-8.3.2.tgz", + "integrity": "sha512-FbJD49OZZZv1I8aclHQ+gcQxU+Y9nNWQMuod1sewE7/YjGQUJAaeVcf6WrSfQDBRPke+WoVsUtdRFIqPOsRrnw==", + "license": "MIT", + "peerDependencies": { + "echarts": "^6.0.0", + "vue": "^3.3.0" + } + }, "node_modules/vue-router": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.3.0.tgz", @@ -7752,6 +7780,21 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/zrender": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/zrender/-/zrender-6.1.0.tgz", + "integrity": "sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==", + "license": "BSD-3-Clause", + "dependencies": { + "tslib": "2.3.0" + } + }, + "node_modules/zrender/node_modules/tslib": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", + "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==", + "license": "0BSD" } } } diff --git a/gui/package.json b/gui/package.json index ec80bac..074450f 100644 --- a/gui/package.json +++ b/gui/package.json @@ -24,7 +24,8 @@ "docker:test:integration:full": "docker compose -f docker-compose.playwright.yml --profile integration up -d && docker compose -f docker-compose.playwright.yml --profile integration run --rm playwright bash -c 'timeout 120 bash -c \"until curl -fs http://api:1323/health; do sleep 1; done\" && timeout 30 bash -c \"until curl -fs http://centrifugo:8000/health; do sleep 1; done\"' && docker compose -f docker-compose.playwright.yml run --rm playwright npx playwright test --config=playwright.integration.config.ts; docker compose -f docker-compose.playwright.yml --profile integration down -v", "docker:test:integration:ui": "docker compose -f docker-compose.playwright.yml --profile integration up -d && docker compose -f docker-compose.playwright.yml --profile integration run --rm --service-ports -e CI=false playwright bash -c 'until curl -fs http://api:1323/health; do sleep 1; done && npx playwright test --config=playwright.integration.config.ts --ui-host=0.0.0.0 --ui-port=9323'", "docker:test:integration:down": "docker compose -f docker-compose.playwright.yml --profile integration down -v", - "docker:shell": "docker compose -f docker-compose.playwright.yml run --rm playwright /bin/bash" + "docker:shell": "docker compose -f docker-compose.playwright.yml run --rm playwright /bin/bash", + "test:history:e2e": "playwright test --config playwright.rate-history.config.ts" }, "dependencies": { "@bufbuild/protobuf": "^1.10.1", @@ -37,12 +38,14 @@ "centrifuge": "^5.2.2", "daisyui": "^4.7.2", "dayjs": "^1.11.10", + "echarts": "^6.1.0", "pinia": "^2.1.7", "postcss": "^8.4.35", "tailwind": "^4.0.0", "tailwindcss": "^3.4.1", "vee-validate": "^4.12.6", "vue": "^3.4.15", + "vue-echarts": "^8.3.2", "vue-router": "^4.2.5", "ws": "^8.16.0", "yup": "^1.4.0" diff --git a/gui/playwright.rate-history.config.ts b/gui/playwright.rate-history.config.ts new file mode 100644 index 0000000..b1111b8 --- /dev/null +++ b/gui/playwright.rate-history.config.ts @@ -0,0 +1,11 @@ +import { defineConfig, devices } from '@playwright/test' + +export default defineConfig({ + testDir: './e2e', + testMatch: '**/rate-history.spec.ts', + workers: 1, + reporter: 'list', + use: { baseURL: 'http://127.0.0.1:4191', trace: 'retain-on-failure', screenshot: 'only-on-failure' }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'], launchOptions: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE ? { executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE } : {} } }], + webServer: { command: 'npm run build-only && npm run preview -- --host 127.0.0.1 --port 4191 --strictPort', url: 'http://127.0.0.1:4191/daq/', reuseExistingServer: false, timeout: 120000 }, +}) diff --git a/gui/src/components/RateHistory.vue b/gui/src/components/RateHistory.vue new file mode 100644 index 0000000..38301f9 --- /dev/null +++ b/gui/src/components/RateHistory.vue @@ -0,0 +1,57 @@ + + + diff --git a/gui/src/components/RateHistoryChart.vue b/gui/src/components/RateHistoryChart.vue new file mode 100644 index 0000000..5bc1604 --- /dev/null +++ b/gui/src/components/RateHistoryChart.vue @@ -0,0 +1,107 @@ + + + + diff --git a/gui/src/components/RunStatistics.vue b/gui/src/components/RunStatistics.vue index 76a9e7f..26ee27e 100644 --- a/gui/src/components/RunStatistics.vue +++ b/gui/src/components/RunStatistics.vue @@ -6,6 +6,8 @@ import { useLDCStore } from '../stores/ldc' import { useMessagesStore } from "@/stores/messages"; import { storeToRefs } from 'pinia' +defineProps<{ compact?: boolean }>() + const gdcStore = useGDCStore() const ldcStore = useLDCStore() const messagesStore = useMessagesStore() @@ -25,7 +27,7 @@ function formatBytes(bytes: number, decimals: number) { + + diff --git a/gui/src/composables/__tests__/useRateHistory.spec.ts b/gui/src/composables/__tests__/useRateHistory.spec.ts new file mode 100644 index 0000000..8cac591 --- /dev/null +++ b/gui/src/composables/__tests__/useRateHistory.spec.ts @@ -0,0 +1,124 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, ref } from 'vue' +import { mount, flushPromises } from '@vue/test-utils' +import { Timestamp } from '@bufbuild/protobuf' +import { GetRateHistoryResponse } from '@/gen/api_pb' +import { mockDuckApiClient } from '@/test/setup' +import { useRateHistory } from '../useRateHistory' + +const origin = Date.parse('2026-11-04T12:00:00Z') +function result(run = 123) { + return new GetRateHistoryResponse({ run, hasData: true, from: Timestamp.fromDate(new Date(origin)), to: Timestamp.fromDate(new Date(origin + 3600000)), latestSample: Timestamp.fromDate(new Date(origin + 3600000)), bins: [], binWidthSeconds: 5 }) +} +function setup() { + const run = ref(123), running = ref(true) + let history!: ReturnType + const wrapper = mount(defineComponent({ setup() { history = useRateHistory(run, running); return () => null } })) + return { wrapper, history, run, running } +} +let cleanup: (() => void) | undefined +beforeEach(() => { + vi.useFakeTimers() + Object.defineProperty(document, 'hidden', { configurable: true, value: false }) + mockDuckApiClient.getRateHistory.mockReset().mockResolvedValue(result()) +}) +afterEach(() => { cleanup?.(); cleanup = undefined; vi.useRealTimers() }) + +describe('rate history requests', () => { + it('polls after completion, requests a bounded whole-run series, and preserves the run after Stop', async () => { + const { wrapper, history, run, running } = setup(); cleanup = () => wrapper.unmount() + await flushPromises() + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledWith(expect.objectContaining({ run: 123, maxPoints: 1000 }), expect.objectContaining({ signal: expect.any(AbortSignal) })) + running.value = false; run.value = 124 + await flushPromises() + expect(history.selectedRun.value).toBe(123) + await vi.advanceTimersByTimeAsync(5000) + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledTimes(2) + running.value = true + await flushPromises() + expect(history.selectedRun.value).toBe(124) + }) + it('debounces zoom, retains the overview, and restores automatic requests', async () => { + const { wrapper, history } = setup(); cleanup = () => wrapper.unmount() + await flushPromises() + const overview = history.overview.value + history.zoom({ from: origin + 10000, to: origin + 60000 }) + history.zoom({ from: origin + 20000, to: origin + 50000 }) + await vi.advanceTimersByTimeAsync(250) + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledTimes(2) + const request = mockDuckApiClient.getRateHistory.mock.calls[1][0] as any + expect(request.from.toDate().getTime()).toBe(origin + 20000) + expect(history.overview.value).toBe(overview) + await vi.advanceTimersByTimeAsync(10000) + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledTimes(2) + history.auto(); await flushPromises() + expect(mockDuckApiClient.getRateHistory.mock.calls[2][0]).not.toHaveProperty('from') + }) + it('ignores superseded results even if the transport ignores abort', async () => { + let resolve!: (response: GetRateHistoryResponse) => void + mockDuckApiClient.getRateHistory.mockImplementationOnce(() => new Promise(done => { resolve = done })) + const { wrapper, history } = setup(); cleanup = () => wrapper.unmount() + mockDuckApiClient.getRateHistory.mockResolvedValue(result(222)) + history.selectRun(222) + await flushPromises() + resolve(result(123)); await flushPromises() + expect(history.selectedRun.value).toBe(222) + expect(history.response.value?.run).toBe(222) + }) + it('pauses hidden pages, resumes on visibility, and cleans timers on unmount', async () => { + const { wrapper } = setup(); await flushPromises() + Object.defineProperty(document, 'hidden', { configurable: true, value: true }) + document.dispatchEvent(new Event('visibilitychange')) + await vi.advanceTimersByTimeAsync(10000) + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledTimes(1) + Object.defineProperty(document, 'hidden', { configurable: true, value: false }) + document.dispatchEvent(new Event('visibilitychange')); await flushPromises() + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledTimes(2) + wrapper.unmount() + await vi.advanceTimersByTimeAsync(10000) + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledTimes(2) + }) + it('does not overlap slow automatic requests', async () => { + let resolve!: (value: GetRateHistoryResponse) => void + mockDuckApiClient.getRateHistory.mockImplementationOnce(() => new Promise(done => { resolve = done })) + const { wrapper } = setup(); cleanup = () => wrapper.unmount() + await vi.advanceTimersByTimeAsync(20000) + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledTimes(1) + resolve(result()); await flushPromises() + await vi.advanceTimersByTimeAsync(5000) + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledTimes(2) + }) + it('ends automatic polling only after final stopped-run data settles', async () => { + const stopped = result(); stopped.runStop = Timestamp.fromDate(new Date(origin + 3600000)) + mockDuckApiClient.getRateHistory.mockResolvedValue(stopped) + const { wrapper } = setup(); cleanup = () => wrapper.unmount() + await flushPromises() + await vi.advanceTimersByTimeAsync(30000) + expect(mockDuckApiClient.getRateHistory).toHaveBeenCalledTimes(4) + }) + it('keeps zoom history across requests and restores prior views', async () => { + const { wrapper, history } = setup(); cleanup = () => wrapper.unmount() + await flushPromises() + history.zoom({ from: origin + 10000, to: origin + 60000 }) + await vi.advanceTimersByTimeAsync(250) + history.zoom({ from: origin + 20000, to: origin + 40000 }) + await vi.advanceTimersByTimeAsync(250) + expect(history.canGoBack.value).toBe(true) + history.back(); await flushPromises() + expect(history.window.value).toEqual({ from: origin + 10000, to: origin + 60000 }) + history.back(); await flushPromises() + expect(history.window.value).toBeNull() + expect(history.mode.value).toBe('auto') + expect(history.canGoBack.value).toBe(false) + }) + it('keeps the last successful data on failure and bounds the resize budget', async () => { + const { wrapper, history } = setup(); cleanup = () => wrapper.unmount() + await flushPromises() + const previous = history.response.value + mockDuckApiClient.getRateHistory.mockRejectedValue(new Error('Server unavailable')) + history.setWidth(5000); await vi.advanceTimersByTimeAsync(250) + expect(history.pointBudget.value).toBe(2000) + expect(history.response.value).toBe(previous) + expect(history.error.value).toBe('Server unavailable') + }) +}) diff --git a/gui/src/composables/useRateHistory.ts b/gui/src/composables/useRateHistory.ts new file mode 100644 index 0000000..f0f52cb --- /dev/null +++ b/gui/src/composables/useRateHistory.ts @@ -0,0 +1,156 @@ +import { computed, onMounted, onUnmounted, ref, shallowRef, watch, type Ref } from 'vue' +import { Timestamp } from '@bufbuild/protobuf' +import duckApiClient from '@/api/client' +import type { GetRateHistoryResponse } from '@/gen/api_pb' + +export type TimeWindow = { from: number; to: number } +export const timestampMillis = (value?: Timestamp) => value?.toDate().getTime() + +export function useRateHistory(liveRun: Ref, running: Ref) { + const selectedRun = ref(0) + const followLive = ref(true) + const mode = ref<'auto' | 'manual'>('auto') + const zoomHistory = ref<(TimeWindow | null)[]>([]) + const canGoBack = computed(() => zoomHistory.value.length > 0) + const window = ref(null) + // Optional demo limit makes adaptive rebinning visible in short test runs. + const configuredLimit = Number(import.meta.env.VITE_RATE_HISTORY_MAX_POINTS) + const pointLimit = Number.isInteger(configuredLimit) && configuredLimit >= 10 && configuredLimit <= 2000 ? configuredLimit : 2000 + const pointBudget = ref(Math.min(1000, pointLimit)) + const response = shallowRef(null) + const overview = shallowRef(null) + const loading = ref(false) + const error = ref('') + const updatedAt = ref(null) + const domain = computed(() => { + const data = overview.value ?? response.value + const from = timestampMillis(data?.from) + const to = timestampMillis(data?.to) + return from !== undefined && to !== undefined && to > from ? { from, to } : null + }) + let timer: ReturnType | undefined + let zoomTimer: ReturnType | undefined + let controller: AbortController | undefined + let generation = 0 + let disposed = false + let mounted = false + let stoppedStablePolls = 0 + + function cancel() { + clearTimeout(timer) + clearTimeout(zoomTimer) + zoomTimer = undefined + generation++ + controller?.abort() + loading.value = false + } + + async function refresh() { + cancel() + if (disposed || !mounted || selectedRun.value <= 0 || document.hidden) return + const requestGeneration = generation + controller = new AbortController() + loading.value = true + try { + const bounds = mode.value === 'manual' ? window.value : null + const result = await duckApiClient.getRateHistory({ + run: selectedRun.value, + maxPoints: pointBudget.value, + ...(bounds ? { from: Timestamp.fromDate(new Date(bounds.from)), to: Timestamp.fromDate(new Date(bounds.to)) } : {}), + }, { signal: controller.signal }) + if (generation !== requestGeneration || disposed) return + const previousLatest = timestampMillis(response.value?.latestSample) + stoppedStablePolls = result.runStop && previousLatest === timestampMillis(result.latestSample) ? stoppedStablePolls + 1 : 0 + response.value = result + if (mode.value === 'auto' || !overview.value) overview.value = result + updatedAt.value = Date.now() + error.value = '' + } catch (cause) { + if (generation !== requestGeneration || disposed) return + error.value = cause instanceof Error ? cause.message : 'Could not load rate history.' + } finally { + if (generation === requestGeneration && !disposed) { + loading.value = false + // Allow the final collector writes to arrive after Stop before ending polling. + if (mode.value === 'auto' && !document.hidden && stoppedStablePolls < 3) { + timer = setTimeout(() => void refresh(), 5000) + } + } + } + } + + function selectRun(run: number, follow = false) { + if (!Number.isInteger(run) || run <= 0 || run > 2147483647) return + cancel() + zoomHistory.value = [] + selectedRun.value = run + followLive.value = follow + mode.value = 'auto' + window.value = null + response.value = overview.value = null + updatedAt.value = null + stoppedStablePolls = 0 + error.value = '' + void refresh() + } + function auto() { + zoomHistory.value = [] + mode.value = 'auto' + window.value = null + stoppedStablePolls = 0 + void refresh() + } + function manual() { + cancel() + mode.value = 'manual' + window.value = domain.value ? { ...domain.value } : null + } + function zoom(bounds: TimeWindow) { + if (!Number.isFinite(bounds.from) || !Number.isFinite(bounds.to) || bounds.from >= bounds.to) return + const previous = mode.value === 'manual' ? window.value : null + const sameWindow = previous && Math.abs(previous.from - bounds.from) < 1 && Math.abs(previous.to - bounds.to) < 1 + if (!sameWindow && zoomTimer === undefined) { + zoomHistory.value.push(previous ? { ...previous } : null) + if (zoomHistory.value.length > 50) zoomHistory.value.shift() + } + cancel() + mode.value = 'manual' + window.value = bounds + zoomTimer = setTimeout(() => { zoomTimer = undefined; void refresh() }, 250) + } + function back() { + if (!canGoBack.value) return + const previous = zoomHistory.value.pop()! + cancel() + mode.value = previous ? 'manual' : 'auto' + window.value = previous + stoppedStablePolls = 0 + void refresh() + } + function setWidth(width: number) { + const budget = Math.min(pointLimit, Math.max(100, Math.round(width))) + if (Math.abs(budget - pointBudget.value) < 50) return + pointBudget.value = budget + clearTimeout(zoomTimer) + zoomTimer = setTimeout(() => void refresh(), 250) + } + function visibilityChanged() { + if (document.hidden) cancel() + else if (mode.value === 'auto') void refresh() + } + watch([liveRun, running], ([run, active]) => { + if (followLive.value && run > 0 && (selectedRun.value === 0 || active && run !== selectedRun.value)) selectRun(run, true) + }) + onMounted(() => { + mounted = true + document.addEventListener('visibilitychange', visibilityChanged) + if (liveRun.value > 0 && selectedRun.value === 0) selectRun(liveRun.value, true) + else void refresh() + }) + onUnmounted(() => { + disposed = true + cancel() + document.removeEventListener('visibilitychange', visibilityChanged) + }) + return { selectedRun, followLive, mode, window, pointBudget, response, overview, domain, loading, error, updatedAt, canGoBack, back, pause: cancel, refresh, selectRun, auto, manual, zoom, setWidth } +} diff --git a/gui/src/stores/__tests__/messages.spec.ts b/gui/src/stores/__tests__/messages.spec.ts index b50661d..ec81b7a 100644 --- a/gui/src/stores/__tests__/messages.spec.ts +++ b/gui/src/stores/__tests__/messages.spec.ts @@ -236,6 +236,18 @@ describe('Messages Store', () => { }) describe('state messages', () => { + it('keeps DAQ controls independent of simulator lifecycle', () => { + const state = (host: string, value: string) => simulatePublication({ host, timestamp: '2026-11-04T15:00:00Z', type: 'state', value: JSON.stringify({ state: value }), run: 3 }) + state('ldc1', 'RUNNING') + state('simulator-1', 'INITIALIZED') + expect(store.status).toBe('RUNNING') + expect(store.stopRunEnabled).toBe(true) + state('simulator-1', 'RUNNING') + state('ldc1', 'INITIALIZED') + expect(store.status).toBe('INITIALIZED') + expect(store.startRunEnabled).toBe(true) + }) + it('should process RUNNING state and update control states', () => { simulatePublication({ ...mockWebSocketMessages.stateMessage, diff --git a/gui/src/stores/messages.ts b/gui/src/stores/messages.ts index 867a7b3..5a7bd36 100644 --- a/gui/src/stores/messages.ts +++ b/gui/src/stores/messages.ts @@ -237,6 +237,9 @@ export const useMessagesStore = defineStore("messages", () => { } break; case "state": + // A simulator can keep running while DAQ receivers stop between runs. + // Its lifecycle must not disable the acquisition Start/Stop controls. + if (evtParsed.host.startsWith("simulator-")) break; const stateData: StateType = JSON.parse(evtParsed.value); states.value[evtParsed.host] = stateData.state; diff --git a/gui/src/test/setup.ts b/gui/src/test/setup.ts index fc4aad5..5863c1b 100644 --- a/gui/src/test/setup.ts +++ b/gui/src/test/setup.ts @@ -18,6 +18,7 @@ const mockDuckApiClient = { getGDCs: vi.fn(() => Promise.resolve({ gdcs: [] })), getEquipments: vi.fn(() => Promise.resolve({ equipments: [] })), getProcessStates: vi.fn(() => Promise.resolve({ states: {} })), + getRateHistory: vi.fn(() => Promise.resolve({ hasData: false, bins: [], gdcs: [] })), getRunNumber: vi.fn(() => Promise.resolve({ runNumber: 0 })), updateDecoderConfiguration: vi.fn(() => Promise.resolve({})), createGDC: vi.fn(() => Promise.resolve({})), diff --git a/gui/src/views/HomeView.vue b/gui/src/views/HomeView.vue index 798ac59..9739fdc 100644 --- a/gui/src/views/HomeView.vue +++ b/gui/src/views/HomeView.vue @@ -5,6 +5,16 @@ import LogMessages from '@/components/LogMessages.vue' import RunControl from '@/components/RunControl.vue'; import RunStatistics from '@/components/RunStatistics.vue'; import Status from '@/components/Status.vue'; +import RateHistory from '@/components/RateHistory.vue'; +import { computed } from 'vue'; +import { useGDCStore } from '@/stores/gdc'; +import { useLDCStore } from '@/stores/ldc'; +const gdcStore = useGDCStore(); +const ldcStore = useLDCStore(); +const compactOverview = computed(() => { + const count = gdcStore.gdcs.length + ldcStore.ldcs.length; + return count > 0 && count <= 4; +}); + +