Skip to main content

gadk_platform/
lib.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! gadk-platform: overridable time, UUID and task-execution seams, the ADK tracking header
17//! value, the injectable environment ([`env`](mod@env)), and shared helpers with exact output
18//! formats: double-quoted strings ([`go_quote`]), shortest round-trip floats
19//! ([`go_format_float_g`]), simple one-rune casing ([`go_to_lower`], [`go_to_upper`]), query
20//! escaping ([`go_query_escape`]), `%v`-style rendering of a JSON value ([`go_sprint_value`]),
21//! RFC 3339 parsing ([`go_parse_rfc3339`]), lexical path functions ([`go_path_clean`],
22//! [`go_path_join`], [`go_path_dir`], [`go_path_base`]), Unix [`go_filepath_rel`] and
23//! [`go_filepath_is_local`], safe resolution of an untrusted relative path ([`safe_subpath`]),
24//! URL parsing ([`go_url`]), error wrapping with a prefix ([`GoWrapped`]), a built-in MIME
25//! table and content sniffing ([`go_mime`]), durations ([`GoDuration`], [`go_parse_duration`],
26//! [`go_format_duration`]) and the flag parser the launcher uses ([`go_flag`]).
27
28pub mod env;
29mod exec;
30mod go_err;
31pub mod go_flag;
32mod go_fmt;
33pub mod go_mime;
34mod go_path;
35mod go_time;
36pub mod go_url;
37mod safe_subpath;
38mod time;
39mod tracking;
40mod uuid;
41
42pub use exec::{TaskRunner, TokioTaskRunner};
43pub use futures::future::BoxFuture;
44pub use go_err::{GoWrapped, go_errno_text};
45pub use go_fmt::{
46    go_format_float_g, go_format_float_v, go_query_escape, go_quote, go_quote_bytes,
47    go_sprint_value, go_to_lower, go_to_upper, go_type_name,
48};
49pub use go_path::{
50    go_filepath_is_local, go_filepath_rel, go_path_base, go_path_clean, go_path_dir, go_path_join,
51};
52pub use go_time::{
53    GoDuration, go_format_duration, go_format_rfc3339_nano, go_parse_duration, go_parse_rfc3339,
54};
55pub use safe_subpath::{
56    ERR_NOT_VALID_RELATIVE_PATH, ERR_SYMLINK_IN_RELATIVE_PATH, SafeSubpathError,
57    SafeSubpathErrorKind, is_link_like, safe_subpath,
58};
59pub use time::TimeProvider;
60pub use tracking::tracking_header;
61pub use uuid::UuidProvider;
62
63use chrono::{DateTime, Duration, TimeZone, Utc};
64use std::sync::Arc;
65use std::sync::atomic::{AtomicU64, Ordering};
66
67/// Explicit replacement for context-carried providers: the clock, UUID source and task runner.
68#[derive(Clone)]
69pub struct Platform {
70    time: Arc<dyn TimeProvider>,
71    uuid: Arc<dyn UuidProvider>,
72    tasks: Arc<dyn TaskRunner>,
73}
74
75impl Default for Platform {
76    fn default() -> Self {
77        Self {
78            time: Arc::new(time::SystemTime),
79            uuid: Arc::new(uuid::RandomUuid),
80            tasks: Arc::new(TokioTaskRunner),
81        }
82    }
83}
84
85impl std::fmt::Debug for Platform {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.write_str("Platform")
88    }
89}
90
91impl Platform {
92    /// Current time from the configured [`TimeProvider`].
93    pub fn now(&self) -> DateTime<Utc> {
94        self.time.now()
95    }
96
97    /// New identifier from the configured [`UuidProvider`].
98    pub fn new_uuid(&self) -> String {
99        self.uuid.new_uuid()
100    }
101
102    /// Runs all tasks on the configured [`TaskRunner`] and waits for them.
103    /// An empty task list returns immediately without invoking the runner.
104    pub async fn run_tasks(&self, tasks: Vec<BoxFuture<'static, ()>>) {
105        if tasks.is_empty() {
106            return;
107        }
108        self.tasks.run(tasks).await;
109    }
110
111    /// Returns this platform with its time provider replaced.
112    pub fn with_time(mut self, p: impl TimeProvider + 'static) -> Self {
113        self.time = Arc::new(p);
114        self
115    }
116
117    /// Returns this platform with its UUID provider replaced.
118    pub fn with_uuid(mut self, p: impl UuidProvider + 'static) -> Self {
119        self.uuid = Arc::new(p);
120        self
121    }
122
123    /// Returns this platform with its task runner replaced.
124    pub fn with_task_runner(mut self, r: impl TaskRunner + 'static) -> Self {
125        self.tasks = Arc::new(r);
126        self
127    }
128
129    /// Time starts at 2000-01-01T00:00:00Z + `seed` seconds and advances 1 ms per call;
130    /// UUIDs are v4-formatted strings derived from a seeded counter.
131    pub fn deterministic(seed: u64) -> Self {
132        let base = Utc
133            .with_ymd_and_hms(2000, 1, 1, 0, 0, 0)
134            .single()
135            .unwrap_or_default()
136            + Duration::seconds(i64::try_from(seed % 1_000_000_000).unwrap_or(0));
137        let ticks = Arc::new(AtomicU64::new(0));
138        let ids = Arc::new(AtomicU64::new(0));
139        Self::default()
140            .with_time(move || {
141                let ms = i64::try_from(ticks.fetch_add(1, Ordering::SeqCst)).unwrap_or(i64::MAX);
142                Duration::try_milliseconds(ms)
143                    .and_then(|d| base.checked_add_signed(d))
144                    .unwrap_or(DateTime::<Utc>::MAX_UTC)
145            })
146            .with_uuid(move || {
147                let n = ids.fetch_add(1, Ordering::SeqCst);
148                let mut b = [0u8; 16];
149                b[..8].copy_from_slice(&seed.to_be_bytes());
150                b[8..].copy_from_slice(&n.to_be_bytes());
151                ::uuid::Builder::from_random_bytes(b)
152                    .into_uuid()
153                    .to_string()
154            })
155    }
156}