re_sdk/
lib.rs

1//! The Rerun logging SDK
2//!
3//! This is the bare-bones version of the [`rerun`](https://docs.rs/rerun/) crate.
4//! `rerun` exports everything in `re_sdk`, so in most cases you want to use `rerun`
5//! instead.
6//!
7//! Please read [the docs for the `rerun` crate](https://docs.rs/rerun/) instead.
8//!
9//! ## Feature flags
10#![doc = document_features::document_features!()]
11//!
12
13// TODO(#6330): remove unwrap()
14#![allow(clippy::unwrap_used)]
15#![warn(missing_docs)] // Let's keep the this crate well-documented!
16
17// ----------------
18// Private modules:
19
20mod binary_stream_sink;
21mod global;
22mod log_sink;
23mod recording_stream;
24mod spawn;
25
26// -------------
27// Public items:
28
29pub use spawn::{spawn, SpawnError, SpawnOptions};
30
31pub use self::recording_stream::{
32    forced_sink_path, RecordingStream, RecordingStreamBuilder, RecordingStreamError,
33    RecordingStreamResult,
34};
35
36/// The default port of a Rerun gRPC /proxy server.
37pub const DEFAULT_SERVER_PORT: u16 = re_uri::DEFAULT_PROXY_PORT;
38
39/// The default URL of a Rerun gRPC /proxy server.
40///
41/// This isn't used to _host_ the server, only to _connect_ to it.
42pub const DEFAULT_CONNECT_URL: &str =
43    const_format::concatcp!("rerun+http://127.0.0.1:", DEFAULT_SERVER_PORT, "/proxy");
44
45/// The default address of a Rerun gRPC server which an SDK connects to.
46#[deprecated(since = "0.22.0", note = "migrate to connect_grpc")]
47pub fn default_server_addr() -> std::net::SocketAddr {
48    std::net::SocketAddr::from(([127, 0, 0, 1], DEFAULT_SERVER_PORT))
49}
50
51/// The default amount of time to wait for the gRPC connection to resume during a flush
52#[allow(clippy::unnecessary_wraps)]
53pub fn default_flush_timeout() -> Option<std::time::Duration> {
54    // NOTE: This is part of the SDK and meant to be used where we accept `Option<std::time::Duration>` values.
55    Some(std::time::Duration::from_secs(3))
56}
57
58pub use re_log_types::{
59    entity_path, ApplicationId, EntityPath, EntityPathPart, Instance, StoreId, StoreKind,
60};
61pub use re_memory::MemoryLimit;
62pub use re_types::archetypes::RecordingProperties;
63
64pub use global::cleanup_if_forked_child;
65
66#[cfg(not(target_arch = "wasm32"))]
67impl crate::sink::LogSink for re_log_encoding::FileSink {
68    fn send(&self, msg: re_log_types::LogMsg) {
69        Self::send(self, msg);
70    }
71
72    #[inline]
73    fn flush_blocking(&self) {
74        Self::flush_blocking(self);
75    }
76}
77
78// ---------------
79// Public modules:
80
81/// Different destinations for log messages.
82///
83/// This is how you select whether the log stream ends up
84/// sent over gRPC, written to file, etc.
85pub mod sink {
86    pub use crate::binary_stream_sink::{BinaryStreamSink, BinaryStreamStorage};
87    pub use crate::log_sink::{BufferedSink, CallbackSink, LogSink, MemorySink, MemorySinkStorage};
88
89    pub use crate::log_sink::GrpcSink;
90
91    #[cfg(not(target_arch = "wasm32"))]
92    pub use re_log_encoding::{FileSink, FileSinkError};
93}
94
95/// Things directly related to logging.
96pub mod log {
97    pub use re_chunk::{
98        Chunk, ChunkBatcher, ChunkBatcherConfig, ChunkBatcherError, ChunkBatcherResult,
99        ChunkComponents, ChunkError, ChunkId, ChunkResult, PendingRow, RowId, TimeColumn,
100    };
101    pub use re_log_types::LogMsg;
102}
103
104/// Time-related types.
105pub mod time {
106    pub use re_log_types::{Duration, TimeCell, TimeInt, TimePoint, TimeType, Timeline, Timestamp};
107}
108pub use time::{TimeCell, TimePoint, Timeline};
109
110pub use re_types::{
111    Archetype, ArchetypeName, AsComponents, Component, ComponentBatch, ComponentDescriptor,
112    ComponentName, DatatypeName, DeserializationError, DeserializationResult,
113    GenericIndicatorComponent, Loggable, LoggableBatch, NamedIndicatorComponent,
114    SerializationError, SerializationResult, SerializedComponentBatch, SerializedComponentColumn,
115};
116
117pub use re_byte_size::SizeBytes;
118
119#[cfg(feature = "data_loaders")]
120pub use re_data_loader::{DataLoader, DataLoaderError, DataLoaderSettings, LoadedData};
121
122/// Methods for spawning the web viewer and streaming the SDK log stream to it.
123#[cfg(feature = "web_viewer")]
124pub mod web_viewer;
125
126/// Method for spawning a gRPC server and streaming the SDK log stream to it.
127#[cfg(feature = "server")]
128pub mod grpc_server;
129
130/// Re-exports of other crates.
131pub mod external {
132    pub use re_grpc_client;
133    pub use re_grpc_server;
134    pub use re_log;
135    pub use re_log_encoding;
136    pub use re_log_types;
137
138    pub use re_chunk::external::*;
139    pub use re_log::external::*;
140    pub use re_log_types::external::*;
141
142    #[cfg(feature = "data_loaders")]
143    pub use re_data_loader;
144}
145
146#[cfg(feature = "web_viewer")]
147pub use web_viewer::serve_web_viewer;
148
149// -----
150// Misc:
151
152/// The version of the Rerun SDK.
153pub fn build_info() -> re_build_info::BuildInfo {
154    re_build_info::build_info!()
155}
156
157const RERUN_ENV_VAR: &str = "RERUN";
158
159/// Helper to get the value of the `RERUN` environment variable.
160fn get_rerun_env() -> Option<bool> {
161    std::env::var(RERUN_ENV_VAR)
162        .ok()
163        .and_then(|s| match s.to_lowercase().as_str() {
164            "0" | "false" | "off" => Some(false),
165            "1" | "true" | "on" => Some(true),
166            _ => {
167                re_log::warn!(
168                    "Invalid value for environment variable {RERUN_ENV_VAR}={s:?}. Expected 'on' or 'off'. It will be ignored"
169                );
170                None
171            }
172        })
173}
174
175/// Checks the `RERUN` environment variable. If not found, returns the argument.
176///
177/// Also adds some helpful logging.
178pub fn decide_logging_enabled(default_enabled: bool) -> bool {
179    // We use `info_once` so that we can call this function
180    // multiple times without spamming the log.
181    match get_rerun_env() {
182        Some(true) => {
183            re_log::info_once!(
184                "Rerun Logging is enabled by the '{RERUN_ENV_VAR}' environment variable."
185            );
186            true
187        }
188        Some(false) => {
189            re_log::info_once!(
190                "Rerun Logging is disabled by the '{RERUN_ENV_VAR}' environment variable."
191            );
192            false
193        }
194        None => {
195            if !default_enabled {
196                re_log::info_once!(
197                    "Rerun Logging has been disabled. Turn it on with the '{RERUN_ENV_VAR}' environment variable."
198                );
199            }
200            default_enabled
201        }
202    }
203}
204
205// ----------------------------------------------------------------------------
206
207/// Creates a new [`re_log_types::StoreInfo`] which can be used with [`RecordingStream::new`].
208#[track_caller] // track_caller so that we can see if we are being called from an official example.
209pub fn new_store_info(
210    application_id: impl Into<re_log_types::ApplicationId>,
211) -> re_log_types::StoreInfo {
212    re_log_types::StoreInfo {
213        application_id: application_id.into(),
214        store_id: StoreId::random(StoreKind::Recording),
215        cloned_from: None,
216        store_source: re_log_types::StoreSource::RustSdk {
217            rustc_version: env!("RE_BUILD_RUSTC_VERSION").into(),
218            llvm_version: env!("RE_BUILD_LLVM_VERSION").into(),
219        },
220        started: None,
221        store_version: Some(re_build_info::CrateVersion::LOCAL),
222    }
223}