aws_runtime/
invocation_id.rs
1use std::fmt::Debug;
7use std::sync::{Arc, Mutex};
8
9use fastrand::Rng;
10use http_02x::{HeaderName, HeaderValue};
11
12use aws_smithy_runtime_api::box_error::BoxError;
13use aws_smithy_runtime_api::client::interceptors::context::BeforeTransmitInterceptorContextMut;
14use aws_smithy_runtime_api::client::interceptors::Intercept;
15use aws_smithy_runtime_api::client::runtime_components::RuntimeComponents;
16use aws_smithy_types::config_bag::{ConfigBag, Storable, StoreReplace};
17#[cfg(feature = "test-util")]
18pub use test_util::{NoInvocationIdGenerator, PredefinedInvocationIdGenerator};
19
20#[allow(clippy::declare_interior_mutable_const)] const AMZ_SDK_INVOCATION_ID: HeaderName = HeaderName::from_static("amz-sdk-invocation-id");
22
23pub trait InvocationIdGenerator: Debug + Send + Sync {
25 fn generate(&self) -> Result<Option<InvocationId>, BoxError>;
28}
29
30#[derive(Clone, Debug)]
32pub struct SharedInvocationIdGenerator(Arc<dyn InvocationIdGenerator>);
33
34impl SharedInvocationIdGenerator {
35 pub fn new(gen: impl InvocationIdGenerator + 'static) -> Self {
37 Self(Arc::new(gen))
38 }
39}
40
41impl InvocationIdGenerator for SharedInvocationIdGenerator {
42 fn generate(&self) -> Result<Option<InvocationId>, BoxError> {
43 self.0.generate()
44 }
45}
46
47impl Storable for SharedInvocationIdGenerator {
48 type Storer = StoreReplace<Self>;
49}
50
51#[derive(Debug, Default)]
53pub struct DefaultInvocationIdGenerator {
54 rng: Mutex<Rng>,
55}
56
57impl DefaultInvocationIdGenerator {
58 pub fn new() -> Self {
60 Default::default()
61 }
62
63 pub fn with_seed(seed: u64) -> Self {
65 Self {
66 rng: Mutex::new(Rng::with_seed(seed)),
67 }
68 }
69}
70
71impl InvocationIdGenerator for DefaultInvocationIdGenerator {
72 fn generate(&self) -> Result<Option<InvocationId>, BoxError> {
73 let mut rng = self.rng.lock().unwrap();
74 let mut random_bytes = [0u8; 16];
75 rng.fill(&mut random_bytes);
76
77 let id = uuid::Builder::from_random_bytes(random_bytes).into_uuid();
78 Ok(Some(InvocationId::new(id.to_string())))
79 }
80}
81
82#[non_exhaustive]
84#[derive(Debug, Default)]
85pub struct InvocationIdInterceptor {
86 default: DefaultInvocationIdGenerator,
87}
88
89impl InvocationIdInterceptor {
90 pub fn new() -> Self {
92 Self::default()
93 }
94}
95
96impl Intercept for InvocationIdInterceptor {
97 fn name(&self) -> &'static str {
98 "InvocationIdInterceptor"
99 }
100
101 fn modify_before_retry_loop(
102 &self,
103 _ctx: &mut BeforeTransmitInterceptorContextMut<'_>,
104 _runtime_components: &RuntimeComponents,
105 cfg: &mut ConfigBag,
106 ) -> Result<(), BoxError> {
107 let gen = cfg
108 .load::<SharedInvocationIdGenerator>()
109 .map(|gen| gen as &dyn InvocationIdGenerator)
110 .unwrap_or(&self.default);
111 if let Some(id) = gen.generate()? {
112 cfg.interceptor_state().store_put::<InvocationId>(id);
113 }
114
115 Ok(())
116 }
117
118 fn modify_before_transmit(
119 &self,
120 ctx: &mut BeforeTransmitInterceptorContextMut<'_>,
121 _runtime_components: &RuntimeComponents,
122 cfg: &mut ConfigBag,
123 ) -> Result<(), BoxError> {
124 let headers = ctx.request_mut().headers_mut();
125 if let Some(id) = cfg.load::<InvocationId>() {
126 headers.append(AMZ_SDK_INVOCATION_ID, id.0.clone());
127 }
128 Ok(())
129 }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct InvocationId(HeaderValue);
135
136impl InvocationId {
137 pub fn new(invocation_id: String) -> Self {
142 Self(
143 HeaderValue::try_from(invocation_id)
144 .expect("invocation ID must be a valid HTTP header value"),
145 )
146 }
147}
148
149impl Storable for InvocationId {
150 type Storer = StoreReplace<Self>;
151}
152
153#[cfg(feature = "test-util")]
154mod test_util {
155 use std::sync::{Arc, Mutex};
156
157 use super::*;
158
159 impl InvocationId {
160 pub fn new_from_str(uuid: &'static str) -> Self {
162 InvocationId(HeaderValue::from_static(uuid))
163 }
164 }
165
166 #[derive(Debug)]
168 pub struct PredefinedInvocationIdGenerator {
169 pre_generated_ids: Arc<Mutex<Vec<InvocationId>>>,
170 }
171
172 impl PredefinedInvocationIdGenerator {
173 pub fn new(mut invocation_ids: Vec<InvocationId>) -> Self {
175 invocation_ids.reverse();
178
179 Self {
180 pre_generated_ids: Arc::new(Mutex::new(invocation_ids)),
181 }
182 }
183 }
184
185 impl InvocationIdGenerator for PredefinedInvocationIdGenerator {
186 fn generate(&self) -> Result<Option<InvocationId>, BoxError> {
187 Ok(Some(
188 self.pre_generated_ids
189 .lock()
190 .expect("this will never be under contention")
191 .pop()
192 .expect("testers will provide enough invocation IDs"),
193 ))
194 }
195 }
196
197 #[derive(Debug, Default)]
199 pub struct NoInvocationIdGenerator;
200
201 impl NoInvocationIdGenerator {
202 pub fn new() -> Self {
204 Self
205 }
206 }
207
208 impl InvocationIdGenerator for NoInvocationIdGenerator {
209 fn generate(&self) -> Result<Option<InvocationId>, BoxError> {
210 Ok(None)
211 }
212 }
213}
214
215#[cfg(test)]
216mod tests {
217 use aws_smithy_runtime_api::client::interceptors::context::{
218 BeforeTransmitInterceptorContextMut, Input, InterceptorContext,
219 };
220 use aws_smithy_runtime_api::client::interceptors::Intercept;
221 use aws_smithy_runtime_api::client::orchestrator::HttpRequest;
222 use aws_smithy_runtime_api::client::runtime_components::RuntimeComponentsBuilder;
223 use aws_smithy_types::config_bag::ConfigBag;
224
225 use super::*;
226
227 fn expect_header<'a>(
228 context: &'a BeforeTransmitInterceptorContextMut<'_>,
229 header_name: &str,
230 ) -> &'a str {
231 context.request().headers().get(header_name).unwrap()
232 }
233
234 #[test]
235 fn default_id_generator() {
236 let rc = RuntimeComponentsBuilder::for_tests().build().unwrap();
237 let mut ctx = InterceptorContext::new(Input::doesnt_matter());
238 ctx.enter_serialization_phase();
239 ctx.set_request(HttpRequest::empty());
240 let _ = ctx.take_input();
241 ctx.enter_before_transmit_phase();
242
243 let mut cfg = ConfigBag::base();
244 let interceptor = InvocationIdInterceptor::new();
245 let mut ctx = Into::into(&mut ctx);
246 interceptor
247 .modify_before_retry_loop(&mut ctx, &rc, &mut cfg)
248 .unwrap();
249 interceptor
250 .modify_before_transmit(&mut ctx, &rc, &mut cfg)
251 .unwrap();
252
253 let expected = cfg.load::<InvocationId>().expect("invocation ID was set");
254 let header = expect_header(&ctx, "amz-sdk-invocation-id");
255 assert_eq!(expected.0, header, "the invocation ID in the config bag must match the invocation ID in the request header");
256 assert_eq!(header.len(), 36);
258 }
259
260 #[cfg(feature = "test-util")]
261 #[test]
262 fn custom_id_generator() {
263 use aws_smithy_types::config_bag::Layer;
264 let rc = RuntimeComponentsBuilder::for_tests().build().unwrap();
265 let mut ctx = InterceptorContext::new(Input::doesnt_matter());
266 ctx.enter_serialization_phase();
267 ctx.set_request(HttpRequest::empty());
268 let _ = ctx.take_input();
269 ctx.enter_before_transmit_phase();
270
271 let mut cfg = ConfigBag::base();
272 let mut layer = Layer::new("test");
273 layer.store_put(SharedInvocationIdGenerator::new(
274 PredefinedInvocationIdGenerator::new(vec![InvocationId::new(
275 "the-best-invocation-id".into(),
276 )]),
277 ));
278 cfg.push_layer(layer);
279
280 let interceptor = InvocationIdInterceptor::new();
281 let mut ctx = Into::into(&mut ctx);
282 interceptor
283 .modify_before_retry_loop(&mut ctx, &rc, &mut cfg)
284 .unwrap();
285 interceptor
286 .modify_before_transmit(&mut ctx, &rc, &mut cfg)
287 .unwrap();
288
289 let header = expect_header(&ctx, "amz-sdk-invocation-id");
290 assert_eq!("the-best-invocation-id", header);
291 }
292}