cratefield-core 0.10.1

Cratefield harness kernel: Module trait, Harness builder, ports, errors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Port traits (ADR 0002, architecture section 5). Modules see these traits
//! and nothing else — never a Cloudflare binding, never a vendor client.
//!
//! All traits are `Send + Sync` and object-safe, used as `Arc<dyn Trait>`.
//! Async methods use `async_trait` until native `async fn` in traits is
//! ergonomic for trait objects.

mod actor;
mod auth;
mod blob;
mod captcha;
mod classifier;
mod clock;
mod custom_hostnames;
mod database;
mod defer;
mod dispatcher;
mod embedder;
mod http;
mod idgen;
mod inbound_mail;
mod kv;
mod mailer;
mod payments;
mod push;
mod rate_limiter;
mod realtime;
pub(crate) mod signer;
mod speech;
mod text_model;
mod tracker;
mod url_safety;
mod vector_index;

pub use actor::{
    ACTOR_CALL_TIMEOUT, ActorContext, ActorError, ActorHandler, ActorHandlers, ActorStore,
    ActorWrites, Actors, MAX_ACTOR_KEY_BYTES, MAX_ACTOR_KIND_BYTES, MAX_ACTOR_MESSAGE_BYTES,
    MAX_ACTOR_REPLY_BYTES, MAX_ACTOR_VALUE_BYTES, ScopedActors, check_actor_call, run_actor_alarm,
    run_actor_message, validate_actor_key, validate_actor_kind,
};
pub use auth::{Auth, AuthError, Caller, Subject, Unconfigured};
pub use blob::{
    Blob, BlobError, BlobMeta, BlobObject, BlobPage, BlobStream, DEFAULT_PRESIGN_TTL,
    MAX_BLOB_BYTES, MAX_LARGE_BLOB_BYTES, MAX_LIST_LIMIT, MAX_MULTIPART_PARTS, MAX_PRESIGN_TTL,
    MIN_MULTIPART_PART_BYTES, PartReceipt, PendingUpload, PresignedPut, ScopedBlob, UploadId,
    blob_error_from_stream, check_blob_size, check_part_number, limit_stream,
};
pub use captcha::{Captcha, CaptchaBinding, CaptchaError, Verdict};
pub use classifier::{
    Answer, AnswerValue, Calibration, Classifier, ClassifierError, ClassifierProfile,
    DEFAULT_MAX_STATE_CHARS, Question, validate_questions,
};
pub use clock::{Clock, SystemClock, timeout};
pub use custom_hostnames::{
    CertificateStatus, CustomHostname, CustomHostnameError, CustomHostnames, DnsRecordType,
    HostnameClaim, HostnameRefusal, ProviderStatus, Validation, ValidationMethod, check_hostname,
};
pub use database::{Database, DbError, Row, Rows, Statement, TryFromValue};
pub use defer::{Defer, NoopDefer};
pub use dispatcher::{DispatchError, Dispatcher};
pub use embedder::{EmbedError, Embedder, Embeddings};
pub use http::{
    BoundedHttpClient, ByteStream, DEFAULT_RESPONSE_TIMEOUT, DEFAULT_STREAM_IDLE_TIMEOUT,
    DEFAULT_STREAM_TOTAL_TIMEOUT, HttpClient, HttpError, HttpPolicy, MAX_CONCURRENT_REQUESTS,
    MAX_RESPONSE_BYTES, MAX_RESPONSE_TIMEOUT, MAX_STREAM_BYTES, MAX_STREAM_IDLE_TIMEOUT,
    MAX_STREAM_TOTAL_TIMEOUT, StatusOnly, StreamPolicy, declared_content_length,
};
pub use idgen::{IdGen, UlidIdGen};
pub use inbound_mail::{InboundMailError, InboundMailSource, InboundMessage, receive_mail};
pub use kv::{KeyValue, KvError};
pub use mailer::{MailError, MailProvider, Mailer, Message, SendOutcome};
pub use payments::{
    Charge, CheckoutRequest, CheckoutSession, ConnectAccountLink, ConnectAccountLinkRequest,
    Dispute, DisputeListRequest, DisputePage, DisputePhase, DisputeStatus, LineItem, Money,
    Payments, PaymentsError, PortalSession, PortalSessionRequest, Refund, RefundRequest,
    Subscription, SubscriptionCheckoutRequest, SubscriptionStatus, TransferCharge, UsageReport,
    UsageReported, WebhookEvent,
};
pub use push::{
    LocKeys, Notification, Platform, Priority, Push, PushError, PushOutcome, Recipient,
    RoutingPush, retry_after, ttl_secs,
};
pub use rate_limiter::{Decision, Quota, RateLimitError, RateLimiter};
pub use realtime::{Member, Realtime, RealtimeError, RoomContext, RoomHandler};
pub use signer::{Kid, MAX_KID_NAME, Payload, SignatureError, Signer};
pub use speech::{
    AudioFormat, DEFAULT_MAX_AUDIO_BYTES, DEFAULT_MAX_AUDIO_SECONDS, DEFAULT_MAX_SYNTHESIS_CHARS,
    NotConfiguredSpeech, Speech, SpeechCapabilities, SpeechError, SpeechLimit, SpeechLimits,
    SpeechUsage, Synthesis, SynthesizeRequest, TranscribeRequest, Transcript, Voice, WordTiming,
    check_synthesize, check_transcribe, primary_subtag, wav_duration,
};
pub use text_model::{
    Capability, Completion, CompletionBuilder, DEFAULT_MAX_TOKENS, FinishReason, ImageLimit,
    ImageMediaType, MAX_IMAGE_ENCODED_BYTES, MAX_PROMPT_IMAGE_ENCODED_BYTES, MAX_PROMPT_IMAGES,
    ModelTier, Part, Prompt, Role, RoutingTextModel, TextDelta, TextModel, TextModelError,
    ToolCall, ToolChoice, ToolResult, ToolSpec, Turn, completion_deltas, encode_image,
    encoded_image_len, stream_owned,
};
pub use tracker::{
    Credential, Destination, Filed, InboundStatusError, RoutingTracker, Severity, StatusUpdate,
    StatusWebhook, TicketComment, TicketDraft, TicketState, TicketStatus, Tracker, TrackerError,
    receive_status,
};
pub use url_safety::{
    CachedUrlSafety, DEFAULT_CACHE_CAPACITY, DEFAULT_MAX_BATCH, DEFAULT_MAX_URL_LEN,
    DEFAULT_NEGATIVE_TTL, ThreatType, UrlSafety, UrlSafetyError, UrlSafetyLimit, UrlSafetyLimits,
    UrlSafetySource, UrlVerdict, check_batch, check_url,
};
pub use vector_index::{
    ExactVectorIndex, MAX_NAMESPACE_BYTES, VectorFilter, VectorIndex, VectorIndexError,
    VectorMatch, VectorNamespace, VectorRecord,
};

