cc-lb-plugin-wire 0.1.1

cc-lb plugin wire format — handshake and shared types between cc-lb host and plugins.
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
extern crate alloc;

use alloc::{
    collections::{BTreeMap, BTreeSet},
    string::{String, ToString},
};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::identity::PluginIdentity;

/// Augmented metadata combining plugin identity with negotiated capabilities.
///
/// This is the single source of truth for negotiated plugin capabilities and versions.
/// It encapsulates the result of a successful handshake and self-check.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AugmentedMetadata {
    /// The plugin's identity metadata (magic, abi_envelope, name, version).
    pub identity: PluginIdentity,

    /// Negotiated wire function versions: function_name -> negotiated_version.
    /// Ordered via BTreeMap for deterministic serialization.
    pub negotiated_functions: BTreeMap<String, u32>,

    /// Negotiated capabilities offered by the plugin.
    /// Ordered via BTreeSet for deterministic serialization.
    pub negotiated_capabilities: BTreeSet<String>,

    /// Unix timestamp (seconds) when handshake was completed.
    pub handshake_completed_at: i64,

    /// Whether the self-check passed successfully.
    pub self_check_passed: bool,

    /// Unix timestamp (seconds) when self-check was completed.
    pub self_check_completed_at: i64,

    /// Unix timestamp (seconds) when this metadata expires and re-handshake is needed.
    pub expires_at: i64,
}

/// Record in the plugin registry, tracking a deployed plugin instance.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PluginRegistryRecord {
    /// Unique plugin instance identifier (UUID or similar).
    pub plugin_id: String,

    /// Augmented metadata for this plugin instance.
    pub augmented_metadata: AugmentedMetadata,

    /// Unix timestamp (seconds) when the plugin was registered.
    pub registered_at: i64,
}

/// Error type for augmented metadata operations.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum AugmentedMetadataError {
    #[error("identity validation failed: {0}")]
    IdentityValidationFailed(String),

    #[error(
        "augmented metadata serialization exceeds max size of {} bytes",
        crate::limits::AUGMENTED_METADATA_MAX_BYTES
    )]
    SizeLimitExceeded,

    #[error("invalid timestamp: {0}")]
    InvalidTimestamp(String),

    #[error("expires_at must be after handshake_completed_at")]
    ExpirationBeforeHandshake,

    #[error("no negotiated functions")]
    NoNegotiatedFunctions,

    #[error("serialization failed: {0}")]
    SerializationFailed(String),
}

impl AugmentedMetadata {
    /// Validate this augmented metadata.
    pub fn validate(&self) -> Result<(), AugmentedMetadataError> {
        // Validate identity.
        self.identity
            .validate()
            .map_err(|e| AugmentedMetadataError::IdentityValidationFailed(e.to_string()))?;

        // Validate timestamps.
        if self.handshake_completed_at <= 0 {
            return Err(AugmentedMetadataError::InvalidTimestamp(
                "handshake_completed_at must be positive".to_string(),
            ));
        }

        if self.self_check_completed_at <= 0 {
            return Err(AugmentedMetadataError::InvalidTimestamp(
                "self_check_completed_at must be positive".to_string(),
            ));
        }

        if self.expires_at <= 0 {
            return Err(AugmentedMetadataError::InvalidTimestamp(
                "expires_at must be positive".to_string(),
            ));
        }

        if self.expires_at <= self.handshake_completed_at {
            return Err(AugmentedMetadataError::ExpirationBeforeHandshake);
        }

        // Validate negotiated functions.
        if self.negotiated_functions.is_empty() {
            return Err(AugmentedMetadataError::NoNegotiatedFunctions);
        }

        // Validate size limit.
        self.check_size_limit()?;

        Ok(())
    }

    /// Check that serialized size does not exceed AUGMENTED_METADATA_MAX_BYTES.
    pub fn check_size_limit(&self) -> Result<(), AugmentedMetadataError> {
        let serialized = serde_json::to_vec(self)
            .map_err(|e| AugmentedMetadataError::SerializationFailed(e.to_string()))?;

        if serialized.len() > crate::limits::AUGMENTED_METADATA_MAX_BYTES {
            return Err(AugmentedMetadataError::SizeLimitExceeded);
        }

        Ok(())
    }

