bmux_plugin_sdk 0.0.1-alpha.0

Plugin SDK for bmux — the types and traits plugin authors need
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
use crate::{CapabilityId, HostScope, InterfaceId, PluginError, Result};
use bmux_perf_telemetry::{PhaseChannel, PhasePayload, emit as emit_phase_timing};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::fmt;
use std::time::Instant;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ServiceKind {
    Query,
    Command,
    Event,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct PluginService {
    pub capability: HostScope,
    pub kind: ServiceKind,
    pub interface_id: String,
}

/// BPDL-generated descriptor for an interface-level service endpoint.
///
/// Unlike [`PluginService`], this is cheap to expose from generated Rust
/// bindings because every field is a typed static identifier. Hosts convert it
/// into a [`PluginService`] when building a plugin declaration.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServiceInterfaceDescriptor {
    pub capability: CapabilityId,
    pub kind: ServiceKind,
    pub interface_id: InterfaceId,
}

/// Type-level plugin contract exported by BPDL-generated API crates.
///
/// Rust plugin implementations associate themselves with one contract type via
/// `RustPlugin::Contract`. Hosts then derive generated services from that type,
/// so providers do not manually list BPDL services in manifests or plugin impls.
pub trait PluginContract {
    /// Return service declarations generated from the plugin contract.
    ///
    /// # Errors
    ///
    /// Returns if any generated capability cannot be represented as a host scope.
    fn service_declarations() -> Result<Vec<PluginService>>;
}

/// Explicit marker for plugins that do not have a BPDL contract.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoPluginContract;

impl PluginContract for NoPluginContract {
    fn service_declarations() -> Result<Vec<PluginService>> {
        Ok(Vec::new())
    }
}

impl ServiceInterfaceDescriptor {
    /// Convert this generated descriptor into a manifest-compatible service
    /// declaration.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::InvalidCapabilityId`] if the generated capability
    /// cannot be represented as a host scope. This should only happen for
    /// invalid BPDL input or hand-written descriptors.
    pub fn to_plugin_service(&self) -> Result<PluginService> {
        Ok(PluginService {
            capability: HostScope::new(self.capability.as_str())?,
            kind: self.kind,
            interface_id: self.interface_id.as_str().to_string(),
        })
    }
}

