coil-runtime 0.1.1

HTTP runtime and request handling for the Coil framework.
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
use super::*;
use crate::builder::CustomerHookSet;
use coil_assets::ActiveAssetManifest;
use coil_storage::execution::ObjectStoreClientConfig;
use std::fmt;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use url::Url;

mod execution;
mod shared_state;
#[cfg(test)]
mod testing;

pub(crate) use shared_state::shared_state_root;
#[cfg(test)]
pub(crate) use testing::{shared_cache_runtime_for_test, shared_jobs_runtime_for_test};

#[derive(Clone)]
pub(crate) struct SharedJobsRuntimeHandle {
    namespace: String,
    runtime: Arc<OnceLock<Result<Arc<dyn coil_jobs::JobsCoordinationRuntime>, String>>>,
}

impl SharedJobsRuntimeHandle {
    pub(crate) fn new(namespace: impl Into<String>) -> Self {
        Self {
            namespace: namespace.into(),
            runtime: Arc::new(OnceLock::new()),
        }
    }

    pub(crate) fn get_or_init(
        &self,
        runtime: &JobsRuntimeServices,
    ) -> Result<Arc<dyn coil_jobs::JobsCoordinationRuntime>, RuntimeJobsError> {
        let namespace = self.namespace.clone();
        self.runtime
            .get_or_init(|| shared_jobs_runtime(runtime, namespace.clone()))
            .clone()
            .map_err(|error| {
                RuntimeJobsError::Jobs(JobsModelError::LiveSharedBackendRequiresExplicitRuntime {
                    backend: runtime.backend,
                    namespace: error,
                })
            })
    }
}

impl fmt::Debug for SharedJobsRuntimeHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedJobsRuntimeHandle")
            .field("namespace", &self.namespace)
            .field("initialized", &self.runtime.get().is_some())
            .finish()
    }
}

#[derive(Debug, Clone)]
pub struct RuntimePlan {
    pub config: PlatformConfig,
    pub auth_package_name: String,
    pub auth_package: AuthModelPackageSelection,
    pub approved_outbound_http_endpoints: BTreeMap<String, Url>,
    pub shared_backend_scope: String,
    pub shared_state_root: PathBuf,
    pub cache_topology: CacheTopology,
    pub cache_planner: CachePlanner,
    pub i18n: I18nRuntimeServices,
    pub seo: SeoRuntimeServices,
    pub browser: BrowserSecurityServices,
    pub cli: CliRuntimeServices,
    pub data: DataRuntimeServices,
    pub jobs: JobsRuntimeServices,
    pub observability: ObservabilityRuntimeServices,
    pub http: HttpRuntimePlan,
    pub handlers: BTreeMap<String, HandlerDefinition>,
    pub storage_planner: StoragePlanner,
    pub storefront_catalog: StorefrontCatalog,
    pub theme_asset_manifest: Option<ActiveAssetManifest>,
    pub template: TemplateRuntimeServices,
    pub tls: TlsRuntimeServices,
    pub wasm: WasmRuntimeServices,
    pub services: Vec<ServiceDescriptor>,
    pub modules: Vec<ModuleManifest>,
    pub install_migrations: MigrationPlan,
    pub extension_registry: ExtensionRegistry,
    pub registered_extension_slots: Vec<RegisteredExtensionSlot>,
    pub installed_extensions: Vec<InstalledExtensionSummary>,
    pub linked_customer_plugins: Vec<LinkedCustomerPluginSummary>,
    pub(crate) customer_hooks: CustomerHookSet,
    pub(crate) shared_jobs_runtime: SharedJobsRuntimeHandle,
    pub module_jobs: Vec<RegisteredModuleJob>,
    pub module_event_subscriptions: Vec<RegisteredEventSubscription>,
    pub module_data_repositories: Vec<RegisteredDataRepository>,
    pub module_search_contributions: Vec<RegisteredSearchContribution>,
    pub module_report_definitions: Vec<RegisteredReportDefinition>,
    pub module_bulk_operations: Vec<RegisteredBulkOperation>,
    pub registered_runtime_jobs: Vec<RuntimeJobDefinition>,
    pub registered_runtime_event_subscriptions: Vec<RuntimeEventSubscriptionDefinition>,
    pub jobs_domain: JobsDomain,
    pub ops_catalog: OpsCatalog,
}

