1use super::*;
2
3impl StoredIdempotentResponse {
5 pub fn from_parts(status_code: usize, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
17 let replayed_wire: Vec<u8> = build_replayed_wire(status_code, &headers, &body);
18 Self {
19 status_code,
20 headers,
21 body,
22 replayed_wire,
23 stored_at_ms: idempotency_now_ms(),
24 }
25 }
26
27 pub fn capture(response: &Response) -> Self {
37 let mut headers: Vec<(String, String)> = Vec::with_capacity(response.get_headers().len());
38 for (name, values) in response.get_headers() {
39 if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED)
40 && let Some(last) = values.back()
41 {
42 headers.push((name.clone(), last.clone()));
43 }
44 }
45 Self::from_parts(
46 response.get_status_code(),
47 headers,
48 response.get_body().clone(),
49 )
50 }
51
52 pub fn apply_to_response(&self, response: &mut Response) {
58 response.set_status_code(self.get_status_code());
59 for (name, val) in self.get_headers() {
60 response.set_header(name, val);
61 }
62 response
63 .set_header(HEADER_IDEMPOTENT_REPLAYED, HEADER_VALUE_REPLAYED_TRUE)
64 .set_body(self.get_body().clone());
65 }
66}
67
68impl Default for IdempotencyConfig {
70 fn default() -> Self {
76 Self {
77 header_name: DEFAULT_IDEMPOTENCY_KEY_HEADER.to_owned(),
78 ttl_ms: DEFAULT_IDEMPOTENCY_TTL_MS,
79 in_flight_ttl_ms: DEFAULT_IN_FLIGHT_TTL_MS,
80 max_entries: DEFAULT_IDEMPOTENCY_MAX_ENTRIES,
81 max_bytes: DEFAULT_IDEMPOTENCY_MAX_BYTES,
82 max_body_bytes: DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES,
83 max_key_len: DEFAULT_MAX_KEY_LEN,
84 methods: vec![Method::Post, Method::Put, Method::Patch, Method::Delete],
85 require_key_prefixes: Vec::new(),
86 cache_server_errors: false,
87 }
88 }
89}
90
91impl IdempotencyConfig {
93 pub fn with_header_name<S>(mut self, name: S) -> Self
103 where
104 S: AsRef<str>,
105 {
106 self.set_header_name(name.as_ref().trim().to_ascii_lowercase());
107 self
108 }
109
110 pub fn with_ttl_ms(mut self, ttl_ms: u64) -> Self {
120 self.set_ttl_ms(ttl_ms.max(1));
121 self
122 }
123
124 pub fn with_in_flight_ttl_ms(mut self, in_flight_ttl_ms: u64) -> Self {
134 self.set_in_flight_ttl_ms(in_flight_ttl_ms.max(1));
135 self
136 }
137
138 pub fn with_limits(mut self, max_entries: usize, max_bytes: usize) -> Self {
149 self.set_max_entries(max_entries.max(1))
150 .set_max_bytes(max_bytes.max(1));
151 self
152 }
153
154 pub fn with_require_key_prefixes<I, S>(mut self, prefixes: I) -> Self
164 where
165 I: IntoIterator<Item = S>,
166 S: Into<String>,
167 {
168 self.set_require_key_prefixes(prefixes.into_iter().map(Into::into).collect());
169 self
170 }
171
172 pub fn with_methods(mut self, methods: Vec<Method>) -> Self {
182 self.set_methods(methods);
183 self
184 }
185
186 pub fn with_cache_server_errors(mut self, cache_server_errors: bool) -> Self {
196 self.set_cache_server_errors(cache_server_errors);
197 self
198 }
199}
200
201impl Default for InMemoryIdempotencyStore {
203 fn default() -> Self {
209 Self::new(
210 DEFAULT_IDEMPOTENCY_MAX_ENTRIES,
211 DEFAULT_IDEMPOTENCY_MAX_BYTES,
212 )
213 }
214}
215
216impl InMemoryIdempotencyStore {
218 pub fn new(max_entries: usize, max_bytes: usize) -> Self {
229 let shards: Box<[IdempotencyShard; IDEMPOTENCY_SHARD_COUNT]> =
230 Box::new(from_fn(|_: usize| IdempotencyShard {
231 map: RwLock::new(hash_map_xx_hash3_64()),
232 }));
233 Self {
234 inner: Arc::new(InMemoryIdempotencyStoreInner {
235 max_entries: max_entries.max(1),
236 max_bytes: max_bytes.max(1),
237 entry_count: AtomicUsize::new(0),
238 total_bytes: AtomicUsize::new(0),
239 shards,
240 }),
241 }
242 }
243
244 #[inline(always)]
250 pub fn len(&self) -> usize {
251 let Self { inner } = self;
252 inner.entry_count.load(Ordering::Relaxed)
253 }
254
255 #[inline(always)]
261 pub fn is_empty(&self) -> bool {
262 self.len() == 0
263 }
264
265 #[inline(always)]
271 pub fn total_bytes(&self) -> usize {
272 let Self { inner } = self;
273 inner.total_bytes.load(Ordering::Relaxed)
274 }
275
276 #[inline]
288 pub fn acquire_sync(
289 &self,
290 key: &str,
291 fingerprint: u64,
292 in_flight_ttl_ms: u64,
293 ) -> IdempotencyLookup {
294 let Self { inner } = self;
295 let idx: usize = idempotency_shard_index(key);
296 let now_ms: u64 = idempotency_now_ms();
297 if inner.entry_count.load(Ordering::Relaxed) > 0
298 && let Ok(read_guard) = inner.shards[idx].map.read()
299 && let Some(existing) = read_guard.get(key)
300 && now_ms < existing.expires_at_ms
301 {
302 if existing.fingerprint != fingerprint {
303 return IdempotencyLookup::FingerprintMismatch;
304 }
305 return match &existing.state {
306 IdempotencySlotState::InFlight => IdempotencyLookup::InFlight,
307 IdempotencySlotState::Completed(resp) => {
308 IdempotencyLookup::Replayed(Arc::clone(resp))
309 }
310 };
311 }
312 let Ok(mut map): Result<
313 RwLockWriteGuard<'_, HashMapXxHash3_64<String, IdempotencySlot>>,
314 _,
315 > = inner.shards[idx].map.write() else {
316 return IdempotencyLookup::Acquired;
317 };
318 if let Some(existing) = map.get_mut(key) {
319 if now_ms < existing.expires_at_ms {
320 if existing.fingerprint != fingerprint {
321 return IdempotencyLookup::FingerprintMismatch;
322 }
323 return match &existing.state {
324 IdempotencySlotState::InFlight => IdempotencyLookup::InFlight,
325 IdempotencySlotState::Completed(resp) => {
326 IdempotencyLookup::Replayed(Arc::clone(resp))
327 }
328 };
329 }
330 let prev_footprint: usize = existing.footprint_bytes;
331 let footprint: usize = key.len() + ENTRY_OVERHEAD_BYTES;
332 existing.fingerprint = fingerprint;
333 existing.state = IdempotencySlotState::InFlight;
334 existing.expires_at_ms = now_ms.saturating_add(in_flight_ttl_ms);
335 existing.footprint_bytes = footprint;
336 if footprint >= prev_footprint {
337 inner
338 .total_bytes
339 .fetch_add(footprint - prev_footprint, Ordering::Relaxed);
340 } else {
341 inner
342 .total_bytes
343 .fetch_sub(prev_footprint - footprint, Ordering::Relaxed);
344 }
345 return IdempotencyLookup::Acquired;
346 }
347 let footprint: usize = key.len() + ENTRY_OVERHEAD_BYTES;
348 while (inner.entry_count.load(Ordering::Relaxed) >= inner.max_entries
349 || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.max_bytes)
350 && !map.is_empty()
351 {
352 let oldest: Option<String> = map
353 .iter()
354 .min_by_key(|(_, slot): &(&String, &IdempotencySlot)| slot.expires_at_ms)
355 .map(|(k, _): (&String, &IdempotencySlot)| k.clone());
356 if let Some(evict_key) = oldest
357 && let Some(removed) = map.remove(&evict_key)
358 {
359 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
360 inner
361 .total_bytes
362 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
363 } else {
364 break;
365 }
366 }
367 map.insert(
368 key.to_owned(),
369 IdempotencySlot {
370 fingerprint,
371 state: IdempotencySlotState::InFlight,
372 expires_at_ms: now_ms.saturating_add(in_flight_ttl_ms),
373 footprint_bytes: footprint,
374 },
375 );
376 inner.entry_count.fetch_add(1, Ordering::Relaxed);
377 inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
378 IdempotencyLookup::Acquired
379 }
380
381 #[inline]
390 pub fn complete_sync(
391 &self,
392 key: String,
393 fingerprint: u64,
394 response: Arc<StoredIdempotentResponse>,
395 ttl_ms: u64,
396 ) {
397 let Self { inner } = self;
398 let footprint: usize = estimate_response_bytes(&key, &response);
399 if footprint > inner.max_bytes {
400 self.release_sync(&key);
401 return;
402 }
403 let idx: usize = idempotency_shard_index(&key);
404 let now_ms: u64 = idempotency_now_ms();
405 let Ok(mut map): Result<
406 RwLockWriteGuard<'_, HashMapXxHash3_64<String, IdempotencySlot>>,
407 _,
408 > = inner.shards[idx].map.write() else {
409 return;
410 };
411 if let Some(existing) = map.get_mut(&key) {
412 let prev_footprint: usize = existing.footprint_bytes;
413 let projected_bytes: usize = inner
414 .total_bytes
415 .load(Ordering::Relaxed)
416 .saturating_sub(prev_footprint)
417 .saturating_add(footprint);
418 if projected_bytes <= inner.max_bytes {
419 existing.fingerprint = fingerprint;
420 existing.state = IdempotencySlotState::Completed(response);
421 existing.expires_at_ms = now_ms.saturating_add(ttl_ms);
422 existing.footprint_bytes = footprint;
423 if footprint >= prev_footprint {
424 inner
425 .total_bytes
426 .fetch_add(footprint - prev_footprint, Ordering::Relaxed);
427 } else {
428 inner
429 .total_bytes
430 .fetch_sub(prev_footprint - footprint, Ordering::Relaxed);
431 }
432 return;
433 }
434 if let Some(prev) = map.remove(&key) {
435 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
436 inner
437 .total_bytes
438 .fetch_sub(prev.footprint_bytes, Ordering::Relaxed);
439 }
440 }
441 while (inner.entry_count.load(Ordering::Relaxed) >= inner.max_entries
442 || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.max_bytes)
443 && !map.is_empty()
444 {
445 let oldest: Option<String> = map
446 .iter()
447 .min_by_key(|(_, slot): &(&String, &IdempotencySlot)| slot.expires_at_ms)
448 .map(|(k, _): (&String, &IdempotencySlot)| k.clone());
449 if let Some(evict_key) = oldest
450 && let Some(removed) = map.remove(&evict_key)
451 {
452 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
453 inner
454 .total_bytes
455 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
456 } else {
457 break;
458 }
459 }
460 map.insert(
461 key,
462 IdempotencySlot {
463 fingerprint,
464 state: IdempotencySlotState::Completed(response),
465 expires_at_ms: now_ms.saturating_add(ttl_ms),
466 footprint_bytes: footprint,
467 },
468 );
469 inner.entry_count.fetch_add(1, Ordering::Relaxed);
470 inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
471 }
472
473 #[inline]
479 pub fn release_sync(&self, key: &str) {
480 let Self { inner } = self;
481 let idx: usize = idempotency_shard_index(key);
482 let Ok(mut map) = inner.shards[idx].map.write() else {
483 return;
484 };
485 let is_inflight: bool = map
486 .get(key)
487 .is_some_and(|s: &IdempotencySlot| matches!(s.state, IdempotencySlotState::InFlight));
488 if is_inflight && let Some(removed) = map.remove(key) {
489 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
490 inner
491 .total_bytes
492 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
493 }
494 }
495}
496
497impl IdempotencyStore for InMemoryIdempotencyStore {
499 #[inline]
512 fn acquire<'a>(
513 &'a self,
514 key: &'a str,
515 fingerprint: u64,
516 in_flight_ttl_ms: u64,
517 ) -> IdempotencyFuture<'a, IdempotencyLookup> {
518 let outcome: IdempotencyLookup = self.acquire_sync(key, fingerprint, in_flight_ttl_ms);
519 Box::pin(ready(outcome))
520 }
521
522 #[inline]
536 fn complete<'a>(
537 &'a self,
538 key: String,
539 fingerprint: u64,
540 response: Arc<StoredIdempotentResponse>,
541 ttl_ms: u64,
542 ) -> IdempotencyFuture<'a, ()> {
543 self.complete_sync(key, fingerprint, response, ttl_ms);
544 Box::pin(ready(()))
545 }
546
547 #[inline]
558 fn release<'a>(&'a self, key: &'a str) -> IdempotencyFuture<'a, ()> {
559 self.release_sync(key);
560 Box::pin(ready(()))
561 }
562
563 fn release_on_drop(&self, key: &str) {
569 self.release_sync(key);
570 }
571
572 fn purge_expired(&self) -> usize {
578 let Self { inner } = self;
579 if inner.entry_count.load(Ordering::Relaxed) == 0 {
580 return 0;
581 }
582 let now_ms: u64 = idempotency_now_ms();
583 let mut evicted: usize = 0;
584 let mut freed: usize = 0;
585 for shard in inner.shards.iter() {
586 if let Ok(mut map) = shard.map.write() {
587 if map.is_empty() {
588 continue;
589 }
590 map.retain(|_: &String, slot: &mut IdempotencySlot| {
591 if now_ms >= slot.expires_at_ms {
592 evicted += 1;
593 freed += slot.footprint_bytes;
594 false
595 } else {
596 true
597 }
598 });
599 }
600 }
601 if evicted > 0 {
602 inner.entry_count.fetch_sub(evicted, Ordering::Relaxed);
603 inner.total_bytes.fetch_sub(freed, Ordering::Relaxed);
604 }
605 evicted
606 }
607}
608
609impl Drop for IdempotencyInFlightGuardInner {
611 fn drop(&mut self) {
613 let Self {
614 settled,
615 storage_key,
616 store,
617 ..
618 } = self;
619 if !*settled.get_mut() {
620 store.release_on_drop(storage_key);
621 }
622 }
623}
624
625impl IdempotencyInFlightGuard {
627 pub(crate) fn claim_settlement(&self) -> bool {
633 let Self { inner } = self;
634 !inner.settled.swap(true, Ordering::AcqRel)
635 }
636
637 pub(crate) fn storage_key(&self) -> &str {
643 let Self { inner } = self;
644 &inner.storage_key
645 }
646
647 pub(crate) fn fingerprint(&self) -> u64 {
653 let Self { inner } = self;
654 inner.fingerprint
655 }
656}
657
658impl IdempotencyPlugin {
660 pub fn init(config: IdempotencyConfig) -> &'static Self {
670 let local: InMemoryIdempotencyStore =
671 InMemoryIdempotencyStore::new(config.get_max_entries(), config.get_max_bytes());
672 let store: Arc<dyn IdempotencyStore> = Arc::new(local.clone());
673 IDEMPOTENCY_PLUGIN.get_or_init(|| Self::new_instance_with_local(config, store, Some(local)))
674 }
675
676 pub fn init_with_store(
687 config: IdempotencyConfig,
688 store: Arc<dyn IdempotencyStore>,
689 ) -> &'static Self {
690 IDEMPOTENCY_PLUGIN.get_or_init(|| Self::new_instance(config, store))
691 }
692
693 pub fn new_instance(config: IdempotencyConfig, store: Arc<dyn IdempotencyStore>) -> Self {
704 Self::new_instance_with_local(config, store, None)
705 }
706
707 pub(crate) fn new_instance_with_local(
719 config: IdempotencyConfig,
720 store: Arc<dyn IdempotencyStore>,
721 local_store: Option<InMemoryIdempotencyStore>,
722 ) -> Self {
723 let mut guarded_method_mask: u16 = 0;
724 let mut has_unknown_method: bool = false;
725 for m in config.get_methods() {
726 let bit: u16 = method_bit(m);
727 if bit != 0 {
728 guarded_method_mask |= bit;
729 } else {
730 has_unknown_method = true;
731 }
732 }
733 let require_prefixes: Box<[String]> = config
734 .get_require_key_prefixes()
735 .iter()
736 .filter(|p: &&String| !p.trim().is_empty())
737 .map(|p: &String| normalize_prefix(p))
738 .collect::<Vec<String>>()
739 .into_boxed_slice();
740 let prebuilt_bad_key_wire: Vec<u8> =
741 build_static_error_wire(HttpStatus::BadRequest, BODY_BAD_KEY, None);
742 let prebuilt_in_flight_wire: Vec<u8> = build_static_error_wire(
743 HttpStatus::Conflict,
744 BODY_IN_FLIGHT,
745 Some(IN_FLIGHT_RETRY_AFTER),
746 );
747 let prebuilt_mismatch_wire: Vec<u8> = build_static_error_wire(
748 HttpStatus::UnprocessableEntity,
749 BODY_FINGERPRINT_MISMATCH,
750 None,
751 );
752 Self {
753 config,
754 guarded_method_mask,
755 has_unknown_method,
756 require_prefixes,
757 store,
758 local_store,
759 prebuilt_bad_key_wire,
760 prebuilt_in_flight_wire,
761 prebuilt_mismatch_wire,
762 }
763 }
764
765 #[inline(always)]
771 pub fn get() -> Option<&'static Self> {
772 IDEMPOTENCY_PLUGIN.get()
773 }
774
775 #[inline(always)]
781 pub fn get_config(&self) -> &IdempotencyConfig {
782 let Self { config, .. } = self;
783 config
784 }
785
786 #[inline(always)]
792 pub fn get_store(&self) -> &Arc<dyn IdempotencyStore> {
793 let Self { store, .. } = self;
794 store
795 }
796
797 #[inline(always)]
803 pub(crate) fn get_local_store(&self) -> Option<&InMemoryIdempotencyStore> {
804 let Self { local_store, .. } = self;
805 local_store.as_ref()
806 }
807
808 #[inline(always)]
818 pub(crate) fn is_guarded_method(&self, method: &Method) -> bool {
819 let Self {
820 config,
821 guarded_method_mask,
822 has_unknown_method,
823 ..
824 } = self;
825 let bit: u16 = method_bit(method);
826 if bit != 0 {
827 return (guarded_method_mask & bit) != 0;
828 }
829 *has_unknown_method && config.get_methods().iter().any(|m: &Method| m == method)
830 }
831
832 #[inline]
842 pub(crate) fn requires_key(&self, path: &str) -> bool {
843 let Self {
844 require_prefixes, ..
845 } = self;
846 require_prefixes
847 .iter()
848 .any(|prefix: &String| path_matches_prefix(path, prefix))
849 }
850}
851
852impl ServerHook for IdempotencyRequestHook {
854 #[inline(always)]
865 async fn new(_: &mut Stream, _: &mut Context) -> Self {
866 Self
867 }
868
869 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
881 let Some(plugin) = IdempotencyPlugin::get() else {
882 return Status::Continue;
883 };
884 let config: &IdempotencyConfig = plugin.get_config();
885 let (lookup, acquired_key, fingerprint): (IdempotencyLookup, Option<String>, u64) = {
886 let req: &Request = ctx.get_request();
887 let method: &Method = req.get_method();
888 if !plugin.is_guarded_method(method) {
889 return Status::Continue;
890 }
891 let path: &str = req.get_path();
892 let raw_key: Option<&str> =
893 find_header_back_ref(req.get_headers(), config.get_header_name());
894 let Some(key_slice) = raw_key else {
895 if plugin.requires_key(path) {
896 let _: Result<(), ResponseError> =
897 stream.try_send(&plugin.prebuilt_bad_key_wire).await;
898 return Status::Reject;
899 }
900 return Status::Continue;
901 };
902 let trimmed: &str = key_slice.trim();
903 if !is_valid_idempotency_key(trimmed, config.get_max_key_len()) {
904 let _: Result<(), ResponseError> =
905 stream.try_send(&plugin.prebuilt_bad_key_wire).await;
906 return Status::Reject;
907 }
908 let fingerprint: u64 = compute_request_fingerprint(method, path, req.get_body());
909 let mut key_buf: [u8; STACK_STORAGE_KEY_CAP] = [0u8; STACK_STORAGE_KEY_CAP];
910 if let Some(local) = plugin.get_local_store() {
911 if let Some(stack_key) =
912 build_storage_key_stack(method, path, trimmed, &mut key_buf)
913 {
914 let res: IdempotencyLookup =
915 local.acquire_sync(stack_key, fingerprint, config.get_in_flight_ttl_ms());
916 let owned: Option<String> = if matches!(res, IdempotencyLookup::Acquired) {
917 Some(stack_key.to_owned())
918 } else {
919 None
920 };
921 (res, owned, fingerprint)
922 } else {
923 let owned_key: String = build_storage_key(method, path, trimmed);
924 let res: IdempotencyLookup =
925 local.acquire_sync(&owned_key, fingerprint, config.get_in_flight_ttl_ms());
926 let owned: Option<String> = if matches!(res, IdempotencyLookup::Acquired) {
927 Some(owned_key)
928 } else {
929 None
930 };
931 (res, owned, fingerprint)
932 }
933 } else {
934 let owned_key: String = build_storage_key(method, path, trimmed);
935 let res: IdempotencyLookup = plugin
936 .get_store()
937 .acquire(&owned_key, fingerprint, config.get_in_flight_ttl_ms())
938 .await;
939 let owned: Option<String> = if matches!(res, IdempotencyLookup::Acquired) {
940 Some(owned_key)
941 } else {
942 None
943 };
944 (res, owned, fingerprint)
945 }
946 };
947 match lookup {
948 IdempotencyLookup::Acquired => {
949 if let Some(storage_key) = acquired_key {
950 let guard: IdempotencyInFlightGuard = IdempotencyInFlightGuard {
951 inner: Arc::new(IdempotencyInFlightGuardInner {
952 settled: AtomicBool::new(false),
953 storage_key,
954 fingerprint,
955 store: Arc::clone(plugin.get_store()),
956 }),
957 };
958 ctx.set_attribute(ATTR_IDEMPOTENCY_GUARD, guard);
959 }
960 Status::Continue
961 }
962 IdempotencyLookup::InFlight => {
963 let _: Result<(), ResponseError> =
964 stream.try_send(&plugin.prebuilt_in_flight_wire).await;
965 Status::Reject
966 }
967 IdempotencyLookup::FingerprintMismatch => {
968 let _: Result<(), ResponseError> =
969 stream.try_send(&plugin.prebuilt_mismatch_wire).await;
970 Status::Reject
971 }
972 IdempotencyLookup::Replayed(cached) => {
973 let _: Result<(), ResponseError> =
974 stream.try_send(cached.get_replayed_wire()).await;
975 Status::Reject
976 }
977 }
978 }
979}
980
981impl ServerHook for IdempotencyResponseHook {
983 #[inline(always)]
994 async fn new(_: &mut Stream, _: &mut Context) -> Self {
995 Self
996 }
997
998 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
1010 let Some(plugin) = IdempotencyPlugin::get() else {
1011 return Status::Continue;
1012 };
1013 let Some(guard) =
1014 ctx.try_get_attribute::<IdempotencyInFlightGuard, _>(ATTR_IDEMPOTENCY_GUARD)
1015 else {
1016 return Status::Continue;
1017 };
1018 ctx.remove_attribute(ATTR_IDEMPOTENCY_GUARD);
1019 if !guard.claim_settlement() {
1020 return Status::Continue;
1021 }
1022 let config: &IdempotencyConfig = plugin.get_config();
1023 let status_code: usize = ctx.get_response().get_status_code();
1024 let body_len: usize = ctx.get_response().get_body().len();
1025 let status_ok: bool =
1026 config.get_cache_server_errors() || status_code < NON_CACHEABLE_STATUS_MIN;
1027 if status_ok && body_len <= config.get_max_body_bytes() {
1028 let stored: Arc<StoredIdempotentResponse> =
1029 Arc::new(StoredIdempotentResponse::capture(ctx.get_response()));
1030 let fp: u64 = guard.fingerprint();
1031 let owned_key: String = match Arc::try_unwrap(guard.inner) {
1032 Ok(mut inner) => take(&mut inner.storage_key),
1033 Err(arc_inner) => arc_inner.storage_key.clone(),
1034 };
1035 if let Some(local) = plugin.get_local_store() {
1036 local.complete_sync(owned_key, fp, stored, config.get_ttl_ms());
1037 } else {
1038 plugin
1039 .get_store()
1040 .complete(owned_key, fp, stored, config.get_ttl_ms())
1041 .await;
1042 }
1043 } else if let Some(local) = plugin.get_local_store() {
1044 local.release_sync(guard.storage_key());
1045 } else {
1046 plugin.get_store().release(guard.storage_key()).await;
1047 }
1048 Status::Continue
1049 }
1050}