    /// Create AugmentedMetadata from handshake and self-check responses.
    ///
    /// Combines:
    /// - Plugin identity from handshake
    /// - Negotiated functions and capabilities from handshake
    /// - Self-check result
    ///
    /// # Arguments
    /// * `identity` - The plugin's identity metadata
    /// * `negotiated_functions` - BTreeMap of function_name -> negotiated_version
    /// * `negotiated_capabilities` - BTreeSet of negotiated capability names
    /// * `handshake_completed_at` - Timestamp when handshake completed
    /// * `self_check_passed` - Whether self-check passed
    /// * `self_check_completed_at` - Timestamp when self-check completed
    /// * `ttl_seconds` - TTL for this metadata in seconds
    pub fn from_handshake_and_self_check(
        identity: PluginIdentity,
        negotiated_functions: BTreeMap<String, u32>,
        negotiated_capabilities: BTreeSet<String>,
        handshake_completed_at: i64,
        self_check_passed: bool,
        self_check_completed_at: i64,
        ttl_seconds: u64,
    ) -> Result<Self, AugmentedMetadataError> {
        let expires_at = handshake_completed_at + ttl_seconds as i64;

        let metadata = AugmentedMetadata {
            identity,
            negotiated_functions,
            negotiated_capabilities,
            handshake_completed_at,
            self_check_passed,
            self_check_completed_at,
            expires_at,
        };

        metadata.validate()?;
        Ok(metadata)
    }

    /// Check if this metadata has expired.
    pub fn is_expired(&self, now_timestamp: i64) -> bool {
        now_timestamp >= self.expires_at
    }

    /// Get the TTL remaining in seconds.
    pub fn ttl_seconds(&self, now_timestamp: i64) -> i64 {
        (self.expires_at - now_timestamp).max(0)
    }
}

impl PluginRegistryRecord {
    /// Validate this registry record.
    pub fn validate(&self) -> Result<(), AugmentedMetadataError> {
        if self.plugin_id.is_empty() {
            return Err(AugmentedMetadataError::InvalidTimestamp(
                "plugin_id must not be empty".to_string(),
            ));
        }

        if self.registered_at <= 0 {
            return Err(AugmentedMetadataError::InvalidTimestamp(
                "registered_at must be positive".to_string(),
            ));
        }

        self.augmented_metadata.validate()?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_test_identity() -> PluginIdentity {
        PluginIdentity {
            magic: crate::identity::CC_LB_PLUGIN_MAGIC,
            abi_envelope: 1,
            plugin_name: "test-plugin".to_string(),
            plugin_version: "1.0.0".to_string(),
        }
    }

    #[test]
    fn test_augmented_metadata_valid() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let mut capabilities = BTreeSet::new();
        capabilities.insert("async".to_string());

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: capabilities,
            handshake_completed_at: 1000,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        assert!(metadata.validate().is_ok());
    }

    #[test]
    fn test_augmented_metadata_no_functions() {
        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: BTreeMap::new(),
            negotiated_capabilities: BTreeSet::new(),
            handshake_completed_at: 1000,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        assert_eq!(
            metadata.validate(),
            Err(AugmentedMetadataError::NoNegotiatedFunctions)
        );
    }

