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`]), the flag parser the launcher uses ([`go_flag`]) and the wording of
27//! JSON type-mismatch errors ([`json_kind`], [`json_expected_found`]).
28
29pub mod env;
30mod exec;
31mod go_err;
32pub mod go_flag;
33mod go_fmt;
34pub mod go_mime;
35mod go_path;
36mod go_time;
37pub mod go_url;
38mod json_kind;
39mod safe_subpath;
40mod time;
41mod tracking;
42mod uuid;
43
44pub use exec::{TaskRunner, TokioTaskRunner};
45pub use futures::future::BoxFuture;
46pub use go_err::{GoWrapped, go_errno_text};
47pub use go_fmt::{
48    go_format_float_g, go_format_float_v, go_query_escape, go_quote, go_quote_bytes,
49    go_sprint_value, go_to_lower, go_to_upper, go_type_name,
50};
51pub use go_path::{
52    go_filepath_is_local, go_filepath_rel, go_path_base, go_path_clean, go_path_dir, go_path_join,
53};
54pub use go_time::{
55    GoDuration, go_format_duration, go_format_rfc3339_nano, go_parse_duration, go_parse_rfc3339,
56};
57pub use json_kind::{json_expected_found, json_kind, json_kind_article, json_text_kind_article};
58pub use safe_subpath::{
59    ERR_NOT_VALID_RELATIVE_PATH, ERR_SYMLINK_IN_RELATIVE_PATH, SafeSubpathError,
60    SafeSubpathErrorKind, is_link_like, safe_subpath,
61};
62pub use time::TimeProvider;
63pub use tracking::tracking_header;
64pub use uuid::UuidProvider;
65
66use chrono::{DateTime, Duration, TimeZone, Utc};
67use std::sync::Arc;
68use std::sync::atomic::{AtomicU64, Ordering};
69
70/// Explicit replacement for context-carried providers: the clock, UUID source and task runner.
71#[derive(Clone)]
72pub struct Platform {
73    time: Arc<dyn TimeProvider>,
74    uuid: Arc<dyn UuidProvider>,
75    tasks: Arc<dyn TaskRunner>,
76}
77
78impl Default for Platform {
79    fn default() -> Self {
80        Self {
81            time: Arc::new(time::SystemTime),
82            uuid: Arc::new(uuid::RandomUuid),
83            tasks: Arc::new(TokioTaskRunner),
84        }
85    }
86}
87
88impl std::fmt::Debug for Platform {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.write_str("Platform")
91    }
92}
93
94impl Platform {
95    /// Current time from the configured [`TimeProvider`].
96    pub fn now(&self) -> DateTime<Utc> {
97        self.time.now()
98    }
99
100    /// New identifier from the configured [`UuidProvider`].
101    pub fn new_uuid(&self) -> String {
102        self.uuid.new_uuid()
103    }
104
105    /// Runs all tasks on the configured [`TaskRunner`] and waits for them.
106    /// An empty task list returns immediately without invoking the runner.
107    pub async fn run_tasks(&self, tasks: Vec<BoxFuture<'static, ()>>) {
108        if tasks.is_empty() {
109            return;
110        }
111        self.tasks.run(tasks).await;
112    }
113
114    /// Returns this platform with its time provider replaced.
115    pub fn with_time(mut self, p: impl TimeProvider + 'static) -> Self {
116        self.time = Arc::new(p);
117        self
118    }
119
120    /// Returns this platform with its UUID provider replaced.
121    pub fn with_uuid(mut self, p: impl UuidProvider + 'static) -> Self {
122        self.uuid = Arc::new(p);
123        self
124    }
125
126    /// Returns this platform with its task runner replaced.
127    pub fn with_task_runner(mut self, r: impl TaskRunner + 'static) -> Self {
128        self.tasks = Arc::new(r);
129        self
130    }
131
132    /// Time starts at 2000-01-01T00:00:00Z + `seed` seconds and advances 1 ms per call;
133    /// UUIDs are v4-formatted strings derived from a seeded counter.
134    pub fn deterministic(seed: u64) -> Self {
135        let base = Utc
136            .with_ymd_and_hms(2000, 1, 1, 0, 0, 0)
137            .single()
138            .unwrap_or_default()
139            + Duration::seconds(i64::try_from(seed % 1_000_000_000).unwrap_or(0));
140        let ticks = Arc::new(AtomicU64::new(0));
141        let ids = Arc::new(AtomicU64::new(0));
142        Self::default()
143            .with_time(move || {
144                let ms = i64::try_from(ticks.fetch_add(1, Ordering::SeqCst)).unwrap_or(i64::MAX);
145                Duration::try_milliseconds(ms)
146                    .and_then(|d| base.checked_add_signed(d))
147                    .unwrap_or(DateTime::<Utc>::MAX_UTC)
148            })
149            .with_uuid(move || {
150                let n = ids.fetch_add(1, Ordering::SeqCst);
151                let mut b = [0u8; 16];
152                b[..8].copy_from_slice(&seed.to_be_bytes());
153                b[8..].copy_from_slice(&n.to_be_bytes());
154                ::uuid::Builder::from_random_bytes(b)
155                    .into_uuid()
156                    .to_string()
157            })
158    }
159}