forked from dial9-rs/dial9
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriter.rs
More file actions
2401 lines (2164 loc) · 88.7 KB
/
writer.rs
File metadata and controls
2401 lines (2164 loc) · 88.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use dial9_trace_format::encoder::{Encoder, RawEncoder};
use crate::rate_limit::rate_limited;
use crate::telemetry::collector::Batch;
use crate::telemetry::events::clock_pair;
use crate::telemetry::format::{ClockSyncEvent, SegmentMetadataEvent};
use std::collections::{BTreeMap, VecDeque};
use std::fs::{self, File};
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use metrique_timesource::time_source;
/// Trait for writing encoded telemetry batches to a destination.
pub trait TraceWriter: Send {
/// Flush buffered data to the underlying storage.
fn flush(&mut self) -> std::io::Result<()>;
/// Returns true if the writer rotated to a new file since the last call to this method.
fn take_rotated(&mut self) -> bool {
false
}
/// Finalize the writer: flush, rename `.active` → `.bin`, and prevent
/// further writes. This is a terminal operation — the writer becomes
/// inert afterward.
fn finalize(&mut self) -> std::io::Result<()> {
self.flush()
}
/// Transcode encoded bytes into this writer.
fn write_encoded_batch(&mut self, batch: &Batch) -> std::io::Result<()>;
/// Return the current segment metadata entries. Default returns empty.
fn segment_metadata(&self) -> &[(String, String)] {
&[]
}
/// Merge the segment metadata entries that will be written into the next
/// rotated segment (e.g. merged static + runtime names). Default is a no-op.
fn update_segment_metadata(&mut self, _entries: Vec<(String, String)>) {}
/// Write a `SegmentMetadataEvent` into the current segment. Called before
/// finalize so that single-segment traces contain runtime→worker mappings.
/// Default is a no-op.
fn write_current_segment_metadata(&mut self) -> std::io::Result<()> {
Ok(())
}
/// Returns `true` when the flush loop should drain all thread-local
/// buffers before the next step. For `RotatingWriter` this fires when a
/// rotation boundary is crossed *or* when a periodic drain interval
/// elapses (whichever comes first). Default returns `false`.
fn should_drain(&self) -> bool {
false
}
/// Called by the flush loop after thread-local buffers have been drained
/// and flushed. The writer may rotate the segment, advance a drain timer,
/// or do nothing. Returns `true` if a segment rotation occurred.
fn drained(&mut self) -> std::io::Result<bool> {
Ok(false)
}
}
impl<W: TraceWriter + ?Sized> TraceWriter for Box<W> {
fn flush(&mut self) -> std::io::Result<()> {
(**self).flush()
}
fn take_rotated(&mut self) -> bool {
(**self).take_rotated()
}
fn finalize(&mut self) -> std::io::Result<()> {
(**self).finalize()
}
fn write_encoded_batch(&mut self, batch: &Batch) -> std::io::Result<()> {
(**self).write_encoded_batch(batch)
}
fn segment_metadata(&self) -> &[(String, String)] {
(**self).segment_metadata()
}
fn update_segment_metadata(&mut self, entries: Vec<(String, String)>) {
(**self).update_segment_metadata(entries)
}
fn write_current_segment_metadata(&mut self) -> std::io::Result<()> {
(**self).write_current_segment_metadata()
}
fn should_drain(&self) -> bool {
(**self).should_drain()
}
fn drained(&mut self) -> std::io::Result<bool> {
(**self).drained()
}
}
#[derive(Default, Clone)]
struct SegmentMetadata {
entries: Vec<(String, String)>,
}
impl SegmentMetadata {
fn new(entries: Vec<(String, String)>) -> Self {
Self { entries }
}
/// Merge incoming entries with existing ones. Incoming entries take priority
/// on key conflict; existing entries with keys not in the incoming set are preserved.
/// Returns `true` if the resulting entries differ from the previous state.
fn merge(&mut self, entries: impl Iterator<Item = (String, String)>) -> bool {
let mut merged: Vec<(String, String)> = entries.collect();
for (k, v) in &self.entries {
if !merged.iter().any(|(mk, _)| mk == k) {
merged.push((k.clone(), v.clone()));
}
}
if merged == self.entries {
return false;
}
self.entries = merged;
true
}
}
/// A writer that discards all events. Useful for benchmarking hook overhead
/// without I/O costs.
#[derive(Debug)]
pub struct NullWriter;
impl TraceWriter for NullWriter {
fn write_encoded_batch(&mut self, _batch: &Batch) -> std::io::Result<()> {
Ok(())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// Default rotation period: 1 minute.
const DEFAULT_ROTATION_PERIOD: Duration = Duration::from_secs(60);
/// Default maximum interval between thread-local buffer drains.
const DEFAULT_DRAIN_INTERVAL: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SegmentArtifact {
Retained { index: u32 },
Active,
}
struct ExistingSegments {
closed_files: VecDeque<(PathBuf, u64)>,
next_active_index: u32,
}
/// A writer that rotates trace files to bound disk usage and time.
///
/// Rotation triggers when *either* condition is met:
/// - `max_file_size`: the current file exceeds this many bytes
/// - `rotation_period`: a wall-clock-aligned time boundary is crossed
/// (default: 1 minute, aligned to round minute boundaries)
///
/// **Prefer time-based rotation.** Time-based rotation is coordinated with the
/// flush loop: thread-local buffers are drained before the segment is sealed,
/// so each segment contains events from a clean, non-overlapping time window.
/// Size-based rotation fires immediately when the threshold is crossed and does
/// not drain thread-local buffers, so segments may contain events that overlap
/// in time. Set `max_file_size` large enough that time-based rotation fires
/// first under normal conditions (e.g. 100 MB or more). Size-based rotation
/// then acts as a safety valve for unexpected data bursts.
///
/// `max_total_size` controls eviction: oldest retained files for this trace
/// family are deleted when total size exceeds this budget, including artifacts
/// left by previous writer lifetimes.
///
/// Files are named `{base_path}.0.bin`, `{base_path}.1.bin`, etc.
/// Each file is a self-contained trace with its own header.
pub struct RotatingWriter {
base_path: PathBuf,
max_file_size: u64,
max_total_size: u64,
/// How often to rotate based on wall-clock time. `Duration::MAX` disables
/// time-based rotation (used by `single_file()`).
rotation_period: Duration,
/// The next wall-clock instant at which time-based rotation should fire.
next_rotation_time: SystemTime,
/// Tracks (path, size) of closed files oldest-first. The active file is
/// not in this list — its size comes from `encoder.bytes_written()`.
closed_files: VecDeque<(PathBuf, u64)>,
/// Path of the currently active (being-written) file.
active_path: PathBuf,
state: WriterState,
next_index: u32,
/// Set after rotation; cleared by `take_rotated()`.
did_rotate: bool,
/// Metadata written at the start of each segment. Updated by the flush
/// thread to include runtime names alongside any user-provided entries.
segment_metadata: SegmentMetadata,
/// Events silently dropped because the writer was finished/stopped.
dropped_events: usize,
/// Whether any real (non-metadata) events have been written to the current segment.
/// Reset on rotation; used by `finalize()` to avoid sealing empty segments.
has_real_events: bool,
/// How often the flush loop should drain thread-local buffers, independent
/// of rotation. Defaults to `min(rotation_period, 30s)`.
drain_interval: Duration,
/// Next wall-clock instant at which `should_drain()` returns true.
next_drain_time: SystemTime,
}
impl std::fmt::Debug for RotatingWriter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RotatingWriter")
.field("base_path", &self.base_path)
.field("max_file_size", &self.max_file_size)
.field("max_total_size", &self.max_total_size)
.finish_non_exhaustive()
}
}
// the write side is obviously marge larger than the `Finished` size so clippy warns on this
// but we don't want to force going through a pointer every time we want to write.
#[allow(clippy::large_enum_variant)]
enum WriterState {
/// Writer is open and events can be written
Active {
writer: RawEncoder<BufWriter<File>>,
need_metadata: bool,
},
/// Writer has been finalized or stopped — no encoder, no fd, no writes.
Finished,
}
#[bon::bon]
impl RotatingWriter {
/// Create a new rotating writer. For additional options like `segment_metadata`,
/// use [`RotatingWriter::builder()`].
pub fn new(
base_path: impl Into<PathBuf>,
max_file_size: u64,
max_total_size: u64,
) -> std::io::Result<Self> {
Self::create(
base_path,
max_file_size,
max_total_size,
DEFAULT_ROTATION_PERIOD,
SegmentMetadata::default(),
)
}
/// Create a `RotatingWriterBuilder` for advanced configuration.
#[builder(builder_type = RotatingWriterBuilder, finish_fn = build)]
pub fn builder(
base_path: impl Into<PathBuf>,
max_file_size: u64,
max_total_size: u64,
/// How often to rotate based on wall-clock time, aligned to round
/// boundaries (e.g. a 60 s period rotates at the top of each minute).
/// Defaults to 60 seconds.
rotation_period: Option<Duration>,
segment_metadata: Option<Vec<(String, String)>>,
) -> std::io::Result<Self> {
Self::create(
base_path,
max_file_size,
max_total_size,
rotation_period.unwrap_or(DEFAULT_ROTATION_PERIOD),
segment_metadata
.map(SegmentMetadata::new)
.unwrap_or_default(),
)
}
fn create(
base_path: impl Into<PathBuf>,
max_file_size: u64,
max_total_size: u64,
rotation_period: Duration,
segment_metadata: SegmentMetadata,
) -> std::io::Result<Self> {
if rotation_period == Duration::from_secs(0) {
return Err(std::io::Error::other("Rotation period must not be zero"));
}
let base_path = base_path.into();
if let Some(parent) = base_path.parent() {
fs::create_dir_all(parent)?;
}
let existing_segments = Self::discover_existing_segments(&base_path)?;
let first_path = Self::active_path(&base_path, existing_segments.next_active_index);
let file = File::create(&first_path)?;
let writer = BufWriter::new(file);
let state = Self::prepare_segment(writer)?;
let now = time_source().system_time().as_std();
let drain_interval = rotation_period.min(DEFAULT_DRAIN_INTERVAL);
let next_index = existing_segments
.next_active_index
.checked_add(1)
.ok_or_else(|| std::io::Error::other("trace segment index overflow"))?;
let mut writer = Self {
base_path,
max_file_size,
max_total_size,
rotation_period,
next_rotation_time: Self::next_boundary(now, rotation_period),
closed_files: existing_segments.closed_files,
active_path: first_path,
state,
next_index,
did_rotate: false,
segment_metadata,
dropped_events: 0,
has_real_events: false,
drain_interval,
next_drain_time: Self::next_boundary(now, drain_interval),
};
writer.evict_oldest()?;
Ok(writer)
}
/// Create a writer that writes to a single file with no rotation or eviction.
/// The segment is written to `{stem}.0.bin.active` while active, then sealed
/// to `{stem}.0.bin` on `finalize`. The background worker will symbolize
/// and gzip it to `{stem}.0.bin.gz`.
///
/// Note: This API does not allow the ability to provide custom segment metadata.
/// Time-based rotation is disabled.
pub fn single_file(path: impl Into<PathBuf>) -> std::io::Result<Self> {
let path = path.into();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let active_path = Self::active_path(&path, 0);
let file = File::create(&active_path)?;
let writer = BufWriter::new(file);
let state = Self::prepare_segment(writer)?;
let now = time_source().system_time().as_std();
Ok(Self {
base_path: path,
max_file_size: u64::MAX,
max_total_size: u64::MAX,
rotation_period: Duration::MAX,
next_rotation_time: Self::next_boundary(now, Duration::MAX),
closed_files: VecDeque::new(),
active_path,
state,
next_index: 1,
did_rotate: false,
segment_metadata: SegmentMetadata::default(),
dropped_events: 0,
has_real_events: false,
drain_interval: DEFAULT_DRAIN_INTERVAL,
next_drain_time: Self::next_boundary(now, DEFAULT_DRAIN_INTERVAL),
})
}
/// The base path used for trace segment files.
pub fn base_path(&self) -> &Path {
&self.base_path
}
/// The path of the currently active (being-written) segment file.
pub fn current_active_path(&self) -> &Path {
&self.active_path
}
/// Create an encoder, write the file header, segment metadata, and a
/// clock-sync anchor, then convert to a [`RawEncoder`] for the
/// remainder of the file's lifetime.
fn prepare_segment(writer: BufWriter<File>) -> std::io::Result<WriterState> {
let mut encoder = Encoder::new_to(writer)?;
let (mono, real) = clock_pair();
encoder.write(&ClockSyncEvent {
timestamp_ns: mono,
realtime_ns: real,
})?;
Ok(WriterState::Active {
writer: encoder.into_raw_encoder(),
need_metadata: true,
})
}
fn write_metadata_if_needed(&mut self) -> std::io::Result<()> {
match &mut self.state {
WriterState::Active {
writer,
need_metadata,
} => {
if *need_metadata {
Self::write_segment_metadata(writer, &self.segment_metadata.entries)?;
}
*need_metadata = false;
Ok(())
}
WriterState::Finished => Ok(()),
}
}
/// Write a `SegmentMetadataEvent` and a fresh `ClockSyncEvent` into
/// the current active segment.
fn write_segment_metadata(
writer: &mut RawEncoder<BufWriter<File>>,
entries: &[(String, String)],
) -> std::io::Result<()> {
let mut enc = Encoder::new();
let entries = entries.to_vec();
let (mono, real) = clock_pair();
enc.write(&SegmentMetadataEvent {
timestamp_ns: mono,
entries,
})?;
enc.write(&ClockSyncEvent {
timestamp_ns: mono,
realtime_ns: real,
})?;
writer.write_raw(&enc.finish())?;
Ok(())
}
fn file_path(base: &Path, index: u32) -> PathBuf {
let stem = base.file_stem().unwrap_or_default().to_string_lossy();
let parent = base.parent().unwrap_or(Path::new("."));
parent.join(format!("{}.{}.bin", stem, index))
}
/// Path for a segment that is actively being written.
fn active_path(base: &Path, index: u32) -> PathBuf {
let stem = base.file_stem().unwrap_or_default().to_string_lossy();
let parent = base.parent().unwrap_or(Path::new("."));
parent.join(format!("{}.{}.bin.active", stem, index))
}
/// Discover retained segment artifacts from previous writer lifetimes.
///
/// `closed_files` keeps one canonical path per segment index, but its size
/// accounts for every retained on-disk artifact for that index (`.bin`,
/// `.bin.gz`, or future write-back variants). Stale `.active` files belong
/// to dead writers and are not consumable by the worker, so discard them
/// before creating the new active segment.
fn discover_existing_segments(base: &Path) -> std::io::Result<ExistingSegments> {
let stem = base.file_stem().unwrap_or_default().to_string_lossy();
let parent = base.parent().unwrap_or(Path::new("."));
let mut retained_sizes = BTreeMap::<u32, u64>::new();
if parent.exists() {
for entry in fs::read_dir(parent)? {
let entry = entry?;
let path = entry.path();
let metadata = match entry.metadata() {
Ok(metadata) => metadata,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(e),
};
if !metadata.is_file() {
continue;
}
let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
continue;
};
match Self::parse_segment_artifact(file_name, &stem) {
Some(SegmentArtifact::Retained { index }) => {
*retained_sizes.entry(index).or_default() += metadata.len();
}
Some(SegmentArtifact::Active) => {
tracing::warn!(
path = %path.display(),
"discarding stale active trace segment from a previous writer"
);
match fs::remove_file(path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
}
None => {}
}
}
}
let next_active_index = retained_sizes
.last_key_value()
.map(|(&index, _)| {
index
.checked_add(1)
.ok_or_else(|| std::io::Error::other("trace segment index overflow"))
})
.transpose()?
.unwrap_or(0);
let closed_files = retained_sizes
.into_iter()
.map(|(index, size)| (Self::file_path(base, index), size))
.collect();
Ok(ExistingSegments {
closed_files,
next_active_index,
})
}
fn parse_segment_artifact(file_name: &str, stem: &str) -> Option<SegmentArtifact> {
let rest = file_name.strip_prefix(stem)?.strip_prefix('.')?;
if rest
.strip_suffix(".bin.active")
.and_then(|index| index.parse::<u32>().ok())
.is_some()
{
return Some(SegmentArtifact::Active);
}
let (index, suffix) = rest.split_once(".bin")?;
if !suffix.is_empty() && !suffix.starts_with('.') {
return None;
}
Some(SegmentArtifact::Retained {
index: index.parse().ok()?,
})
}
/// Compute the next wall-clock-aligned rotation boundary after `now`.
///
/// For a 60 s period, if `now` is 14:03:22 the result is 14:04:00.
/// Returns a far-future time when `period` is `Duration::MAX` (time
/// rotation disabled).
fn next_boundary(now: SystemTime, period: Duration) -> SystemTime {
if period == Duration::MAX {
// ~year 2554 — far enough to never trigger, small enough to not overflow.
return SystemTime::UNIX_EPOCH + Duration::from_secs(u32::MAX as u64 * 4);
}
let epoch_dur = now
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default();
let period_nanos = period.as_nanos();
if period_nanos == 0 {
return now;
}
let epoch_nanos = epoch_dur.as_nanos();
let next_nanos = ((epoch_nanos / period_nanos) + 1) * period_nanos;
SystemTime::UNIX_EPOCH + Duration::from_nanos(next_nanos as u64)
}
fn rotate(&mut self) -> std::io::Result<()> {
let WriterState::Active { writer: raw, .. } = &mut self.state else {
return Ok(());
};
// Advance timers up front. If anything below fails the flush loop must
// NOT see should_drain() return true on the next 5ms tick — otherwise
// it busy-spins re-attempting the same failing rotate.
let now = time_source().system_time().as_std();
self.next_rotation_time = Self::next_boundary(now, self.rotation_period);
self.next_drain_time = Self::next_boundary(now, self.drain_interval);
// Best-effort flush. If the underlying file is gone the buffered bytes
// are already lost; proceed to rotate rather than erroring.
let _ = raw.flush();
let closed_size = raw.bytes_written();
let sealed_path = Self::file_path(&self.base_path, self.next_index - 1);
// Seal the current segment. If `.active` was removed externally
// (operator, log rotation, container teardown) abandon the segment
// and start a fresh one. On any other error give up cleanly: mark
// the writer Finished so writes and rotations stop, instead of
// leaving inconsistent state.
match fs::rename(&self.active_path, &sealed_path) {
Ok(()) => self.closed_files.push_back((sealed_path, closed_size)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
rate_limited!(Duration::from_secs(60), {
tracing::warn!(
"active trace file {} disappeared before sealing; \
abandoning segment and starting a fresh one",
self.active_path.display()
);
});
}
Err(e) => {
self.state = WriterState::Finished;
return Err(e);
}
}
let new_path = Self::active_path(&self.base_path, self.next_index);
self.next_index += 1;
// Open the new active file. NotFound here typically means the parent
// directory itself was removed (the most likely real-world cause of
// the original `.active` file disappearing too). Try to recreate the
// directory once and retry. If that still fails, mark Finished so the
// writer stops cleanly rather than retrying every drain cycle.
let file = match File::create(&new_path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
if let Some(parent) = new_path.parent()
&& let Err(mkdir_err) = fs::create_dir_all(parent)
{
self.state = WriterState::Finished;
return Err(mkdir_err);
}
match File::create(&new_path) {
Ok(f) => f,
Err(e) => {
self.state = WriterState::Finished;
return Err(e);
}
}
}
Err(e) => {
self.state = WriterState::Finished;
return Err(e);
}
};
let writer = BufWriter::new(file);
self.state = match Self::prepare_segment(writer) {
Ok(s) => s,
Err(e) => {
let _ = std::fs::remove_file(&new_path);
self.state = WriterState::Finished;
return Err(e);
}
};
self.active_path = new_path;
self.did_rotate = true;
self.has_real_events = false;
tracing::debug!(
segment_index = self.next_index - 1,
"rotated to new trace segment"
);
self.evict_oldest()?;
Ok(())
}
/// Total size across all files (closed + active).
fn total_size(&self) -> u64 {
let closed: u64 = self.closed_files.iter().map(|(_, s)| s).sum();
let active = match &self.state {
WriterState::Active { writer, .. } => writer.bytes_written(),
WriterState::Finished => 0,
};
closed + active
}
fn evict_oldest(&mut self) -> std::io::Result<()> {
// Always keep at least the current file.
while self.total_size() > self.max_total_size && !self.closed_files.is_empty() {
if let Some((path, _size)) = self.closed_files.pop_front()
&& let Err(e) = Self::remove_segment_artifacts(&path)
{
rate_limited!(Duration::from_secs(60), {
tracing::warn!("failed to evict old trace segment {}: {e}", path.display());
});
}
}
// If even the current file alone exceeds total budget, stop writing.
if self.total_size() > self.max_total_size {
self.state = WriterState::Finished;
}
Ok(())
}
fn remove_segment_artifacts(path: &Path) -> std::io::Result<()> {
let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
return Ok(());
};
let Some(parent) = path.parent() else {
return Ok(());
};
match fs::read_dir(parent) {
Ok(entries) => {
for entry in entries {
let entry = entry?;
let artifact_name = entry.file_name();
let Some(artifact_name) = artifact_name.to_str() else {
continue;
};
if artifact_name == file_name
|| artifact_name
.strip_prefix(file_name)
.is_some_and(|suffix| suffix.starts_with('.'))
{
match fs::remove_file(entry.path()) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
}
}
Ok(())
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
/// Rotate if the current file exceeds max_file_size.
/// Called after writing a complete logical unit (def + event).
fn maybe_rotate(&mut self) -> std::io::Result<()> {
let WriterState::Active { writer: raw, .. } = &self.state else {
return Ok(());
};
if raw.bytes_written() > self.max_file_size {
self.rotate()?;
}
Ok(())
}
}
impl TraceWriter for RotatingWriter {
fn flush(&mut self) -> std::io::Result<()> {
if let WriterState::Active { writer: raw, .. } = &mut self.state {
raw.flush()?;
}
Ok(())
}
fn take_rotated(&mut self) -> bool {
std::mem::take(&mut self.did_rotate)
}
fn segment_metadata(&self) -> &[(String, String)] {
&self.segment_metadata.entries
}
fn update_segment_metadata(&mut self, entries: Vec<(String, String)>) {
if self.segment_metadata.merge(entries.into_iter()) {
match &mut self.state {
WriterState::Active { need_metadata, .. } => *need_metadata = true,
WriterState::Finished => {}
}
}
}
fn write_current_segment_metadata(&mut self) -> std::io::Result<()> {
self.write_metadata_if_needed()
}
fn should_drain(&self) -> bool {
self.has_real_events && time_source().system_time() >= self.next_drain_time
}
fn drained(&mut self) -> std::io::Result<bool> {
if !self.has_real_events {
return Ok(false);
}
let now = time_source().system_time();
if now >= self.next_rotation_time {
self.rotate()?;
return Ok(true);
}
// Periodic drain without rotation — just advance the drain timer.
self.next_drain_time = Self::next_boundary(now.as_std(), self.drain_interval);
Ok(false)
}
fn finalize(&mut self) -> std::io::Result<()> {
if matches!(self.state, WriterState::Finished) {
rate_limited!(Duration::from_secs(60), {
tracing::warn!("writer is already closed.");
});
}
// Best-effort flush: if the file is gone the bytes are already lost.
let _ = self.flush();
if self
.active_path
.extension()
.is_some_and(|ext| ext == "active")
{
if self.has_real_events {
let sealed = Self::file_path(&self.base_path, self.next_index - 1);
match fs::rename(&self.active_path, &sealed) {
Ok(()) => self.active_path = sealed,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
rate_limited!(Duration::from_secs(60), {
tracing::warn!(
"active trace file {} disappeared before finalize; \
dropping segment",
self.active_path.display()
);
});
}
Err(e) => {
self.state = WriterState::Finished;
return Err(e);
}
}
} else {
// No real events — just header + metadata. Remove instead of
// sealing so the background worker doesn't upload an empty segment.
tracing::debug!(
"removing empty final segment {}",
self.active_path.display()
);
if let Err(e) = fs::remove_file(&self.active_path)
&& e.kind() != std::io::ErrorKind::NotFound
{
self.state = WriterState::Finished;
return Err(e);
}
}
}
if self.has_real_events {
self.evict_oldest()?;
}
self.state = WriterState::Finished;
Ok(())
}
fn write_encoded_batch(&mut self, batch: &Batch) -> std::io::Result<()> {
self.write_metadata_if_needed()?;
let WriterState::Active { writer: raw, .. } = &mut self.state else {
self.dropped_events += batch.event_count as usize;
return Ok(());
};
if batch.event_count > 0 {
// Note: we do NOT advance next_rotation_time or next_drain_time
// when the first event arrives in an empty segment, even if the
// timers are stale. The drain state machine (Idle → EpochBumped →
// drain) takes 3 flush cycles (~15ms) to complete, so by the time
// drained() is called there will be multiple batches in the segment,
// not a single event. Advancing the timers here would skip rotation
// windows and produce fewer segments than expected.
// Raw-copy the thread-local batch. Each batch is self-contained
// (starts with its own header), so the next batch's header acts as
// the reset frame for decoders.
raw.write_raw(&batch.encoded_bytes)?;
self.has_real_events = true;
self.maybe_rotate()?;
}
Ok(())
}
}
impl Drop for RotatingWriter {
fn drop(&mut self) {
if self.dropped_events > 0 {
rate_limited!(Duration::from_secs(60), {
tracing::info!(
target: "dial9_telemetry",
dropped_events = self.dropped_events,
"RotatingWriter dropped events after finalization"
);
});
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::telemetry::format::WorkerParkEvent;
use crate::telemetry::{TelemetryEvent, format};
use std::io::Read;
use tempfile::TempDir;
/// Encode a single park event into a self-contained batch (header + event),
/// matching the format produced by ThreadLocalBuffer.
fn test_batch() -> Batch {
let mut enc = Encoder::new_to(Vec::new()).unwrap();
enc.write_infallible(&WorkerParkEvent {
timestamp_ns: 1000,
worker_id: crate::telemetry::format::WorkerId::from(0usize),
local_queue: 2,
cpu_time_ns: 0,
tid: 0,
});
Batch {
encoded_bytes: enc.into_inner(),
event_count: 1,
}
}
fn rotating_file(base: &std::path::Path, i: u32) -> String {
format!("{}.{}.bin", base.display(), i)
}
/// Read all non-metadata events from a trace file.
fn read_trace_events(path: &str) -> Vec<TelemetryEvent> {
let data = std::fs::read(path).unwrap();
format::decode_events(&data)
.unwrap()
.into_iter()
.filter(|e| {
!matches!(
e,
TelemetryEvent::SegmentMetadata { .. } | TelemetryEvent::ClockSync { .. }
)
})
.collect()
}
/// Total size of all trace files in a directory, including write-back
/// artifacts such as `.bin.gz`.
fn total_disk_usage(dir: &std::path::Path) -> u64 {
std::fs::read_dir(dir)
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| {
e.file_name().to_str().is_some_and(|name| {
name.ends_with(".bin")
|| name.ends_with(".bin.active")
|| name.contains(".bin.")
})
})
.map(|e| e.metadata().unwrap().len())
.sum()
}
/// Write one batch to a temp file and return the file size.
/// This captures the actual overhead (header + schema + event) so tests
/// don't depend on hardcoded format sizes.
fn single_event_file_size() -> u64 {
let dir = TempDir::new().unwrap();
let path = dir.path().join("probe.bin");
let mut w = RotatingWriter::single_file(&path).unwrap();
w.write_encoded_batch(&test_batch()).unwrap();
w.flush().unwrap();
std::fs::metadata(w.current_active_path()).unwrap().len()
}
#[test]
fn test_writer_creation() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("test_trace_v2.bin");
let writer = RotatingWriter::single_file(&path);
assert!(writer.is_ok());
}
#[test]
fn test_write_event() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("test_event_v2.bin");
let mut writer = RotatingWriter::single_file(&path).unwrap();
writer.write_encoded_batch(&test_batch()).unwrap();
writer.flush().unwrap();
let metadata = std::fs::metadata(writer.current_active_path()).unwrap();
assert!(
metadata.len() > 0,
"file should not be empty after writing an event"
);
}
#[test]
fn test_write_batch_sizes() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("test_batch_v2.bin");
let mut writer = RotatingWriter::single_file(&path).unwrap();
let one_event_size = single_event_file_size();
for _ in 0..2 {
writer.write_encoded_batch(&test_batch()).unwrap();
}
writer.flush().unwrap();
let metadata = std::fs::metadata(writer.current_active_path()).unwrap();
// Two events should be larger than one event
assert!(metadata.len() > one_event_size);
}
#[test]
fn test_binary_format_header() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("test_format_v2.bin");
let writer = RotatingWriter::single_file(&path).unwrap();
let active = writer.current_active_path().to_owned();
drop(writer);
let mut file = std::fs::File::open(&active).unwrap();
let mut magic = [0u8; 4];
file.read_exact(&mut magic).unwrap();
assert_eq!(&magic, b"TRC\0");
}
#[test]
fn test_rotating_writer_creation() {
let dir = TempDir::new().unwrap();
let base = dir.path().join("trace");
let mut writer = RotatingWriter::new(&base, 1024, 4096).unwrap();
writer.finalize().unwrap();
// No real events were written, so finalize removes the empty segment.
assert!(
!dir.path().join("trace.0.bin").exists(),
"empty segment should not be sealed"
);
assert!(
!dir.path().join("trace.0.bin.active").exists(),
"active file should be removed"
);
}
#[test]
fn test_rotating_writer_rotation() {
let dir = TempDir::new().unwrap();
let base = dir.path().join("trace");
// Set max_file_size to fit ~1 event so rotation triggers quickly
let one_event = single_event_file_size();
let mut writer = RotatingWriter::new(&base, one_event, 100_000).unwrap();
for _ in 0..3 {
writer.write_encoded_batch(&test_batch()).unwrap();
}