    #[test]
    fn test_augmented_metadata_invalid_handshake_timestamp() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: BTreeSet::new(),
            handshake_completed_at: 0,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        assert!(metadata.validate().is_err());
    }

    #[test]
    fn test_augmented_metadata_expiration_before_handshake() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: BTreeSet::new(),
            handshake_completed_at: 2000,
            self_check_passed: true,
            self_check_completed_at: 2100,
            expires_at: 1000,
        };

        assert_eq!(
            metadata.validate(),
            Err(AugmentedMetadataError::ExpirationBeforeHandshake)
        );
    }

    #[test]
    fn test_augmented_metadata_serde() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);
        functions.insert("observe".to_string(), 2);

        let mut capabilities = BTreeSet::new();
        capabilities.insert("async".to_string());
        capabilities.insert("streaming".to_string());

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: capabilities,
            handshake_completed_at: 1000,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        let json = serde_json::to_string(&metadata).unwrap();
        let deserialized: AugmentedMetadata = serde_json::from_str(&json).unwrap();
        assert_eq!(metadata, deserialized);
    }

    #[test]
    fn test_augmented_metadata_deny_unknown_fields() {
        let json = r#"{"identity":{"magic":[204,27,112,16,0,1,0,0],"abi_envelope":1,"plugin_name":"test","plugin_version":"1.0"},"negotiated_functions":{"route":1},"negotiated_capabilities":[],"handshake_completed_at":1000,"self_check_passed":true,"self_check_completed_at":1100,"expires_at":2000,"unknown":"field"}"#;
        let result: Result<AugmentedMetadata, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[test]
    fn test_augmented_metadata_size_limit() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let mut capabilities = BTreeSet::new();
        // Add a huge capability name to exceed size limit
        capabilities.insert("x".repeat(crate::limits::AUGMENTED_METADATA_MAX_BYTES + 1));

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: capabilities,
            handshake_completed_at: 1000,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        assert_eq!(
            metadata.validate(),
            Err(AugmentedMetadataError::SizeLimitExceeded)
        );
    }

    #[test]
    fn test_from_handshake_and_self_check() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let mut capabilities = BTreeSet::new();
        capabilities.insert("async".to_string());

        let metadata = AugmentedMetadata::from_handshake_and_self_check(
            make_test_identity(),
            functions,
            capabilities,
            1000,
            true,
            1100,
            3600,
        );

        assert!(metadata.is_ok());
        let m = metadata.unwrap();
        assert_eq!(m.handshake_completed_at, 1000);
        assert!(m.self_check_passed);
        assert_eq!(m.expires_at, 1000 + 3600);
    }

    #[test]
    fn test_from_handshake_and_self_check_validates() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        // Try with invalid timestamp
        let result = AugmentedMetadata::from_handshake_and_self_check(
            make_test_identity(),
            functions,
            BTreeSet::new(),
            0,
            true,
            1100,
            3600,
        );

        assert!(result.is_err());
    }

    #[test]
    fn test_is_expired() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: BTreeSet::new(),
            handshake_completed_at: 1000,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        assert!(!metadata.is_expired(1999));
        assert!(metadata.is_expired(2000));
        assert!(metadata.is_expired(2001));
    }

    #[test]
    fn test_ttl_seconds() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: BTreeSet::new(),
            handshake_completed_at: 1000,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        assert_eq!(metadata.ttl_seconds(1500), 500);
        assert_eq!(metadata.ttl_seconds(2000), 0);
        assert_eq!(metadata.ttl_seconds(2100), 0);
    }

    #[test]
    fn test_plugin_registry_record_valid() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: BTreeSet::new(),
            handshake_completed_at: 1000,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        let record = PluginRegistryRecord {
            plugin_id: "plugin-uuid-123".to_string(),
            augmented_metadata: metadata,
            registered_at: 900,
        };

        assert!(record.validate().is_ok());
    }

    #[test]
    fn test_plugin_registry_record_empty_id() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: BTreeSet::new(),
            handshake_completed_at: 1000,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        let record = PluginRegistryRecord {
            plugin_id: String::new(),
            augmented_metadata: metadata,
            registered_at: 900,
        };

        assert!(record.validate().is_err());
    }

    #[test]
    fn test_plugin_registry_record_serde() {
        let mut functions = BTreeMap::new();
        functions.insert("route".to_string(), 1);

        let metadata = AugmentedMetadata {
            identity: make_test_identity(),
            negotiated_functions: functions,
            negotiated_capabilities: BTreeSet::new(),
            handshake_completed_at: 1000,
            self_check_passed: true,
            self_check_completed_at: 1100,
            expires_at: 2000,
        };

        let record = PluginRegistryRecord {
            plugin_id: "plugin-123".to_string(),
            augmented_metadata: metadata,
            registered_at: 900,
        };

        let json = serde_json::to_string(&record).unwrap();
        let deserialized: PluginRegistryRecord = serde_json::from_str(&json).unwrap();
        assert_eq!(record, deserialized);
    }

    #[test]
    fn test_plugin_registry_record_deny_unknown_fields() {
        let json = r#"{"plugin_id":"test","augmented_metadata":{"identity":{"magic":[204,27,112,16,0,1,0,0],"abi_envelope":1,"plugin_name":"test","plugin_version":"1.0"},"negotiated_functions":{"route":1},"negotiated_capabilities":[],"handshake_completed_at":1000,"self_check_passed":true,"self_check_completed_at":1100,"expires_at":2000},"registered_at":900,"unknown":"field"}"#;
        let result: Result<PluginRegistryRecord, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }
}