ruststream 0.6.1

Async messaging framework for Rust: broker-agnostic traits, router, codecs, and a conformance harness for broker authors.
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
//! `AsyncAPI` 3.0 document generation from a [`RustStream`](crate::runtime::RustStream) service.
//!
//! [`build_spec`] turns a service's registered handlers and metadata into a [`Spec`] that
//! serializes to an `AsyncAPI` 3.0 document ([`to_json`](Spec::to_json) / [`to_yaml`](Spec::to_yaml)).
//! Hosting it over HTTP is the user's concern; [`render_viewer_html`] produces a ready-to-serve HTML
//! page that renders the document with the `AsyncAPI` React component from a CDN.
//!
//! The document covers info, servers, channels, operations, and per-message payload JSON schemas
//! (for message types that implement [`schemars::JsonSchema`]).

use std::collections::BTreeMap;

use serde::Serialize;
use serde_json::Value;

use crate::runtime::App;

/// An `AsyncAPI` 3.0 document.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Spec {
    /// The `AsyncAPI` specification version (always `"3.0.0"`).
    pub asyncapi: String,
    /// Service metadata.
    pub info: Info,
    /// Servers (one per broker the service connects to), keyed by server name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub servers: BTreeMap<String, Server>,
    /// Channels, keyed by channel id (the name).
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub channels: BTreeMap<String, Channel>,
    /// Operations, keyed by operation id.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub operations: BTreeMap<String, Operation>,
    /// Reusable components (message definitions).
    pub components: Components,
}

impl Spec {
    /// Serializes the document to pretty-printed JSON.
    ///
    /// # Errors
    ///
    /// Returns [`serde_json::Error`] if serialization fails (not expected for a well-formed spec).
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Serializes the document to YAML.
    ///
    /// # Errors
    ///
    /// Returns [`serde_norway::Error`] if serialization fails (not expected for a well-formed spec).
    pub fn to_yaml(&self) -> Result<String, serde_norway::Error> {
        serde_norway::to_string(self)
    }
}

/// An `AsyncAPI` server: where and how clients reach a broker.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Server {
    /// The host (and optional port), e.g. `"nats.example.com:4222"`. Absent for an in-process
    /// broker with no network address (the in-memory broker).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub host: Option<String>,
    /// The messaging protocol, e.g. `"nats"`.
    pub protocol: String,
    /// Optional human description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// References into `components.securitySchemes` describing how clients authenticate. Empty
    /// (and absent from the document) unless the service author attached schemes with
    /// [`ServerSpec::with_security`](crate::ServerSpec::with_security).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub security: Vec<Reference>,
}

/// `AsyncAPI` `Info` object: service title, version, and optional description.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Info {
    /// Service title.
    pub title: String,
    /// Service version.
    pub version: String,
    /// Optional description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// An `AsyncAPI` channel: an address plus the messages that flow over it.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Channel {
    /// The channel address (the broker name / subject).
    pub address: String,
    /// Messages on this channel, keyed by message name, referencing component definitions.
    pub messages: BTreeMap<String, Reference>,
}

/// An `AsyncAPI` operation: an action on a channel.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Operation {
    /// The action; `"receive"` for subscribers.
    pub action: String,
    /// Reference to the channel this operation acts on.
    pub channel: Reference,
    /// The messages this operation handles.
    pub messages: Vec<Reference>,
    /// Optional human description, typically from the handler's doc comment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Reusable `AsyncAPI` components.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Components {
    /// Message definitions, keyed by message name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub messages: BTreeMap<String, MessageObject>,
    /// Security scheme definitions the servers reference, keyed by scheme name (the server's
    /// name, `-N`-suffixed when a server declares several).
    #[serde(rename = "securitySchemes", skip_serializing_if = "BTreeMap::is_empty")]
    pub security_schemes: BTreeMap<String, Value>,
}

/// An `AsyncAPI` message definition.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct MessageObject {
    /// The message name.
    pub name: String,
    /// Optional human description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The JSON Schema of the payload, when the message type implements
    /// [`schemars::JsonSchema`]. Absent for raw-bytes handlers and types without a schema.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<Value>,
}

