1use std::collections::{BTreeMap, HashMap, HashSet};
34use std::sync::{Arc, Mutex};
35use std::time::Duration;
36
37use indexmap::IndexMap;
38use serde::{Deserialize, Serialize};
39use serde_json::value::RawValue;
40use sha2::{Digest, Sha256};
41
42use crate::json_utils::remove_preserving_order;
43
44#[cfg(not(target_family = "wasm"))]
46pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
47#[cfg(target_family = "wasm")]
49pub type Clock = Arc<dyn Fn() -> u64>;
50
51fn system_now() -> u64 {
53 crate::now_ms() / 1000
54}
55
56const MAX_TTL_SECS: u64 = 81 * 60;
59
60pub(crate) const DELETE_TIMEOUT: Duration =
63 Duration::from_millis(if cfg!(test) { 500 } else { 10_000 });
64
65const EXPIRY_MARGIN_SECS: u64 = 5;
67
68const MIN_IDLE_SECS: u64 = 60;
71
72#[derive(Clone, Copy, Debug, PartialEq)]
78pub struct AutoCache {
79 pub ttl: Duration,
82 pub implicit_floor: u64,
84 pub implicit_ceiling: u64,
88 pub min_tokens: u64,
90 pub min_gain: u64,
92 pub cached_ratio: f64,
94 pub storage_ratio_per_hour: f64,
96}
97
98impl Default for AutoCache {
99 fn default() -> Self {
100 Self {
101 ttl: Duration::from_secs(60 * 60),
102 implicit_floor: 4_096,
103 implicit_ceiling: 16_000,
104 min_tokens: 1_024,
105 min_gain: 256,
106 cached_ratio: 0.1,
107 storage_ratio_per_hour: 0.5 / 0.75,
108 }
109 }
110}
111
112impl AutoCache {
113 pub fn for_spec(spec: &crate::catalog::ModelSpec) -> Self {
119 Self::priced(spec.pricing.as_ref())
120 }
121
122 fn priced(pricing: Option<&crate::catalog::Pricing>) -> Self {
126 let ratio = pricing
127 .and_then(|pricing| Some((pricing.cache_read?, pricing.input)))
128 .filter(|(read, input)| *read >= 0.0 && *input > 0.0)
129 .map(|(read, input)| read / input);
130 let default = Self::default();
131 Self {
132 cached_ratio: ratio.unwrap_or(default.cached_ratio),
133 ..default
134 }
135 }
136}
137
138#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
140pub struct Lease {
141 pub name: String,
143 pub digest: String,
147 pub covers: usize,
149 pub tokens: u64,
151 pub expires_at: u64,
153 pub model: String,
155}
156
157impl Lease {
158 pub(crate) fn live_at(&self, now: u64) -> bool {
160 self.expires_at > now + EXPIRY_MARGIN_SECS
161 }
162}
163
164#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
166pub enum CacheEvent {
167 Created {
169 name: String,
171 tokens: u64,
173 estimated: u64,
175 covers: usize,
177 ttl_secs: u64,
179 at: u64,
181 },
182 Retired {
184 name: String,
186 at: u64,
188 },
189 Lost {
191 name: String,
193 at: u64,
195 },
196 Extended {
198 name: String,
200 expires_at: u64,
202 at: u64,
204 },
205 CreateFailed {
207 status: Option<u16>,
209 message: String,
211 at: u64,
213 },
214}
215
216#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
218pub struct CreatedCache {
219 pub name: String,
221 pub tokens: u64,
223 pub at: u64,
225}
226
227#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
231pub struct CacheReport {
232 pub created: Vec<CreatedCache>,
234 pub reads: BTreeMap<String, u64>,
236 pub retired: Vec<String>,
239 pub lost: Vec<String>,
241 pub token_hours: f64,
244 pub live: Vec<Lease>,
246}
247
248#[derive(Clone, Debug, Default)]
249struct Line {
250 premium: f64,
253 implicit: Option<f64>,
255 rolled_at: u64,
256 last_call: Option<u64>,
257 longest_gap: u64,
258 failed_at: Option<u64>,
261}
262
263#[derive(Clone, Debug)]
264struct Life {
265 tokens: u64,
266 created: u64,
267 expires_at: u64,
268 ended: Option<u64>,
269 last_read: u64,
270 reads: u64,
272 line_gap: u64,
273}
274
275#[derive(Default)]
277struct Lineage {
278 firsts: HashSet<String>,
280 run_start: Option<u64>,
283 run_reads: u64,
286 owed: u64,
289}
290
291#[derive(Default)]
292pub(crate) struct Book {
293 pub(crate) leases: HashMap<String, Lease>,
294 lives: BTreeMap<String, Life>,
295 lineages: HashMap<String, Lineage>,
296 displaced: HashMap<String, Lease>,
299 pub(crate) closes: u64,
302 lines: HashMap<String, Line>,
303 events: Vec<CacheEvent>,
304 report: CacheReport,
305 calibration: Option<f64>,
308}
309
310#[derive(Clone)]
326pub struct CacheBook {
327 inner: Arc<Mutex<Book>>,
328 pub(crate) create: Arc<futures::lock::Mutex<()>>,
330 policy: AutoCache,
331 clock: Clock,
332 pub(crate) display_prefix: Arc<str>,
333}
334
335impl std::fmt::Debug for CacheBook {
336 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337 f.debug_struct("CacheBook")
338 .field("policy", &self.policy)
339 .field("display_prefix", &self.display_prefix)
340 .finish_non_exhaustive()
341 }
342}
343
344impl CacheBook {
345 pub fn new(policy: AutoCache) -> Self {
347 Self {
348 inner: Arc::default(),
349 create: Arc::default(),
350 policy,
351 clock: Arc::new(system_now),
352 display_prefix: Arc::from("rig-cache-"),
353 }
354 }
355
356 pub fn with_clock(
358 mut self,
359 clock: impl Fn() -> u64
360 + crate::wasm_compat::WasmCompatSend
361 + crate::wasm_compat::WasmCompatSync
362 + 'static,
363 ) -> Self {
364 self.clock = Arc::new(clock);
365 self
366 }
367
368 pub fn with_display_prefix(mut self, prefix: &str) -> Self {
371 self.display_prefix = Arc::from(prefix);
372 self
373 }
374
375 pub fn policy(&self) -> AutoCache {
377 self.policy
378 }
379
380 pub(crate) fn book(&self) -> std::sync::MutexGuard<'_, Book> {
381 crate::lock(&self.inner)
382 }
383
384 pub(crate) fn now(&self) -> u64 {
385 (self.clock)()
386 }
387
388 pub fn events(&self) -> Vec<CacheEvent> {
390 self.book().events.clone()
391 }
392
393 pub fn leases(&self) -> Vec<Lease> {
396 let book = self.book();
397 let held = book.leases.values().chain(book.displaced.values());
398 let mut leases: Vec<Lease> = held.cloned().collect();
399 leases.sort_by(|a, b| a.name.cmp(&b.name));
400 leases
401 }
402
403 pub fn restore(&self, leases: Vec<Lease>) {
407 let now = self.now();
408 let mut book = self.book();
409 let mut bad = Vec::new();
410 for lease in leases {
411 if !lease
412 .name
413 .strip_prefix("cachedContents/")
414 .is_some_and(super::cached_content::is_resource_id)
415 {
416 bad.push(lease);
417 continue;
418 }
419 book.lives.entry(lease.name.clone()).or_insert(Life {
420 tokens: lease.tokens,
421 created: now,
422 expires_at: lease.expires_at,
423 ended: None,
424 last_read: now,
425 reads: 1,
427 line_gap: 0,
428 });
429 book.hold(lease);
430 }
431 drop(book);
432 for lease in &bad {
433 self.lost(lease);
434 }
435 }
436
437 pub fn report(&self) -> CacheReport {
439 let now = self.now();
440 let book = self.book();
441 let mut report = book.report.clone();
442 report.token_hours = book
443 .lives
444 .values()
445 .map(|life| {
446 let end = life.ended.unwrap_or(now).min(life.expires_at);
447 life.tokens as f64 * end.saturating_sub(life.created) as f64 / 3600.0
448 })
449 .sum();
450 report.live = book.leases.values().cloned().collect();
451 report.live.sort_by(|a, b| a.name.cmp(&b.name));
452 report
453 }
454
455 pub(crate) fn retired(&self, lease: &Lease) {
456 let now = self.now();
457 let mut book = self.book();
458 book.forget(lease, now);
459 book.events.push(CacheEvent::Retired {
460 name: lease.name.clone(),
461 at: now,
462 });
463 book.report.retired.push(lease.name.clone());
464 tracing::info!(target: "gemini.cache.retired", name = %lease.name);
465 }
466
467 pub(crate) fn lost(&self, lease: &Lease) {
468 let now = self.now();
469 let mut book = self.book();
470 book.forget(lease, now);
471 book.events.push(CacheEvent::Lost {
472 name: lease.name.clone(),
473 at: now,
474 });
475 book.report.lost.push(lease.name.clone());
476 tracing::info!(target: "gemini.cache.lost", name = %lease.name);
477 }
478}
479
480impl Book {
481 fn holds(&self, lease: &Lease) -> bool {
483 self.leases
484 .get(&lease.digest)
485 .is_some_and(|held| held.name == lease.name)
486 }
487
488 fn owns(&self, lease: &Lease) -> bool {
490 self.holds(lease) || self.displaced.contains_key(&lease.name)
491 }
492
493 fn hold(&mut self, lease: Lease) {
496 let (held, other) = match self.leases.remove(&lease.digest) {
497 Some(old) if old.expires_at > lease.expires_at => (old, Some(lease)),
498 old => (lease, old),
499 };
500 if let Some(other) = other.filter(|other| other.name != held.name) {
501 self.displaced.insert(other.name.clone(), other);
502 }
503 self.leases.insert(held.digest.clone(), held);
504 }
505
506 fn forget(&mut self, lease: &Lease, now: u64) {
509 self.displaced.remove(&lease.name);
510 if self.holds(lease) {
511 self.leases.remove(&lease.digest);
512 let next = self
513 .displaced
514 .values()
515 .filter(|other| other.digest == lease.digest && other.live_at(now))
516 .max_by_key(|other| other.expires_at)
517 .map(|other| other.name.clone());
518 if let Some(next) = next.and_then(|name| self.displaced.remove(&name)) {
519 self.hold(next);
520 }
521 }
522 if let Some(life) = self.lives.get_mut(&lease.name)
523 && life.ended.is_none()
524 {
525 life.ended = Some(now);
526 }
527 }
528}
529
530pub(crate) fn short_digest(digest: &str) -> &str {
531 digest.get(..40).unwrap_or(digest)
532}
533
534const PREFIX_KEYS: [&str; 3] = ["systemInstruction", "tools", "toolConfig"];
538
539pub(crate) struct Parsed {
541 pub(crate) rest: Vec<(String, Box<RawValue>)>,
543 pub(crate) prefix: [Option<Box<RawValue>>; 3],
545 pub(crate) contents: Vec<Box<RawValue>>,
546 pub(crate) has_cached_content: bool,
547}
548
549pub(crate) fn parse(bytes: &[u8]) -> Option<Parsed> {
550 let members: IndexMap<String, Box<RawValue>> = serde_json::from_slice(bytes).ok()?;
552 let mut parsed = Parsed {
553 rest: Vec::new(),
554 prefix: [None, None, None],
555 contents: Vec::new(),
556 has_cached_content: false,
557 };
558 for (key, value) in members {
559 if key == "contents" {
560 parsed.contents = serde_json::from_str(value.get()).ok()?;
561 } else if let Some(slot) = PREFIX_KEYS.iter().position(|prefix| *prefix == key) {
562 if value.get() != "null"
563 && let Some(field) = parsed.prefix.get_mut(slot)
564 {
565 *field = Some(value);
566 }
567 } else {
568 if key == "cachedContent" && value.get() != "null" {
569 parsed.has_cached_content = true;
570 }
571 parsed.rest.push((key, value));
572 }
573 }
574 Some(parsed)
575}
576
577fn hex(bytes: &[u8]) -> String {
578 use std::fmt::Write;
579 bytes.iter().fold(String::new(), |mut out, byte| {
580 let _ = write!(out, "{byte:02x}");
581 out
582 })
583}
584
585pub(crate) struct Digested {
587 pub(crate) d: Vec<String>,
589 pub(crate) prefix: u64,
591 pub(crate) contents: Vec<u64>,
593}
594
595pub(crate) fn digests(model: &str, parsed: &Parsed) -> Digested {
596 let mut hasher = Sha256::new();
597 hasher.update(model.as_bytes());
598 let mut prefix = 0;
599 for field in &parsed.prefix {
600 hasher.update([0u8]);
601 if let Some(raw) = field {
602 prefix += digest(&mut hasher, raw.get());
603 }
604 }
605 let mut state = hasher.finalize().to_vec();
606 let mut d = vec![hex(&state)];
607 let mut contents = Vec::with_capacity(parsed.contents.len());
608 for content in &parsed.contents {
609 let mut hasher = Sha256::new();
610 hasher.update(&state);
611 contents.push(digest(&mut hasher, content.get()));
612 state = hasher.finalize().to_vec();
613 d.push(hex(&state));
614 }
615 Digested {
616 d,
617 prefix,
618 contents,
619 }
620}
621
622fn digest(hasher: &mut Sha256, fragment: &str) -> u64 {
628 let Ok(mut value) = serde_json::from_str::<serde_json::Value>(fragment) else {
629 hasher.update(fragment.as_bytes());
630 return (fragment.len() / 4) as u64;
631 };
632 hasher.update(crate::json_utils::to_canonical_string(&value).as_bytes());
633 fn scrub(value: &mut serde_json::Value) {
634 match value {
635 serde_json::Value::Object(map) => {
636 remove_preserving_order(map, "thoughtSignature");
637 map.values_mut().for_each(scrub);
638 }
639 serde_json::Value::Array(items) => items.iter_mut().for_each(scrub),
640 _ => {}
641 }
642 }
643 scrub(&mut value);
644 (value.to_string().len() / 4) as u64
645}
646
647pub(crate) fn is_user_text(raw: &RawValue) -> bool {
649 #[derive(Deserialize)]
650 struct Content {
651 role: Option<String>,
652 #[serde(default)]
653 parts: Vec<serde_json::Map<String, serde_json::Value>>,
654 }
655 serde_json::from_str::<Content>(raw.get()).is_ok_and(|content| {
656 content.role.as_deref() == Some("user")
657 && content.parts.iter().any(|part| part.contains_key("text"))
658 && !content
659 .parts
660 .iter()
661 .any(|part| part.contains_key("functionResponse"))
662 })
663}
664
665pub(crate) fn stripped(parsed: &Parsed, lease: &Lease) -> Option<Vec<u8>> {
667 let name = serde_json::value::to_raw_value(&lease.name).ok()?;
668 let contents = serde_json::value::to_raw_value(&parsed.contents.get(lease.covers..)?).ok()?;
669 let mut out: IndexMap<&str, &RawValue> = IndexMap::new();
670 out.insert("cachedContent", &name);
671 out.insert("contents", &contents);
672 out.extend(
673 parsed
674 .rest
675 .iter()
676 .filter(|(key, _)| key != "cachedContent")
677 .map(|(key, value)| (key.as_str(), &**value)),
678 );
679 serde_json::to_vec(&out).ok()
680}
681
682pub(crate) fn cache_body(
685 model: &str,
686 parsed: &Parsed,
687 covers: usize,
688 display_name: &str,
689 ttl_secs: u64,
690) -> Option<Vec<u8>> {
691 let mut bytes = b"{".to_vec();
692 let mut field = |key: &str, value: &str| {
693 if bytes.len() > 1 {
694 bytes.push(b',');
695 }
696 bytes.extend(format!("\"{key}\":").as_bytes());
697 bytes.extend(value.as_bytes());
698 };
699 field(
700 "model",
701 &serde_json::to_string(&format!("models/{model}")).ok()?,
702 );
703 field("displayName", &serde_json::to_string(display_name).ok()?);
704 field("ttl", &format!("\"{ttl_secs}s\""));
705 for (key, value) in PREFIX_KEYS.iter().zip(&parsed.prefix) {
706 if let Some(value) = value {
707 field(key, value.get());
708 }
709 }
710 if covers > 0 {
711 let contents = serde_json::value::to_raw_value(&parsed.contents.get(..covers)?).ok()?;
712 field("contents", contents.get());
713 }
714 bytes.push(b'}');
715 Some(bytes)
716}
717
718pub(crate) struct Plan {
723 pub(crate) read: Option<Lease>,
724 pub(crate) create: Option<Create>,
725 pub(crate) retire: Vec<Lease>,
726 pub(crate) extend: Option<(Lease, u64)>,
727 pub(crate) line: String,
728 pub(crate) coverable: u64,
729 pub(crate) closes: u64,
730}
731
732pub(crate) struct Create {
733 pub(crate) covers: usize,
734 pub(crate) digest: String,
735 pub(crate) ttl_secs: u64,
736 estimate: u64,
738 expected: u64,
740 pub(crate) replaces: Option<Lease>,
741}
742
743impl CacheBook {
744 pub(crate) fn plan(&self, model: &str, digested: &Digested, roll_allowed: bool) -> Plan {
745 let p = self.policy;
746 let now = self.now();
747 let n = digested.contents.len();
748 let at = |k: usize| digested.d.get(k).map_or("", String::as_str);
750 let (prefix_estimate, content_estimates) = (digested.prefix, &digested.contents);
751 let mut guard = self.book();
752 let book = &mut *guard;
753 let calibration = book.calibration.unwrap_or(1.0);
754
755 let lineage = book.lineages.entry(at(0).to_owned()).or_default();
758 if n >= 1 {
759 lineage.firsts.insert(at(1).to_owned());
760 }
761 let shared = lineage.firsts.len() >= 2;
762
763 let idle: Vec<Lease> = book
765 .leases
766 .values()
767 .filter(|lease| lease.covers > 0 && lease.model == model)
768 .filter(|lease| {
769 book.lives.get(&lease.name).is_some_and(|life| {
770 now.saturating_sub(life.last_read)
771 > MIN_IDLE_SECS.max(life.line_gap.saturating_mul(3))
772 })
773 })
774 .cloned()
775 .collect();
776
777 let read = (0..n.max(1))
779 .rev()
780 .find_map(|k| {
781 book.leases
782 .get(at(k))
783 .filter(|lease| lease.model == model)
784 .filter(|lease| lease.live_at(now))
785 .cloned()
786 })
787 .filter(|lease| !idle.iter().any(|gone| gone.name == lease.name));
788 let covered = read.as_ref().map_or(0, |lease| lease.covers);
789 let tail: u64 = content_estimates
790 .get(covered..n.saturating_sub(1).max(covered))
791 .unwrap_or_default()
792 .iter()
793 .sum();
794 let coverable = match &read {
795 Some(lease) => lease.tokens + (tail as f64 * calibration) as u64,
796 None => ((prefix_estimate + tail) as f64 * calibration) as u64,
797 };
798
799 let line_key = read
801 .as_ref()
802 .filter(|lease| lease.covers > 0)
803 .map_or_else(|| at(1.min(n)).to_owned(), |lease| lease.digest.clone());
804 let held_prefix = book.leases.get(at(0));
805 let prefix_leased = held_prefix.is_some_and(|lease| lease.live_at(now));
806 let prefix_proven = held_prefix
807 .and_then(|lease| book.lives.get(&lease.name))
808 .is_some_and(|life| life.reads > 1);
809 let prefix_unread = held_prefix.is_some() && !prefix_proven;
810 let line = book.lines.entry(line_key.clone()).or_insert_with(|| Line {
811 rolled_at: now,
812 ..Line::default()
813 });
814 if let Some(last) = line.last_call {
815 line.longest_gap = line.longest_gap.max(now.saturating_sub(last));
816 }
817 line.last_call = Some(now);
818 let longest_gap = line.longest_gap;
819 let ttl_secs = p
820 .ttl
821 .as_secs()
822 .max(longest_gap.saturating_mul(2).min(MAX_TTL_SECS))
823 .max(1);
824
825 let lineage = book.lineages.entry(at(0).to_owned()).or_default();
828 let in_run = |start: &u64| ttl_secs > now.saturating_sub(*start) + EXPIRY_MARGIN_SECS;
829 if lineage.run_start.as_ref().is_some_and(in_run) {
830 lineage.run_reads += 1;
831 } else {
832 lineage.run_start = Some(now);
833 lineage.run_reads = 0;
834 }
835 if prefix_proven {
836 lineage.owed = 0;
837 }
838 let owed = lineage
839 .owed
840 .max(1)
841 .saturating_mul(1 + u64::from(prefix_unread));
842
843 let mut plan = Plan {
844 read: read.clone(),
845 create: None,
846 retire: idle,
847 extend: None,
848 line: line_key,
849 coverable,
850 closes: book.closes,
851 };
852
853 let implicit_serving = line.implicit.is_none_or(|ratio| ratio >= 0.5);
855 if coverable >= p.implicit_ceiling && implicit_serving {
856 plan.read = None;
857 return plan;
858 }
859
860 let next_call = longest_gap.min(MAX_TTL_SECS / 2);
864 let may_create = ttl_secs > next_call + EXPIRY_MARGIN_SECS
865 && !line.failed_at.is_some_and(|at| coverable < at + p.min_gain);
866 if read.is_none()
867 && shared
868 && !prefix_leased
869 && (prefix_estimate as f64 * calibration) as u64 >= p.min_tokens
870 && may_create
871 && (prefix_proven || lineage.run_reads >= owed)
872 {
873 lineage.owed = owed;
874 plan.create = Some(Create {
875 covers: 0,
876 digest: at(0).to_owned(),
877 ttl_secs,
878 estimate: prefix_estimate,
879 expected: (prefix_estimate as f64 * calibration) as u64,
880 replaces: None,
881 });
882 } else if n >= 2 && roll_allowed && may_create {
883 let cached = read.as_ref().map_or(0, |lease| lease.tokens);
884 let gain = coverable.saturating_sub(cached);
885 let held_hours = now.saturating_sub(line.rolled_at).max(60) as f64 / 3600.0;
886 let cost = coverable as f64 * (1.0 + p.storage_ratio_per_hour * held_hours);
887 if gain >= p.min_gain && coverable >= p.min_tokens && line.premium >= cost {
888 plan.create = Some(Create {
889 covers: n - 1,
890 digest: at(n - 1).to_owned(),
891 ttl_secs,
892 estimate: prefix_estimate
893 + content_estimates
894 .get(..n - 1)
895 .unwrap_or_default()
896 .iter()
897 .sum::<u64>(),
898 expected: coverable,
899 replaces: read.clone().filter(|lease| lease.covers > 0),
900 });
901 }
902 }
903
904 if plan.create.is_none()
906 && let Some(lease) = &read
907 && longest_gap > 0
908 && lease.expires_at.saturating_sub(now) < longest_gap.saturating_mul(3) / 2
909 {
910 plan.extend = Some((lease.clone(), ttl_secs));
911 }
912 plan
913 }
914
915 pub(crate) fn observe(&self, line: &str, read: Option<&str>, coverable: u64, cached: u64) {
917 let p = self.policy;
918 let mut book = self.book();
919 if let Some(name) = read {
920 *book.report.reads.entry(name.to_owned()).or_default() += 1;
921 }
922 let entry = book.lines.entry(line.to_owned()).or_default();
923 let mut missed = coverable.saturating_sub(cached) as f64;
924 if read.is_none() && coverable >= p.implicit_floor {
925 let ratio = cached as f64 / coverable.max(1) as f64;
926 let implicit = entry
927 .implicit
928 .map_or(ratio, |ewma| 0.5 * ewma + 0.5 * ratio);
929 entry.implicit = Some(implicit);
930 if implicit >= 0.5 {
931 missed = 0.0;
932 }
933 }
934 entry.premium += missed * (1.0 - p.cached_ratio);
935 }
936
937 pub(crate) fn created(
938 &self,
939 from_line: &str,
940 create: &Create,
941 name: String,
942 tokens: u64,
943 model: &str,
944 ) -> Lease {
945 let now = self.now();
946 let lease = Lease {
947 name: name.clone(),
948 digest: create.digest.clone(),
949 covers: create.covers,
950 tokens,
951 expires_at: now + create.ttl_secs,
952 model: model.to_owned(),
953 };
954 let mut book = self.book();
955 if create.estimate > 0 && tokens > 0 {
956 let ratio = tokens as f64 / create.estimate as f64;
957 book.calibration = Some(book.calibration.map_or(ratio, |c| 0.5 * c + 0.5 * ratio));
958 }
959 let previous = book.lines.get(from_line).cloned().unwrap_or_default();
960 if create.covers > 0 {
961 book.lines.insert(
962 lease.digest.clone(),
963 Line {
964 premium: 0.0,
965 implicit: previous.implicit,
966 rolled_at: now,
967 last_call: previous.last_call,
968 longest_gap: previous.longest_gap,
969 failed_at: None,
970 },
971 );
972 }
973 book.lives.insert(
974 name.clone(),
975 Life {
976 tokens,
977 created: now,
978 expires_at: lease.expires_at,
979 ended: None,
980 last_read: now,
981 reads: 0,
982 line_gap: previous.longest_gap,
983 },
984 );
985 book.events.push(CacheEvent::Created {
986 name: name.clone(),
987 tokens,
988 estimated: create.expected,
989 covers: create.covers,
990 ttl_secs: create.ttl_secs,
991 at: now,
992 });
993 book.report.created.push(CreatedCache {
994 name,
995 tokens,
996 at: now,
997 });
998 book.hold(lease.clone());
999 tracing::info!(target: "gemini.cache.created", name = %lease.name, tokens, covers = create.covers);
1000 lease
1001 }
1002
1003 pub(crate) fn create_failed(
1004 &self,
1005 line: &str,
1006 coverable: u64,
1007 status: Option<u16>,
1008 message: String,
1009 ) {
1010 let now = self.now();
1011 let mut book = self.book();
1012 if let Some(entry) = book.lines.get_mut(line) {
1013 entry.failed_at = Some(coverable);
1014 }
1015 book.events.push(CacheEvent::CreateFailed {
1016 status,
1017 message,
1018 at: now,
1019 });
1020 }
1021
1022 pub(crate) fn owns(&self, lease: &Lease) -> bool {
1024 self.book().owns(lease)
1025 }
1026
1027 pub(crate) fn extended(&self, lease: &Lease, ttl_secs: u64) -> bool {
1030 let now = self.now();
1031 let expires_at = now + ttl_secs;
1032 let mut guard = self.book();
1033 let book = &mut *guard;
1034 let owned = book.owns(lease);
1035 let held = book.leases.get_mut(&lease.digest);
1036 let held = held.filter(|held| held.name == lease.name);
1037 if let Some(owned) = held.or(book.displaced.get_mut(&lease.name)) {
1038 owned.expires_at = expires_at;
1039 }
1040 if let Some(life) = book.lives.get_mut(&lease.name) {
1041 life.expires_at = expires_at;
1042 }
1043 book.events.push(CacheEvent::Extended {
1044 name: lease.name.clone(),
1045 expires_at,
1046 at: now,
1047 });
1048 tracing::info!(target: "gemini.cache.extended", name = %lease.name, expires_at);
1049 owned
1050 }
1051
1052 pub(crate) fn touched(&self, lease: &Lease) {
1053 let now = self.now();
1054 let mut book = self.book();
1055 let gap = book
1056 .lines
1057 .get(&lease.digest)
1058 .map_or(0, |line| line.longest_gap);
1059 if let Some(life) = book.lives.get_mut(&lease.name) {
1060 life.last_read = now;
1061 life.reads += 1;
1062 life.line_gap = life.line_gap.max(gap);
1063 }
1064 }
1065}
1066
1067#[cfg(test)]
1068mod tests;