Skip to content

Commit d1c5f09

Browse files
committed
Make connection-close telemetry flush blocking
Add flushSync method to metricsAggregator that holds the lock only while draining the batch, then calls exporter.export synchronously. Update Interceptor.Close to use flushSync so telemetry is guaranteed to be delivered before the connection returns to the pool, matching JDBC's blocking flush(true) behavior on session close. Co-authored-by: Isaac
1 parent edc6e10 commit d1c5f09

2 files changed

Lines changed: 18 additions & 2 deletions

File tree

telemetry/aggregator.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,13 +197,29 @@ func (agg *metricsAggregator) flushLoop() {
197197
}
198198
}
199199

200-
// flush flushes pending metrics to exporter.
200+
// flush flushes pending metrics to exporter asynchronously (fire-and-forget).
201201
func (agg *metricsAggregator) flush(ctx context.Context) {
202202
agg.mu.Lock()
203203
defer agg.mu.Unlock()
204204
agg.flushUnlocked(ctx)
205205
}
206206

207+
// flushSync flushes pending metrics synchronously, blocking until the export
208+
// completes. Used on connection close to guarantee delivery before returning.
209+
func (agg *metricsAggregator) flushSync(ctx context.Context) {
210+
agg.mu.Lock()
211+
if len(agg.batch) == 0 {
212+
agg.mu.Unlock()
213+
return
214+
}
215+
metrics := make([]*telemetryMetric, len(agg.batch))
216+
copy(metrics, agg.batch)
217+
agg.batch = agg.batch[:0]
218+
agg.mu.Unlock()
219+
220+
agg.exporter.export(ctx, metrics)
221+
}
222+
207223
// flushUnlocked flushes without locking (caller must hold lock).
208224
func (agg *metricsAggregator) flushUnlocked(ctx context.Context) {
209225
if len(agg.batch) == 0 {

telemetry/interceptor.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,6 @@ func (i *Interceptor) Close(ctx context.Context) error {
200200
return nil
201201
}
202202

203-
i.aggregator.flush(ctx)
203+
i.aggregator.flushSync(ctx)
204204
return nil
205205
}

0 commit comments

Comments
 (0)