use crate::config::Config;
use crate::module::Module;
use std::sync::Arc;
use tracing::warn;

/// Every port a module can declare in `requires()` / `optional()`
/// (architecture section 4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Port {
    Db,
    Auth,
    Mailer,
    Captcha,
    RateLimiter,
    Signer,
    KeyValue,
    Blob,
    Push,
    Payments,
    Tracker,
    Realtime,
    TextModel,
    Classifier,
    VectorIndex,
    Embedder,
    CustomHostnames,
    /// Whether a URL is safe to fetch (issue #857): malware, social
    /// engineering and unwanted-software verdicts by capability, never
    /// by vendor.
    UrlSafety,
    HttpClient,
    Clock,
    IdGen,
    Defer,
    /// Per-key serialized state with transactional storage and an alarm
    /// (issue #583): the durable-object pattern behind one runtime-neutral
    /// trait.
    Actor,
}

/// Declares [`Port::ALL`] and, from the same list, a match that has to be
/// exhaustive.
///
/// `ALL` is walked by [`Ports::provides`], so a variant missing from it
/// is a port no bundle ever reports — which is exactly the bug that left
/// `Port::Auth` out of `provides` when that was fifteen hand-written
/// branches. Writing the list twice is what made it possible; writing it
/// once is what stops it.
///
/// `#[non_exhaustive]` does not make an in-crate match non-exhaustive, so
/// the check is real here even though a downstream `match` on `Port`
/// needs a wildcard.
macro_rules! ports {
    ($($variant:ident),+ $(,)?) => {
        impl Port {
            /// Every port.
            pub const ALL: &'static [Port] = &[$(Port::$variant),+];
        }

        /// Never called. It exists so that a variant absent from the list
        /// above is a compile error here.
        #[expect(dead_code, reason = "its only job is to be exhaustive")]
        fn every_port_is_in_all(port: Port) {
            match port {
                $(Port::$variant => {}),+
            }
        }
    };
}