#[derive(Debug, Clone)]
pub(crate) enum MetadataAuditBackendSelection {
    LocalSqlite {
        root: std::path::PathBuf,
        namespace: String,
    },
    SharedPostgres {
        runtime: coil_data::DataRuntime,
    },
}

impl RuntimePlan {
    pub fn auth_package(&self) -> &dyn AuthModelPackage {
        self.auth_package.package()
    }

    pub(crate) fn metadata_audit_backend_selection(&self) -> MetadataAuditBackendSelection {
        match self.config.storage.deployment {
            coil_config::StorageDeployment::Distributed => {
                MetadataAuditBackendSelection::SharedPostgres {
                    runtime: self.data.clone(),
                }
            }
            coil_config::StorageDeployment::SingleNode => {
                MetadataAuditBackendSelection::LocalSqlite {
                    root: std::path::PathBuf::from(&self.config.storage.local_root),
                    namespace: self.shared_backend_namespace(),
                }
            }
        }
    }

    pub fn approved_outbound_http_endpoints(&self) -> &BTreeMap<String, Url> {
        &self.approved_outbound_http_endpoints
    }

    pub fn tenant_id(&self) -> i64 {
        self.config.auth.tenant_id
    }

    pub fn jobs_host(
        &self,
        scheduler_node_id: impl Into<String>,
    ) -> Result<JobsHost, RuntimeJobsError> {
        let scheduler_node_id =
            validate_runtime_identifier("scheduler_node_id", scheduler_node_id.into())?;
        let namespace = self.shared_backend_namespace();
        let shared_runtime = self.shared_jobs_runtime.get_or_init(&self.jobs)?;
        Ok(JobsHost::new(
            self.config.app.name.clone(),
            scheduler_node_id,
            self.jobs.clone(),
            self.observability.telemetry.clone(),
            self.jobs.describe().clone(),
            self.registered_runtime_jobs.clone(),
            self.registered_runtime_event_subscriptions.clone(),
            self.jobs_domain.clone(),
            shared_runtime,
            namespace,
        ))
    }

    pub fn ops_host(
        &self,
        scheduler_node_id: impl Into<String>,
    ) -> Result<OpsHost, RuntimeOpsError> {
        Ok(OpsHost::new(
            OpsPlanner::new(self.jobs.clone(), self.ops_catalog.clone())?,
            self.jobs_host(scheduler_node_id)?,
        ))
    }

    pub fn search_host(
        &self,
        scheduler_node_id: impl Into<String>,
    ) -> Result<SearchHost, RuntimeSearchError> {
        Ok(SearchHost::new(
            self.ops_catalog.search.clone(),
            self.ops_host(scheduler_node_id)?,
        ))
    }

    pub fn cache_host(&self) -> Result<CacheHost, RuntimeCacheError> {
        let namespace = self.cache_namespace()?;
        let shared_namespace = self.shared_backend_namespace();
        if self.cache_planner.topology().supports_shared_invalidation() {
            #[cfg(test)]
            {
                let backend = match self
                    .cache_planner
                    .topology()
                    .l2()
                    .expect("shared cache runtime requires distributed l2")
                {
                    coil_cache::DistributedCacheBackend::Redis => {
                        coil_cache::CacheBackendKind::Redis
                    }
                    coil_cache::DistributedCacheBackend::Valkey => {
                        coil_cache::CacheBackendKind::Valkey
                    }
                };
                let runtime = shared_cache_runtime_for_test(backend, shared_namespace.clone());
                return Ok(CacheHost::new(
                    self.config.app.name.clone(),
                    namespace,
                    self.cache_planner,
                    Some(runtime),
                    shared_namespace,
                ));
            }

            #[cfg(not(test))]
            {
                let backend = match self
                    .cache_planner
                    .topology()
                    .l2()
                    .expect("shared cache runtime requires distributed l2")
                {
                    coil_cache::DistributedCacheBackend::Redis => {
                        coil_cache::CacheBackendKind::Redis
                    }
                    coil_cache::DistributedCacheBackend::Valkey => {
                        coil_cache::CacheBackendKind::Valkey
                    }
                };
                let runtime = shared_cache_runtime(backend, shared_namespace.clone());
                return Ok(CacheHost::new(
                    self.config.app.name.clone(),
                    namespace,
                    self.cache_planner,
                    Some(runtime),
                    shared_namespace,
                ));
            }
        }

        Ok(CacheHost::new(
            self.config.app.name.clone(),
            namespace,
            self.cache_planner,
            None,
            shared_namespace,
        ))
    }