/// A JSON `$ref` pointer.
#[derive(Debug, Clone, Serialize)]
pub struct Reference {
    /// The reference target, e.g. `#/components/messages/Order`.
    #[serde(rename = "$ref")]
    pub reference: String,
}

impl Reference {
    fn new(target: impl Into<String>) -> Self {
        Self {
            reference: target.into(),
        }
    }
}

/// Builds an [`AsyncAPI`](Spec) 3.0 document from a service's handlers and metadata.
///
/// Each registered subscriber becomes a channel (addressed by its name), a `receive` operation,
/// and a message component named after the handler's input type.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "memory")]
/// # fn demo() -> Result<(), serde_json::Error> {
/// use ruststream::asyncapi::build_spec;
/// use ruststream::memory::MemoryBroker;
/// use ruststream::runtime::{AppInfo, Context, HandlerMetadata, HandlerResult, RustStream};
///
/// let app = RustStream::new(AppInfo::new("orders", "1.0.0")).with_broker(
///     MemoryBroker::new(),
///     |b| {
///         let subscriber = b.broker().subscribe("orders");
///         b.handle(
///             subscriber,
///             |_msg: &_, _ctx: &mut Context| async { HandlerResult::Ack },
///             HandlerMetadata::raw("orders"),
///         );
///     },
/// );
///
/// let spec = build_spec(&app);
/// assert_eq!(spec.info.title, "orders");
/// let json = spec.to_json()?;
/// assert!(json.contains("\"asyncapi\""));
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn build_spec<A: App>(app: &A) -> Spec {
    let info = Info {
        title: app.info().title.clone(),
        version: app.info().version.clone(),
        description: app.info().description.clone(),
    };

    let mut security_schemes = BTreeMap::new();
    let servers = app
        .servers()
        .iter()
        .map(|(name, spec)| {
            let security = spec
                .security
                .iter()
                .enumerate()
                .map(|(index, scheme)| {
                    let key = if index == 0 {
                        name.clone()
                    } else {
                        format!("{name}-{index}")
                    };
                    security_schemes.insert(key.clone(), security_scheme_object(scheme));
                    Reference::new(format!("#/components/securitySchemes/{key}"))
                })
                .collect();
            (
                name.clone(),
                Server {
                    host: spec.host.clone(),
                    protocol: spec.protocol.clone(),
                    description: spec.description.clone(),
                    security,
                },
            )
        })
        .collect();

    let mut channels = BTreeMap::new();
    let mut operations = BTreeMap::new();
    let mut messages = BTreeMap::new();

    for handler in app.handlers() {
        let name = handler.name.as_ref();
        let payload = handler
            .payload_schema
            .as_deref()
            .and_then(|json| serde_json::from_str::<Value>(json).ok());
        // The JsonSchema derive captures the type's own doc comment (and a schemars title /
        // rename), so a documented payload type feeds the component without a Message impl.
        let schema_str = |key: &str| {
            payload
                .as_ref()
                .and_then(|schema| schema.get(key))
                .and_then(Value::as_str)
                .map(str::to_owned)
        };
        // A `Message` impl on the input type names the component; the schema title is next; the
        // type name is the fallback.
        let message_name = handler
            .message_name
            .as_ref()
            .map(ToString::to_string)
            .or_else(|| schema_str("title"))
            .unwrap_or_else(|| message_name(handler.input_type));

        channels.entry(name.to_owned()).or_insert_with(|| Channel {
            address: name.to_owned(),
            messages: BTreeMap::from([(
                message_name.clone(),
                Reference::new(format!("#/components/messages/{message_name}")),
            )]),
        });

        operations.insert(
            operation_id(name),
            Operation {
                action: "receive".to_owned(),
                channel: Reference::new(format!("#/channels/{name}")),
                messages: vec![Reference::new(format!(
                    "#/channels/{name}/messages/{message_name}"
                ))],
                description: handler.description.as_ref().map(ToString::to_string),
            },
        );

        // Message::DESCRIPTION wins, then the type's own doc comment from the schema, then the
        // handler doc (already on the operation) so plain types keep their description.
        let message_description = handler
            .message_description
            .as_ref()
            .map(ToString::to_string)
            .or_else(|| schema_str("description"))
            .or_else(|| handler.description.as_ref().map(ToString::to_string));

        messages
            .entry(message_name.clone())
            .or_insert_with(|| MessageObject {
                name: message_name,
                description: message_description,
                payload,
            });
    }

    Spec {
        asyncapi: "3.0.0".to_owned(),
        info,
        servers,
        channels,
        operations,
        components: Components {
            messages,
            security_schemes,
        },
    }
}

