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