    #[cfg(test)]
    pub fn browser_host(&self) -> Result<BrowserHost, BrowserHostBuildError> {
        BrowserHost::new_with_scope(
            self.config.app.name.clone(),
            self.browser.clone(),
            self.shared_backend_scope.clone(),
        )
    }

    pub fn tls_host(&self) -> Result<TlsHost, RuntimeTlsError> {
        self.tls_host_with_secret_resolver(&crate::server::EnvironmentSecretResolver)
    }

    pub fn tls_host_with_secret_resolver<R: crate::server::SecretResolver>(
        &self,
        resolver: &R,
    ) -> Result<TlsHost, RuntimeTlsError> {
        let account_secret = self
            .config
            .tls
            .account_secret
            .as_ref()
            .map(|secret| resolver.resolve(secret))
            .transpose()?;
        TlsHost::new(
            self.config.app.name.clone(),
            self.tls.clone(),
            self.data.clone(),
            self.shared_backend_scope.clone(),
            account_secret,
        )
    }

    pub fn tls_validation_host_with_secret_resolver<R: crate::server::SecretResolver>(
        &self,
        resolver: &R,
    ) -> Result<TlsHost, RuntimeTlsError> {
        let account_secret = self
            .config
            .tls
            .account_secret
            .as_ref()
            .map(|secret| resolver.resolve(secret))
            .transpose()?;
        TlsHost::new_for_validation(
            self.config.app.name.clone(),
            self.tls.clone(),
            self.shared_backend_scope.clone(),
            account_secret,
        )
    }

    pub fn storage_host(&self) -> StorageHost {
        self.storage_host_with_object_store(None)
    }

    pub fn storage_host_with_object_store(
        &self,
        object_store: Option<ObjectStoreClientConfig>,
    ) -> StorageHost {
        StorageHost::new(
            self.config.app.name.clone(),
            self.storage_planner.clone(),
            self.config.assets.cdn_base_url.clone(),
            object_store,
        )
    }

    pub fn wasm_host(&self) -> WasmHost {
        WasmHost::new(
            self.clone(),
            self.config.app.name.clone(),
            self.wasm.clone(),
            self.extension_registry.clone(),
            self.config.i18n.default_locale.clone(),
            self.registered_runtime_jobs.clone(),
        )
    }

    pub fn wasm_host_with_secret_resolver<R: SecretResolver>(
        &self,
        resolver: &R,
    ) -> Result<WasmHost, RuntimeServerError> {
        let wasm_secrets = self.wasm_secret_values(resolver)?;
        let storage_host =
            self.storage_host_with_object_store(self.object_store_client_config(resolver)?);
        Ok(WasmHost::with_host_services(
            self.clone(),
            self.config.app.name.clone(),
            self.wasm.clone(),
            self.extension_registry.clone(),
            self.config.i18n.default_locale.clone(),
            self.registered_runtime_jobs.clone(),
            RuntimeWasmHostServices::with_runtime_secrets(self.clone(), storage_host, wasm_secrets),
        ))
    }

    pub fn wasm_secret_values<R: SecretResolver>(
        &self,
        resolver: &R,
    ) -> Result<BTreeMap<String, String>, RuntimeServerError> {
        self.config
            .wasm
            .secret_bindings
            .iter()
            .map(|(name, secret)| {
                resolver
                    .resolve(secret)
                    .map(|value| (name.clone(), value))
                    .map_err(|error| RuntimeServerError::Secret(error))
            })
            .collect()
    }

