Diffinery

homeflare/celldpublic

280 lines · 11.0 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! Workers KV, reified sans-IO.
4//!
5//! A KV namespace is a cell, and this module holds the parts of it that decide
6//! an *address* or publish a *bound*. It is deliberately smaller than it first
7//! was, and the reason is worth recording.
8//!
9//! The first version also carried the key, value, metadata and expiry checks,
10//! on [`cron`](crate::cron)'s rule that a second implementation is a second set
11//! of answers. That rule still holds — but the second caller here is JavaScript,
12//! and reaching Rust from the harness costs a host op, which D1 set the bar at
13//! one and Workflows came in under. So the bounds ship as *data*
14//! (`__cell.kvLimits`) and the harness compares against them, which leaves one
15//! source of truth and one implementation. The Rust checks became a copy
16//! nothing called, and `twin_gate` found them: "tested by the DST, run by
17//! nobody — production has its own copy".
18//!
19//! What stays is what production genuinely reads: the bounds themselves, the
20//! shard function, the cell name, and the large-value reference. Those decide
21//! where data lives and what celld will accept, and every runtime path must
22//! agree about them exactly.
23//!
24//! Deliberately absent: the SQL, the object-store I/O for a large value, and
25//! the HMAC that turns a cell name into a cell scope. The first two are the
26//! cell's, and the third needs crypto, which this crate does not have.
27
28/// The Durable Object class every KV namespace runs as.
29///
30/// One fleet-wide name, not one per script, and that is a decision rather than
31/// an omission. A namespace is a resource several Workers can bind, the same
32/// way a D1 database is, so two scripts naming one namespace mean to reach one
33/// set of cells. A workflow class carries its script because a workflow
34/// instance is script-scoped; a namespace is not.
35pub const RESERVED_CLASS: &str = "__KvNamespace";
36
37/// Upstream's limits, which this crate refuses rather than truncates.
38pub const MAX_KEY_BYTES: usize = 512;
39pub const MAX_VALUE_BYTES: usize = 25 * 1024 * 1024;
40
41/// The largest value celld stores inside the namespace cell.
42///
43/// A cell's writes replicate as LTX, so an inline value is paid for twice: once
44/// in SQLite and once on the wire, on every write. Upstream permits 25 MiB, and
45/// 25 MiB inline would make a single `put` the most expensive operation in the
46/// runtime.
47///
48/// Above this bound the bytes go to the fleet bucket and the row names them,
49/// which is the split Cloudflare's own KV rearchitecture made for the same
50/// reason — small values in the database, large ones in object storage.
51///
52/// A repeated equal-size fleet A/B found that the inline path is faster at
53/// 1 MiB and the bucket path is faster at 2 MiB. Thus, 1 MiB is the largest
54/// measured size before the latency crossover. This limit also keeps the same
55/// 1 MiB cap that a workflow step return uses.
56pub const MAX_INLINE_VALUE_BYTES: usize = 1024 * 1024;
57pub const MAX_METADATA_BYTES: usize = 1024;
58/// Upstream refuses a shorter expiry outright, so a caller learns at the call
59/// and not sixty seconds later.
60pub const MIN_EXPIRATION_TTL_MS: i64 = 60_000;
61/// One `get`/`getWithMetadata` bulk call. A CLI chunks beneath this rather
62/// than inheriting it; the binding is where the ceiling belongs.
63pub const MAX_BULK_KEYS: usize = 100;
64/// One `list` page.
65pub const MAX_LIST_LIMIT: usize = 1000;
66
67/// The row format and object layout for a large value written with an epoch.
68///
69/// A bare digest is the legacy format. The reader accepts it, but the writer
70/// never creates it and the collector never sweeps its object subtree. A v2
71/// reference includes the ownership epoch that wrote the object, so an older
72/// collector cannot address an object from a later owner.
73#[derive(Clone, Copy, Debug, Eq, PartialEq)]
74pub enum BlobRef<'a> {
75 Legacy { digest: &'a str },
76 V2 { epoch: u64, digest: &'a str },
77}
78
79/// Why a persisted or listed large-value reference is not safe to use.
80#[derive(Clone, Copy, Debug, Eq, PartialEq)]
81pub enum BlobRefError {
82 Shape,
83 Version,
84 Epoch,
85 Digest,
86}
87
88impl std::fmt::Display for BlobRefError {
89 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 formatter.write_str(match self {
91 BlobRefError::Shape => "the KV blob reference has an invalid shape",
92 BlobRefError::Version => "the KV blob reference has an unknown version",
93 BlobRefError::Epoch => "the KV blob reference has an invalid epoch",
94 BlobRefError::Digest => "the KV blob reference has an invalid digest",
95 })
96 }
97}
98
99impl std::error::Error for BlobRefError {}
100
101impl<'a> BlobRef<'a> {
102 /// Read a SQLite `blob_id`. Bare SHA-256 digests remain readable for the
103 /// shipped-layout migration, and every structured reference is strict.
104 pub fn parse(reference: &'a str) -> Result<Self, BlobRefError> {
105 if !reference.contains(':') {
106 validate_blob_digest(reference)?;
107 return Ok(Self::Legacy { digest: reference });
108 }
109 let mut parts = reference.split(':');
110 let version = parts.next();
111 let epoch = parts.next();
112 let digest = parts.next();
113 if parts.next().is_some() {
114 return Err(BlobRefError::Shape);
115 }
116 if version != Some("v2") {
117 return Err(BlobRefError::Version);
118 }
119 let (Some(epoch), Some(digest)) = (epoch, digest) else {
120 return Err(BlobRefError::Shape);
121 };
122 Ok(Self::V2 {
123 epoch: parse_blob_epoch(epoch)?,
124 digest: validate_blob_digest(digest)?,
125 })
126 }
127
128 /// Mint the only reference a new write can commit.
129 pub fn v2(epoch: u64, digest: &'a str) -> Result<Self, BlobRefError> {
130 if epoch == 0 {
131 return Err(BlobRefError::Epoch);
132 }
133 Ok(Self::V2 {
134 epoch,
135 digest: validate_blob_digest(digest)?,
136 })
137 }
138
139 /// Parse the suffix below `kv/blobs-v2/<cell>/`.
140 pub fn parse_object_suffix(suffix: &'a str) -> Result<Self, BlobRefError> {
141 let mut parts = suffix.split('/');
142 let epoch = parts.next();
143 let digest = parts.next();
144 if parts.next().is_some() {
145 return Err(BlobRefError::Shape);
146 }
147 let (Some(epoch), Some(digest)) = (epoch, digest) else {
148 return Err(BlobRefError::Shape);
149 };
150 Ok(Self::V2 {
151 epoch: parse_blob_epoch(epoch)?,
152 digest: validate_blob_digest(digest)?,
153 })
154 }
155
156 pub fn digest(self) -> &'a str {
157 match self {
158 Self::Legacy { digest } | Self::V2 { digest, .. } => digest,
159 }
160 }
161
162 pub fn epoch(self) -> Option<u64> {
163 match self {
164 Self::Legacy { .. } => None,
165 Self::V2 { epoch, .. } => Some(epoch),
166 }
167 }
168
169 pub fn encode(self) -> String {
170 match self {
171 Self::Legacy { digest } => digest.to_string(),
172 Self::V2 { epoch, digest } => format!("v2:e{epoch}:{digest}"),
173 }
174 }
175
176 /// Map a persisted reference to its fleet-bucket object key.
177 pub fn object_key(self, cell: &str) -> String {
178 match self {
179 Self::Legacy { digest } => format!("kv/blobs/{cell}/{digest}"),
180 Self::V2 { epoch, digest } => {
181 format!("kv/blobs-v2/{cell}/e{epoch}/{digest}")
182 }
183 }
184 }
185
186 /// The only subtree that a v2 collector can list.
187 pub fn v2_object_prefix(cell: &str) -> String {
188 format!("kv/blobs-v2/{cell}/")
189 }
190
191 /// A cell can read a legacy reference or a v2 reference from its current
192 /// epoch or an older epoch. A later epoch is outside this activation's
193 /// authority and indicates invalid restored state.
194 pub fn readable_by(self, activation_epoch: u64) -> bool {
195 self.epoch().is_none_or(|epoch| epoch <= activation_epoch)
196 }
197
198 /// A new write must use exactly the epoch that authorized this activation.
199 pub fn writable_by(self, activation_epoch: u64) -> bool {
200 self.epoch() == Some(activation_epoch)
201 }
202
203 /// A collector can remove only the v2 objects from its epoch or an older
204 /// epoch. Legacy objects remain outside this collector by migration policy.
205 pub fn collectable_by(self, collector_epoch: u64) -> bool {
206 self.epoch().is_some_and(|epoch| epoch <= collector_epoch)
207 }
208}
209
210fn validate_blob_digest(digest: &str) -> Result<&str, BlobRefError> {
211 (digest.len() == 64
212 && digest
213 .as_bytes()
214 .iter()
215 .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()))
216 .then_some(digest)
217 .ok_or(BlobRefError::Digest)
218}
219
220fn parse_blob_epoch(epoch: &str) -> Result<u64, BlobRefError> {
221 let digits = epoch.strip_prefix('e').ok_or(BlobRefError::Epoch)?;
222 if digits.is_empty() || digits.starts_with('0') {
223 return Err(BlobRefError::Epoch);
224 }
225 digits
226 .parse::<u64>()
227 .ok()
228 .filter(|epoch| *epoch > 0)
229 .ok_or(BlobRefError::Epoch)
230}
231
232/// The number of shards a namespace has in v1.
233///
234/// One. The shard still travels in every cell name (see [`cell_name`]) so that
235/// raising this number stays a rehash of some keys rather than a rename of
236/// every cell in every fleet.
237pub const SHARDS: u32 = 1;
238
239/// Which shard owns a key.
240///
241/// FNV-1a over the key's bytes. The algorithm is written out rather than
242/// depended upon because this crate has no dependencies, and it is pinned
243/// forever for a harder reason: changing it moves keys between cells, so a
244/// namespace written by one release becomes unreadable by the next. Test
245/// `kv_units::shard_of_is_pinned` holds the vectors that say so.
246pub fn shard_of(key: &str, shards: u32) -> u32 {
247 debug_assert!(shards > 0, "a namespace has at least one shard");
248 const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
249 const PRIME: u64 = 0x0000_0100_0000_01b3;
250 let mut hash = OFFSET;
251 for byte in key.as_bytes() {
252 hash ^= u64::from(*byte);
253 hash = hash.wrapping_mul(PRIME);
254 }
255 (hash % u64::from(shards.max(1))) as u32
256}
257
258/// The Durable Object name a namespace's shard lives at.
259///
260/// The shard travels in the name from the first release, when there is only
261/// shard zero and nothing reads it. That is not tidiness: the name is hashed
262/// into the cell scope, so adding the shard later would change every existing
263/// cell's address, and a rename of every cell in every fleet is not a
264/// migration anyone can write. Paying one character now keeps the later change
265/// to what it should be — a rehash that moves some keys.
266pub fn cell_name(namespace_id: &str, shard: u32) -> String {
267 format!("{namespace_id}/{shard}")
268}
269
270/// How many keys a `list` page may return.
271///
272/// Upstream caps the page at 1000 and defaults to it. A caller asking for zero
273/// or a negative count gets the default rather than an empty page, because an
274/// empty page with `list_complete: false` is a scan that never ends.
275pub fn list_limit(requested: Option<i64>) -> usize {
276 match requested {
277 Some(limit) if limit > 0 => (limit as usize).min(MAX_LIST_LIMIT),
278 _ => MAX_LIST_LIMIT,
279 }
280}