/// Renders a [`SecurityScheme`](crate::SecurityScheme) as its `AsyncAPI` security scheme object.
fn security_scheme_object(scheme: &crate::SecurityScheme) -> Value {
    use crate::capability::SecuritySchemeKind as Kind;

    // Raw payloads round-trip through the string the constructor serialized, so parsing them
    // back cannot fail; Null is the unreachable fallback, not an error path.
    let parse = |raw: &str| serde_json::from_str::<Value>(raw).unwrap_or(Value::Null);
    let mut object = match &scheme.kind {
        Kind::UserPassword => serde_json::json!({ "type": "userPassword" }),
        Kind::ApiKey { location } => {
            serde_json::json!({ "type": "apiKey", "in": location.as_api() })
        }
        Kind::X509 => serde_json::json!({ "type": "X509" }),
        Kind::Plain => serde_json::json!({ "type": "plain" }),
        Kind::ScramSha256 => serde_json::json!({ "type": "scramSha256" }),
        Kind::ScramSha512 => serde_json::json!({ "type": "scramSha512" }),
        Kind::Gssapi => serde_json::json!({ "type": "gssapi" }),
        Kind::Http { scheme } => serde_json::json!({ "type": "http", "scheme": scheme }),
        Kind::HttpApiKey { name, location } => serde_json::json!({
            "type": "httpApiKey",
            "name": name,
            "in": location.as_api(),
        }),
        Kind::OpenIdConnect { url } => serde_json::json!({
            "type": "openIdConnect",
            "openIdConnectUrl": url,
        }),
        Kind::Oauth2 { flows } => serde_json::json!({ "type": "oauth2", "flows": parse(flows) }),
        Kind::Custom { object } => parse(object),
    };
    if let (Some(description), Some(fields)) = (&scheme.description, object.as_object_mut()) {
        fields.insert("description".to_owned(), Value::String(description.clone()));
    }
    object
}

/// Renders a self-contained HTML page that displays `spec_url` using the `AsyncAPI` React component.
///
/// The component and its styles load from a CDN (jsDelivr) by default; override
/// [`cdn_base`](ViewerOptions::cdn_base) to pin a version or self-host for offline / locked-down
/// deployments. Serve the returned HTML from your own HTTP stack alongside the spec document.
///
/// # Examples
///
/// ```
/// use ruststream::asyncapi::{render_viewer_html, ViewerOptions};
///
/// let html = render_viewer_html("/asyncapi.json", &ViewerOptions::default());
/// assert!(html.contains("/asyncapi.json"));
/// ```
#[must_use]
pub fn render_viewer_html(spec_url: &str, opts: &ViewerOptions<'_>) -> String {
    let title = opts.title;
    let cdn = opts.cdn_base.trim_end_matches('/');
    let spec = spec_url.replace('"', "&quot;");
    format!(
        "<!DOCTYPE html>\n\
<html lang=\"en\">\n\
<head>\n\
  <meta charset=\"utf-8\" />\n\
  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n\
  <title>{title}</title>\n\
  <link rel=\"stylesheet\" href=\"{cdn}/styles/default.min.css\" />\n\
</head>\n\
<body>\n\
  <div id=\"asyncapi\"></div>\n\
  <script src=\"{cdn}/browser/standalone/index.js\"></script>\n\
  <script>\n\
    AsyncApiStandalone.render(\n\
      {{ schema: {{ url: \"{spec}\" }}, config: {{ show: {{ sidebar: true }} }} }},\n\
      document.getElementById(\"asyncapi\"),\n\
    );\n\
  </script>\n\
</body>\n\
</html>\n"
    )
}

