farp 1.2.0

Forge API Gateway Registration Protocol (FARP) - Schema-aware service discovery and gateway integration
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! Manifest operations including creation, validation, checksums, and diffing.

use crate::errors::{Error, Result};
use crate::types::*;
use crate::version::{is_compatible, PROTOCOL_VERSION};
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};

/// Creates a new schema manifest with default values
///
/// # Arguments
///
/// * `service_name` - The logical service name
/// * `service_version` - The service version (semver recommended)
/// * `instance_id` - Unique instance identifier
///
/// # Examples
///
/// ```
/// use farp::manifest::new_manifest;
///
/// let manifest = new_manifest("user-service", "v1.2.3", "instance-123");
/// assert_eq!(manifest.service_name, "user-service");
/// ```
pub fn new_manifest(
    service_name: impl Into<String>,
    service_version: impl Into<String>,
    instance_id: impl Into<String>,
) -> SchemaManifest {
    SchemaManifest {
        version: PROTOCOL_VERSION.to_string(),
        service_name: service_name.into(),
        service_version: service_version.into(),
        instance_id: instance_id.into(),
        instance: None,
        schemas: Vec::new(),
        capabilities: Vec::new(),
        endpoints: SchemaEndpoints::default(),
        routing: RoutingConfig::default(),
        auth: None,
        webhook: None,
        hints: None,
        route_table: Vec::new(),
        updated_at: chrono::Utc::now().timestamp(),
        checksum: String::new(),
        routes_checksum: None,
    }
}

impl SchemaManifest {
    /// Adds a schema descriptor to the manifest
    pub fn add_schema(&mut self, descriptor: SchemaDescriptor) {
        self.schemas.push(descriptor);
    }

    /// Adds a capability to the manifest
    pub fn add_capability(&mut self, capability: impl Into<String>) {
        let cap = capability.into();
        if !self.capabilities.contains(&cap) {
            self.capabilities.push(cap);
        }
    }

    /// Updates the checksum based on all schema hashes
    pub fn update_checksum(&mut self) -> Result<()> {
        let checksum = calculate_manifest_checksum(self)?;
        self.checksum = checksum;
        self.updated_at = chrono::Utc::now().timestamp();
        Ok(())
    }

    /// Updates the routes checksum based on the route table and routing config.
    /// Services SHOULD call this after building their route table.
    pub fn update_routes_checksum(&mut self) -> Result<()> {
        let checksum = calculate_routes_checksum(self)?;
        self.routes_checksum = Some(checksum);
        Ok(())
    }

    /// Validates the manifest for correctness
    pub fn validate(&self) -> Result<()> {
        // Check protocol version compatibility
        if !is_compatible(&self.version) {
            return Err(Error::incompatible_version(
                self.version.clone(),
                PROTOCOL_VERSION.to_string(),
            ));
        }

        // Check required fields
        if self.service_name.is_empty() {
            return Err(Error::validation(
                "service_name",
                "service name is required",
            ));
        }

        if self.instance_id.is_empty() {
            return Err(Error::validation("instance_id", "instance ID is required"));
        }

        // Validate health endpoint
        if self.endpoints.health.is_empty() {
            return Err(Error::validation(
                "endpoints.health",
                "health endpoint is required",
            ));
        }

        // Validate each schema descriptor
        for (i, schema) in self.schemas.iter().enumerate() {
            validate_schema_descriptor(schema).map_err(|e| {
                Error::invalid_manifest(format!("invalid schema at index {i}: {e}"))
            })?;
        }

        // Verify checksum if present
        if !self.checksum.is_empty() {
            let expected = calculate_manifest_checksum(self)?;
            if self.checksum != expected {
                return Err(Error::checksum_mismatch(expected, self.checksum.clone()));
            }
        }

        Ok(())
    }

    /// Retrieves a schema descriptor by type
    pub fn get_schema(&self, schema_type: SchemaType) -> Option<&SchemaDescriptor> {
        self.schemas.iter().find(|s| s.schema_type == schema_type)
    }

    /// Checks if the manifest includes a specific capability
    pub fn has_capability(&self, capability: &str) -> bool {
        self.capabilities.iter().any(|c| c == capability)
    }

    /// Serializes the manifest to JSON
    pub fn to_json(&self) -> Result<Vec<u8>> {
        serde_json::to_vec(self).map_err(Error::from)
    }

    /// Serializes the manifest to pretty-printed JSON
    pub fn to_pretty_json(&self) -> Result<Vec<u8>> {
        serde_json::to_vec_pretty(self).map_err(Error::from)
    }

    /// Deserializes a manifest from JSON
    pub fn from_json(data: &[u8]) -> Result<Self> {
        serde_json::from_slice(data).map_err(|e| Error::invalid_manifest(e.to_string()))
    }
}

