Skip to main content

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#![warn(missing_docs)] // Let's keep the this crate well-documented!
14
15// ----------------
16// Private modules:
17
18mod binary_stream_sink;
19mod global;
20mod log_sink;
21mod recording_stream;
22mod spawn;
23
24// ---------------
25// Public modules:
26
27pub mod blueprint;
28
29// -------------
30// Public items:
31
32pub use spawn::{SpawnError, SpawnOptions, spawn};
33
34pub use self::recording_stream::{
35    RecordingStream, RecordingStreamBuilder, RecordingStreamError, RecordingStreamResult,
36    forced_sink_path,
37};
38
39/// The default port of a Rerun gRPC /proxy server.
40pub const DEFAULT_SERVER_PORT: u16 = re_uri::DEFAULT_PROXY_PORT;
41
42/// The default URL of a Rerun gRPC /proxy server.
43///
44/// This isn't used to _host_ the server, only to _connect_ to it.
45pub const DEFAULT_CONNECT_URL: &str =
46    const_format::concatcp!("rerun+http://127.0.0.1:", DEFAULT_SERVER_PORT, "/proxy");
47
48pub use global::cleanup_if_forked_child;
49pub use re_log_types::{
50    ApplicationId, EntityPath, EntityPathFilter, EntityPathPart, Instance, StoreId, StoreKind,
51    entity_path,
52};
53pub use re_sdk_types::archetypes::RecordingInfo;
54
55#[cfg(not(target_arch = "wasm32"))]
56impl crate::sink::LogSink for re_log_encoding::FileSink {
57    fn send(&self, msg: re_log_types::LogMsg) {
58        Self::send(self, msg);
59    }
60
61    #[inline]
62    fn flush_blocking(&self, timeout: std::time::Duration) -> Result<(), sink::SinkFlushError> {
63        use re_log_encoding::FileFlushError;
64
65        Self::flush_blocking(self, timeout).map_err(|err| match err {
66            FileFlushError::Failed { message } => sink::SinkFlushError::Failed { message },
67            FileFlushError::Timeout => sink::SinkFlushError::Timeout,
68        })
69    }
70}
71
72// ---------------
73// Public modules:
74
75/// Different destinations for log messages.
76///
77/// This is how you select whether the log stream ends up
78/// sent over gRPC, written to file, etc.
79pub mod sink {
80    #[cfg(not(target_arch = "wasm32"))]
81    pub use re_log_encoding::{FileSink, FileSinkError};
82
83    pub use crate::binary_stream_sink::{BinaryStreamSink, BinaryStreamStorage};
84    pub use crate::log_sink::{
85        BufferedSink, CallbackSink, GrpcSink, GrpcSinkConnectionFailure, GrpcSinkConnectionState,
86        IntoMultiSink, LogSink, MemorySink, MemorySinkStorage, MultiSink, SinkFlushError,
87    };
88}
89
90/// Things directly related to logging.
91pub mod log {
92    pub use re_chunk::{
93        Chunk, ChunkBatcher, ChunkBatcherConfig, ChunkBatcherError, ChunkBatcherResult,
94        ChunkComponents, ChunkError, ChunkId, ChunkResult, PendingRow, RowId, TimeColumn,
95    };
96    pub use re_log_types::LogMsg;
97}
98
99/// Time-related types.
100pub mod time {
101    pub use re_log_types::{Duration, TimeCell, TimeInt, TimePoint, TimeType, Timeline, Timestamp};
102}
103
104pub use re_sdk_types::{
105    Archetype, ArchetypeName, AsComponents, Component, ComponentBatch, ComponentDescriptor,
106    ComponentIdentifier, ComponentType, DatatypeName, DeserializationError, DeserializationResult,
107    Loggable, SerializationError, SerializationResult, SerializedComponentBatch,
108    SerializedComponentColumn,
109};
110pub use time::{TimeCell, TimePoint, Timeline};
111
112/// Transformation and reinterpretation of components.
113///
114/// # Experimental
115///
116/// This is an experimental API and may change in future releases.
117pub mod lenses;
118
119pub use re_byte_size::SizeBytes;
120#[cfg(feature = "data_loaders")]
121pub use re_data_loader::{DataLoader, DataLoaderError, DataLoaderSettings, LoadedData};
122
123/// Methods for spawning the web viewer and streaming the SDK log stream to it.
124#[cfg(feature = "web_viewer")]
125pub mod web_viewer;
126
127/// Method for spawning a gRPC server and streaming the SDK log stream to it.
128#[cfg(feature = "server")]
129pub mod grpc_server;
130
131#[cfg(feature = "server")]
132pub use re_grpc_server::{MemoryLimit, PlaybackBehavior, ServerOptions};
133
134/// Re-exports of other crates.
135pub mod external {
136    pub use re_chunk::external::*;
137    #[cfg(feature = "data_loaders")]
138    pub use re_data_loader::{self, external::*};
139    #[cfg(feature = "server")]
140    pub use re_grpc_server;
141    pub use re_log::external::*;
142    pub use re_log_types::external::*;
143    pub use {re_grpc_client, re_log, re_log_encoding, re_log_types, re_uri};
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    let s = std::env::var(RERUN_ENV_VAR).ok()?;
162    match s.to_lowercase().as_str() {
163        "0" | "false" | "off" => Some(false),
164        "1" | "true" | "on" => Some(true),
165        _ => {
166            re_log::warn!(
167                "Invalid value for environment variable {RERUN_ENV_VAR}={s:?}. Expected 'on' or 'off'. It will be ignored"
168            );
169            None
170        }
171    }
172}
173
174/// Checks the `RERUN` environment variable. If not found, returns the argument.
175///
176/// Also adds some helpful logging.
177pub fn decide_logging_enabled(default_enabled: bool) -> bool {
178    // We use `info_once` so that we can call this function
179    // multiple times without spamming the log.
180    match get_rerun_env() {
181        Some(true) => {
182            re_log::info_once!(
183                "Rerun Logging is enabled by the '{RERUN_ENV_VAR}' environment variable."
184            );
185            true
186        }
187        Some(false) => {
188            re_log::info_once!(
189                "Rerun Logging is disabled by the '{RERUN_ENV_VAR}' environment variable."
190            );
191            false
192        }
193        None => {
194            if !default_enabled {
195                re_log::info_once!(
196                    "Rerun Logging has been disabled. Turn it on with the '{RERUN_ENV_VAR}' environment variable."
197                );
198            }
199            default_enabled
200        }
201    }
202}
203
204// ----------------------------------------------------------------------------
205
206/// Creates a new [`re_log_types::StoreInfo`] which can be used with [`RecordingStream::new`].
207#[track_caller] // track_caller so that we can see if we are being called from an official example.
208pub fn new_store_info(
209    application_id: impl Into<re_log_types::ApplicationId>,
210) -> re_log_types::StoreInfo {
211    let store_id = StoreId::random(StoreKind::Recording, application_id.into());
212
213    re_log_types::StoreInfo::new(
214        store_id,
215        re_log_types::StoreSource::RustSdk {
216            rustc_version: env!("RE_BUILD_RUSTC_VERSION").into(),
217            llvm_version: env!("RE_BUILD_LLVM_VERSION").into(),
218        },
219    )
220}