/// Options for [`render_viewer_html`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ViewerOptions<'a> {
    /// The HTML page title.
    pub title: &'a str,
    /// Base URL the `AsyncAPI` React assets load from (no trailing slash required).
    pub cdn_base: &'a str,
}

impl<'a> ViewerOptions<'a> {
    /// Sets the HTML page title.
    #[must_use]
    pub const fn with_title(mut self, title: &'a str) -> Self {
        self.title = title;
        self
    }

    /// Sets the base URL the `AsyncAPI` React assets load from.
    #[must_use]
    pub const fn with_cdn_base(mut self, cdn_base: &'a str) -> Self {
        self.cdn_base = cdn_base;
        self
    }
}

impl Default for ViewerOptions<'_> {
    fn default() -> Self {
        Self {
            title: "AsyncAPI",
            cdn_base: "https://cdn.jsdelivr.net/npm/@asyncapi/react-component@2.6.4",
        }
    }
}

/// Takes the final path segment of a type name as the message name (`a::b::Order` -> `Order`).
fn message_name(type_name: &str) -> String {
    type_name
        .rsplit("::")
        .next()
        .unwrap_or(type_name)
        .to_owned()
}

/// Derives a stable operation id from a name.
fn operation_id(name: &str) -> String {
    let sanitized: String = name
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '_' })
        .collect();
    format!("receive_{sanitized}")
}

#[cfg(test)]
mod tests {
    use crate::{ApiKeyLocation, HttpApiKeyLocation, SecurityScheme};

    use super::security_scheme_object;

    #[test]
    fn every_scheme_kind_renders_its_document_object() {
        let cases = [
            (
                SecurityScheme::user_password(),
                serde_json::json!({ "type": "userPassword" }),
            ),
            (
                SecurityScheme::api_key(ApiKeyLocation::Password),
                serde_json::json!({ "type": "apiKey", "in": "password" }),
            ),
            (
                SecurityScheme::x509(),
                serde_json::json!({ "type": "X509" }),
            ),
            (
                SecurityScheme::plain(),
                serde_json::json!({ "type": "plain" }),
            ),
            (
                SecurityScheme::scram_sha256(),
                serde_json::json!({ "type": "scramSha256" }),
            ),
            (
                SecurityScheme::scram_sha512(),
                serde_json::json!({ "type": "scramSha512" }),
            ),
            (
                SecurityScheme::gssapi(),
                serde_json::json!({ "type": "gssapi" }),
            ),
            (
                SecurityScheme::http("bearer"),
                serde_json::json!({ "type": "http", "scheme": "bearer" }),
            ),
            (
                SecurityScheme::http_api_key("X-Api-Key", HttpApiKeyLocation::Header),
                serde_json::json!({ "type": "httpApiKey", "name": "X-Api-Key", "in": "header" }),
            ),
            (
                SecurityScheme::open_id_connect("https://idp.example.com/.well-known"),
                serde_json::json!({
                    "type": "openIdConnect",
                    "openIdConnectUrl": "https://idp.example.com/.well-known",
                }),
            ),
            (
                SecurityScheme::oauth2(serde_json::json!({ "clientCredentials": {} })),
                serde_json::json!({ "type": "oauth2", "flows": { "clientCredentials": {} } }),
            ),
            (
                SecurityScheme::custom(serde_json::json!({ "type": "symmetricEncryption" })),
                serde_json::json!({ "type": "symmetricEncryption" }),
            ),
        ];
        for (scheme, expected) in cases {
            assert_eq!(security_scheme_object(&scheme), expected);
        }
    }

    #[test]
    fn description_lands_in_the_rendered_object() {
        let object = security_scheme_object(&SecurityScheme::plain().with_description("over TLS"));
        assert_eq!(object["description"], "over TLS");
    }
}