/// Validates a schema descriptor
pub fn validate_schema_descriptor(sd: &SchemaDescriptor) -> Result<()> {
    // Check schema type
    if !sd.schema_type.is_valid() {
        return Err(Error::UnsupportedType(sd.schema_type));
    }

    // Check spec version
    if sd.spec_version.is_empty() {
        return Err(Error::validation(
            "spec_version",
            "spec version is required",
        ));
    }

    // Validate location
    validate_schema_location(&sd.location)?;

    // For inline schemas, inline_schema must be present
    if sd.location.location_type == LocationType::Inline && sd.inline_schema.is_none() {
        return Err(Error::validation(
            "inline_schema",
            "inline schema is required for inline location type",
        ));
    }

    // Check hash
    if sd.hash.is_empty() {
        return Err(Error::validation("hash", "schema hash is required"));
    }

    // Validate hash format (should be 64 hex characters for SHA256)
    if sd.hash.len() != 64 {
        return Err(Error::validation(
            "hash",
            "invalid hash format (expected 64 hex characters)",
        ));
    }

    // Check content type
    if sd.content_type.is_empty() {
        return Err(Error::validation(
            "content_type",
            "content type is required",
        ));
    }

    Ok(())
}

/// Validates a schema location
fn validate_schema_location(sl: &SchemaLocation) -> Result<()> {
    if !sl.location_type.is_valid() {
        return Err(Error::invalid_location(format!(
            "invalid location type: {}",
            sl.location_type
        )));
    }

    match sl.location_type {
        LocationType::HTTP => {
            if sl.url.is_none() || sl.url.as_ref().unwrap().is_empty() {
                return Err(Error::invalid_location("URL required for HTTP location"));
            }
        }
        LocationType::Registry => {
            if sl.registry_path.is_none() || sl.registry_path.as_ref().unwrap().is_empty() {
                return Err(Error::invalid_location(
                    "registry path required for registry location",
                ));
            }
        }
        LocationType::Inline => {
            // No additional validation needed for inline
        }
    }

    Ok(())
}

/// Calculates the SHA256 checksum of a manifest by combining all schema hashes
pub fn calculate_manifest_checksum(manifest: &SchemaManifest) -> Result<String> {
    if manifest.schemas.is_empty() {
        return Ok(String::new());
    }

    // Sort schemas by type for deterministic hashing
    let mut sorted_schemas = manifest.schemas.clone();
    sorted_schemas.sort_by(|a, b| a.schema_type.as_str().cmp(b.schema_type.as_str()));

    // Concatenate all schema hashes
    let combined: String = sorted_schemas.iter().map(|s| s.hash.as_str()).collect();

    // Calculate SHA256 of combined hashes
    let mut hasher = Sha256::new();
    hasher.update(combined.as_bytes());
    let result = hasher.finalize();
    Ok(hex::encode(result))
}

/// Calculates the SHA256 checksum of a schema
pub fn calculate_schema_checksum(schema: &serde_json::Value) -> Result<String> {
    // Serialize to canonical JSON (map keys are sorted by serde_json)
    let data = serde_json::to_vec(schema)?;

    // Calculate SHA256
    let mut hasher = Sha256::new();
    hasher.update(&data);
    let result = hasher.finalize();
    Ok(hex::encode(result))
}

/// Represents the difference between two manifests
#[derive(Debug, Clone, PartialEq)]
pub struct ManifestDiff {
    /// Schemas present in new but not in old
    pub schemas_added: Vec<SchemaDescriptor>,
    /// Schemas present in old but not in new
    pub schemas_removed: Vec<SchemaDescriptor>,
    /// Schemas present in both but with different hashes
    pub schemas_changed: Vec<SchemaChangeDiff>,
    /// New capabilities
    pub capabilities_added: Vec<String>,
    /// Removed capabilities
    pub capabilities_removed: Vec<String>,
    /// Whether endpoints changed
    pub endpoints_changed: bool,
    /// Whether routing configuration changed
    pub routing_changed: bool,
    /// Whether the routes checksum changed
    pub routes_checksum_changed: bool,
}

/// Represents a changed schema
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SchemaChangeDiff {
    pub schema_type: SchemaType,
    pub old_hash: String,
    pub new_hash: String,
}

impl ManifestDiff {
    /// Returns true if there are any changes
    pub fn has_changes(&self) -> bool {
        !self.schemas_added.is_empty()
            || !self.schemas_removed.is_empty()
            || !self.schemas_changed.is_empty()
            || !self.capabilities_added.is_empty()
            || !self.capabilities_removed.is_empty()
            || self.endpoints_changed
            || self.routing_changed
            || self.routes_checksum_changed
    }

