Measure takes a given Pubsub implementation, publishes a message & immediately receives it, and returns the observed latency.
(ctx context.Context, p Pubsub)
| 32 | |
| 33 | // Measure takes a given Pubsub implementation, publishes a message & immediately receives it, and returns the observed latency. |
| 34 | func (lm *LatencyMeasurer) Measure(ctx context.Context, p Pubsub) (send, recv time.Duration, err error) { |
| 35 | var ( |
| 36 | start time.Time |
| 37 | res = make(chan time.Duration, 1) |
| 38 | ) |
| 39 | |
| 40 | msg := []byte(uuid.New().String()) |
| 41 | lm.logger.Debug(ctx, "performing measurement", slog.F("msg", msg)) |
| 42 | |
| 43 | cancel, err := p.Subscribe(lm.latencyChannelName(), func(ctx context.Context, in []byte) { |
| 44 | if !bytes.Equal(in, msg) { |
| 45 | lm.logger.Warn(ctx, "received unexpected message", slog.F("got", in), slog.F("expected", msg)) |
| 46 | return |
| 47 | } |
| 48 | |
| 49 | res <- time.Since(start) |
| 50 | }) |
| 51 | if err != nil { |
| 52 | return -1, -1, xerrors.Errorf("failed to subscribe: %w", err) |
| 53 | } |
| 54 | defer cancel() |
| 55 | |
| 56 | start = time.Now() |
| 57 | err = p.Publish(lm.latencyChannelName(), msg) |
| 58 | if err != nil { |
| 59 | return -1, -1, xerrors.Errorf("failed to publish: %w", err) |
| 60 | } |
| 61 | |
| 62 | send = time.Since(start) |
| 63 | select { |
| 64 | case <-ctx.Done(): |
| 65 | lm.logger.Error(ctx, "context canceled before message could be received", slog.Error(ctx.Err()), slog.F("msg", msg)) |
| 66 | return send, -1, ctx.Err() |
| 67 | case recv = <-res: |
| 68 | return send, recv, nil |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | func (lm *LatencyMeasurer) latencyChannelName() string { |
| 73 | return fmt.Sprintf("latency-measure:%s", lm.channel) |