    pub fn shared_backend_clients<R: SecretResolver>(
        &self,
        resolver: &R,
    ) -> Result<SharedBackendClients, RuntimeServerError> {
        Ok(SharedBackendClients::from_config(&self.config, resolver)?)
    }

    pub fn object_store_client_config<R: SecretResolver>(
        &self,
        resolver: &R,
    ) -> Result<Option<ObjectStoreClientConfig>, RuntimeServerError> {
        Ok(SharedBackendClients::object_store_client_config(
            &self.config,
            resolver,
        )?)
    }

    pub fn server_host<R: SecretResolver>(
        &self,
        resolver: &R,
        cookie_secret: &[u8],
        csrf_secret: &[u8],
    ) -> Result<HttpServerHost, RuntimeServerError> {
        if self.browser.sessions.store == coil_core::SessionStoreTopology::Memory {
            return Err(BrowserHostBuildError::MemoryStoreRequiresTestOnlyBrowserHost.into());
        }

        let wasm_secrets = self.wasm_secret_values(resolver)?;
        let payment_webhook_secret =
            crate::server::resolve_commerce_payment_webhook_secret(&self.config, resolver)?;
        HttpServerHost::new(
            self.clone(),
            self.shared_backend_clients(resolver)?,
            wasm_secrets,
            payment_webhook_secret,
            cookie_secret.to_vec(),
            csrf_secret.to_vec(),
        )
    }

    #[cfg(test)]
    pub(crate) fn server_host_with_checkout_client<R: SecretResolver>(
        &self,
        resolver: &R,
        cookie_secret: &[u8],
        csrf_secret: &[u8],
        hosted_checkout_client: std::sync::Arc<dyn crate::server::HostedCheckoutClient>,
    ) -> Result<HttpServerHost, RuntimeServerError> {
        if self.browser.sessions.store == coil_core::SessionStoreTopology::Memory {
            return Err(BrowserHostBuildError::MemoryStoreRequiresTestOnlyBrowserHost.into());
        }

        let wasm_secrets = self.wasm_secret_values(resolver)?;
        let payment_webhook_secret =
            crate::server::resolve_commerce_payment_webhook_secret(&self.config, resolver)?;
        HttpServerHost::new_with_checkout_client(
            self.clone(),
            self.shared_backend_clients(resolver)?,
            wasm_secrets,
            payment_webhook_secret,
            cookie_secret.to_vec(),
            csrf_secret.to_vec(),
            hosted_checkout_client,
        )
    }

    pub fn serve_from_env(
        self,
        bind_override: Option<String>,
    ) -> Result<(), RuntimeBootstrapError> {
        let cookie_secret = required_env_bytes("COIL_COOKIE_SECRET")?;
        let csrf_secret = required_env_bytes("COIL_CSRF_SECRET")?;
        let bind = bind_override.unwrap_or_else(|| self.config.server.bind.clone());
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .map_err(|error| RuntimeBootstrapError::Serve {
                reason: error.to_string(),
            })?;
        let server = {
            let _runtime_guard = runtime.enter();
            self.server_host(
                &crate::server::EnvironmentSecretResolver,
                &cookie_secret,
                &csrf_secret,
            )?
        };

        runtime.block_on(async move {
            let listener = tokio::net::TcpListener::bind(&bind)
                .await
                .map_err(|error| RuntimeBootstrapError::Bind {
                    bind: bind.clone(),
                    reason: error.to_string(),
                })?;
            server
                .serve(listener)
                .await
                .map_err(|error| RuntimeBootstrapError::Serve {
                    reason: error.to_string(),
                })
        })
    }

    pub(crate) fn cache_namespace(&self) -> Result<CacheNamespace, CacheModelError> {
        CacheNamespace::new(format!("customer-app:{}", self.config.app.name))
    }

    pub(crate) fn shared_backend_namespace(&self) -> String {
        format!(
            "customer-app:{}:{}",
            self.config.app.name, self.shared_backend_scope
        )
    }

    pub(crate) fn shared_state_root(&self) -> &PathBuf {
        &self.shared_state_root
    }
}

