Skip to main content

minco_plugin_realtime/
lib.rs

1//! Application-owned Minco plugin `realtime`.
2#![forbid(unsafe_code)]
3
4use async_trait::async_trait;
5use minco_core::{
6    CapabilityProvision, ConfigurationField, ConfigurationValueKind, IdleCostClass, Plugin,
7    PluginContext, PluginDescriptor, PluginError, PluginId, PluginStability, ResourceIntent,
8    ResourceKind, WakeSource,
9};
10use semver::{Version, VersionReq};
11use serde::{Deserialize, Serialize};
12use std::sync::{Arc, Mutex};
13
14pub const DEFAULT_MAX_EVENT_BYTES: usize = 5 * 1024;
15/// Dependency-free browser subscriber distributed with the crate archive.
16pub const REALTIME_CLIENT_MODULE: &str = include_str!("../assets/realtime-client.mjs");
17
18/// A provider-neutral realtime channel without a leading slash.
19#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub struct RealtimeChannel(String);
21
22impl RealtimeChannel {
23    pub fn parse(value: impl Into<String>) -> Result<Self, RealtimeError> {
24        let value = value.into();
25        let segments = value.split('/').collect::<Vec<_>>();
26        let valid = (1..=4).contains(&segments.len())
27            && segments.iter().all(|segment| {
28                (1..=50).contains(&segment.len())
29                    && segment
30                        .bytes()
31                        .next()
32                        .is_some_and(|byte| byte.is_ascii_alphanumeric())
33                    && segment
34                        .bytes()
35                        .next_back()
36                        .is_some_and(|byte| byte.is_ascii_alphanumeric())
37                    && segment
38                        .bytes()
39                        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
40            });
41        if !valid {
42            return Err(RealtimeError::InvalidChannel);
43        }
44        Ok(Self(value))
45    }
46
47    #[must_use]
48    pub fn as_str(&self) -> &str {
49        &self.0
50    }
51}
52
53#[derive(Debug, thiserror::Error, PartialEq, Eq)]
54pub enum RealtimeError {
55    #[error(
56        "realtime channel must contain one to four slash-separated AppSync-compatible segments of 1 to 50 bytes"
57    )]
58    InvalidChannel,
59    #[error("invalid realtime configuration: {0}")]
60    InvalidConfiguration(String),
61    #[error("realtime envelope is invalid: {0}")]
62    InvalidEnvelope(String),
63    #[error("realtime publication was rejected: {0}")]
64    Rejected(String),
65    #[error("realtime publication is temporarily unavailable: {0}")]
66    Unavailable(String),
67    #[error("realtime publication failed: {0}")]
68    Publish(String),
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(deny_unknown_fields)]
73pub struct RealtimeEnvelope {
74    pub id: String,
75    pub event_type: String,
76    pub occurred_at: String,
77    pub payload: serde_json::Value,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct RealtimePublication {
82    pub channel: RealtimeChannel,
83    pub envelope: RealtimeEnvelope,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(deny_unknown_fields)]
88pub struct RealtimePlan {
89    #[serde(default = "default_namespace")]
90    pub namespace: String,
91    #[serde(default = "default_max_event_bytes")]
92    pub max_event_bytes: usize,
93    #[serde(default = "default_subscriber_claim")]
94    pub subscriber_claim: String,
95}
96
97impl Default for RealtimePlan {
98    fn default() -> Self {
99        Self {
100            namespace: default_namespace(),
101            max_event_bytes: default_max_event_bytes(),
102            subscriber_claim: default_subscriber_claim(),
103        }
104    }
105}
106
107impl RealtimePlan {
108    pub fn validate(&self) -> Result<(), RealtimeError> {
109        let namespace = RealtimeChannel::parse(self.namespace.clone())?;
110        if namespace.as_str().contains('/') {
111            return Err(RealtimeError::InvalidConfiguration(
112                "namespace must be one portable channel segment".into(),
113            ));
114        }
115        if !namespace
116            .as_str()
117            .bytes()
118            .next()
119            .is_some_and(|byte| byte.is_ascii_alphanumeric())
120            || !namespace
121                .as_str()
122                .bytes()
123                .next_back()
124                .is_some_and(|byte| byte.is_ascii_alphanumeric())
125        {
126            return Err(RealtimeError::InvalidConfiguration(
127                "namespace must start and end with an ASCII alphanumeric character".into(),
128            ));
129        }
130        if !(256..=240 * 1024).contains(&self.max_event_bytes) {
131            return Err(RealtimeError::InvalidConfiguration(
132                "max_event_bytes must be between 256 and the AppSync Events 240 KiB limit".into(),
133            ));
134        }
135        if !(1..=128).contains(&self.subscriber_claim.len())
136            || !self.subscriber_claim.bytes().all(|byte| {
137                byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/')
138            })
139        {
140            return Err(RealtimeError::InvalidConfiguration(
141                "subscriber_claim must be a bounded OIDC claim name".into(),
142            ));
143        }
144        Ok(())
145    }
146}
147
148fn default_namespace() -> String {
149    "minco".into()
150}
151
152const fn default_max_event_bytes() -> usize {
153    DEFAULT_MAX_EVENT_BYTES
154}
155
156fn default_subscriber_claim() -> String {
157    "sub".into()
158}
159
160#[async_trait]
161pub trait RealtimePublisher: Send + Sync + std::fmt::Debug {
162    async fn publish(&self, publication: &RealtimePublication) -> Result<(), RealtimeError>;
163}
164
165#[derive(Clone)]
166pub struct RealtimePublisherService {
167    publisher: Arc<dyn RealtimePublisher>,
168    plan: RealtimePlan,
169}
170
171impl std::fmt::Debug for RealtimePublisherService {
172    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        formatter
174            .debug_struct("RealtimePublisherService")
175            .field("plan", &self.plan)
176            .finish_non_exhaustive()
177    }
178}
179
180impl RealtimePublisherService {
181    #[must_use]
182    pub fn new(publisher: Arc<dyn RealtimePublisher>, plan: RealtimePlan) -> Self {
183        Self { publisher, plan }
184    }
185
186    pub async fn publish(&self, publication: &RealtimePublication) -> Result<(), RealtimeError> {
187        self.plan.validate()?;
188        validate_publication(publication, self.plan.max_event_bytes)?;
189        self.publisher.publish(publication).await
190    }
191}
192
193fn validate_publication(
194    publication: &RealtimePublication,
195    max_event_bytes: usize,
196) -> Result<(), RealtimeError> {
197    if publication.envelope.id.trim().is_empty()
198        || publication.envelope.event_type.trim().is_empty()
199        || publication.envelope.occurred_at.trim().is_empty()
200    {
201        return Err(RealtimeError::InvalidEnvelope(
202            "id, event_type, and occurred_at are required".into(),
203        ));
204    }
205    let encoded = serde_json::to_vec(&publication.envelope)
206        .map_err(|error| RealtimeError::InvalidEnvelope(error.to_string()))?;
207    if encoded.len() > max_event_bytes {
208        return Err(RealtimeError::InvalidEnvelope(format!(
209            "encoded envelope is {} bytes; limit is {max_event_bytes}",
210            encoded.len()
211        )));
212    }
213    Ok(())
214}
215
216#[derive(Debug, Default)]
217pub struct MemoryRealtimePublisher {
218    publications: Mutex<Vec<RealtimePublication>>,
219}
220
221impl MemoryRealtimePublisher {
222    #[must_use]
223    pub fn published(&self) -> Vec<RealtimePublication> {
224        self.publications
225            .lock()
226            .unwrap_or_else(std::sync::PoisonError::into_inner)
227            .clone()
228    }
229}
230
231#[async_trait]
232impl RealtimePublisher for MemoryRealtimePublisher {
233    async fn publish(&self, publication: &RealtimePublication) -> Result<(), RealtimeError> {
234        self.publications
235            .lock()
236            .map_err(|_| RealtimeError::Publish("realtime memory lock was poisoned".into()))?
237            .push(publication.clone());
238        Ok(())
239    }
240}
241
242#[derive(Debug, Clone, Default)]
243pub struct RealtimePlugin {
244    publisher: Option<Arc<dyn RealtimePublisher>>,
245}
246
247impl RealtimePlugin {
248    #[must_use]
249    pub fn with_publisher(mut self, publisher: Arc<dyn RealtimePublisher>) -> Self {
250        self.publisher = Some(publisher);
251        self
252    }
253}
254
255impl Plugin for RealtimePlugin {
256    fn descriptor(&self) -> PluginDescriptor {
257        let mut descriptor = PluginDescriptor::new(
258            PluginId::new("realtime").expect("static plugin ID"),
259            Version::new(1, 0, 0),
260            "Subscriber-only realtime invalidation with backend-owned publication",
261        );
262        descriptor.documentation = Some("https://docs.rs/minco-plugin-realtime".into());
263        descriptor.core_compatibility =
264            VersionReq::parse(concat!("^", env!("CARGO_PKG_VERSION"))).expect("package version");
265        descriptor.stability = PluginStability::Beta;
266        descriptor.provides.push(CapabilityProvision {
267            name: "realtime.publish".into(),
268            version: Version::new(1, 0, 0),
269        });
270        descriptor.configuration = realtime_configuration_fields();
271        descriptor
272    }
273
274    fn configure_descriptor(
275        &self,
276        descriptor: &mut PluginDescriptor,
277        configuration: Option<&serde_json::Value>,
278    ) -> Result<(), PluginError> {
279        let plan = serde_json::from_value::<RealtimePlan>(
280            configuration
281                .cloned()
282                .unwrap_or_else(|| serde_json::json!({})),
283        )
284        .map_err(|source| PluginError::InvalidConfiguration {
285            plugin: descriptor.id.clone(),
286            source,
287        })?;
288        plan.validate()
289            .map_err(|error| PluginError::Installation(error.to_string()))?;
290        descriptor.resources.push(realtime_resource());
291        Ok(())
292    }
293
294    fn install(&self, context: &mut PluginContext<'_>) -> Result<(), PluginError> {
295        let plan = context.configuration::<RealtimePlan>()?;
296        plan.validate()
297            .map_err(|error| PluginError::Installation(error.to_string()))?;
298        context.services().insert(Arc::new(plan.clone()))?;
299        if let Some(publisher) = &self.publisher {
300            context
301                .services()
302                .insert(Arc::new(RealtimePublisherService::new(
303                    publisher.clone(),
304                    plan,
305                )))?;
306        }
307        Ok(())
308    }
309}
310
311fn realtime_resource() -> ResourceIntent {
312    ResourceIntent {
313        id: "realtime-api".into(),
314        kind: ResourceKind::Custom("realtime-event-api".into()),
315        idle_cost: IdleCostClass::ProviderManaged,
316        wake_sources: vec![WakeSource::HttpRequest],
317        dependencies: Vec::new(),
318    }
319}
320
321fn realtime_configuration_fields() -> Vec<ConfigurationField> {
322    vec![
323        ConfigurationField {
324            key: "namespace".into(),
325            kind: ConfigurationValueKind::String,
326            required: false,
327            secret: false,
328            description: "Portable namespace prepended to subscriber channels".into(),
329            default: Some(serde_json::json!(default_namespace())),
330        },
331        ConfigurationField {
332            key: "max_event_bytes".into(),
333            kind: ConfigurationValueKind::Integer,
334            required: false,
335            secret: false,
336            description: "Maximum encoded envelope size; 5120 bytes keeps one billing unit".into(),
337            default: Some(serde_json::json!(DEFAULT_MAX_EVENT_BYTES)),
338        },
339        ConfigurationField {
340            key: "subscriber_claim".into(),
341            kind: ConfigurationValueKind::String,
342            required: false,
343            secret: false,
344            description: "OIDC claim that must equal the first channel segment after the namespace"
345                .into(),
346            default: Some(serde_json::json!(default_subscriber_claim())),
347        },
348    ]
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354    use minco_core::{PluginManager, PluginSelection};
355    use minco_test::PluginConformance;
356    use std::sync::Arc;
357
358    #[test]
359    fn descriptor_has_the_reviewed_identity() {
360        assert_eq!(
361            RealtimePlugin::default().descriptor().id.as_str(),
362            "realtime"
363        );
364    }
365
366    #[test]
367    fn package_exposes_the_receive_only_browser_module() {
368        assert!(REALTIME_CLIENT_MODULE.contains("export function createRealtimeClient"));
369        assert!(!REALTIME_CLIENT_MODULE.contains("publish("));
370    }
371
372    #[test]
373    fn passes_the_public_plugin_conformance_kit() {
374        PluginConformance::for_package(env!("CARGO_MANIFEST_DIR"))
375            .with_plugin(RealtimePlugin::default())
376            .run()
377            .assert_passed();
378    }
379
380    #[test]
381    fn channel_accepts_portable_segments_and_rejects_provider_specific_paths() {
382        let channel = RealtimeChannel::parse("orders/tenant-42/order-7").expect("valid channel");
383        assert_eq!(channel.as_str(), "orders/tenant-42/order-7");
384
385        for invalid in [
386            "",
387            "/orders/tenant-42",
388            "orders/tenant_42",
389            "orders/-tenant-42",
390            "orders/tenant-42-",
391            "orders//tenant-42",
392            "orders/tenant-42/one/two/three",
393        ] {
394            assert!(
395                RealtimeChannel::parse(invalid).is_err(),
396                "accepted {invalid}"
397            );
398        }
399    }
400
401    #[tokio::test]
402    async fn memory_publisher_records_a_valid_envelope() {
403        let publisher = Arc::new(MemoryRealtimePublisher::default());
404        let service = RealtimePublisherService::new(publisher.clone(), RealtimePlan::default());
405        let publication = RealtimePublication {
406            channel: RealtimeChannel::parse("orders/tenant-42").unwrap(),
407            envelope: RealtimeEnvelope {
408                id: "evt-7".into(),
409                event_type: "order.updated".into(),
410                occurred_at: "2026-08-04T03:50:44Z".into(),
411                payload: serde_json::json!({"order_id": "order-7"}),
412            },
413        };
414
415        service.publish(&publication).await.unwrap();
416
417        assert_eq!(publisher.published(), vec![publication]);
418    }
419
420    #[tokio::test]
421    async fn oversized_envelope_fails_before_publication() {
422        let publisher = Arc::new(MemoryRealtimePublisher::default());
423        let service = RealtimePublisherService::new(publisher.clone(), RealtimePlan::default());
424        let publication = RealtimePublication {
425            channel: RealtimeChannel::parse("orders/tenant-42").unwrap(),
426            envelope: RealtimeEnvelope {
427                id: "evt-8".into(),
428                event_type: "order.updated".into(),
429                occurred_at: "2026-08-04T03:50:44Z".into(),
430                payload: serde_json::json!({"content": "x".repeat(DEFAULT_MAX_EVENT_BYTES)}),
431            },
432        };
433
434        let error = service.publish(&publication).await.unwrap_err();
435
436        assert!(matches!(error, RealtimeError::InvalidEnvelope(_)));
437        assert!(publisher.published().is_empty());
438    }
439
440    #[tokio::test]
441    async fn invalid_standalone_plan_fails_before_publication() {
442        let publisher = Arc::new(MemoryRealtimePublisher::default());
443        let service = RealtimePublisherService::new(
444            publisher.clone(),
445            RealtimePlan {
446                max_event_bytes: 0,
447                ..RealtimePlan::default()
448            },
449        );
450        let publication = RealtimePublication {
451            channel: RealtimeChannel::parse("orders/tenant-42").unwrap(),
452            envelope: RealtimeEnvelope {
453                id: "evt-9".into(),
454                event_type: "order.updated".into(),
455                occurred_at: "2026-08-04T03:50:44Z".into(),
456                payload: serde_json::json!({"order_id": "order-7"}),
457            },
458        };
459
460        let error = service.publish(&publication).await.unwrap_err();
461
462        assert!(matches!(error, RealtimeError::InvalidConfiguration(_)));
463        assert!(publisher.published().is_empty());
464    }
465
466    #[test]
467    fn composition_installs_validated_plan_and_explicit_publisher() {
468        let publisher = Arc::new(MemoryRealtimePublisher::default());
469        let mut manager = PluginManager::default();
470        manager
471            .register(RealtimePlugin::default().with_publisher(publisher))
472            .unwrap();
473        let id = PluginId::new("realtime").unwrap();
474        let mut selection = PluginSelection::default();
475        selection.enabled.insert(id.clone());
476        selection.configuration.insert(
477            id,
478            serde_json::json!({
479                "namespace": "orders",
480                "max_event_bytes": 4096,
481                "subscriber_claim": "tenant_id"
482            }),
483        );
484
485        let application = manager.compose(&selection).unwrap();
486
487        let plan = application.services.get::<RealtimePlan>().unwrap();
488        assert_eq!(plan.namespace, "orders");
489        assert_eq!(plan.max_event_bytes, 4096);
490        assert_eq!(plan.subscriber_claim, "tenant_id");
491        assert!(
492            application
493                .services
494                .get::<RealtimePublisherService>()
495                .is_ok()
496        );
497        assert!(application.graph.resources.contains_key("realtime-api"));
498    }
499}