ports!(
    Db,
    Auth,
    Mailer,
    Captcha,
    RateLimiter,
    Signer,
    KeyValue,
    Blob,
    Push,
    Payments,
    Tracker,
    Realtime,
    TextModel,
    Classifier,
    VectorIndex,
    Embedder,
    CustomHostnames,
    UrlSafety,
    HttpClient,
    Clock,
    IdGen,
    Defer,
    Actor,
);

impl Port {
    pub fn name(&self) -> &'static str {
        match self {
            Port::Db => "Database",
            Port::Auth => "Auth",
            Port::Mailer => "Mailer",
            Port::Captcha => "Captcha",
            Port::RateLimiter => "RateLimiter",
            Port::Signer => "Signer",
            Port::KeyValue => "KeyValue",
            Port::Blob => "Blob",
            Port::Push => "Push",
            Port::Payments => "Payments",
            Port::Tracker => "Tracker",
            Port::Realtime => "Realtime",
            Port::TextModel => "TextModel",
            Port::Classifier => "Classifier",
            Port::VectorIndex => "vector_index",
            Port::Embedder => "embedder",
            Port::CustomHostnames => "custom_hostnames",
            Port::UrlSafety => "url_safety",
            Port::HttpClient => "HttpClient",
            Port::Clock => "Clock",
            Port::IdGen => "IdGen",
            Port::Defer => "Defer",
            Port::Actor => "actor",
        }
    }
}

/// The per-request bundle of resolved port implementations plus the typed
/// config the runtime built from environment/secrets.
///
/// Every port is optional: the Cloudflare runtime resolves what the venture's
/// bindings actually provide and leaves the rest `None`.
pub struct Ports {
    pub config: Arc<dyn Config>,
    pub db: Option<Arc<dyn Database>>,
    /// Who a request's credentials speak for (issue #153). `None` is a
    /// deployment that cannot identify a caller at all; a module needing
    /// one declares [`Port::Auth`] and is refused composition here.
    pub auth: Option<Arc<dyn Auth>>,
    pub mailer: Option<Arc<dyn Mailer>>,
    pub captcha: Option<Arc<dyn Captcha>>,
    pub rate_limiter: Option<Arc<dyn RateLimiter>>,
    pub signer: Option<Arc<dyn Signer>>,
    pub kv: Option<Arc<dyn KeyValue>>,
    pub blob: Option<Arc<dyn Blob>>,
    pub push: Option<Arc<dyn Push>>,
    pub payments: Option<Arc<dyn Payments>>,
    pub tracker: Option<Arc<dyn Tracker>>,
    pub realtime: Option<Arc<dyn Realtime>>,
    /// A text completion by [`ModelTier`](crate::ModelTier), never by
    /// vendor (issue #429).
    pub text_model: Option<Arc<dyn TextModel>>,
    /// A typed, calibrated decision by a set of
    /// [`Question`](crate::Question)s, never by vendor (issue #456) —
    /// the sibling of `text_model`.
    pub classifier: Option<Arc<dyn Classifier>>,
    /// Nearest-neighbour search over tenant-scoped namespaces (issue
    /// #561), the output side of embeddings, as `text_model` is.
    pub vector_index: Option<Arc<dyn VectorIndex>>,
    /// Text into embedding vectors (issue #561), the input side of
    /// [`Ports::vector_index`].
    pub embedder: Option<Arc<dyn Embedder>>,
    /// Custom hostnames a customer owns, served by a venture (issue
    /// #590) — Cloudflare for `SaaS` behind the same trait on every
    /// runtime.
    pub custom_hostnames: Option<Arc<dyn CustomHostnames>>,
    /// Whether a URL is safe to fetch (issue #857), the read side of
    /// link generation, as `captcha` is of form posts.
    pub url_safety: Option<Arc<dyn UrlSafety>>,
    pub http: Option<Arc<dyn HttpClient>>,
    pub clock: Option<Arc<dyn Clock>>,
    pub id_gen: Option<Arc<dyn IdGen>>,
    pub defer: Option<Arc<dyn Defer>>,
    /// Per-key serialized state with transactional storage and an alarm
    /// (issue #583). The harness wraps it in a [`ScopedActors`] per module,
    /// so a module only reaches the kinds it declared.
    pub actors: Option<Arc<dyn Actors>>,
    /// Set by the runtime when the venture mounts sidecar modules. Not a
    /// [`Port`], so `view_for` never copies it and no module can reach it.
    pub dispatcher: Option<Arc<dyn Dispatcher>>,
    /// How this deployment turns a host into a tenant, and a tenant into
    /// its database (TENANT-ROUTING.md §3-§5). `None` is the *no registry*
    /// deployment — Cloudflare, the browser, and native in development and
    /// test — which resolves every host to the implicit tenant and hands
    /// back [`Ports::db`].
    ///
    /// Not a [`Port`] for the same reason `dispatcher` is not: `view_for`
    /// must never copy it into a module's view. A module reaches a
    /// database through the `TenantConn` extractor, which can only give it
    /// the one the request resolved.
    pub tenants: Option<Arc<dyn crate::tenant::TenantRouting>>,
}