#[cfg(test)]
fn shared_jobs_runtime(
    runtime: &JobsRuntimeServices,
    namespace: String,
) -> Result<Arc<dyn coil_jobs::JobsCoordinationRuntime>, String> {
    Ok(crate::plan::shared_jobs_runtime_for_test(
        runtime, namespace,
    ))
}

#[cfg(not(test))]
fn shared_jobs_runtime(
    runtime: &JobsRuntimeServices,
    namespace: String,
) -> Result<Arc<dyn coil_jobs::JobsCoordinationRuntime>, String> {
    if use_emulated_shared_backends() {
        return Ok(emulated_shared_jobs_runtime(runtime, namespace));
    }
    coil_jobs::JobsBackendAdapter::live_shared_runtime(runtime, namespace, PathBuf::new())
        .map_err(|error| error.to_string())
}

#[cfg(test)]
fn shared_cache_runtime(
    backend: coil_cache::CacheBackendKind,
    namespace: String,
) -> Arc<dyn coil_cache::DistributedCacheRuntime> {
    crate::plan::shared_cache_runtime_for_test(backend, namespace)
}

#[cfg(not(test))]
fn shared_cache_runtime(
    backend: coil_cache::CacheBackendKind,
    namespace: String,
) -> Arc<dyn coil_cache::DistributedCacheRuntime> {
    if use_emulated_shared_backends() {
        return emulated_shared_cache_runtime(backend, namespace);
    }
    coil_cache::DistributedCacheClient::live_shared_runtime(backend, namespace, PathBuf::new())
}

fn use_emulated_shared_backends() -> bool {
    std::env::var("COIL_EMULATED_SHARED_BACKENDS")
        .map(|value| {
            let normalized = value.trim().to_ascii_lowercase();
            matches!(normalized.as_str(), "1" | "true" | "yes" | "on")
        })
        .unwrap_or(false)
}

#[cfg(not(test))]
fn emulated_shared_jobs_runtime(
    runtime: &JobsRuntimeServices,
    namespace: String,
) -> Arc<dyn coil_jobs::JobsCoordinationRuntime> {
    use std::collections::BTreeMap;
    use std::sync::{Mutex, OnceLock};

    static REGISTRY: OnceLock<
        Mutex<BTreeMap<String, Arc<dyn coil_jobs::JobsCoordinationRuntime>>>,
    > = OnceLock::new();

    let key = format!(
        "{:?}:{}:{}:{}:{}:{}",
        runtime.backend,
        runtime.topology.work_queue.as_str(),
        runtime.topology.scheduled_queue.as_str(),
        runtime.topology.domain_events_queue.as_str(),
        runtime.topology.dead_letter_queue.as_str(),
        namespace
    );
    let registry = REGISTRY.get_or_init(|| Mutex::new(BTreeMap::new()));
    let mut guard = registry.lock().expect("emulated jobs registry mutex poisoned");
    guard
        .entry(key)
        .or_insert_with(|| coil_jobs::JobsBackendAdapter::emulated_shared_runtime(runtime))
        .clone()
}

#[cfg(not(test))]
fn emulated_shared_cache_runtime(
    backend: coil_cache::CacheBackendKind,
    namespace: String,
) -> Arc<dyn coil_cache::DistributedCacheRuntime> {
    use std::collections::BTreeMap;
    use std::sync::{Mutex, OnceLock};

    static REGISTRY: OnceLock<
        Mutex<BTreeMap<String, Arc<dyn coil_cache::DistributedCacheRuntime>>>,
    > = OnceLock::new();

    let key = format!("{backend:?}:{namespace}");
    let registry = REGISTRY.get_or_init(|| Mutex::new(BTreeMap::new()));
    let mut guard = registry.lock().expect("emulated cache registry mutex poisoned");
    guard
        .entry(key)
        .or_insert_with(|| coil_cache::DistributedCacheClient::emulated_shared_runtime(backend))
        .clone()
}

fn required_env_bytes(name: &'static str) -> Result<Vec<u8>, RuntimeBootstrapError> {
    match std::env::var(name) {
        Ok(value) if !value.is_empty() => Ok(value.into_bytes()),
        _ => Err(RuntimeBootstrapError::MissingEnvironmentVariable { name }),
    }
}