1use std::time::Duration;
2use std::{collections::BTreeMap, fmt, rc::Rc};
3
4use super::{RequestId, lifecycle::CancellationToken};
5
6#[derive(Clone, Eq, PartialEq)]
8pub struct InvocationExtension {
9 key: String,
10 value: Vec<u8>,
11}
12
13impl fmt::Debug for InvocationExtension {
14 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
15 formatter
16 .debug_struct("InvocationExtension")
17 .field("key", &self.key)
18 .field("value", &"<redacted>")
19 .finish()
20 }
21}
22
23impl InvocationExtension {
24 pub fn new(key: impl Into<String>, value: Vec<u8>) -> Self {
26 Self {
27 key: key.into(),
28 value,
29 }
30 }
31
32 pub fn key(&self) -> &str {
34 &self.key
35 }
36
37 pub fn value(&self) -> &[u8] {
39 &self.value
40 }
41}
42
43#[derive(Clone, Eq, PartialEq)]
45pub struct SealedInvocationExtension {
46 key: String,
47 issuer: String,
48 audience: Vec<String>,
49 value: Vec<u8>,
50 proof: String,
51}
52
53impl SealedInvocationExtension {
54 pub fn signed(
59 key: impl Into<String>,
60 issuer: impl Into<String>,
61 audience: impl IntoIterator<Item = impl Into<String>>,
62 value: Vec<u8>,
63 proof: impl Into<String>,
64 ) -> Self {
65 Self {
66 key: key.into(),
67 issuer: issuer.into(),
68 audience: audience.into_iter().map(Into::into).collect(),
69 value,
70 proof: proof.into(),
71 }
72 }
73
74 pub fn key(&self) -> &str {
76 &self.key
77 }
78
79 pub fn issuer(&self) -> &str {
81 &self.issuer
82 }
83
84 pub fn audience(&self) -> &[String] {
86 &self.audience
87 }
88
89 pub fn value(&self) -> &[u8] {
91 &self.value
92 }
93
94 pub fn proof(&self) -> &str {
96 &self.proof
97 }
98
99 pub fn covers(&self, capability_id: &str, operation: &str) -> bool {
101 let target = format!("{capability_id}:{operation}");
102 self.audience.iter().any(|audience| audience == &target)
103 }
104}
105
106impl fmt::Debug for SealedInvocationExtension {
107 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
108 formatter
109 .debug_struct("SealedInvocationExtension")
110 .field("key", &self.key)
111 .field("issuer", &self.issuer)
112 .field("audience", &self.audience)
113 .field("value", &"<redacted>")
114 .field("proof", &"<redacted>")
115 .finish()
116 }
117}
118
119#[derive(Clone, Debug, Eq, PartialEq)]
121pub enum InvocationContextError {
122 EmptyExtensionKey,
124 ExtensionAlreadySet { key: String },
126 SealedExtensionAlreadySet { key: String },
128 InvalidSealedExtension { key: String },
130}
131
132impl std::fmt::Display for InvocationContextError {
133 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 match self {
135 Self::EmptyExtensionKey => {
136 formatter.write_str("Invocation Context extension key is empty")
137 }
138 Self::ExtensionAlreadySet { key } => {
139 write!(
140 formatter,
141 "Invocation Context extension `{key}` is already set"
142 )
143 }
144 Self::SealedExtensionAlreadySet { key } => {
145 write!(
146 formatter,
147 "sealed Invocation Context extension `{key}` is already set"
148 )
149 }
150 Self::InvalidSealedExtension { key } => {
151 write!(
152 formatter,
153 "sealed Invocation Context extension `{key}` has invalid provenance"
154 )
155 }
156 }
157 }
158}
159
160#[derive(Clone, Debug)]
162pub struct InvocationContext {
163 pub(crate) execution: Option<super::settlement::ExecutionScope>,
164 pub(super) caller_instance: Option<Rc<str>>,
165 pub(super) request_id: RequestId,
166 pub(super) deadline: Option<Duration>,
167 pub(super) remaining_budget: Option<Duration>,
168 pub(super) cancellation: CancellationToken,
169 pub(super) extensions: BTreeMap<String, InvocationExtension>,
170 pub(super) sealed_extensions: BTreeMap<String, SealedInvocationExtension>,
171}
172
173impl InvocationContext {
174 pub fn retain_execution(&self) -> Result<super::ExecutionLease, super::RuntimeFailure> {
177 self.execution
178 .as_ref()
179 .ok_or(super::RuntimeFailure::AdmissionClosed)?
180 .retain()
181 }
182 pub fn new(
184 request_id: RequestId,
185 deadline: Option<Duration>,
186 cancellation: CancellationToken,
187 ) -> Self {
188 Self {
189 execution: None,
190 caller_instance: None,
191 request_id,
192 deadline,
193 remaining_budget: None,
194 cancellation,
195 extensions: BTreeMap::new(),
196 sealed_extensions: BTreeMap::new(),
197 }
198 }
199
200 #[must_use]
202 pub fn with_caller_instance(mut self, caller_instance: impl Into<String>) -> Self {
203 self.caller_instance = Some(Rc::from(caller_instance.into()));
204 self
205 }
206
207 pub(crate) fn with_shared_caller_instance(mut self, caller_instance: Rc<str>) -> Self {
208 self.caller_instance = Some(caller_instance);
209 self
210 }
211
212 pub(super) fn for_caller(mut self, caller_instance: &str) -> Self {
213 if self.caller_instance.as_deref() != Some(caller_instance) {
214 self.caller_instance = Some(Rc::from(caller_instance));
215 }
216 self
217 }
218
219 pub fn caller_instance(&self) -> Option<&str> {
221 self.caller_instance.as_deref()
222 }
223
224 pub const fn request_id(&self) -> RequestId {
226 self.request_id
227 }
228
229 pub const fn deadline(&self) -> Option<Duration> {
231 self.deadline
232 }
233
234 pub const fn remaining_budget(&self) -> Option<Duration> {
240 self.remaining_budget
241 }
242
243 pub fn cancellation(&self) -> CancellationToken {
245 self.cancellation.clone()
246 }
247
248 pub fn with_extension(
250 mut self,
251 key: impl Into<String>,
252 value: Vec<u8>,
253 ) -> Result<Self, InvocationContextError> {
254 let extension = InvocationExtension::new(key, value);
255 if extension.key().is_empty() {
256 return Err(InvocationContextError::EmptyExtensionKey);
257 }
258 if self.sealed_extensions.contains_key(extension.key()) {
259 return Err(InvocationContextError::SealedExtensionAlreadySet {
260 key: extension.key().to_owned(),
261 });
262 }
263 if self.extensions.contains_key(extension.key()) {
264 return Err(InvocationContextError::ExtensionAlreadySet {
265 key: extension.key().to_owned(),
266 });
267 }
268 self.extensions
269 .insert(extension.key().to_owned(), extension);
270 Ok(self)
271 }
272
273 pub fn with_sealed_extension(
275 mut self,
276 extension: SealedInvocationExtension,
277 ) -> Result<Self, InvocationContextError> {
278 if extension.key().is_empty() {
279 return Err(InvocationContextError::EmptyExtensionKey);
280 }
281 if extension.issuer().is_empty()
282 || extension.audience().is_empty()
283 || extension.proof().is_empty()
284 || extension.audience().iter().any(String::is_empty)
285 {
286 return Err(InvocationContextError::InvalidSealedExtension {
287 key: extension.key().to_owned(),
288 });
289 }
290 if self.sealed_extensions.contains_key(extension.key())
291 || self.extensions.contains_key(extension.key())
292 {
293 return Err(InvocationContextError::SealedExtensionAlreadySet {
294 key: extension.key().to_owned(),
295 });
296 }
297 self.sealed_extensions
298 .insert(extension.key().to_owned(), extension);
299 Ok(self)
300 }
301
302 pub fn extension(&self, key: &str) -> Option<&[u8]> {
304 self.extensions.get(key).map(InvocationExtension::value)
305 }
306
307 pub fn extensions(&self) -> impl Iterator<Item = &InvocationExtension> {
309 self.extensions.values()
310 }
311
312 pub fn sealed_extension(&self, key: &str) -> Option<&SealedInvocationExtension> {
314 self.sealed_extensions.get(key)
315 }
316
317 pub fn sealed_extensions(&self) -> impl Iterator<Item = &SealedInvocationExtension> {
319 self.sealed_extensions.values()
320 }
321
322 #[must_use]
327 pub fn for_target(mut self, capability_id: &str, operation: &str) -> Self {
328 self.sealed_extensions
329 .retain(|_, extension| extension.covers(capability_id, operation));
330 self
331 }
332
333 pub fn is_cancelled(&self) -> bool {
335 self.cancellation.is_cancelled()
336 }
337
338 pub fn is_expired(&self, now: Duration) -> bool {
340 self.deadline.is_some_and(|deadline| deadline <= now)
341 }
342}
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347
348 #[test]
349 fn resolved_caller_reuses_matching_storage_and_overrides_spoofed_identity() {
350 let context = InvocationContext::new(1, None, CancellationToken::new())
351 .with_caller_instance("consumer".to_owned());
352 let original = context.caller_instance().unwrap().as_ptr();
353 let context = context.for_caller("consumer");
354 assert_eq!(context.caller_instance().unwrap().as_ptr(), original);
355
356 let context = context.for_caller("resolved-consumer");
357 assert_eq!(context.caller_instance(), Some("resolved-consumer"));
358 }
359
360 #[test]
361 fn cloning_context_reuses_caller_storage() {
362 let context = InvocationContext::new(1, None, CancellationToken::new())
363 .with_caller_instance("consumer".to_owned());
364 let cloned = context.clone();
365
366 assert_eq!(
367 context.caller_instance().unwrap().as_ptr(),
368 cloned.caller_instance().unwrap().as_ptr()
369 );
370 }
371}