impl PluginService {
    /// Validate that this service definition has a non-empty interface ID.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::InvalidServiceInterfaceId`] if the interface ID
    /// is empty or contains only whitespace.
    pub fn validate(&self, plugin_id: &str) -> Result<()> {
        if self.interface_id.trim().is_empty() {
            return Err(PluginError::InvalidServiceInterfaceId {
                plugin_id: plugin_id.to_string(),
                capability: self.capability.as_str().to_string(),
                kind: self.kind,
            });
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProviderId {
    Plugin(String),
    Host,
}

impl ProviderId {
    #[must_use]
    pub const fn display_name(&self) -> &str {
        match self {
            Self::Plugin(plugin_id) => plugin_id.as_str(),
            Self::Host => "host",
        }
    }
}

impl fmt::Display for ProviderId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.display_name())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegisteredService {
    pub capability: HostScope,
    pub kind: ServiceKind,
    pub interface_id: String,
    pub provider: ProviderId,
}

impl RegisteredService {
    #[must_use]
    pub fn key(&self) -> (HostScope, ServiceKind, String) {
        (
            self.capability.clone(),
            self.kind,
            self.interface_id.clone(),
        )
    }
}

pub const CURRENT_SERVICE_PROTOCOL_VERSION: u16 = 1;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ServiceProtocolVersion(pub u16);

impl ServiceProtocolVersion {
    #[must_use]
    pub const fn current() -> Self {
        Self(CURRENT_SERVICE_PROTOCOL_VERSION)
    }
}

impl Default for ServiceProtocolVersion {
    fn default() -> Self {
        Self::current()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ServiceEnvelopeKind {
    Request,
    Response,
    Event,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceEnvelope {
    pub version: ServiceProtocolVersion,
    pub request_id: u64,
    pub kind: ServiceEnvelopeKind,
    #[serde(with = "bmux_codec::serde_bytes_vec")]
    pub payload: Vec<u8>,
}

impl ServiceEnvelope {
    #[must_use]
    pub const fn new(request_id: u64, kind: ServiceEnvelopeKind, payload: Vec<u8>) -> Self {
        Self {
            version: ServiceProtocolVersion::current(),
            request_id,
            kind,
            payload,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceRequest {
    pub caller_plugin_id: String,
    pub service: RegisteredService,
    pub operation: String,
    #[serde(with = "bmux_codec::serde_bytes_vec")]
    pub payload: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceError {
    pub code: String,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceResponse {
    #[serde(with = "bmux_codec::serde_bytes_vec")]
    pub payload: Vec<u8>,
    pub error: Option<ServiceError>,
}

impl ServiceResponse {
    #[must_use]
    pub const fn ok(payload: Vec<u8>) -> Self {
        Self {
            payload,
            error: None,
        }
    }

    #[must_use]
    pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            payload: Vec::new(),
            error: Some(ServiceError {
                code: code.into(),
                message: message.into(),
            }),
        }
    }
}

/// Serialize a service message using the bmux binary codec.
///
/// # Errors
///
/// Returns [`PluginError::ServiceProtocol`] if serialization fails.
pub fn encode_service_message<T>(message: &T) -> Result<Vec<u8>>
where
    T: Serialize,
{
    let timing_enabled = PhaseChannel::Service.enabled();
    let started_at = timing_enabled.then(Instant::now);
    let result = bmux_codec::to_vec(message).map_err(|error| PluginError::ServiceProtocol {
        details: error.to_string(),
    });
    if let Some(started_at) = started_at {
        emit_service_codec_timing::<T>("typed_service.message_encode", started_at, &result);
    }
    result
}

/// Deserialize a service message from binary codec bytes.
///
/// # Errors
///
/// Returns [`PluginError::ServiceProtocol`] if deserialization fails.
pub fn decode_service_message<T>(payload: &[u8]) -> Result<T>
where
    T: DeserializeOwned,
{
    let timing_enabled = PhaseChannel::Service.enabled();
    let started_at = timing_enabled.then(Instant::now);
    let result = bmux_codec::from_bytes(payload).map_err(|error| PluginError::ServiceProtocol {
        details: error.to_string(),
    });
    if let Some(started_at) = started_at {
        let total_us = started_at.elapsed().as_micros();
        let payload = PhasePayload::new("typed_service.message_decode")
            .field("type_name", std::any::type_name::<T>())
            .field("input_bytes", payload.len())
            .field("ok", result.is_ok())
            .field("total_us", total_us)
            .finish();
        emit_phase_timing(PhaseChannel::Service, &payload);
    }
    result
}

fn emit_service_codec_timing<T>(phase: &str, started_at: Instant, result: &Result<Vec<u8>>)
where
    T: ?Sized,
{
    let total_us = started_at.elapsed().as_micros();
    let output_bytes = result.as_ref().map_or(0, Vec::len);
    let payload = PhasePayload::new(phase)
        .field("type_name", std::any::type_name::<T>())
        .field("output_bytes", output_bytes)
        .field("ok", result.is_ok())
        .field("total_us", total_us)
        .finish();
    emit_phase_timing(PhaseChannel::Service, &payload);
}

/// Encode a typed message into a service envelope with the given request ID and kind.
///
/// Serializes both the inner message and the outer envelope using the binary codec.
///
/// # Errors
///
/// Returns [`PluginError::ServiceProtocol`] if serialization of the message
/// or the envelope fails.
pub fn encode_service_envelope<T>(
    request_id: u64,
    kind: ServiceEnvelopeKind,
    message: &T,
) -> Result<Vec<u8>>
where
    T: Serialize,
{
    encode_service_message(&ServiceEnvelope::new(
        request_id,
        kind,
        encode_service_message(message)?,
    ))
}

/// Decode a service envelope and extract the typed payload.
///
/// Validates the protocol version and envelope kind before deserializing
/// the inner payload.
///
/// # Errors
///
/// Returns [`PluginError::ServiceProtocol`] if the envelope cannot be
/// deserialized, the protocol version is unsupported, the envelope kind
/// does not match `expected_kind`, or the inner payload fails to deserialize.
pub fn decode_service_envelope<T>(
    payload: &[u8],
    expected_kind: ServiceEnvelopeKind,
) -> Result<(u64, T)>
where
    T: DeserializeOwned,
{
    let envelope: ServiceEnvelope = decode_service_message(payload)?;
    if envelope.version != ServiceProtocolVersion::current() {
        return Err(PluginError::ServiceProtocol {
            details: format!(
                "unsupported service protocol version {}; expected {}",
                envelope.version.0,
                ServiceProtocolVersion::current().0,
            ),
        });
    }
    if envelope.kind != expected_kind {
        return Err(PluginError::ServiceProtocol {
            details: format!(
                "unexpected service envelope kind {:?}; expected {:?}",
                envelope.kind, expected_kind,
            ),
        });
    }
    Ok((
        envelope.request_id,
        decode_service_message::<T>(&envelope.payload)?,
    ))
}

#[cfg(test)]
mod tests {
    use super::{
        ProviderId, RegisteredService, ServiceEnvelopeKind, ServiceError, ServiceKind,
        ServiceRequest, ServiceResponse, decode_service_envelope, decode_service_message,
        encode_service_envelope, encode_service_message,
    };
    use crate::HostScope;

    #[test]
    fn service_message_roundtrip() {
        let response = ServiceResponse::ok(vec![1, 2, 3]);
        let bytes = encode_service_message(&response).expect("service response should encode");
        let decoded: ServiceResponse =
            decode_service_message(&bytes).expect("service response should decode");
        assert_eq!(decoded, response);
    }

    #[test]
    fn service_envelope_roundtrip() {
        let request = ServiceRequest {
            caller_plugin_id: "example.native".to_string(),
            service: RegisteredService {
                capability: HostScope::new("bmux.permissions.read")
                    .expect("capability should parse"),
                kind: ServiceKind::Query,
                interface_id: "permissions-state".to_string(),
                provider: ProviderId::Plugin("bmux.permissions".to_string()),
            },
            operation: "list".to_string(),
            payload: vec![4, 5, 6],
        };

        let bytes = encode_service_envelope(41, ServiceEnvelopeKind::Request, &request)
            .expect("service envelope should encode");
        let (request_id, decoded): (u64, ServiceRequest) =
            decode_service_envelope(&bytes, ServiceEnvelopeKind::Request)
                .expect("service envelope should decode");
        assert_eq!(request_id, 41);
        assert_eq!(decoded, request);
    }

    // ── Level 1F: Extended plugin service protocol round-trips ───────────────

    #[test]
    fn service_response_error_roundtrip() {
        let response = ServiceResponse::error("NOT_FOUND", "resource not found");
        let bytes = encode_service_message(&response).expect("error response should encode");
        let decoded: ServiceResponse =
            decode_service_message(&bytes).expect("error response should decode");
        assert_eq!(decoded, response);
        assert!(decoded.error.is_some());
        let err = decoded.error.unwrap();
        assert_eq!(err.code, "NOT_FOUND");
        assert_eq!(err.message, "resource not found");
    }

    #[test]
    fn service_error_standalone_roundtrip() {
        let error = ServiceError {
            code: "INTERNAL".to_string(),
            message: "something went wrong".to_string(),
        };
        let bytes = encode_service_message(&error).expect("service error should encode");
        let decoded: ServiceError =
            decode_service_message(&bytes).expect("service error should decode");
        assert_eq!(decoded, error);
    }

    #[test]
    fn provider_id_host_roundtrip() {
        let provider = ProviderId::Host;
        let bytes = encode_service_message(&provider).expect("host provider should encode");
        let decoded: ProviderId =
            decode_service_message(&bytes).expect("host provider should decode");
        assert_eq!(decoded, provider);
    }

    #[test]
    fn provider_id_plugin_roundtrip() {
        let provider = ProviderId::Plugin("my-plugin".to_string());
        let bytes = encode_service_message(&provider).expect("plugin provider should encode");
        let decoded: ProviderId =
            decode_service_message(&bytes).expect("plugin provider should decode");
        assert_eq!(decoded, provider);
    }

    #[test]
    fn service_kind_all_variants_roundtrip() {
        for kind in &[ServiceKind::Query, ServiceKind::Command, ServiceKind::Event] {
            let bytes = encode_service_message(kind).expect("service kind should encode");
            let decoded: ServiceKind =
                decode_service_message(&bytes).expect("service kind should decode");
            assert_eq!(&decoded, kind);
        }
    }

    #[test]
    fn service_envelope_kind_all_variants_roundtrip() {
        for kind in &[
            ServiceEnvelopeKind::Request,
            ServiceEnvelopeKind::Response,
            ServiceEnvelopeKind::Event,
        ] {
            let bytes = encode_service_message(kind).expect("envelope kind should encode");
            let decoded: ServiceEnvelopeKind =
                decode_service_message(&bytes).expect("envelope kind should decode");
            assert_eq!(&decoded, kind);
        }
    }

    #[test]
    fn service_envelope_response_kind_roundtrip() {
        let response = ServiceResponse::ok(vec![7, 8, 9]);
        let bytes = encode_service_envelope(99, ServiceEnvelopeKind::Response, &response)
            .expect("response envelope should encode");
        let (request_id, decoded): (u64, ServiceResponse) =
            decode_service_envelope(&bytes, ServiceEnvelopeKind::Response)
                .expect("response envelope should decode");
        assert_eq!(request_id, 99);
        assert_eq!(decoded, response);
    }

    #[test]
    fn registered_service_with_host_provider_roundtrip() {
        let service = RegisteredService {
            capability: HostScope::new("bmux.storage").expect("capability should parse"),
            kind: ServiceKind::Command,
            interface_id: "storage-command/v1".to_string(),
            provider: ProviderId::Host,
        };
        let bytes = encode_service_message(&service).expect("registered service should encode");
        let decoded: RegisteredService =
            decode_service_message(&bytes).expect("registered service should decode");
        assert_eq!(decoded, service);
    }
}