    /// Returns true only if route-affecting changes were detected.
    /// Gateway implementations SHOULD use this to decide whether to remount routes.
    pub fn has_route_changes(&self) -> bool {
        !self.schemas_added.is_empty()
            || !self.schemas_removed.is_empty()
            || self.routing_changed
            || self.routes_checksum_changed
    }
}

/// Compares two manifests and returns the differences
pub fn diff_manifests(old: &SchemaManifest, new: &SchemaManifest) -> ManifestDiff {
    let mut diff = ManifestDiff {
        schemas_added: Vec::new(),
        schemas_removed: Vec::new(),
        schemas_changed: Vec::new(),
        capabilities_added: Vec::new(),
        capabilities_removed: Vec::new(),
        endpoints_changed: false,
        routing_changed: false,
        routes_checksum_changed: false,
    };

    // Build maps for easier comparison
    let old_schemas: HashMap<SchemaType, &SchemaDescriptor> =
        old.schemas.iter().map(|s| (s.schema_type, s)).collect();
    let new_schemas: HashMap<SchemaType, &SchemaDescriptor> =
        new.schemas.iter().map(|s| (s.schema_type, s)).collect();

    // Find added and changed schemas
    for (schema_type, new_schema) in &new_schemas {
        if let Some(old_schema) = old_schemas.get(schema_type) {
            // Schema exists in both, check if changed
            if old_schema.hash != new_schema.hash {
                diff.schemas_changed.push(SchemaChangeDiff {
                    schema_type: *schema_type,
                    old_hash: old_schema.hash.clone(),
                    new_hash: new_schema.hash.clone(),
                });
            }
        } else {
            // Schema is new
            diff.schemas_added.push((*new_schema).clone());
        }
    }

    // Find removed schemas
    for (schema_type, old_schema) in &old_schemas {
        if !new_schemas.contains_key(schema_type) {
            diff.schemas_removed.push((*old_schema).clone());
        }
    }

    // Compare capabilities
    let old_caps: HashSet<&String> = old.capabilities.iter().collect();
    let new_caps: HashSet<&String> = new.capabilities.iter().collect();

    for cap in &new_caps {
        if !old_caps.contains(cap) {
            diff.capabilities_added.push((*cap).clone());
        }
    }

    for cap in &old_caps {
        if !new_caps.contains(cap) {
            diff.capabilities_removed.push((*cap).clone());
        }
    }

    // Compare endpoints (simple comparison)
    if old.endpoints != new.endpoints {
        diff.endpoints_changed = true;
    }

    // Compare routing configuration
    if old.routing != new.routing {
        diff.routing_changed = true;
    }

    // Compare routes checksum
    if old.routes_checksum != new.routes_checksum {
        diff.routes_checksum_changed = true;
    }

    diff
}