impl Ports {
    /// An empty bundle with no ports resolved and an
    /// [`EmptyConfig`](crate::config::EmptyConfig).
    pub fn empty() -> Self {
        Self::with_config(Arc::new(crate::config::EmptyConfig))
    }

    pub fn with_config(config: Arc<dyn Config>) -> Self {
        Self {
            config,
            db: None,
            auth: None,
            mailer: None,
            captcha: None,
            rate_limiter: None,
            signer: None,
            kv: None,
            blob: None,
            push: None,
            payments: None,
            tracker: None,
            realtime: None,
            text_model: None,
            classifier: None,
            vector_index: None,
            embedder: None,
            custom_hostnames: None,
            url_safety: None,
            http: None,
            clock: None,
            id_gen: None,
            defer: None,
            actors: None,
            dispatcher: None,
            tenants: None,
        }
    }

    /// The set of ports this bundle actually provides.
    ///
    /// Walks [`Port::ALL`] and asks [`Self::has`], so a variant added to
    /// the enum cannot be left out of the answer: the match in `has` is
    /// exhaustive and the compiler refuses a new one until it is
    /// handled. Written out as fifteen `if`s, it had already lost one —
    /// `Port::Auth` was missing, so this reported fourteen of fifteen
    /// and a bundle with a verifier wired said it had none.
    #[must_use]
    pub fn provides(&self) -> Vec<Port> {
        Port::ALL
            .iter()
            .copied()
            .filter(|port| self.has(*port))
            .collect()
    }

    /// Whether one port is wired in this bundle.
    ///
    /// The exhaustive match is the point. `dispatcher` and `tenants` are
    /// deliberately absent from [`Port`] — no module may reach either —
    /// so they have nothing to answer here.
    #[must_use]
    pub fn has(&self, port: Port) -> bool {
        match port {
            Port::Db => self.db.is_some(),
            Port::Auth => self.auth.is_some(),
            Port::Mailer => self.mailer.is_some(),
            Port::Captcha => self.captcha.is_some(),
            Port::RateLimiter => self.rate_limiter.is_some(),
            Port::Signer => self.signer.is_some(),
            Port::KeyValue => self.kv.is_some(),
            Port::Blob => self.blob.is_some(),
            Port::Push => self.push.is_some(),
            Port::Payments => self.payments.is_some(),
            Port::Tracker => self.tracker.is_some(),
            Port::Realtime => self.realtime.is_some(),
            Port::TextModel => self.text_model.is_some(),
            Port::Classifier => self.classifier.is_some(),
            Port::VectorIndex => self.vector_index.is_some(),
            Port::Embedder => self.embedder.is_some(),
            Port::CustomHostnames => self.custom_hostnames.is_some(),
            Port::UrlSafety => self.url_safety.is_some(),
            Port::HttpClient => self.http.is_some(),
            Port::Clock => self.clock.is_some(),
            Port::IdGen => self.id_gen.is_some(),
            Port::Defer => self.defer.is_some(),
            Port::Actor => self.actors.is_some(),
        }
    }

