-
Notifications
You must be signed in to change notification settings - Fork 373
/
recording_stream.rs
1786 lines (1580 loc) · 64.5 KB
/
recording_stream.rs
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::sync::{atomic::AtomicI64, Arc};
use ahash::HashMap;
use crossbeam::channel::{Receiver, Sender};
use re_log_types::{
ApplicationId, DataCell, DataCellError, DataRow, DataTable, DataTableBatcher,
DataTableBatcherConfig, DataTableBatcherError, EntityPath, LogMsg, RowId, StoreId, StoreInfo,
StoreKind, StoreSource, Time, TimeInt, TimePoint, TimeType, Timeline, TimelineName,
};
use re_types::components::InstanceKey;
use re_types_core::{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 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: &'static str,
/// 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),
}
/// 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`].
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`].
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = Some(enabled);
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`].
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.
pub fn batcher_config(mut self, config: DataTableBatcherConfig) -> Self {
self.batcher_config = Some(config);
self
}
#[doc(hidden)]
pub fn store_source(mut self, store_source: StoreSource) -> Self {
self.store_source = Some(store_source);
self
}
#[allow(clippy::wrong_self_convention)]
#[doc(hidden)]
pub fn is_official_example(mut self, is_official_example: bool) -> Self {
self.is_official_example = is_official_example;
self
}
#[doc(hidden)]
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.
///
/// `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(re_sdk::default_server_addr(), re_sdk::default_flush_timeout())?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn connect(
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())
}
}
/// 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.
///
/// `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(re_sdk::default_flush_timeout())?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn spawn(
self,
flush_timeout: Option<std::time::Duration>,
) -> RecordingStreamResult<RecordingStream> {
self.spawn_opts(&Default::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> {
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(connect_addr, flush_timeout);
}
spawn(opts)?;
self.connect(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`).
///
/// ## 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(), true)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "web_viewer")]
pub fn serve(
self,
bind_ip: &str,
web_port: WebViewerServerPort,
ws_port: RerunServerPort,
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)?;
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 Self {
application_id,
store_kind,
store_id,
store_source,
default_enabled,
enabled,
batcher_config,
is_official_example,
} = self;
let enabled = enabled.unwrap_or_else(|| crate::decide_logging_enabled(default_enabled));
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(|| DataTableBatcherConfig::from_env().unwrap_or_default());
(enabled, store_info, batcher_config)
}
}
// ----------------------------------------------------------------------------
/// 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: Arc<Option<RecordingStreamInner>>,
}
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<()>>,
pid_at_creation: u32,
}
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;
}
// 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 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::random(),
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())
})
.map_err(|err| RecordingStreamError::SpawnThread { name: NAME, err })?
};
Ok(RecordingStreamInner {
info,
tick: AtomicI64::new(0),
cmds_tx,
batcher,
batcher_to_sink_handle: Some(batcher_to_sink_handle),
pid_at_creation: std::process::id(),
})
}
#[inline]
pub fn is_forked_child(&self) -> bool {
self.pid_at_creation != std::process::id()
}
}
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: 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: 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][crate::archetypes].
///
/// The data will be timestamped automatically based on the [`RecordingStream`]'s internal clock.
/// See [`RecordingStream::set_time_sequence`] etc for more information.
///
/// 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:
/// ```
/// # use re_sdk as 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][crate::archetypes].
///
/// 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 [`re_types::components::ViewCoordinates`] and
/// [`re_types::components::AnnotationContext`].
///
/// 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.
///
/// 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<()> {
self.log_component_batches(
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.
///
/// 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<()> {
if !self.is_enabled() {
return Ok(()); // silently drop the message
}
let ent_path = ent_path.into();
let mut num_instances = 0;
let comp_batches: Result<Vec<_>, _> = comp_batches
.into_iter()
.map(|comp_batch| {
num_instances = usize::max(num_instances, comp_batch.num_instances());
comp_batch
.to_arrow()
.map(|array| (comp_batch.arrow_field(), array))
})
.collect();
let comp_batches = comp_batches?;
let cells: Result<Vec<_>, _> = comp_batches
.into_iter()
.map(|(field, array)| {
// NOTE: Unreachable, a top-level Field will always be a component, and thus an
// extension.
use re_log_types::external::arrow2::datatypes::DataType;
let DataType::Extension(fqname, _, _) = field.data_type else {
return Err(SerializationError::missing_extension_metadata(field.name))
.map_err(Into::into);
};
DataCell::try_from_arrow(fqname.into(), array)
})
.collect();
let cells = cells?;
let mut instanced: Vec<DataCell> = Vec::new();
let mut splatted: Vec<DataCell> = Vec::new();
for cell in cells {
if num_instances > 1 && cell.num_instances() == 1 {
splatted.push(cell);
} else {
instanced.push(cell);
}
}
// NOTE: The timepoint is irrelevant, the `RecordingStream` will overwrite it using its
// internal clock.
let timepoint = TimePoint::timeless();
let instanced = if instanced.is_empty() {
None
} else {
Some(DataRow::from_cells(
RowId::random(),
timepoint.clone(),
ent_path.clone(),
num_instances as _,
instanced,
)?)
};
// TODO(#1893): unsplit splats once new data cells are in
let splatted = if splatted.is_empty() {
None
} else {
splatted.push(DataCell::from_native([InstanceKey::SPLAT]));
Some(DataRow::from_cells(
RowId::random(),
timepoint,
ent_path,
1,
splatted,
)?)
};
if let Some(splatted) = splatted {
self.record_row(splatted, !timeless);
}
// Always the primary component last so range-based queries will include the other data.
// Since the primary component can't be splatted it must be in here, see(#1215).
if let Some(instanced) = instanced {
self.record_row(instanced, !timeless);
}
Ok(())
}
}
#[allow(clippy::needless_pass_by_value)]
fn forwarding_thread(
info: StoreInfo,
mut sink: Box<dyn LogSink>,
cmds_rx: Receiver<Command>,
tables: Receiver<DataTable>,
) {
/// Returns `true` to indicate that processing can continue; i.e. `false` means immediate
/// shutdown.
fn handle_cmd(info: &StoreInfo, cmd: Command, sink: &mut Box<dyn LogSink>) -> bool {
match cmd {
Command::RecordMsg(msg) => {
sink.send(msg);
}
Command::SwapSink(new_sink) => {
re_log::trace!("Swapping sink…");
let backlog = {
// Capture the backlog if it exists.
let backlog = sink.drain_backlog();
// Flush the underlying sink if possible.
sink.drop_if_disconnected();
sink.flush_blocking();
backlog
};
// Send the recording info to the new sink. This is idempotent.
{
re_log::debug!(
app_id = %info.application_id,
rec_id = %info.store_id,
"setting recording info",
);
new_sink.send(
re_log_types::SetStoreInfo {
row_id: re_log_types::RowId::random(),
info: info.clone(),
}
.into(),
);
new_sink.send_all(backlog);
}
*sink = new_sink;
}
Command::Flush(oneshot) => {
re_log::trace!("Flushing…");
// Flush the underlying sink if possible.
sink.drop_if_disconnected();
sink.flush_blocking();
drop(oneshot); // signals the oneshot
}
Command::PopPendingTables => {
// Wake up and skip the current iteration so that we can drain all pending tables
// before handling the next command.
}
Command::Shutdown => return false,
}
true
}
use crossbeam::select;
loop {
// NOTE: Always pop tables first, this is what makes `Command::PopPendingTables` possible,
// which in turns makes `RecordingStream::flush_blocking` well defined.
while let Ok(table) = tables.try_recv() {
let table = match table.to_arrow_msg() {
Ok(table) => table,
Err(err) => {
re_log::error!(%err,
"couldn't serialize table; data dropped (this is a bug in Rerun!)");
continue;
}
};
sink.send(LogMsg::ArrowMsg(info.store_id.clone(), table));
}
select! {
recv(tables) -> res => {
let Ok(table) = res else {
// The batcher is gone, which can only happen if the `RecordingStream` itself
// has been dropped.
re_log::trace!("Shutting down forwarding_thread: batcher is gone");
break;
};
let table = match table.to_arrow_msg() {
Ok(table) => table,
Err(err) => {
re_log::error!(%err,
"couldn't serialize table; data dropped (this is a bug in Rerun!)");
continue;
}
};
sink.send(LogMsg::ArrowMsg(info.store_id.clone(), table));
}
recv(cmds_rx) -> res => {
let Ok(cmd) = res else {
// All command senders are gone, which can only happen if the
// `RecordingStream` itself has been dropped.
re_log::trace!("Shutting down forwarding_thread: all command senders are gone");
break;
};
if !handle_cmd(&info, cmd, &mut sink) {
break; // shutdown
}
}
}
// NOTE: The receiving end of the command stream is owned solely by this thread.
// Past this point, all command writes will return `ErrDisconnected`.
}
}
impl RecordingStream {
/// Check if logging is enabled on this `RecordingStream`.
///
/// If not, all recording calls will be ignored.
#[inline]
pub fn is_enabled(&self) -> bool {
self.inner.is_some()
}
/// The [`StoreInfo`] associated with this `RecordingStream`.
#[inline]
pub fn store_info(&self) -> Option<&StoreInfo> {
(*self.inner).as_ref().map(|inner| &inner.info)
}
/// Determine whether a fork has happened since creating this `RecordingStream`. In general, this means our
/// batcher/sink threads are gone and all data logged since the fork has been dropped.
///
/// It is essential that [`crate::cleanup_if_forked_child`] be called after forking the process. SDK-implementations
/// should do this during their initialization phase.
#[inline]
pub fn is_forked_child(&self) -> bool {
(*self.inner)
.as_ref()
.map_or(false, |inner| inner.is_forked_child())
}
}