/// Calculates a SHA256 hash of the route-affecting fields in a manifest.
/// This hash is used by gateways to detect whether route remounting is needed.
pub fn calculate_routes_checksum(manifest: &SchemaManifest) -> Result<String> {
    #[derive(serde::Serialize)]
    struct RouteEntry {
        path: String,
        methods: Vec<String>,
        protocol: String,
    }

    #[derive(serde::Serialize)]
    struct RouteCanonical {
        strategy: String,
        base_path: String,
        subdomain: String,
        rewrite: Vec<PathRewrite>,
        strip_prefix: bool,
        routes: Vec<RouteEntry>,
        health: String,
        graphql: String,
        openapi: String,
        asyncapi: String,
    }

    let mut sorted_routes: Vec<RouteEntry> = manifest
        .route_table
        .iter()
        .map(|r| {
            let mut methods = r.methods.clone();
            methods.sort();
            RouteEntry {
                path: r.path.clone(),
                methods,
                protocol: r.protocol.clone(),
            }
        })
        .collect();

    sorted_routes.sort_by(|a, b| {
        a.path
            .cmp(&b.path)
            .then_with(|| a.protocol.cmp(&b.protocol))
    });

    let canonical = RouteCanonical {
        strategy: format!("{}", manifest.routing.strategy),
        base_path: manifest.routing.base_path.clone().unwrap_or_default(),
        subdomain: manifest.routing.subdomain.clone().unwrap_or_default(),
        rewrite: manifest.routing.rewrite.clone(),
        strip_prefix: manifest.routing.strip_prefix,
        routes: sorted_routes,
        health: manifest.endpoints.health.clone(),
        graphql: manifest.endpoints.graphql.clone().unwrap_or_default(),
        openapi: manifest.endpoints.openapi.clone().unwrap_or_default(),
        asyncapi: manifest.endpoints.asyncapi.clone().unwrap_or_default(),
    };

    let data = serde_json::to_vec(&canonical).map_err(Error::Serialization)?;

    let mut hasher = Sha256::new();
    hasher.update(&data);
    let result = hasher.finalize();

    Ok(hex::encode(result))
}

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

    #[test]
    fn test_new_manifest() {
        let manifest = new_manifest("test-service", "v1.0.0", "instance-123");
        assert_eq!(manifest.service_name, "test-service");
        assert_eq!(manifest.service_version, "v1.0.0");
        assert_eq!(manifest.instance_id, "instance-123");
        assert_eq!(manifest.version, PROTOCOL_VERSION);
    }

    #[test]
    fn test_add_schema() {
        let mut manifest = new_manifest("test", "v1", "id1");
        let schema = SchemaDescriptor {
            schema_type: SchemaType::OpenAPI,
            spec_version: "3.1.0".to_string(),
            location: SchemaLocation {
                location_type: LocationType::HTTP,
                url: Some("http://example.com/openapi.json".to_string()),
                registry_path: None,
                headers: None,
            },
            content_type: "application/json".to_string(),
            inline_schema: None,
            hash: "a".repeat(64),
            size: 1024,
            compatibility: None,
            metadata: None,
        };

        manifest.add_schema(schema);
        assert_eq!(manifest.schemas.len(), 1);
    }

    #[test]
    fn test_add_capability() {
        let mut manifest = new_manifest("test", "v1", "id1");
        manifest.add_capability("rest");
        manifest.add_capability("grpc");
        manifest.add_capability("rest"); // Duplicate should be ignored

        assert_eq!(manifest.capabilities.len(), 2);
        assert!(manifest.has_capability("rest"));
        assert!(manifest.has_capability("grpc"));
        assert!(!manifest.has_capability("websocket"));
    }

    #[test]
    fn test_validate_schema_descriptor() {
        let valid = SchemaDescriptor {
            schema_type: SchemaType::OpenAPI,
            spec_version: "3.1.0".to_string(),
            location: SchemaLocation {
                location_type: LocationType::HTTP,
                url: Some("http://example.com/openapi.json".to_string()),
                registry_path: None,
                headers: None,
            },
            content_type: "application/json".to_string(),
            inline_schema: None,
            hash: "a".repeat(64),
            size: 1024,
            compatibility: None,
            metadata: None,
        };

        assert!(validate_schema_descriptor(&valid).is_ok());
    }

    #[test]
    fn test_validate_schema_descriptor_invalid_hash() {
        let invalid = SchemaDescriptor {
            schema_type: SchemaType::OpenAPI,
            spec_version: "3.1.0".to_string(),
            location: SchemaLocation {
                location_type: LocationType::HTTP,
                url: Some("http://example.com/openapi.json".to_string()),
                registry_path: None,
                headers: None,
            },
            content_type: "application/json".to_string(),
            inline_schema: None,
            hash: "invalid".to_string(), // Too short
            size: 1024,
            compatibility: None,
            metadata: None,
        };

        assert!(validate_schema_descriptor(&invalid).is_err());
    }

    #[test]
    fn test_calculate_manifest_checksum() {
        let mut manifest = new_manifest("test", "v1", "id1");
        manifest.add_schema(SchemaDescriptor {
            schema_type: SchemaType::OpenAPI,
            spec_version: "3.1.0".to_string(),
            location: SchemaLocation {
                location_type: LocationType::HTTP,
                url: Some("http://example.com".to_string()),
                registry_path: None,
                headers: None,
            },
            content_type: "application/json".to_string(),
            inline_schema: None,
            hash: "a".repeat(64),
            size: 1024,
            compatibility: None,
            metadata: None,
        });

        let checksum = calculate_manifest_checksum(&manifest).unwrap();
        assert_eq!(checksum.len(), 64); // SHA256 produces 64 hex characters
    }

    #[test]
    fn test_diff_manifests() {
        let mut old = new_manifest("test", "v1", "id1");
        old.add_capability("rest");

        let mut new = new_manifest("test", "v1", "id1");
        new.add_capability("grpc");

        let diff = diff_manifests(&old, &new);

        assert_eq!(diff.capabilities_added.len(), 1);
        assert_eq!(diff.capabilities_removed.len(), 1);
        assert!(diff.has_changes());
    }

    #[test]
    fn test_manifest_serialization() {
        let manifest = new_manifest("test-service", "v1.0.0", "instance-123");

        let json = manifest.to_json().unwrap();
        let deserialized = SchemaManifest::from_json(&json).unwrap();

        assert_eq!(deserialized.service_name, "test-service");
        assert_eq!(deserialized.instance_id, "instance-123");
    }
}