-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlib.rs
More file actions
1838 lines (1485 loc) · 52.6 KB
/
lib.rs
File metadata and controls
1838 lines (1485 loc) · 52.6 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
/*!
Emit diagnostic events to rolling files.
All file IO is performed on batches in a dedicated background thread.
This library writes newline delimited JSON by default, like:
```text
{"ts_start":"2024-05-29T03:35:13.922768000Z","ts":"2024-05-29T03:35:13.943506000Z","module":"my_app","msg":"in_ctxt failed with `a` is odd","tpl":"in_ctxt failed with `err`","a":1,"err":"`a` is odd","lvl":"warn","span_id":"0a3686d1b788b277","span_parent":"1a50b58f2ef93f3b","trace_id":"8dd5d1f11af6ba1db4124072024933cb"}
```
# Getting started
Add `emit` and `emit_file` to your `Cargo.toml`:
```toml
[dependencies.emit]
version = "1.17.2"
[dependencies.emit_file]
version = "1.17.2"
```
Initialize `emit` using a rolling file set:
```
fn main() {
let rt = emit::setup()
.emit_to(emit_file::set("./target/logs/my_app.txt").spawn())
.init();
// Your app code goes here
rt.blocking_flush(std::time::Duration::from_secs(30));
}
```
The input to [`set`] is a template for log file naming. The example earlier used `./target/logs/my_app.txt`. From this template, log files will be written to `./target/logs`, each log file name will start with `my_app`, and use `.txt` as its extension.
# File naming
Log files are created using the following naming scheme:
```text
{prefix}.{date}.{counter}.{id}.{ext}
```
where:
- `prefix`: A user-defined name that groups all log files related to the same application together.
- `date`: The rollover interval the file was created in. This isn't necessarily related to the timestamps of events within the file.
- `counter`: The number of milliseconds since the start of the current rollover interval when the file was created.
- `id`: A unique identifier for the file in the interval.
- `ext`: A user-defined file extension.
In the following log file:
```text
log.2024-05-27-03-00.00012557.37c57fa1.txt
```
the parts are:
- `prefix`: `log`.
- `date`: `2024-05-27-03-00`.
- `counter`: `00012557`.
- `id`: `37c57fa1`.
- `ext`: `txt`.
# When files roll
Diagnostic events are only ever written to a single file at a time. That file changes when:
1. The application restarts and [`FileSetBuilder::reuse_files`] is false.
2. The rollover period changes. This is set by [`FileSetBuilder::roll_by_day`], [`FileSetBuilder::roll_by_hour`], and [`FileSetBuilder::roll_by_minute`].
3. The size of the file exceeds [`FileSetBuilder::max_file_size_bytes`].
4. Writing to the file fails.
# Durability
Diagnostic events are written to files in asynchronous batches. Under normal operation, after a call to [`emit::Emitter::blocking_flush`], all events emitted before the call are guaranteed to be written and synced via Rust's [`std::fs::File::sync_all`] method. This is usually enough to guarantee durability.
# Handling IO failures
If writing a batch fails while attempting to write to a file then the file being written to is considered poisoned and no future attempts will be made to write to it. The batch will instead be retried on a new file. Batches that fail attempting to sync are not retried. Since batches don't have explicit transactions, it's possible on failure for part or all of the failed batch to actually be present in the original file. That means diagnostic events may be duplicated in the case of an IO error while writing them.
# Troubleshooting
If you're not seeing diagnostics appear in files as expected, you can rule out configuration issues in `emit_file` by configuring `emit`'s internal logger, and collect metrics from it:
```
# mod emit_term {
# pub fn stdout() -> impl emit::runtime::InternalEmitter + Send + Sync + 'static {
# emit::runtime::AssertInternal(emit::emitter::from_fn(|_| {}))
# }
# }
use emit::metric::Source;
fn main() {
// 1. Initialize the internal logger
// Diagnostics produced by `emit_file` itself will go here
let internal = emit::setup()
.emit_to(emit_term::stdout())
.init_internal();
let mut reporter = emit::metric::Reporter::new();
let rt = emit::setup()
.emit_to({
let files = emit_file::set("./target/logs/my_app.txt").spawn();
// 2. Add `emit_file`'s metrics to a reporter so we can see what it's up to
// You can do this independently of the internal emitter
reporter.add_source(files.metric_source());
files
})
.init();
// Your app code goes here
rt.blocking_flush(std::time::Duration::from_secs(30));
// 3. Report metrics after attempting to flush
// You could also do this periodically as your application runs
reporter.emit_metrics(&internal.emitter());
}
```
Diagnostics include when batches are written, and any failures observed along the way.
*/
#![doc(html_logo_url = "https://raw.githubusercontent.com/emit-rs/emit/main/asset/logo.svg")]
#![deny(missing_docs)]
mod internal_metrics;
use std::{
fmt,
io::{self, Write},
mem,
path::{Path, PathBuf},
sync::Arc,
thread,
};
use emit::{
clock::{Clock, ErasedClock},
platform::{rand_rng::RandRng, system_clock::SystemClock},
rng::{ErasedRng, Rng},
};
use emit_batcher::BatchError;
use internal_metrics::InternalMetrics;
const DEFAULT_ROLL_BY: RollBy = RollBy::Hour;
const DEFAULT_MAX_FILES: usize = 32;
const DEFAULT_MAX_FILE_SIZE_BYTES: usize = 1024 * 1024 * 1024; // 1GiB
const DEFAULT_REUSE_FILES: bool = false;
pub use internal_metrics::*;
/**
An error attempting to create a [`FileSet`].
*/
pub struct Error(Box<dyn std::error::Error + Send + Sync>);
impl Error {
fn new(e: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
Error(e.into())
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.0.source()
}
}
/**
Create a builder for a [`FileSet`] using the default newline-delimited JSON format.
The builder will use `file_set` as its template for naming log files. See the crate root documentation for details on how this argument is interpreted.
It will use the other following defaults:
- Roll by hour.
- 32 max files.
- 1GiB max file size.
The [`FileSetBuilder`] has configuration options for managing the number and size of log files.
Once configured, call [`FileSetBuilder::spawn`] to complete the builder, passing the resulting [`FileSet`] to [`emit::Setup::emit_to`].
*/
#[cfg(feature = "default_writer")]
pub fn set(file_set: impl AsRef<Path>) -> FileSetBuilder {
FileSetBuilder::new(file_set.as_ref())
}
/**
Create a builder for a [`FileSet`].
The builder will use `file_set` as its template for naming log files. See the crate root documentation for details on how this argument is interpreted.
The `writer` is used to format incoming [`emit::Event`]s into their on-disk format. If formatting fails then the event will be discarded.
The `writer` may finish each event with the separator. If it doesn't, then it will be added automatically.
*/
pub fn set_with_writer(
file_set: impl AsRef<Path>,
writer: impl Fn(&mut FileBuf, &emit::Event<&dyn emit::props::ErasedProps>) -> io::Result<()>
+ Send
+ Sync
+ 'static,
separator: &'static [u8],
) -> FileSetBuilder {
FileSetBuilder::new_with_writer(file_set.as_ref(), writer, separator)
}
/**
A builder for a [`FileSet`].
Use [`set`] or [`set_with_writer`] to begin a [`FileSetBuilder`].
The [`FileSetBuilder`] has configuration options for managing the number and size of log files.
Once configured, call [`FileSetBuilder::spawn`] to complete the builder, passing the resulting [`FileSet`] to [`emit::Setup::emit_to`].
*/
pub struct FileSetBuilder {
file_set: PathBuf,
roll_by: RollBy,
max_files: usize,
max_file_size_bytes: usize,
reuse_files: bool,
writer: Box<
dyn Fn(&mut FileBuf, &emit::Event<&dyn emit::props::ErasedProps>) -> io::Result<()>
+ Send
+ Sync,
>,
separator: &'static [u8],
}
#[derive(Debug, Clone, Copy)]
enum RollBy {
Day,
Hour,
Minute,
}
impl FileSetBuilder {
/**
Create a new [`FileSetBuilder`] using the default newline-delimited JSON format.
The builder will use `file_set` as its template for naming log files. See the crate root documentation for details on how this argument is interpreted.
It will use the other following defaults:
- Roll by hour.
- 32 max files.
- 1GiB max file size.
*/
#[cfg(feature = "default_writer")]
pub fn new(file_set: impl Into<PathBuf>) -> Self {
Self::new_with_writer(file_set, default_writer, b"\n")
}
/**
Create a builder for a [`FileSet`].
The builder will use `file_set` as its template for naming log files. See the crate root documentation for details on how this argument is interpreted.
The `writer` is used to format incoming [`emit::Event`]s into their on-disk format. If formatting fails then the event will be discarded.
The `writer` may finish each event with the separator. If it doesn't, then it will be added automatically.
It will use the other following defaults:
- Roll by hour.
- 32 max files.
- 1GiB max file size.
*/
pub fn new_with_writer(
file_set: impl Into<PathBuf>,
writer: impl Fn(&mut FileBuf, &emit::Event<&dyn emit::props::ErasedProps>) -> io::Result<()>
+ Send
+ Sync
+ 'static,
separator: &'static [u8],
) -> Self {
FileSetBuilder {
file_set: file_set.into(),
roll_by: DEFAULT_ROLL_BY,
max_files: DEFAULT_MAX_FILES,
max_file_size_bytes: DEFAULT_MAX_FILE_SIZE_BYTES,
reuse_files: DEFAULT_REUSE_FILES,
writer: Box::new(writer),
separator,
}
}
/**
Create rolling log files based on the calendar day of when they're written to.
*/
pub fn roll_by_day(mut self) -> Self {
self.roll_by = RollBy::Day;
self
}
/**
Create rolling log files based on the calendar day and hour of when they're written to.
*/
pub fn roll_by_hour(mut self) -> Self {
self.roll_by = RollBy::Hour;
self
}
/**
Create rolling log files based on the calendar day, hour, and minute of when they're written to.
*/
pub fn roll_by_minute(mut self) -> Self {
self.roll_by = RollBy::Minute;
self
}
/**
The maximum number of log files to keep.
Files are deleted from oldest first whenever a new file is created. Older files are determined based on the time period they belong to.
*/
pub fn max_files(mut self, max_files: usize) -> Self {
self.max_files = max_files;
self
}
/**
The maximum size of a file before new writes will roll over to a new one.
The same time period can contain multiple log files. More recently created log files will sort ahead of older ones.
*/
pub fn max_file_size_bytes(mut self, max_file_size_bytes: usize) -> Self {
self.max_file_size_bytes = max_file_size_bytes;
self
}
/**
Whether to re-use log files when first attempting to write to them.
This method can be used for applications that are started a lot and may result in lots of active log files.
Before writing new events to the log file, it will have the configured separator defensively written to it. This ensures any previous partial write doesn't corrupt any new writes.
*/
pub fn reuse_files(mut self, reuse_files: bool) -> Self {
self.reuse_files = reuse_files;
self
}
/**
Specify a writer for incoming [`emit::Event`]s.
The `writer` is used to format incoming [`emit::Event`]s into their on-disk format. If formatting fails then the event will be discarded.
The `writer` may finish each event with the separator. If it doesn't, then it will be added automatically.
*/
pub fn writer(
mut self,
writer: impl Fn(&mut FileBuf, &emit::Event<&dyn emit::props::ErasedProps>) -> io::Result<()>
+ Send
+ Sync
+ 'static,
separator: &'static [u8],
) -> Self {
self.writer = Box::new(writer);
self.separator = separator;
self
}
/**
Complete the builder, returning a [`FileSet`] to pass to [`emit::Setup::emit_to`].
If the file set configuration is invalid this method won't fail or panic, it will discard any events emitted to it. In these cases it will log to [`emit::runtime::internal`] and increment the `configuration_failed` metric on [`FileSet::metric_source`]. See the _Troubleshooting_ section of the crate root docs for more details.
*/
pub fn spawn(self) -> FileSet {
let metrics = Arc::new(InternalMetrics::default());
let inner = match self.spawn_inner(metrics.clone()) {
Ok(inner) => Some(inner),
Err(err) => {
emit::error!(
rt: emit::runtime::internal(),
"file set configuration is invalid; no events will be written: {err}"
);
metrics.configuration_failed.increment();
None
}
};
FileSet { metrics, inner }
}
fn spawn_inner(self, metrics: Arc<InternalMetrics>) -> Result<FileSetInner, Error> {
let (dir, file_prefix, file_ext) = dir_prefix_ext(self.file_set).map_err(Error::new)?;
let mut worker = Worker::new(
metrics.clone(),
StdFilesystem::new(),
SystemClock::new(),
RandRng::new(),
dir,
file_prefix,
file_ext,
self.roll_by,
self.reuse_files,
self.max_files,
self.max_file_size_bytes,
self.separator,
);
let (sender, receiver) = emit_batcher::bounded(10_000);
let handle = emit_batcher::sync::spawn("emit_file_worker", receiver, move |batch| {
worker.on_batch(batch)
})
.map_err(Error::new)?;
Ok(FileSetInner {
sender,
metrics,
writer: self.writer,
separator: self.separator,
_handle: handle,
})
}
}
/**
A handle to an asynchronous, background, rolling file writer.
Create a file set through the [`set`] function, calling [`FileSetBuilder::spawn`] to complete configuration. Pass the resulting [`FileSet`] to [`emit::Setup::emit_to`] to configure `emit` to write diagnostic events through it.
*/
pub struct FileSet {
inner: Option<FileSetInner>,
metrics: Arc<InternalMetrics>,
}
struct FileSetInner {
sender: emit_batcher::Sender<EventBatch>,
metrics: Arc<InternalMetrics>,
writer: Box<
dyn Fn(&mut FileBuf, &emit::Event<&dyn emit::props::ErasedProps>) -> io::Result<()>
+ Send
+ Sync,
>,
separator: &'static [u8],
_handle: thread::JoinHandle<()>,
}
impl emit::Emitter for FileSet {
fn emit<E: emit::event::ToEvent>(&self, evt: E) {
self.inner.emit(evt)
}
fn blocking_flush(&self, timeout: std::time::Duration) -> bool {
self.inner.blocking_flush(timeout)
}
}
impl emit::Emitter for FileSetInner {
fn emit<E: emit::event::ToEvent>(&self, evt: E) {
let evt = evt.to_event();
// NOTE: We could use a rolling capacity to pre-allocate this if we want
let mut buf = FileBuf::new();
match (self.writer)(&mut buf, &evt.erase()) {
Ok(()) => {
// If the buffer didn't finish with the configured separator
// then write it now
if !buf.0.ends_with(self.separator) {
buf.extend_from_slice(self.separator);
}
self.sender.send(buf.into_boxed_slice());
}
Err(err) => {
self.metrics.event_format_failed.increment();
emit::warn!(
rt: emit::runtime::internal(),
"failed to format file event payload: {err}",
)
}
};
}
fn blocking_flush(&self, timeout: std::time::Duration) -> bool {
emit_batcher::blocking_flush(&self.sender, timeout)
}
}
impl FileSet {
/**
Get an [`emit::metric::Source`] for instrumentation produced by the file set.
These metrics can be used to monitor the running health of your diagnostic pipeline.
*/
pub fn metric_source(&self) -> FileSetMetrics {
FileSetMetrics {
channel_metrics: self
.inner
.as_ref()
.map(|inner| inner.sender.metric_source()),
metrics: self.metrics.clone(),
}
}
}
/**
A buffer to format [`emit::Event`]s into before writing them to a file.
*/
pub struct FileBuf(Vec<u8>);
impl FileBuf {
fn new() -> Self {
FileBuf(Vec::new())
}
/**
Push a byte onto the end of the buffer.
*/
pub fn push(&mut self, byte: u8) {
self.0.push(byte)
}
/**
Push a slice of bytes onto the end of the buffer.
*/
pub fn extend_from_slice(&mut self, bytes: &[u8]) {
self.0.extend_from_slice(bytes)
}
fn into_boxed_slice(self) -> Box<[u8]> {
self.0.into_boxed_slice()
}
}
impl io::Write for FileBuf {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.0.write_all(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
#[cfg(feature = "default_writer")]
fn default_writer(
buf: &mut FileBuf,
evt: &emit::Event<&dyn emit::props::ErasedProps>,
) -> io::Result<()> {
use std::ops::ControlFlow;
use emit::{
well_known::{KEY_MDL, KEY_MSG, KEY_TPL, KEY_TS, KEY_TS_START},
Props as _,
};
struct EventValue<'a, P>(&'a emit::Event<'a, P>);
impl<'a, P: emit::Props> sval::Value for EventValue<'a, P> {
fn stream<'sval, S: sval::Stream<'sval> + ?Sized>(
&'sval self,
stream: &mut S,
) -> sval::Result {
stream.record_begin(None, None, None, None)?;
if let Some(extent) = self.0.extent() {
if let Some(range) = extent.as_range() {
stream.record_value_begin(None, &sval::Label::new(KEY_TS_START))?;
sval::stream_display(&mut *stream, &range.start)?;
stream.record_value_end(None, &sval::Label::new(KEY_TS_START))?;
}
stream.record_value_begin(None, &sval::Label::new(KEY_TS))?;
sval::stream_display(&mut *stream, extent.as_point())?;
stream.record_value_end(None, &sval::Label::new(KEY_TS))?;
}
stream.record_value_begin(None, &sval::Label::new(KEY_MDL))?;
sval::stream_display(&mut *stream, self.0.mdl())?;
stream.record_value_end(None, &sval::Label::new(KEY_MDL))?;
stream.record_value_begin(None, &sval::Label::new(KEY_MSG))?;
sval::stream_display(&mut *stream, self.0.msg())?;
stream.record_value_end(None, &sval::Label::new(KEY_MSG))?;
stream.record_value_begin(None, &sval::Label::new(KEY_TPL))?;
sval::stream_display(&mut *stream, self.0.tpl())?;
stream.record_value_end(None, &sval::Label::new(KEY_TPL))?;
let _ = self.0.props().dedup().for_each(|k, v| {
match (|| {
stream.record_value_begin(None, &sval::Label::new_computed(k.get()))?;
stream.value_computed(&v)?;
stream.record_value_end(None, &sval::Label::new_computed(k.get()))?;
Ok::<(), sval::Error>(())
})() {
Ok(()) => ControlFlow::Continue(()),
Err(_) => ControlFlow::Break(()),
}
});
stream.record_end(None, None, None)
}
}
sval_json::stream_to_io_write(buf, EventValue(evt))
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(())
}
struct EventBatch {
bufs: Vec<Box<[u8]>>,
remaining_bytes: usize,
index: usize,
}
impl EventBatch {
fn new() -> Self {
EventBatch {
bufs: Vec::new(),
remaining_bytes: 0,
index: 0,
}
}
fn push(&mut self, buf: impl Into<Box<[u8]>>) {
let item = buf.into();
self.remaining_bytes += item.len();
self.bufs.push(item);
}
}
impl emit_batcher::Channel for EventBatch {
type Item = Box<[u8]>;
fn new() -> Self {
EventBatch::new()
}
fn push<'a>(&mut self, item: Self::Item) {
self.push(item)
}
fn len(&self) -> usize {
self.bufs.len() - self.index
}
fn clear(&mut self) {
self.bufs.clear()
}
}
impl EventBatch {
fn current(&self) -> Option<&[u8]> {
self.bufs.get(self.index).map(|buf| &**buf)
}
fn advance(&mut self) {
let advanced = mem::take(&mut self.bufs[self.index]);
self.index += 1;
self.remaining_bytes -= advanced.len();
}
}
struct Worker {
metrics: Arc<InternalMetrics>,
clock: Box<dyn ErasedClock + Send + Sync>,
rng: Box<dyn ErasedRng + Send + Sync>,
fs: Box<dyn Filesystem + Send + Sync>,
active_file: Option<ActiveFile>,
roll_by: RollBy,
max_files: usize,
max_file_size_bytes: usize,
reuse_files: bool,
dir: String,
file_prefix: String,
file_ext: String,
separator: &'static [u8],
}
impl Worker {
fn new(
metrics: Arc<InternalMetrics>,
fs: impl Filesystem + Send + Sync + 'static,
clock: impl Clock + Send + Sync + 'static,
rng: impl Rng + Send + Sync + 'static,
dir: String,
file_prefix: String,
file_ext: String,
roll_by: RollBy,
reuse_files: bool,
max_files: usize,
max_file_size_bytes: usize,
separator: &'static [u8],
) -> Self {
Worker {
metrics,
fs: Box::new(fs),
clock: Box::new(clock),
rng: Box::new(rng),
active_file: None,
roll_by,
max_files,
max_file_size_bytes,
reuse_files,
dir,
file_prefix,
file_ext,
separator,
}
}
#[emit::span(rt: emit::runtime::internal(), guard: span, "write file batch")]
fn on_batch(&mut self, mut batch: EventBatch) -> Result<(), BatchError<EventBatch>> {
let ts = self.clock.now().unwrap();
let parts = ts.to_parts();
let file_ts = file_ts(self.roll_by, parts);
let mut file = self.active_file.take();
let mut file_set = ActiveFileSet::empty(&self.metrics, &self.dir);
if file.is_none() {
if let Err(err) = self.fs.create_dir_all(Path::new(&self.dir)) {
span.complete_with(emit::span::completion::from_fn(|span| {
emit::warn!(
rt: emit::runtime::internal(),
extent: span.extent(),
props: span.props(),
"failed to create root directory {path}: {err}",
#[emit::as_debug]
path: &self.dir,
err,
)
}));
return Err(emit_batcher::BatchError::retry(err, batch));
}
let _ = file_set
.read(&self.fs, &self.file_prefix, &self.file_ext)
.map_err(|err| {
self.metrics.file_set_read_failed.increment();
emit::warn!(
rt: emit::runtime::internal(),
"failed to files in read {path}: {err}",
#[emit::as_debug]
path: &file_set.dir,
err,
);
err
});
if self.reuse_files {
if let Some(file_name) = file_set.current_file_name() {
let mut path = PathBuf::from(&self.dir);
path.push(file_name);
file = ActiveFile::try_open_reuse(&self.fs, &path)
.map_err(|err| {
self.metrics.file_open_failed.increment();
emit::warn!(
rt: emit::runtime::internal(),
"failed to open {path}: {err}",
#[emit::as_debug]
path,
err,
);
err
})
.ok()
}
}
}
file = file.filter(|file| {
file.file_size_bytes + batch.remaining_bytes <= self.max_file_size_bytes
&& file.file_ts == file_ts
});
let mut file = if let Some(file) = file {
file
} else {
// Leave room for the file we're about to create
file_set.apply_retention(&self.fs, self.max_files.saturating_sub(1));
let mut path = PathBuf::from(self.dir.clone());
let file_id = file_id(
rolling_millis(self.roll_by, ts, parts),
rolling_id(&self.rng),
);
path.push(file_name(
&self.file_prefix,
&self.file_ext,
&file_ts,
&file_id,
));
match ActiveFile::try_open_create(&self.fs, &path) {
Ok(file) => {
self.metrics.file_create.increment();
emit::debug!(
rt: emit::runtime::internal(),
"created {path}",
#[emit::as_debug]
path: file.file_path,
);
file
}
Err(err) => {
self.metrics.file_create_failed.increment();
emit::warn!(
rt: emit::runtime::internal(),
"failed to create {path}: {err}",
#[emit::as_debug]
path,
err,
);
return Err(emit_batcher::BatchError::retry(err, batch));
}
}
};
let written_bytes = batch.remaining_bytes;
while let Some(buf) = batch.current() {
if let Err(err) = file.write_event(buf, self.separator) {
self.metrics.file_write_failed.increment();
span.complete_with(emit::span::completion::from_fn(|span| {
emit::warn!(
rt: emit::runtime::internal(),
extent: span.extent(),
props: span.props(),
"failed to write event to {path}: {err}",
#[emit::as_debug]
path: file.file_path,
err,
)
}));
return Err(emit_batcher::BatchError::retry(err, batch));
}
batch.advance();
}
file.file
.flush()
.map_err(|e| emit_batcher::BatchError::no_retry(e))?;
file.file
.sync_all()
.map_err(|e| emit_batcher::BatchError::no_retry(e))?;
span.complete_with(emit::span::completion::from_fn(|span| {
emit::debug!(
rt: emit::runtime::internal(),
extent: span.extent(),
props: span.props(),
"wrote {written_bytes} bytes to {path}",
written_bytes,
#[emit::as_debug]
path: file.file_path,
)
}));
// Set the active file so the next batch can attempt to use it
// At this point the file is expected to be valid
self.active_file = Some(file);
Ok(())
}
}
struct ActiveFileSet<'a> {
dir: &'a str,
metrics: &'a InternalMetrics,
file_set: Vec<String>,
}
impl<'a> ActiveFileSet<'a> {
fn empty(metrics: &'a InternalMetrics, dir: &'a str) -> Self {
ActiveFileSet {
metrics,
dir,
file_set: Vec::new(),
}
}
fn read(
&mut self,
fs: impl Filesystem,
file_prefix: &str,
file_ext: &str,
) -> Result<(), io::Error> {
self.file_set = Vec::new();
let read_dir = fs.read_dir_files(Path::new(&self.dir))?;
let mut file_set = Vec::new();
for path in read_dir {
let Some(file_name) = path.file_name() else {
continue;
};
let Some(file_name) = file_name.to_str() else {
continue;
};
if file_name.starts_with(&file_prefix) && file_name.ends_with(&file_ext) {
file_set.push(file_name.to_owned());
}
}
file_set.sort_by(|a, b| a.cmp(b).reverse());
self.file_set = file_set;
Ok(())
}
fn current_file_name(&self) -> Option<&str> {
// NOTE: If the clock shifts back (either jitters or through daylight savings)
// Then we may return a file from the future here instead of one that better
// matches the current timestamp. In these cases we'll end up creating a new file
// instead of potentially reusing one that does match.
self.file_set.first().map(|file_name| &**file_name)
}
fn apply_retention(&mut self, fs: impl Filesystem, max_files: usize) {
while self.file_set.len() >= max_files {
let mut path = PathBuf::from(self.dir);
path.push(self.file_set.pop().unwrap());
if let Err(err) = fs.remove_file(&path) {
self.metrics.file_delete_failed.increment();
emit::warn!(
rt: emit::runtime::internal(),
"failed to delete {path}: {err}",
#[emit::as_debug]
path,
err,
);
} else {
self.metrics.file_delete.increment();
emit::debug!(
rt: emit::runtime::internal(),
"deleted {path}",
#[emit::as_debug]
path,
);
}
}
}
}