| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Cloudflare Queue policy, reified sans I/O. |
| 4 | //! |
| 5 | //! A queue is one reserved cell. The cell owns SQL and dispatch, while this |
| 6 | //! module owns the values and transitions that another caller must reproduce: |
| 7 | //! the stable address, the public bounds, the alarm deadline, concurrency |
| 8 | //! admission, retry timing, lease-generation advancement, settlement fencing, |
| 9 | //! purge classification, and deploy-time configuration validation. |
| 10 | //! |
| 11 | //! The lease generation travels in [`PlannedLease`]. A caller cannot select a |
| 12 | //! row and then forget to advance its generation, because this module never |
| 13 | //! returns a bare sequence number for a deliverable row. That prevents a late |
| 14 | //! settlement from an expired lease from acknowledging a newer delivery. |
| 15 | |
| 16 | use crate::Ms; |
| 17 | |
| 18 | /// The runtime-supplied Durable Object class that stores every queue. |
| 19 | pub const RESERVED_CLASS: &str = "__Queue"; |
| 20 | |
| 21 | /// Cloudflare measures a Queue kilobyte as 1000 bytes. |
| 22 | pub const MAX_MESSAGE_BYTES: usize = 128_000; |
| 23 | pub const MAX_SEND_BATCH_BYTES: usize = 256_000; |
| 24 | pub const MAX_BATCH_MESSAGES: usize = 100; |
| 25 | pub const MAX_BATCH_TIMEOUT_SECONDS: u16 = 60; |
| 26 | pub const MAX_RETRIES: u16 = 100; |
| 27 | pub const MAX_CONCURRENCY: u16 = 250; |
| 28 | pub const MAX_DELAY_SECONDS: u32 = 86_400; |
| 29 | |
| 30 | pub const DEFAULT_MAX_BATCH_SIZE: u16 = 10; |
| 31 | pub const DEFAULT_MAX_BATCH_TIMEOUT_SECONDS: u16 = 5; |
| 32 | pub const DEFAULT_MAX_RETRIES: u16 = 3; |
| 33 | |
| 34 | /// Queue retention is deployment-independent in celld v1. Wrangler has no |
| 35 | /// configuration key for it, so accepting one would make a celld project |
| 36 | /// invalid on Cloudflare. |
| 37 | pub const RETENTION_MS: Ms = 4 * 24 * 60 * 60 * 1000; |
| 38 | |
| 39 | /// The Durable Object name that `getByName` hashes for a queue. |
| 40 | /// |
| 41 | /// The identity function is intentional. The queue name is already the |
| 42 | /// fleet-wide resource identity, and prefixing it here would make a project |
| 43 | /// address a different queue from Cloudflare. Both the binding and the |
| 44 | /// operator CLI call this function before the runtime applies the namespace |
| 45 | /// HMAC, so even an identity address has one source. |
| 46 | pub fn cell_name(queue_name: &str) -> &str { |
| 47 | queue_name |
| 48 | } |
| 49 | |
| 50 | /// Choose the one durable alarm from every Queue deadline. |
| 51 | /// |
| 52 | /// A deadline already past becomes `now`. SQLite can retain an overdue row |
| 53 | /// across a crash, and installing its old timestamp as a new alarm can leave |
| 54 | /// the wake index behind the clock instead of scheduling immediate work. |
| 55 | pub fn rearm( |
| 56 | now: Ms, |
| 57 | batch_deadline: Option<Ms>, |
| 58 | earliest_visible: Option<Ms>, |
| 59 | earliest_lease_expiry: Option<Ms>, |
| 60 | next_sweep: Option<Ms>, |
| 61 | ) -> Option<Ms> { |
| 62 | [ |
| 63 | batch_deadline, |
| 64 | earliest_visible, |
| 65 | earliest_lease_expiry, |
| 66 | next_sweep, |
| 67 | ] |
| 68 | .into_iter() |
| 69 | .flatten() |
| 70 | .min() |
| 71 | .map(|deadline| deadline.max(now)) |
| 72 | } |
| 73 | |
| 74 | /// Resolve a retry deadline from Cloudflare's precedence rule. |
| 75 | /// |
| 76 | /// A per-message or per-batch delay wins, including an explicit zero. The |
| 77 | /// configured consumer delay is a fixed default; it does not compound with |
| 78 | /// the attempt number. Cloudflare documents exponential backoff as code an |
| 79 | /// application can implement with `message.attempts`, not as broker behavior. |
| 80 | pub fn retry_at(now: Ms, explicit_seconds: Option<u32>, configured_seconds: Option<u32>) -> Ms { |
| 81 | let seconds = explicit_seconds.or(configured_seconds).unwrap_or(0); |
| 82 | now.saturating_add(Ms::from(seconds).saturating_mul(1000)) |
| 83 | } |
| 84 | |
| 85 | /// Whether a failed current delivery has spent the configured retry count. |
| 86 | /// |
| 87 | /// `attempt` is one for the first delivery. `max_retries = 3` therefore allows |
| 88 | /// attempts one through four, and the fourth failure exhausts the message. |
| 89 | pub fn exhausted(attempt: u16, max_retries: u16) -> bool { |
| 90 | attempt > max_retries |
| 91 | } |
| 92 | |
| 93 | /// The durable transition owed when one persisted lease expires. |
| 94 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 95 | pub struct ExpiredLease { |
| 96 | /// The delivery that just failed. The first delivery is attempt one. |
| 97 | pub attempt: u16, |
| 98 | pub action: ExpiredLeaseAction, |
| 99 | } |
| 100 | |
| 101 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 102 | pub enum ExpiredLeaseAction { |
| 103 | RetryAt(Ms), |
| 104 | Exhausted, |
| 105 | DeletePurged, |
| 106 | } |
| 107 | |
| 108 | /// Spend one failed delivery and decide what replaces its expired lease. |
| 109 | /// |
| 110 | /// Purge wins over retry because a purge is irreversible. Otherwise the same |
| 111 | /// fixed consumer delay and retry ceiling used by an explicit settlement |
| 112 | /// apply to a consumer that did not settle before its lease deadline. |
| 113 | pub fn expire_lease( |
| 114 | now: Ms, |
| 115 | prior_failures: u16, |
| 116 | max_retries: u16, |
| 117 | configured_delay_seconds: Option<u32>, |
| 118 | purge_on_settle: bool, |
| 119 | ) -> ExpiredLease { |
| 120 | let attempt = prior_failures.saturating_add(1); |
| 121 | let action = if purge_on_settle { |
| 122 | ExpiredLeaseAction::DeletePurged |
| 123 | } else if exhausted(attempt, max_retries) { |
| 124 | ExpiredLeaseAction::Exhausted |
| 125 | } else { |
| 126 | ExpiredLeaseAction::RetryAt(retry_at(now, None, configured_delay_seconds)) |
| 127 | }; |
| 128 | ExpiredLease { attempt, action } |
| 129 | } |
| 130 | |
| 131 | /// The fixed lifetime of one persisted Queue lease. |
| 132 | /// |
| 133 | /// Admission, handler execution, and settlement each have a runtime-enforced |
| 134 | /// budget. A lease must cover all three or a live consumer can be reclaimed. |
| 135 | /// The broker stores the resulting absolute deadline once, so a restart or a |
| 136 | /// configuration change cannot lengthen an existing lease. |
| 137 | pub fn lease_duration_ms(admission_wait_ms: Ms, handler_budget_ms: Ms, settle_budget_ms: Ms) -> Ms { |
| 138 | admission_wait_ms |
| 139 | .saturating_add(handler_budget_ms) |
| 140 | .saturating_add(settle_budget_ms) |
| 141 | } |
| 142 | |
| 143 | /// The row facts needed to plan one lease transaction. |
| 144 | /// |
| 145 | /// The SQL query supplies rows in its chosen best-effort delivery order. This |
| 146 | /// function preserves that order and never upgrades it into a FIFO promise. |
| 147 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 148 | pub struct BatchRow { |
| 149 | pub seq: i64, |
| 150 | pub visible_at: Ms, |
| 151 | pub lease_generation: u64, |
| 152 | pub leased_until: Option<Ms>, |
| 153 | /// Purge marks a live lease and lets its consumer finish. The row is |
| 154 | /// deleted when the lease settles or expires, and is never redelivered. |
| 155 | pub purge_on_settle: bool, |
| 156 | } |
| 157 | |
| 158 | /// A row and the generation the new consumer must settle. |
| 159 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 160 | pub struct PlannedLease { |
| 161 | pub seq: i64, |
| 162 | pub generation: u64, |
| 163 | /// True when the previous lease expired. The cell increments the failed |
| 164 | /// attempt in the same transaction that installs this generation. |
| 165 | pub reclaimed: bool, |
| 166 | } |
| 167 | |
| 168 | /// One message identity captured by a Queue lease. |
| 169 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 170 | pub struct LeaseMember<'a> { |
| 171 | pub seq: i64, |
| 172 | pub message_id: &'a str, |
| 173 | pub generation: u64, |
| 174 | } |
| 175 | |
| 176 | /// Decide whether a settlement names the complete current lease batch. |
| 177 | /// |
| 178 | /// A consumer can retain an old settlement after the broker has re-leased a |
| 179 | /// message. The lease ID selects the candidate rows, and this comparison then |
| 180 | /// fences every member by its message identity, sequence, and generation. A |
| 181 | /// complete one-to-one match also rejects a truncated or duplicated batch. |
| 182 | pub fn settlement_matches(current: &[LeaseMember<'_>], submitted: &[LeaseMember<'_>]) -> bool { |
| 183 | if current.is_empty() || current.len() != submitted.len() { |
| 184 | return false; |
| 185 | } |
| 186 | if current.iter().enumerate().any(|(index, member)| { |
| 187 | current[..index] |
| 188 | .iter() |
| 189 | .any(|prior| prior.message_id == member.message_id) |
| 190 | }) { |
| 191 | return false; |
| 192 | } |
| 193 | |
| 194 | let mut matched = vec![false; current.len()]; |
| 195 | for submitted in submitted { |
| 196 | let Some((index, _)) = current.iter().enumerate().find(|(index, current)| { |
| 197 | !matched[*index] |
| 198 | && current.message_id == submitted.message_id |
| 199 | && current.seq == submitted.seq |
| 200 | && current.generation == submitted.generation |
| 201 | }) else { |
| 202 | return false; |
| 203 | }; |
| 204 | matched[index] = true; |
| 205 | } |
| 206 | true |
| 207 | } |
| 208 | |
| 209 | /// Decide whether another batch lease fits the configured concurrency bound. |
| 210 | /// |
| 211 | /// `active_batches` counts persisted lease IDs, not completed settlements. A |
| 212 | /// consumer batch occupies its slot from lease installation until settlement |
| 213 | /// or expiry removes the lease. |
| 214 | pub fn can_install_lease(active_batches: usize, max_concurrency: u16) -> bool { |
| 215 | active_batches < usize::from(max_concurrency) |
| 216 | } |
| 217 | |
| 218 | /// The lease fact needed to classify one row during a Queue purge. |
| 219 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 220 | pub struct PurgeRow { |
| 221 | pub seq: i64, |
| 222 | pub lease_id_present: bool, |
| 223 | pub leased_until: Option<Ms>, |
| 224 | } |
| 225 | |
| 226 | /// All mutations one purge transaction owes. |
| 227 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 228 | pub struct PurgePlan { |
| 229 | /// Rows with no live lease can be deleted immediately. |
| 230 | pub delete: Vec<i64>, |
| 231 | /// Rows with a live lease remain until settlement or expiry. |
| 232 | pub mark_for_settle: Vec<i64>, |
| 233 | } |
| 234 | |
| 235 | /// Partition Queue rows without deleting a row under a live consumer. |
| 236 | pub fn purge_plan(now: Ms, rows: &[PurgeRow]) -> PurgePlan { |
| 237 | let mut plan = PurgePlan::default(); |
| 238 | for row in rows { |
| 239 | if row.lease_id_present && row.leased_until.is_some_and(|until| until > now) { |
| 240 | plan.mark_for_settle.push(row.seq); |
| 241 | } else { |
| 242 | plan.delete.push(row.seq); |
| 243 | } |
| 244 | } |
| 245 | plan |
| 246 | } |
| 247 | |
| 248 | /// All mutations one batch-planning transaction owes. |
| 249 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 250 | pub struct BatchPlan { |
| 251 | pub leases: Vec<PlannedLease>, |
| 252 | /// Purged rows remain while a live consumer can still settle them. Once |
| 253 | /// that lease expires, deletion replaces reclamation and redelivery. |
| 254 | pub delete_purged: Vec<i64>, |
| 255 | } |
| 256 | |
| 257 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 258 | pub enum PlanError { |
| 259 | GenerationExhausted { seq: i64 }, |
| 260 | } |
| 261 | |
| 262 | impl std::fmt::Display for PlanError { |
| 263 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 264 | match self { |
| 265 | Self::GenerationExhausted { seq } => { |
| 266 | write!(f, "queue message {seq} exhausted its lease generation") |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | impl std::error::Error for PlanError {} |
| 273 | |
| 274 | /// Select visible, unleased rows and reclaim expired leases under a new |
| 275 | /// generation. A live lease is never returned. |
| 276 | pub fn batch_plan( |
| 277 | now: Ms, |
| 278 | rows: &[BatchRow], |
| 279 | max_batch_size: usize, |
| 280 | ) -> Result<BatchPlan, PlanError> { |
| 281 | let mut plan = BatchPlan::default(); |
| 282 | for row in rows { |
| 283 | let live_lease = row.leased_until.is_some_and(|until| until > now); |
| 284 | if row.purge_on_settle { |
| 285 | if !live_lease { |
| 286 | plan.delete_purged.push(row.seq); |
| 287 | } |
| 288 | continue; |
| 289 | } |
| 290 | if plan.leases.len() >= max_batch_size || row.visible_at > now || live_lease { |
| 291 | continue; |
| 292 | } |
| 293 | let generation = row |
| 294 | .lease_generation |
| 295 | .checked_add(1) |
| 296 | .ok_or(PlanError::GenerationExhausted { seq: row.seq })?; |
| 297 | plan.leases.push(PlannedLease { |
| 298 | seq: row.seq, |
| 299 | generation, |
| 300 | reclaimed: row.leased_until.is_some(), |
| 301 | }); |
| 302 | } |
| 303 | Ok(plan) |
| 304 | } |
| 305 | |
| 306 | /// The Wrangler Queue values whose bounds celld enforces at deploy time. |
| 307 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 308 | pub struct QueueConfig { |
| 309 | pub max_batch_size: u16, |
| 310 | pub max_batch_timeout_seconds: u16, |
| 311 | pub max_retries: u16, |
| 312 | pub max_concurrency: Option<u16>, |
| 313 | pub delivery_delay_seconds: u32, |
| 314 | pub retry_delay_seconds: Option<u32>, |
| 315 | } |
| 316 | |
| 317 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 318 | pub struct ConfigError { |
| 319 | pub field: &'static str, |
| 320 | pub message: &'static str, |
| 321 | } |
| 322 | |
| 323 | impl std::fmt::Display for ConfigError { |
| 324 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 325 | write!(f, "{} {}", self.field, self.message) |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | impl std::error::Error for ConfigError {} |
| 330 | |
| 331 | /// Validate the Queue bounds that a bad deployment must report up front. |
| 332 | pub fn validate_config(config: &QueueConfig) -> Result<(), ConfigError> { |
| 333 | let fail = |field, message| ConfigError { field, message }; |
| 334 | if !(1..=MAX_BATCH_MESSAGES as u16).contains(&config.max_batch_size) { |
| 335 | return Err(fail("max_batch_size", "must be between 1 and 100")); |
| 336 | } |
| 337 | if config.max_batch_timeout_seconds > MAX_BATCH_TIMEOUT_SECONDS { |
| 338 | return Err(fail( |
| 339 | "max_batch_timeout", |
| 340 | "must be between 0 and 60 seconds", |
| 341 | )); |
| 342 | } |
| 343 | if config.max_retries > MAX_RETRIES { |
| 344 | return Err(fail("max_retries", "must be between 0 and 100")); |
| 345 | } |
| 346 | if config |
| 347 | .max_concurrency |
| 348 | .is_some_and(|value| !(1..=MAX_CONCURRENCY).contains(&value)) |
| 349 | { |
| 350 | return Err(fail("max_concurrency", "must be between 1 and 250")); |
| 351 | } |
| 352 | if config.delivery_delay_seconds > MAX_DELAY_SECONDS { |
| 353 | return Err(fail( |
| 354 | "delivery_delay", |
| 355 | "must be between 0 and 86400 seconds", |
| 356 | )); |
| 357 | } |
| 358 | if config |
| 359 | .retry_delay_seconds |
| 360 | .is_some_and(|value| value > MAX_DELAY_SECONDS) |
| 361 | { |
| 362 | return Err(fail("retry_delay", "must be between 0 and 86400 seconds")); |
| 363 | } |
| 364 | Ok(()) |
| 365 | } |