-
Notifications
You must be signed in to change notification settings - Fork 752
Expand file tree
/
Copy pathrecording_stream.rs
More file actions
2251 lines (2007 loc) · 83 KB
/
recording_stream.rs
File metadata and controls
2251 lines (2007 loc) · 83 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 std::fmt;
use std::io::IsTerminal;
use std::sync::Weak;
use std::sync::{atomic::AtomicI64, Arc};
use ahash::HashMap;
use crossbeam::channel::{Receiver, Sender};
use itertools::Either;
use parking_lot::Mutex;
use re_log_types::{
ApplicationId, ArrowChunkReleaseCallback, DataCell, DataCellError, DataRow, DataTable,
DataTableBatcher, DataTableBatcherConfig, DataTableBatcherError, EntityPath, LogMsg, RowId,
StoreId, StoreInfo, StoreKind, StoreSource, Time, TimeInt, TimePoint, TimeType, Timeline,
TimelineName,
};
use re_types_core::{components::InstanceKey, AsComponents, ComponentBatch, SerializationError};
#[cfg(feature = "web_viewer")]
use re_web_viewer_server::WebViewerServerPort;
#[cfg(feature = "web_viewer")]
use re_ws_comms::RerunServerPort;
use crate::sink::{LogSink, MemorySinkStorage};
// ---
/// Private environment variable meant for tests.
///
/// When set, all recording streams will write to disk at the path indicated by the env-var rather
/// than doing what they were asked to do - `connect()`, `buffered()`, even `save()` will re-use the same sink.
const ENV_FORCE_SAVE: &str = "_RERUN_TEST_FORCE_SAVE";
/// Returns path for force sink if private environment variable `_RERUN_TEST_FORCE_SAVE` is set
///
/// Newly created [`RecordingStream`]s should use a [`crate::sink::FileSink`] pointing to this path.
/// Furthermore, [`RecordingStream::set_sink`] calls after this should not swap out to a new sink but re-use the existing one.
/// Note that creating a new [`crate::sink::FileSink`] to the same file path (even temporarily) can cause
/// a race between file creation (and thus clearing) and pending file writes.
fn forced_sink_path() -> Option<String> {
std::env::var(ENV_FORCE_SAVE).ok()
}
/// Errors that can occur when creating/manipulating a [`RecordingStream`].
#[derive(thiserror::Error, Debug)]
pub enum RecordingStreamError {
/// Error within the underlying file sink.
#[error("Failed to create the underlying file sink: {0}")]
FileSink(#[from] re_log_encoding::FileSinkError),
/// Error within the underlying table batcher.
#[error("Failed to spawn the underlying batcher: {0}")]
DataTableBatcher(#[from] DataTableBatcherError),
/// Error within the underlying data cell.
#[error("Failed to instantiate data cell: {0}")]
DataCell(#[from] DataCellError),
/// Error within the underlying serializer.
#[error("Failed to serialize component data: {0}")]
Serialization(#[from] SerializationError),
/// Error spawning one of the background threads.
#[error("Failed to spawn background thread '{name}': {err}")]
SpawnThread {
/// Name of the thread
name: String,
/// Inner error explaining why the thread failed to spawn.
err: std::io::Error,
},
/// Error spawning a Rerun Viewer process.
#[error(transparent)] // makes bubbling all the way up to main look nice
SpawnViewer(#[from] crate::SpawnError),
/// Failure to host a web viewer and/or Rerun server.
#[cfg(feature = "web_viewer")]
#[error(transparent)]
WebSink(#[from] crate::web_viewer::WebViewerSinkError),
/// An error that can occur because a row in the store has inconsistent columns.
#[error(transparent)]
DataReadError(#[from] re_log_types::DataReadError),
/// An error occurred while attempting to use a [`re_data_source::DataLoader`].
#[cfg(feature = "data_loaders")]
#[error(transparent)]
DataLoaderError(#[from] re_data_source::DataLoaderError),
}
/// Results that can occur when creating/manipulating a [`RecordingStream`].
pub type RecordingStreamResult<T> = Result<T, RecordingStreamError>;
// ---
/// Construct a [`RecordingStream`].
///
/// ``` no_run
/// # use re_sdk::RecordingStreamBuilder;
/// let rec = RecordingStreamBuilder::new("rerun_example_app").save("my_recording.rrd")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct RecordingStreamBuilder {
application_id: ApplicationId,
store_kind: StoreKind,
store_id: Option<StoreId>,
store_source: Option<StoreSource>,
default_enabled: bool,
enabled: Option<bool>,
batcher_config: Option<DataTableBatcherConfig>,
is_official_example: bool,
}
impl RecordingStreamBuilder {
/// Create a new [`RecordingStreamBuilder`] with the given [`ApplicationId`].
///
/// The [`ApplicationId`] is usually the name of your app.
///
/// ```no_run
/// # use re_sdk::RecordingStreamBuilder;
/// let rec = RecordingStreamBuilder::new("rerun_example_app").save("my_recording.rrd")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
//
// NOTE: track_caller so that we can see if we are being called from an official example.
#[track_caller]
pub fn new(application_id: impl Into<ApplicationId>) -> Self {
let application_id = application_id.into();
let is_official_example = crate::called_from_official_rust_example();
Self {
application_id,
store_kind: StoreKind::Recording,
store_id: None,
store_source: None,
default_enabled: true,
enabled: None,
batcher_config: None,
is_official_example,
}
}
/// Set whether or not Rerun is enabled by default.
///
/// If the `RERUN` environment variable is set, it will override this.
///
/// Set also: [`Self::enabled`].
#[inline]
pub fn default_enabled(mut self, default_enabled: bool) -> Self {
self.default_enabled = default_enabled;
self
}
/// Set whether or not Rerun is enabled.
///
/// Setting this will ignore the `RERUN` environment variable.
///
/// Set also: [`Self::default_enabled`].
#[inline]
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = Some(enabled);
self
}
/// Set the `RecordingId` for this context.
///
/// If you're logging from multiple processes and want all the messages to end up in the same
/// recording, you must make sure that they all set the same `RecordingId` using this function.
///
/// Note that many stores can share the same [`ApplicationId`], but they all have
/// unique `RecordingId`s.
///
/// The default is to use a random `RecordingId`.
#[inline]
pub fn recording_id(mut self, recording_id: impl Into<String>) -> Self {
self.store_id = Some(StoreId::from_string(
StoreKind::Recording,
recording_id.into(),
));
self
}
/// Set the [`StoreId`] for this context.
///
/// If you're logging from multiple processes and want all the messages to end up as the same
/// store, you must make sure they all set the same [`StoreId`] using this function.
///
/// Note that many stores can share the same [`ApplicationId`], but they all have
/// unique [`StoreId`]s.
///
/// The default is to use a random [`StoreId`].
#[inline]
pub fn store_id(mut self, store_id: StoreId) -> Self {
self.store_id = Some(store_id);
self
}
/// Specifies the configuration of the internal data batching mechanism.
///
/// See [`DataTableBatcher`] & [`DataTableBatcherConfig`] for more information.
#[inline]
pub fn batcher_config(mut self, config: DataTableBatcherConfig) -> Self {
self.batcher_config = Some(config);
self
}
#[doc(hidden)]
#[inline]
pub fn store_source(mut self, store_source: StoreSource) -> Self {
self.store_source = Some(store_source);
self
}
#[allow(clippy::wrong_self_convention)]
#[doc(hidden)]
#[inline]
pub fn is_official_example(mut self, is_official_example: bool) -> Self {
self.is_official_example = is_official_example;
self
}
#[doc(hidden)]
#[inline]
pub fn blueprint(mut self) -> Self {
self.store_kind = StoreKind::Blueprint;
self
}
/// Creates a new [`RecordingStream`] that starts in a buffering state (RAM).
///
/// ## Example
///
/// ```
/// let rec = re_sdk::RecordingStreamBuilder::new("rerun_example_app").buffered()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn buffered(self) -> RecordingStreamResult<RecordingStream> {
let (enabled, store_info, batcher_config) = self.into_args();
if enabled {
RecordingStream::new(
store_info,
batcher_config,
Box::new(crate::log_sink::BufferedSink::new()),
)
} else {
re_log::debug!("Rerun disabled - call to buffered() ignored");
Ok(RecordingStream::disabled())
}
}
/// Creates a new [`RecordingStream`] that is pre-configured to stream the data through to a
/// [`crate::log_sink::MemorySink`].
///
/// ## Example
///
/// ```
/// # fn log_data(_: &re_sdk::RecordingStream) { }
///
/// let (rec, storage) = re_sdk::RecordingStreamBuilder::new("rerun_example_app").memory()?;
///
/// log_data(&rec);
///
/// let data = storage.take();
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn memory(
self,
) -> RecordingStreamResult<(RecordingStream, crate::log_sink::MemorySinkStorage)> {
let sink = crate::log_sink::MemorySink::default();
let mut storage = sink.buffer();
let (enabled, store_info, batcher_config) = self.into_args();
if enabled {
RecordingStream::new(store_info, batcher_config, Box::new(sink)).map(|rec| {
storage.rec = Some(rec.clone());
(rec, storage)
})
} else {
re_log::debug!("Rerun disabled - call to memory() ignored");
Ok((RecordingStream::disabled(), Default::default()))
}
}
/// Creates a new [`RecordingStream`] that is pre-configured to stream the data through to a
/// remote Rerun instance.
///
/// See also [`Self::connect_opts`] if you wish to configure the TCP connection.
///
/// ## Example
///
/// ```no_run
/// let rec = re_sdk::RecordingStreamBuilder::new("rerun_example_app").connect()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn connect(self) -> RecordingStreamResult<RecordingStream> {
self.connect_opts(crate::default_server_addr(), crate::default_flush_timeout())
}
/// Creates a new [`RecordingStream`] that is pre-configured to stream the data through to a
/// remote Rerun instance.
///
/// `flush_timeout` is the minimum time the [`TcpSink`][`crate::log_sink::TcpSink`] will
/// wait during a flush before potentially dropping data. Note: Passing `None` here can cause a
/// call to `flush` to block indefinitely if a connection cannot be established.
///
/// ## Example
///
/// ```no_run
/// let rec = re_sdk::RecordingStreamBuilder::new("rerun_example_app")
/// .connect_opts(re_sdk::default_server_addr(), re_sdk::default_flush_timeout())?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn connect_opts(
self,
addr: std::net::SocketAddr,
flush_timeout: Option<std::time::Duration>,
) -> RecordingStreamResult<RecordingStream> {
let (enabled, store_info, batcher_config) = self.into_args();
if enabled {
RecordingStream::new(
store_info,
batcher_config,
Box::new(crate::log_sink::TcpSink::new(addr, flush_timeout)),
)
} else {
re_log::debug!("Rerun disabled - call to connect() ignored");
Ok(RecordingStream::disabled())
}
}
/// Creates a new [`RecordingStream`] that is pre-configured to stream the data through to an
/// RRD file on disk.
///
/// ## Example
///
/// ```no_run
/// let rec = re_sdk::RecordingStreamBuilder::new("rerun_example_app").save("my_recording.rrd")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub fn save(
self,
path: impl Into<std::path::PathBuf>,
) -> RecordingStreamResult<RecordingStream> {
let (enabled, store_info, batcher_config) = self.into_args();
if enabled {
RecordingStream::new(
store_info,
batcher_config,
Box::new(crate::sink::FileSink::new(path)?),
)
} else {
re_log::debug!("Rerun disabled - call to save() ignored");
Ok(RecordingStream::disabled())
}
}
/// Creates a new [`RecordingStream`] that is pre-configured to stream the data through to stdout.
///
/// If there isn't any listener at the other end of the pipe, the [`RecordingStream`] will
/// default back to `buffered` mode, in order not to break the user's terminal.
///
/// ## Example
///
/// ```no_run
/// let rec = re_sdk::RecordingStreamBuilder::new("rerun_example_app").stdout()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub fn stdout(self) -> RecordingStreamResult<RecordingStream> {
if std::io::stdout().is_terminal() {
re_log::debug!("Ignored call to stdout() because stdout is a terminal");
return self.buffered();
}
let (enabled, store_info, batcher_config) = self.into_args();
if enabled {
RecordingStream::new(
store_info,
batcher_config,
Box::new(crate::sink::FileSink::stdout()?),
)
} else {
re_log::debug!("Rerun disabled - call to stdout() ignored");
Ok(RecordingStream::disabled())
}
}
/// Spawns a new Rerun Viewer process from an executable available in PATH, then creates a new
/// [`RecordingStream`] that is pre-configured to stream the data through to that viewer over TCP.
///
/// If a Rerun Viewer is already listening on this TCP port, the stream will be redirected to
/// that viewer instead of starting a new one.
///
/// See also [`Self::spawn_opts`] if you wish to configure the behavior of thew Rerun process
/// as well as the underlying TCP connection.
///
/// ## Example
///
/// ```no_run
/// let rec = re_sdk::RecordingStreamBuilder::new("rerun_example_app").spawn()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn spawn(self) -> RecordingStreamResult<RecordingStream> {
self.spawn_opts(&Default::default(), crate::default_flush_timeout())
}
/// Spawns a new Rerun Viewer process from an executable available in PATH, then creates a new
/// [`RecordingStream`] that is pre-configured to stream the data through to that viewer over TCP.
///
/// If a Rerun Viewer is already listening on this TCP port, the stream will be redirected to
/// that viewer instead of starting a new one.
///
/// The behavior of the spawned Viewer can be configured via `opts`.
/// If you're fine with the default behavior, refer to the simpler [`Self::spawn`].
///
/// `flush_timeout` is the minimum time the [`TcpSink`][`crate::log_sink::TcpSink`] will
/// wait during a flush before potentially dropping data. Note: Passing `None` here can cause a
/// call to `flush` to block indefinitely if a connection cannot be established.
///
/// ## Example
///
/// ```no_run
/// let rec = re_sdk::RecordingStreamBuilder::new("rerun_example_app")
/// .spawn_opts(&re_sdk::SpawnOptions::default(), re_sdk::default_flush_timeout())?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn spawn_opts(
self,
opts: &crate::SpawnOptions,
flush_timeout: Option<std::time::Duration>,
) -> RecordingStreamResult<RecordingStream> {
if !self.is_enabled() {
re_log::debug!("Rerun disabled - call to spawn() ignored");
return Ok(RecordingStream::disabled());
}
let connect_addr = opts.connect_addr();
// NOTE: If `_RERUN_TEST_FORCE_SAVE` is set, all recording streams will write to disk no matter
// what, thus spawning a viewer is pointless (and probably not intended).
if forced_sink_path().is_some() {
return self.connect_opts(connect_addr, flush_timeout);
}
spawn(opts)?;
self.connect_opts(connect_addr, flush_timeout)
}
/// Creates a new [`RecordingStream`] that is pre-configured to stream the data through to a
/// web-based Rerun viewer via WebSockets.
///
/// This method needs to be called in a context where a Tokio runtime is already running (see
/// example below).
///
/// If the `open_browser` argument is `true`, your default browser will be opened with a
/// connected web-viewer.
///
/// If not, you can connect to this server using the `rerun` binary (`cargo install rerun-cli`).
///
/// ## Details
/// This method will spawn two servers: one HTTPS server serving the Rerun Web Viewer `.html` and `.wasm` files,
/// and then one WebSocket server that streams the log data to the web viewer (or to a native viewer, or to multiple viewers).
///
/// The WebSocket server will buffer all log data in memory so that late connecting viewers will get all the data.
/// You can limit the amount of data buffered by the WebSocket server with the `server_memory_limit` argument.
/// Once reached, the earliest logged data will be dropped.
/// Note that this means that timeless data may be dropped if logged early.
///
/// ## Example
///
/// ```ignore
/// // Ensure we have a running tokio runtime.
/// let mut tokio_runtime = None;
/// let tokio_runtime_handle = if let Ok(handle) = tokio::runtime::Handle::try_current() {
/// handle
/// } else {
/// let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime");
/// tokio_runtime.get_or_insert(rt).handle().clone()
/// };
/// let _tokio_runtime_guard = tokio_runtime_handle.enter();
///
/// let rec = re_sdk::RecordingStreamBuilder::new("rerun_example_app")
/// .serve("0.0.0.0",
/// Default::default(),
/// Default::default(),
/// re_sdk::MemoryLimit::from_fraction_of_total(0.25),
/// true)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "web_viewer")]
pub fn serve(
self,
bind_ip: &str,
web_port: WebViewerServerPort,
ws_port: RerunServerPort,
server_memory_limit: re_memory::MemoryLimit,
open_browser: bool,
) -> RecordingStreamResult<RecordingStream> {
let (enabled, store_info, batcher_config) = self.into_args();
if enabled {
let sink = crate::web_viewer::new_sink(
open_browser,
bind_ip,
web_port,
ws_port,
server_memory_limit,
)?;
RecordingStream::new(store_info, batcher_config, sink)
} else {
re_log::debug!("Rerun disabled - call to serve() ignored");
Ok(RecordingStream::disabled())
}
}
/// Returns whether or not logging is enabled, a [`StoreInfo`] and the associated batcher
/// configuration.
///
/// This can be used to then construct a [`RecordingStream`] manually using
/// [`RecordingStream::new`].
pub fn into_args(self) -> (bool, StoreInfo, DataTableBatcherConfig) {
let enabled = self.is_enabled();
let Self {
application_id,
store_kind,
store_id,
store_source,
default_enabled: _,
enabled: _,
batcher_config,
is_official_example,
} = self;
let store_id = store_id.unwrap_or(StoreId::random(store_kind));
let store_source = store_source.unwrap_or_else(|| StoreSource::RustSdk {
rustc_version: env!("RE_BUILD_RUSTC_VERSION").into(),
llvm_version: env!("RE_BUILD_LLVM_VERSION").into(),
});
let store_info = StoreInfo {
application_id,
store_id,
is_official_example,
started: Time::now(),
store_source,
store_kind,
};
let batcher_config =
batcher_config.unwrap_or_else(|| match DataTableBatcherConfig::from_env() {
Ok(config) => config,
Err(err) => {
re_log::error!("Failed to parse DataTableBatcherConfig from env: {}", err);
DataTableBatcherConfig::default()
}
});
(enabled, store_info, batcher_config)
}
/// Internal check for whether or not logging is enabled using explicit/default settings & env var.
fn is_enabled(&self) -> bool {
self.enabled
.unwrap_or_else(|| crate::decide_logging_enabled(self.default_enabled))
}
}
// ----------------------------------------------------------------------------
/// A [`RecordingStream`] handles everything related to logging data into Rerun.
///
/// You can construct a new [`RecordingStream`] using [`RecordingStreamBuilder`] or
/// [`RecordingStream::new`].
///
/// ## Sinks
///
/// Data is logged into Rerun via [`LogSink`]s.
///
/// The underlying [`LogSink`] of a [`RecordingStream`] can be changed at any point during its
/// lifetime by calling [`RecordingStream::set_sink`] or one of the higher level helpers
/// ([`RecordingStream::connect`], [`RecordingStream::memory`],
/// [`RecordingStream::save`], [`RecordingStream::disconnect`]).
///
/// See [`RecordingStream::set_sink`] for more information.
///
/// ## Multithreading and ordering
///
/// [`RecordingStream`] can be cheaply cloned and used freely across any number of threads.
///
/// Internally, all operations are linearized into a pipeline:
/// - All operations sent by a given thread will take effect in the same exact order as that
/// thread originally sent them in, from its point of view.
/// - There isn't any well defined global order across multiple threads.
///
/// This means that e.g. flushing the pipeline ([`Self::flush_blocking`]) guarantees that all
/// previous data sent by the calling thread has been recorded; no more, no less.
/// (e.g. it does not mean that all file caches are flushed)
///
/// ## Shutdown
///
/// The [`RecordingStream`] can only be shutdown by dropping all instances of it, at which point
/// it will automatically take care of flushing any pending data that might remain in the pipeline.
///
/// Shutting down cannot ever block.
#[derive(Clone)]
pub struct RecordingStream {
inner: Either<Arc<Option<RecordingStreamInner>>, Weak<Option<RecordingStreamInner>>>,
}
impl RecordingStream {
/// Passes a reference to the [`RecordingStreamInner`], if it exists.
///
/// This works whether the underlying stream is strong or weak.
#[inline]
fn with<F: FnOnce(&RecordingStreamInner) -> R, R>(&self, f: F) -> Option<R> {
use std::ops::Deref as _;
match &self.inner {
Either::Left(strong) => strong.deref().as_ref().map(f),
Either::Right(weak) => weak
.upgrade()
.and_then(|strong| strong.deref().as_ref().map(f)),
}
}
/// Clones the [`RecordingStream`] without incrementing the refcount.
///
/// Useful e.g. if you want to make sure that a detached thread won't prevent the [`RecordingStream`]
/// from flushing during shutdown.
//
// TODO(#5335): shutdown flushing behavior is too brittle.
#[inline]
pub fn clone_weak(&self) -> Self {
Self {
inner: match &self.inner {
Either::Left(strong) => Either::Right(Arc::downgrade(strong)),
Either::Right(weak) => Either::Right(Weak::clone(weak)),
},
}
}
}
// TODO(#5335): shutdown flushing behavior is too brittle.
impl Drop for RecordingStream {
#[inline]
fn drop(&mut self) {
// If this holds the last strong handle to the recording, make sure that all pending
// `DataLoader` threads that were started from the SDK actually run to completion (they
// all hold a weak handle to this very recording!).
//
// NOTE: It's very important to do so from the `Drop` implementation of `RecordingStream`
// itself, because the dataloader threads -- by definition -- will have to send data into
// this very recording, therefore we must make sure that at least one strong handle still lives
// on until they are all finished.
if let Either::Left(strong) = &mut self.inner {
if Arc::strong_count(strong) == 1 {
// Keep the recording alive until all dataloaders are finished.
self.with(|inner| inner.wait_for_dataloaders());
}
}
}
}
struct RecordingStreamInner {
info: StoreInfo,
tick: AtomicI64,
/// The one and only entrypoint into the pipeline: this is _never_ cloned nor publicly exposed,
/// therefore the `Drop` implementation is guaranteed that no more data can come in while it's
/// running.
cmds_tx: Sender<Command>,
batcher: DataTableBatcher,
batcher_to_sink_handle: Option<std::thread::JoinHandle<()>>,
/// Keeps track of the top-level threads that were spawned in order to execute the `DataLoader`
/// machinery in the context of this `RecordingStream`.
///
/// See [`RecordingStream::log_file_from_path`] and [`RecordingStream::log_file_from_contents`].
dataloader_handles: Mutex<Vec<std::thread::JoinHandle<()>>>,
pid_at_creation: u32,
}
impl fmt::Debug for RecordingStreamInner {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RecordingStreamInner")
.field("info", &self.info.store_id)
.finish()
}
}
impl Drop for RecordingStreamInner {
fn drop(&mut self) {
if self.is_forked_child() {
re_log::error_once!("Fork detected while dropping RecordingStreamInner. cleanup_if_forked() should always be called after forking. This is likely a bug in the SDK.");
return;
}
self.wait_for_dataloaders();
// NOTE: The command channel is private, if we're here, nothing is currently capable of
// sending data down the pipeline.
self.batcher.flush_blocking();
self.cmds_tx.send(Command::PopPendingTables).ok();
self.cmds_tx.send(Command::Shutdown).ok();
if let Some(handle) = self.batcher_to_sink_handle.take() {
handle.join().ok();
}
}
}
impl RecordingStreamInner {
fn new(
info: StoreInfo,
batcher_config: DataTableBatcherConfig,
sink: Box<dyn LogSink>,
) -> RecordingStreamResult<Self> {
let on_release = batcher_config.hooks.on_release.clone();
let batcher = DataTableBatcher::new(batcher_config)?;
{
re_log::debug!(
app_id = %info.application_id,
rec_id = %info.store_id,
"setting recording info",
);
sink.send(
re_log_types::SetStoreInfo {
row_id: re_log_types::RowId::new(),
info: info.clone(),
}
.into(),
);
}
let (cmds_tx, cmds_rx) = crossbeam::channel::unbounded();
let batcher_to_sink_handle = {
const NAME: &str = "RecordingStream::batcher_to_sink";
std::thread::Builder::new()
.name(NAME.into())
.spawn({
let info = info.clone();
let batcher = batcher.clone();
move || forwarding_thread(info, sink, cmds_rx, batcher.tables(), on_release)
})
.map_err(|err| RecordingStreamError::SpawnThread {
name: NAME.into(),
err,
})?
};
Ok(RecordingStreamInner {
info,
tick: AtomicI64::new(0),
cmds_tx,
batcher,
batcher_to_sink_handle: Some(batcher_to_sink_handle),
dataloader_handles: Mutex::new(Vec::new()),
pid_at_creation: std::process::id(),
})
}
#[inline]
pub fn is_forked_child(&self) -> bool {
self.pid_at_creation != std::process::id()
}
/// Make sure all pending top-level `DataLoader` threads that were started from the SDK run to completion.
//
// TODO(cmc): At some point we might want to make it configurable, though I cannot really
// think of a use case where you'd want to drop those threads immediately upon
// disconnection.
fn wait_for_dataloaders(&self) {
let dataloader_handles = std::mem::take(&mut *self.dataloader_handles.lock());
for handle in dataloader_handles {
handle.join().ok();
}
}
}
enum Command {
RecordMsg(LogMsg),
SwapSink(Box<dyn LogSink>),
Flush(Sender<()>),
PopPendingTables,
Shutdown,
}
impl Command {
fn flush() -> (Self, Receiver<()>) {
let (tx, rx) = crossbeam::channel::bounded(0); // oneshot
(Self::Flush(tx), rx)
}
}
impl RecordingStream {
/// Creates a new [`RecordingStream`] with a given [`StoreInfo`] and [`LogSink`].
///
/// You can create a [`StoreInfo`] with [`crate::new_store_info`];
///
/// The [`StoreInfo`] is immediately sent to the sink in the form of a
/// [`re_log_types::SetStoreInfo`].
///
/// You can find sinks in [`crate::sink`].
///
/// See also: [`RecordingStreamBuilder`].
#[must_use = "Recording will get closed automatically once all instances of this object have been dropped"]
pub fn new(
info: StoreInfo,
batcher_config: DataTableBatcherConfig,
sink: Box<dyn LogSink>,
) -> RecordingStreamResult<Self> {
let sink = forced_sink_path().map_or(sink, |path| {
re_log::info!("Forcing FileSink because of env-var {ENV_FORCE_SAVE}={path:?}");
// `unwrap` is ok since this force sinks are only used in tests.
Box::new(crate::sink::FileSink::new(path).unwrap()) as Box<dyn LogSink>
});
RecordingStreamInner::new(info, batcher_config, sink).map(|inner| Self {
inner: Either::Left(Arc::new(Some(inner))),
})
}
/// Creates a new no-op [`RecordingStream`] that drops all logging messages, doesn't allocate
/// any memory and doesn't spawn any threads.
///
/// [`Self::is_enabled`] will return `false`.
pub fn disabled() -> Self {
Self {
inner: Either::Left(Arc::new(None)),
}
}
}
impl RecordingStream {
/// Log data to Rerun.
///
/// This is the main entry point for logging data to rerun. It can be used to log anything
/// that implements the [`AsComponents`], such as any [archetype](https://docs.rs/rerun/latest/rerun/archetypes/index.html).
///
/// The data will be timestamped automatically based on the [`RecordingStream`]'s internal clock.
/// See [`RecordingStream::set_time_sequence`] etc for more information.
///
/// The entity path can either be a string
/// (with special characters escaped, split on unescaped slashes)
/// or an [`EntityPath`] constructed with [`crate::entity_path`].
/// See <https://www.rerun.io/docs/concepts/entity-path> for more on entity paths.
///
/// See also: [`Self::log_timeless`] for logging timeless data.
///
/// Internally, the stream will automatically micro-batch multiple log calls to optimize
/// transport.
/// See [SDK Micro Batching] for more information.
///
/// # Example:
/// ```ignore
/// # use rerun;
/// # let (rec, storage) = rerun::RecordingStreamBuilder::new("rerun_example_points3d_simple").memory()?;
/// rec.log(
/// "my/points",
/// &rerun::Points3D::new([(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)]),
/// )?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// [SDK Micro Batching]: https://www.rerun.io/docs/reference/sdk-micro-batching
/// [component bundle]: [`AsComponents`]
#[inline]
pub fn log(
&self,
ent_path: impl Into<EntityPath>,
arch: &impl AsComponents,
) -> RecordingStreamResult<()> {
self.log_with_timeless(ent_path, false, arch)
}
/// Log data to Rerun.
///
/// It can be used to log anything
/// that implements the [`AsComponents`], such as any [archetype](https://docs.rs/rerun/latest/rerun/archetypes/index.html).
///
/// Timeless data is present on all timelines and behaves as if it was recorded infinitely far
/// into the past.
/// All timestamp data associated with this message will be dropped right before sending it to Rerun.
///
/// This is most often used for [`rerun::ViewCoordinates`](https://docs.rs/rerun/latest/rerun/archetypes/struct.ViewCoordinates.html) and
/// [`rerun::AnnotationContext`](https://docs.rs/rerun/latest/rerun/archetypes/struct.AnnotationContext.html).
///
/// Internally, the stream will automatically micro-batch multiple log calls to optimize
/// transport.
/// See [SDK Micro Batching] for more information.
///
/// See also [`Self::log`].
///
/// [SDK Micro Batching]: https://www.rerun.io/docs/reference/sdk-micro-batching
/// [component bundle]: [`AsComponents`]
#[inline]
pub fn log_timeless(
&self,
ent_path: impl Into<EntityPath>,
arch: &impl AsComponents,
) -> RecordingStreamResult<()> {
self.log_with_timeless(ent_path, true, arch)
}
/// Logs the contents of a [component bundle] into Rerun.
///
/// If `timeless` is set to `true`, all timestamp data associated with this message will be
/// dropped right before sending it to Rerun.
/// Timeless data is present on all timelines and behaves as if it was recorded infinitely far
/// into the past.
///
/// Otherwise, the data will be timestamped automatically based on the [`RecordingStream`]'s
/// internal clock.
/// See `RecordingStream::set_time_*` family of methods for more information.
///
/// The entity path can either be a string
/// (with special characters escaped, split on unescaped slashes)
/// or an [`EntityPath`] constructed with [`crate::entity_path`].
/// See <https://www.rerun.io/docs/concepts/entity-path> for more on entity paths.
///
/// Internally, the stream will automatically micro-batch multiple log calls to optimize
/// transport.
/// See [SDK Micro Batching] for more information.
///
/// [SDK Micro Batching]: https://www.rerun.io/docs/reference/sdk-micro-batching
/// [component bundle]: [`AsComponents`]
#[inline]
pub fn log_with_timeless(
&self,
ent_path: impl Into<EntityPath>,
timeless: bool,
arch: &impl AsComponents,
) -> RecordingStreamResult<()> {
let row_id = RowId::new(); // Create row-id as early as possible. It has a timestamp and is used to estimate e2e latency.
self.log_component_batches_impl(
row_id,
ent_path,
timeless,
arch.as_component_batches()
.iter()
.map(|any_comp_batch| any_comp_batch.as_ref()),
)
}
/// Logs a set of [`ComponentBatch`]es into Rerun.
///
/// If `timeless` is set to `false`, all timestamp data associated with this message will be
/// dropped right before sending it to Rerun.
/// Timeless data is present on all timelines and behaves as if it was recorded infinitely far
/// into the past.
///
/// Otherwise, the data will be timestamped automatically based on the [`RecordingStream`]'s
/// internal clock.
/// See `RecordingStream::set_time_*` family of methods for more information.
///
/// The number of instances will be determined by the longest batch in the bundle.
/// All of the batches should have the same number of instances, or length 1 if the component is
/// a splat, or 0 if the component is being cleared.
///
/// The entity path can either be a string
/// (with special characters escaped, split on unescaped slashes)
/// or an [`EntityPath`] constructed with [`crate::entity_path`].
/// See <https://www.rerun.io/docs/concepts/entity-path> for more on entity paths.
///
/// Internally, the stream will automatically micro-batch multiple log calls to optimize
/// transport.
/// See [SDK Micro Batching] for more information.
///
/// [SDK Micro Batching]: https://www.rerun.io/docs/reference/sdk-micro-batching
pub fn log_component_batches<'a>(
&self,
ent_path: impl Into<EntityPath>,
timeless: bool,
comp_batches: impl IntoIterator<Item = &'a dyn ComponentBatch>,
) -> RecordingStreamResult<()> {
let row_id = RowId::new(); // Create row-id as early as possible. It has a timestamp and is used to estimate e2e latency.
self.log_component_batches_impl(row_id, ent_path, timeless, comp_batches)
}
fn log_component_batches_impl<'a>(
&self,
row_id: RowId,
ent_path: impl Into<EntityPath>,
timeless: bool,
comp_batches: impl IntoIterator<Item = &'a dyn ComponentBatch>,
) -> RecordingStreamResult<()> {