Skip to main content

objectiveai_sdk/functions/executions/
retry_token.rs

1//! Retry token for reusing votes from previous executions.
2
3use base64::Engine;
4use serde::{Deserialize, Serialize};
5use schemars::JsonSchema;
6
7/// Token that enables reusing votes from a previous function execution.
8///
9/// Contains identifiers for each task's votes that can be reused in a
10/// subsequent execution. Serialized as base64-encoded JSON.
11#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
12#[serde(transparent)]
13#[schemars(!transparent)]
14#[schemars(rename = "functions.executions.RetryToken")]
15pub struct RetryToken(pub Vec<Option<String>>);
16
17impl RetryToken {
18    pub fn clone_slice(&self, range: std::ops::Range<usize>) -> Self {
19        let len = range.end.saturating_sub(range.start);
20        let mut out = Vec::with_capacity(len);
21        for i in range.start..range.end {
22            out.push(self.0.get(i).cloned().unwrap_or(None));
23        }
24        RetryToken(out)
25    }
26
27    /// Appends another token's entries to this token.
28    pub fn push(&mut self, other: RetryToken) {
29        self.0.extend(other.0)
30    }
31
32    /// Inserts another token's entries at a specific index.
33    pub fn insert(&mut self, index: usize, other: RetryToken) {
34        for (i, token) in other.0.into_iter().enumerate() {
35            self.0[index + i] = token;
36        }
37    }
38
39    /// Serializes the token to a base64-encoded string.
40    pub fn to_string(&self) -> String {
41        let json = serde_json::to_string(self).unwrap();
42        base64::engine::general_purpose::STANDARD.encode(json)
43    }
44
45    /// Attempts to deserialize a token from a base64-encoded string.
46    pub fn try_from_string(s: &str) -> Option<Self> {
47        let json = base64::engine::general_purpose::STANDARD.decode(s).ok()?;
48        let token = serde_json::from_slice(&json).ok()?;
49        Some(token)
50    }
51}