1use super::*;
2
3impl StoredIdempotentResponse {
5 pub fn from_parts(status_code: usize, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
17 let mut replay_resp: Response = Response::default();
18 replay_resp.set_status_code(status_code);
19 for (name, val) in &headers {
20 if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED) {
21 replay_resp.set_header(name, val);
22 }
23 }
24 replay_resp
25 .set_header(HEADER_IDEMPOTENT_REPLAYED, HEADER_VALUE_REPLAYED_TRUE)
26 .set_body(body.clone());
27 let replayed_wire: ResponseData = replay_resp.build();
28 Self {
29 status_code,
30 headers,
31 body,
32 replayed_wire,
33 stored_at_ms: idempotency_now_ms(),
34 }
35 }
36
37 pub fn capture(response: &Response) -> Self {
47 let mut headers: Vec<(String, String)> = Vec::with_capacity(response.get_headers().len());
48 for (name, values) in response.get_headers() {
49 if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED)
50 && let Some(last) = values.back()
51 {
52 headers.push((name.clone(), last.clone()));
53 }
54 }
55 Self::from_parts(
56 response.get_status_code(),
57 headers,
58 response.get_body().clone(),
59 )
60 }
61
62 pub fn apply_to_response(&self, response: &mut Response) {
68 response.set_status_code(self.get_status_code());
69 for (name, val) in self.get_headers() {
70 response.set_header(name, val);
71 }
72 response
73 .set_header(HEADER_IDEMPOTENT_REPLAYED, HEADER_VALUE_REPLAYED_TRUE)
74 .set_body(self.get_body().clone());
75 }
76}
77
78impl Default for IdempotencyConfig {
80 fn default() -> Self {
86 Self {
87 header_name: DEFAULT_IDEMPOTENCY_KEY_HEADER.to_owned(),
88 ttl_ms: DEFAULT_IDEMPOTENCY_TTL_MS,
89 in_flight_ttl_ms: DEFAULT_IN_FLIGHT_TTL_MS,
90 max_entries: DEFAULT_IDEMPOTENCY_MAX_ENTRIES,
91 max_bytes: DEFAULT_IDEMPOTENCY_MAX_BYTES,
92 max_body_bytes: DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES,
93 max_key_len: DEFAULT_MAX_KEY_LEN,
94 methods: vec![Method::Post, Method::Put, Method::Patch, Method::Delete],
95 require_key_prefixes: Vec::new(),
96 cache_server_errors: false,
97 }
98 }
99}
100
101impl IdempotencyConfig {
103 pub fn with_header_name<S>(mut self, name: S) -> Self
113 where
114 S: AsRef<str>,
115 {
116 self.set_header_name(name.as_ref().trim().to_ascii_lowercase());
117 self
118 }
119
120 pub fn with_ttl_ms(mut self, ttl_ms: u64) -> Self {
130 self.set_ttl_ms(ttl_ms.max(1));
131 self
132 }
133
134 pub fn with_in_flight_ttl_ms(mut self, in_flight_ttl_ms: u64) -> Self {
144 self.set_in_flight_ttl_ms(in_flight_ttl_ms.max(1));
145 self
146 }
147
148 pub fn with_limits(mut self, max_entries: usize, max_bytes: usize) -> Self {
159 self.set_max_entries(max_entries.max(1))
160 .set_max_bytes(max_bytes.max(1));
161 self
162 }
163
164 pub fn with_require_key_prefixes<I, S>(mut self, prefixes: I) -> Self
174 where
175 I: IntoIterator<Item = S>,
176 S: Into<String>,
177 {
178 self.set_require_key_prefixes(prefixes.into_iter().map(Into::into).collect());
179 self
180 }
181
182 pub fn with_methods(mut self, methods: Vec<Method>) -> Self {
192 self.set_methods(methods);
193 self
194 }
195
196 pub fn with_cache_server_errors(mut self, cache_server_errors: bool) -> Self {
206 self.set_cache_server_errors(cache_server_errors);
207 self
208 }
209}
210
211impl Default for InMemoryIdempotencyStore {
213 fn default() -> Self {
219 Self::new(
220 DEFAULT_IDEMPOTENCY_MAX_ENTRIES,
221 DEFAULT_IDEMPOTENCY_MAX_BYTES,
222 )
223 }
224}
225
226impl InMemoryIdempotencyStore {
228 pub fn new(max_entries: usize, max_bytes: usize) -> Self {
239 let shards: IdempotencyShardArray =
240 Box::new(from_fn(|_: usize| RwLock::new(hash_map_xx_hash3_64())));
241 Self {
242 inner: Arc::new(InMemoryIdempotencyStoreInner {
243 max_entries: max_entries.max(1),
244 max_bytes: max_bytes.max(1),
245 entry_count: AtomicUsize::new(0),
246 total_bytes: AtomicUsize::new(0),
247 shards,
248 }),
249 }
250 }
251
252 #[inline]
258 pub fn len(&self) -> usize {
259 let Self { inner } = self;
260 inner.entry_count.load(Ordering::Relaxed)
261 }
262
263 #[inline]
269 pub fn is_empty(&self) -> bool {
270 self.len() == 0
271 }
272
273 #[inline]
279 pub fn total_bytes(&self) -> usize {
280 let Self { inner } = self;
281 inner.total_bytes.load(Ordering::Relaxed)
282 }
283
284 pub fn acquire_sync(
296 &self,
297 key: &str,
298 fingerprint: u64,
299 in_flight_ttl_ms: u64,
300 ) -> IdempotencyLookup {
301 let Self { inner } = self;
302 let idx: usize = idempotency_shard_index(key);
303 let now_ms: u64 = idempotency_now_ms();
304 if let Ok(read_guard) = inner.shards[idx].read()
305 && let Some(existing) = read_guard.get(key)
306 && now_ms < existing.expires_at_ms
307 {
308 if existing.fingerprint != fingerprint {
309 return IdempotencyLookup::FingerprintMismatch;
310 }
311 return match &existing.state {
312 IdempotencySlotState::InFlight => IdempotencyLookup::InFlight,
313 IdempotencySlotState::Completed(resp) => {
314 IdempotencyLookup::Replayed(Arc::clone(resp))
315 }
316 };
317 }
318 let Ok(mut map): Result<
319 RwLockWriteGuard<'_, HashMapXxHash3_64<String, IdempotencySlot>>,
320 _,
321 > = inner.shards[idx].write() else {
322 return IdempotencyLookup::Acquired;
323 };
324 if let Some(existing) = map.get(key) {
325 if now_ms < existing.expires_at_ms {
326 if existing.fingerprint != fingerprint {
327 return IdempotencyLookup::FingerprintMismatch;
328 }
329 return match &existing.state {
330 IdempotencySlotState::InFlight => IdempotencyLookup::InFlight,
331 IdempotencySlotState::Completed(resp) => {
332 IdempotencyLookup::Replayed(Arc::clone(resp))
333 }
334 };
335 }
336 if let Some(expired) = map.remove(key) {
337 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
338 inner
339 .total_bytes
340 .fetch_sub(expired.footprint_bytes, Ordering::Relaxed);
341 }
342 }
343 let footprint: usize = key.len() + ENTRY_OVERHEAD_BYTES;
344 while (inner.entry_count.load(Ordering::Relaxed) >= inner.max_entries
345 || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.max_bytes)
346 && !map.is_empty()
347 {
348 let oldest: Option<String> = map
349 .iter()
350 .min_by_key(|(_, slot): &(&String, &IdempotencySlot)| slot.expires_at_ms)
351 .map(|(k, _): (&String, &IdempotencySlot)| k.clone());
352 if let Some(evict_key) = oldest
353 && let Some(removed) = map.remove(&evict_key)
354 {
355 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
356 inner
357 .total_bytes
358 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
359 } else {
360 break;
361 }
362 }
363 map.insert(
364 key.to_owned(),
365 IdempotencySlot {
366 fingerprint,
367 state: IdempotencySlotState::InFlight,
368 expires_at_ms: now_ms.saturating_add(in_flight_ttl_ms),
369 footprint_bytes: footprint,
370 },
371 );
372 inner.entry_count.fetch_add(1, Ordering::Relaxed);
373 inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
374 IdempotencyLookup::Acquired
375 }
376
377 pub fn complete_sync(
386 &self,
387 key: String,
388 fingerprint: u64,
389 response: Arc<StoredIdempotentResponse>,
390 ttl_ms: u64,
391 ) {
392 let Self { inner } = self;
393 let footprint: usize = estimate_response_bytes(&key, &response);
394 if footprint > inner.max_bytes {
395 self.release_sync(&key);
396 return;
397 }
398 let idx: usize = idempotency_shard_index(&key);
399 let now_ms: u64 = idempotency_now_ms();
400 let Ok(mut map): Result<
401 RwLockWriteGuard<'_, HashMapXxHash3_64<String, IdempotencySlot>>,
402 _,
403 > = inner.shards[idx].write() else {
404 return;
405 };
406 if let Some(prev) = map.remove(&key) {
407 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
408 inner
409 .total_bytes
410 .fetch_sub(prev.footprint_bytes, Ordering::Relaxed);
411 }
412 while (inner.entry_count.load(Ordering::Relaxed) >= inner.max_entries
413 || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.max_bytes)
414 && !map.is_empty()
415 {
416 let oldest: Option<String> = map
417 .iter()
418 .min_by_key(|(_, slot): &(&String, &IdempotencySlot)| slot.expires_at_ms)
419 .map(|(k, _): (&String, &IdempotencySlot)| k.clone());
420 if let Some(evict_key) = oldest
421 && let Some(removed) = map.remove(&evict_key)
422 {
423 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
424 inner
425 .total_bytes
426 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
427 } else {
428 break;
429 }
430 }
431 map.insert(
432 key,
433 IdempotencySlot {
434 fingerprint,
435 state: IdempotencySlotState::Completed(response),
436 expires_at_ms: now_ms.saturating_add(ttl_ms),
437 footprint_bytes: footprint,
438 },
439 );
440 inner.entry_count.fetch_add(1, Ordering::Relaxed);
441 inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
442 }
443
444 pub fn release_sync(&self, key: &str) {
450 let Self { inner } = self;
451 let idx: usize = idempotency_shard_index(key);
452 let Ok(mut map) = inner.shards[idx].write() else {
453 return;
454 };
455 let is_inflight: bool = map
456 .get(key)
457 .is_some_and(|s: &IdempotencySlot| matches!(s.state, IdempotencySlotState::InFlight));
458 if is_inflight && let Some(removed) = map.remove(key) {
459 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
460 inner
461 .total_bytes
462 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
463 }
464 }
465}
466
467impl IdempotencyStore for InMemoryIdempotencyStore {
469 fn acquire<'a>(
482 &'a self,
483 key: &'a str,
484 fingerprint: u64,
485 in_flight_ttl_ms: u64,
486 ) -> IdempotencyFuture<'a, IdempotencyLookup> {
487 let outcome: IdempotencyLookup = self.acquire_sync(key, fingerprint, in_flight_ttl_ms);
488 Box::pin(async move { outcome })
489 }
490
491 fn complete<'a>(
505 &'a self,
506 key: String,
507 fingerprint: u64,
508 response: Arc<StoredIdempotentResponse>,
509 ttl_ms: u64,
510 ) -> IdempotencyFuture<'a, ()> {
511 self.complete_sync(key, fingerprint, response, ttl_ms);
512 Box::pin(async {})
513 }
514
515 fn release<'a>(&'a self, key: &'a str) -> IdempotencyFuture<'a, ()> {
526 self.release_sync(key);
527 Box::pin(async {})
528 }
529
530 fn release_on_drop(&self, key: &str) {
536 self.release_sync(key);
537 }
538
539 fn purge_expired(&self) -> usize {
545 let Self { inner } = self;
546 let now_ms: u64 = idempotency_now_ms();
547 let mut evicted: usize = 0;
548 let mut freed: usize = 0;
549 for shard in inner.shards.iter() {
550 if let Ok(mut map) = shard.write() {
551 map.retain(|_: &String, slot: &mut IdempotencySlot| {
552 if now_ms >= slot.expires_at_ms {
553 evicted += 1;
554 freed += slot.footprint_bytes;
555 false
556 } else {
557 true
558 }
559 });
560 }
561 }
562 if evicted > 0 {
563 inner.entry_count.fetch_sub(evicted, Ordering::Relaxed);
564 inner.total_bytes.fetch_sub(freed, Ordering::Relaxed);
565 }
566 evicted
567 }
568}
569
570impl Drop for IdempotencyInFlightGuardInner {
572 fn drop(&mut self) {
574 let Self {
575 settled,
576 storage_key,
577 store,
578 ..
579 } = self;
580 if !settled.swap(true, Ordering::AcqRel) {
581 store.release_on_drop(storage_key);
582 }
583 }
584}
585
586impl IdempotencyInFlightGuard {
588 pub(crate) fn claim_settlement(&self) -> bool {
594 let Self { inner } = self;
595 !inner.settled.swap(true, Ordering::AcqRel)
596 }
597
598 pub(crate) fn storage_key(&self) -> &str {
604 let Self { inner } = self;
605 &inner.storage_key
606 }
607
608 pub(crate) fn fingerprint(&self) -> u64 {
614 let Self { inner } = self;
615 inner.fingerprint
616 }
617}
618
619impl IdempotencyPlugin {
621 pub fn init(config: IdempotencyConfig) -> &'static Self {
631 let store: SharedIdempotencyStore = Arc::new(InMemoryIdempotencyStore::new(
632 config.get_max_entries(),
633 config.get_max_bytes(),
634 ));
635 Self::init_with_store(config, store)
636 }
637
638 pub fn init_with_store(
649 config: IdempotencyConfig,
650 store: SharedIdempotencyStore,
651 ) -> &'static Self {
652 IDEMPOTENCY_PLUGIN.get_or_init(|| Self::new_instance(config, store))
653 }
654
655 pub fn new_instance(config: IdempotencyConfig, store: SharedIdempotencyStore) -> Self {
666 let require_prefixes: Vec<String> = config
667 .get_require_key_prefixes()
668 .iter()
669 .filter(|p: &&String| !p.trim().is_empty())
670 .map(|p: &String| normalize_prefix(p))
671 .collect();
672 let prebuilt_bad_key_wire: ResponseData =
673 build_static_error_wire(HttpStatus::BadRequest, BODY_BAD_KEY, None);
674 let prebuilt_in_flight_wire: ResponseData = build_static_error_wire(
675 HttpStatus::Conflict,
676 BODY_IN_FLIGHT,
677 Some(IN_FLIGHT_RETRY_AFTER),
678 );
679 let prebuilt_mismatch_wire: ResponseData = build_static_error_wire(
680 HttpStatus::UnprocessableEntity,
681 BODY_FINGERPRINT_MISMATCH,
682 None,
683 );
684 Self {
685 config,
686 require_prefixes,
687 store,
688 prebuilt_bad_key_wire,
689 prebuilt_in_flight_wire,
690 prebuilt_mismatch_wire,
691 }
692 }
693
694 #[inline]
700 pub fn get() -> Option<&'static Self> {
701 IDEMPOTENCY_PLUGIN.get()
702 }
703
704 #[inline]
710 pub fn get_config(&self) -> &IdempotencyConfig {
711 let Self { config, .. } = self;
712 config
713 }
714
715 #[inline]
721 pub fn get_store(&self) -> &SharedIdempotencyStore {
722 let Self { store, .. } = self;
723 store
724 }
725
726 #[inline]
736 pub(crate) fn is_guarded_method(&self, method: &Method) -> bool {
737 let Self { config, .. } = self;
738 config.get_methods().iter().any(|m: &Method| m == method)
739 }
740
741 #[inline]
751 pub(crate) fn requires_key(&self, path: &str) -> bool {
752 let Self {
753 require_prefixes, ..
754 } = self;
755 require_prefixes
756 .iter()
757 .any(|prefix: &String| path_matches_prefix(path, prefix))
758 }
759}
760
761impl ServerHook for IdempotencyRequestHook {
763 async fn new(_: &mut Stream, _: &mut Context) -> Self {
774 Self
775 }
776
777 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
789 let Some(plugin) = IdempotencyPlugin::get() else {
790 return Status::Continue;
791 };
792 let method: Method = ctx.get_request().get_method().clone();
793 if !plugin.is_guarded_method(&method) {
794 return Status::Continue;
795 }
796 let config: &IdempotencyConfig = plugin.get_config();
797 let path: &str = ctx.get_request().get_path();
798 let raw_key: Option<&str> =
799 find_header_back_ref(ctx.get_request().get_headers(), config.get_header_name());
800 let Some(key_slice) = raw_key else {
801 if plugin.requires_key(path) {
802 let _: Result<(), ResponseError> =
803 stream.try_send(&plugin.prebuilt_bad_key_wire).await;
804 return Status::Reject;
805 }
806 return Status::Continue;
807 };
808 let trimmed: &str = key_slice.trim();
809 if !is_valid_idempotency_key(trimmed, config.get_max_key_len()) {
810 let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_bad_key_wire).await;
811 return Status::Reject;
812 }
813 let fingerprint: u64 =
814 compute_request_fingerprint(&method, path, ctx.get_request().get_body());
815 let storage_key: String = build_storage_key(&method, path, trimmed);
816 match plugin
817 .get_store()
818 .acquire(&storage_key, fingerprint, config.get_in_flight_ttl_ms())
819 .await
820 {
821 IdempotencyLookup::Acquired => {
822 let guard: IdempotencyInFlightGuard = IdempotencyInFlightGuard {
823 inner: Arc::new(IdempotencyInFlightGuardInner {
824 settled: AtomicBool::new(false),
825 storage_key,
826 fingerprint,
827 store: Arc::clone(plugin.get_store()),
828 }),
829 };
830 ctx.set_attribute(ATTR_IDEMPOTENCY_GUARD, guard);
831 Status::Continue
832 }
833 IdempotencyLookup::InFlight => {
834 let _: Result<(), ResponseError> =
835 stream.try_send(&plugin.prebuilt_in_flight_wire).await;
836 Status::Reject
837 }
838 IdempotencyLookup::FingerprintMismatch => {
839 let _: Result<(), ResponseError> =
840 stream.try_send(&plugin.prebuilt_mismatch_wire).await;
841 Status::Reject
842 }
843 IdempotencyLookup::Replayed(cached) => {
844 let _: Result<(), ResponseError> =
845 stream.try_send(cached.get_replayed_wire()).await;
846 Status::Reject
847 }
848 }
849 }
850}
851
852impl ServerHook for IdempotencyResponseHook {
854 async fn new(_: &mut Stream, _: &mut Context) -> Self {
865 Self
866 }
867
868 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
880 let Some(plugin) = IdempotencyPlugin::get() else {
881 return Status::Continue;
882 };
883 let Some(guard) =
884 ctx.try_get_attribute::<IdempotencyInFlightGuard, _>(ATTR_IDEMPOTENCY_GUARD)
885 else {
886 return Status::Continue;
887 };
888 ctx.remove_attribute(ATTR_IDEMPOTENCY_GUARD);
889 if !guard.claim_settlement() {
890 return Status::Continue;
891 }
892 let config: &IdempotencyConfig = plugin.get_config();
893 let status_code: usize = ctx.get_response().get_status_code();
894 let body_len: usize = ctx.get_response().get_body().len();
895 let status_ok: bool =
896 config.get_cache_server_errors() || status_code < NON_CACHEABLE_STATUS_MIN;
897 if status_ok && body_len <= config.get_max_body_bytes() {
898 let stored: Arc<StoredIdempotentResponse> =
899 Arc::new(StoredIdempotentResponse::capture(ctx.get_response()));
900 plugin
901 .get_store()
902 .complete(
903 guard.storage_key().to_owned(),
904 guard.fingerprint(),
905 stored,
906 config.get_ttl_ms(),
907 )
908 .await;
909 } else {
910 plugin.get_store().release(guard.storage_key()).await;
911 }
912 Status::Continue
913 }
914}