    /// A copy of this bundle in which every port the module did not declare
    /// in `requires()` or `optional()` is `None`, so a module cannot use
    /// what it did not declare (issue #3). Undeclared-but-provided ports are
    /// logged once per module by `Harness::build`.
    #[must_use]
    pub fn view_for(&self, module: &dyn Module) -> Self {
        let declared = module
            .requires()
            .iter()
            .chain(module.optional())
            .copied()
            .collect::<Vec<_>>();
        let allows = |p: &[Port], port: Port| p.contains(&port);
        let mut view = Ports::with_config(self.config.clone());
        if allows(&declared, Port::Db) {
            view.db.clone_from(&self.db);
        }
        if allows(&declared, Port::Auth) {
            view.auth.clone_from(&self.auth);
        }
        if allows(&declared, Port::Mailer) {
            view.mailer.clone_from(&self.mailer);
        }
        if allows(&declared, Port::Captcha) {
            view.captcha.clone_from(&self.captcha);
        }
        if allows(&declared, Port::RateLimiter) {
            view.rate_limiter.clone_from(&self.rate_limiter);
        }
        if allows(&declared, Port::Signer) {
            view.signer.clone_from(&self.signer);
        }
        if allows(&declared, Port::KeyValue) {
            view.kv.clone_from(&self.kv);
        }
        if allows(&declared, Port::Blob) {
            // Scope the store to this module's prefix, the blob equivalent of
            // the table-ownership rule: a module cannot name another's objects.
            // The module's declared large-object ceiling rides along, enforced
            // on the streamed and multipart writes (issue #586).
            view.blob = self.blob.as_ref().map(|blob| {
                Arc::new(
                    ScopedBlob::new(Arc::clone(blob), module.name())
                        .with_max_object_bytes(module.max_blob_object_bytes()),
                ) as Arc<dyn Blob>
            });
        }
        if allows(&declared, Port::Push) {
            view.push.clone_from(&self.push);
        }
        if allows(&declared, Port::Payments) {
            view.payments.clone_from(&self.payments);
        }
        if allows(&declared, Port::Tracker) {
            view.tracker.clone_from(&self.tracker);
        }
        if allows(&declared, Port::Realtime) {
            view.realtime.clone_from(&self.realtime);
        }
        if allows(&declared, Port::TextModel) {
            view.text_model.clone_from(&self.text_model);
        }
        if allows(&declared, Port::Classifier) {
            view.classifier.clone_from(&self.classifier);
        }
        if allows(&declared, Port::VectorIndex) {
            view.vector_index.clone_from(&self.vector_index);
        }
        if allows(&declared, Port::Embedder) {
            view.embedder.clone_from(&self.embedder);
        }
        if allows(&declared, Port::CustomHostnames) {
            view.custom_hostnames.clone_from(&self.custom_hostnames);
        }
        if allows(&declared, Port::UrlSafety) {
            view.url_safety.clone_from(&self.url_safety);
        }
        if allows(&declared, Port::HttpClient) {
            view.http.clone_from(&self.http);
        }
        if allows(&declared, Port::Clock) {
            view.clock.clone_from(&self.clock);
        }
        if allows(&declared, Port::IdGen) {
            view.id_gen.clone_from(&self.id_gen);
        }
        if allows(&declared, Port::Defer) {
            view.defer.clone_from(&self.defer);
        }
        if allows(&declared, Port::Actor) {
            // Scope the host to this module's declared kinds, the actor
            // equivalent of the table-ownership rule.
            view.actors = self.actors.as_ref().map(|actors| {
                Arc::new(ScopedActors::new(
                    Arc::clone(actors),
                    module.name(),
                    module.actor_kinds(),
                    self.clock.clone(),
                )) as Arc<dyn Actors>
            });
        }
        view
    }
}

/// Log (once, at `Harness::build`) the provided ports a module did not
/// declare — the ports `view_for` will hide from it.
pub(crate) fn warn_undeclared_ports(module: &dyn Module, provided: &[Port]) {
    for port in provided {
        if !module.requires().contains(port) && !module.optional().contains(port) {
            warn!(
                module = module.name(),
                port = port.name(),
                "runtime provides a port the module did not declare; hiding it",
            );
        }
    }
}