-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanifest.go
More file actions
547 lines (452 loc) · 15.6 KB
/
manifest.go
File metadata and controls
547 lines (452 loc) · 15.6 KB
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
package farp
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"slices"
"sort"
"strings"
"time"
)
// NewManifest creates a new schema manifest with default values.
func NewManifest(serviceName, serviceVersion, instanceID string) *SchemaManifest {
return &SchemaManifest{
Version: ProtocolVersion,
ServiceName: serviceName,
ServiceVersion: serviceVersion,
InstanceID: instanceID,
Schemas: []SchemaDescriptor{},
Capabilities: []string{},
Endpoints: SchemaEndpoints{},
Routing: RoutingConfig{
Strategy: MountStrategyService, // Default strategy
},
Auth: AuthConfig{},
Webhook: WebhookConfig{},
UpdatedAt: time.Now().Unix(),
}
}
// AddSchema adds a schema descriptor to the manifest.
func (m *SchemaManifest) AddSchema(descriptor SchemaDescriptor) {
m.Schemas = append(m.Schemas, descriptor)
}
// AddCapability adds a capability to the manifest.
func (m *SchemaManifest) AddCapability(capability string) {
// Check if capability already exists
if slices.Contains(m.Capabilities, capability) {
return
}
m.Capabilities = append(m.Capabilities, capability)
}
// UpdateChecksum recalculates the manifest checksum based on all schema hashes.
func (m *SchemaManifest) UpdateChecksum() error {
checksum, err := CalculateManifestChecksum(m)
if err != nil {
return fmt.Errorf("failed to calculate manifest checksum: %w", err)
}
m.Checksum = checksum
m.UpdatedAt = time.Now().Unix()
return nil
}
// Validate validates the manifest for correctness.
func (m *SchemaManifest) Validate() error {
// Check protocol version compatibility
if !IsCompatible(m.Version) {
return fmt.Errorf("%w: manifest version %s, protocol version %s",
ErrIncompatibleVersion, m.Version, ProtocolVersion)
}
// Check required fields
if m.ServiceName == "" {
return &ValidationError{Field: "service_name", Message: "service name is required"}
}
if m.InstanceID == "" {
return &ValidationError{Field: "instance_id", Message: "instance ID is required"}
}
// Validate health endpoint
if m.Endpoints.Health == "" {
return &ValidationError{Field: "endpoints.health", Message: "health endpoint is required"}
}
// Validate instance metadata if present
if m.Instance != nil {
err := ValidateInstanceMetadata(m.Instance)
if err != nil {
return fmt.Errorf("invalid instance metadata: %w", err)
}
}
// Validate routing configuration
err := ValidateRoutingConfig(&m.Routing)
if err != nil {
return fmt.Errorf("invalid routing config: %w", err)
}
// Validate each schema descriptor
for i, schema := range m.Schemas {
err := ValidateSchemaDescriptor(&schema)
if err != nil {
return fmt.Errorf("invalid schema at index %d: %w", i, err)
}
}
// Verify checksum if present
if m.Checksum != "" {
expectedChecksum, err := CalculateManifestChecksum(m)
if err != nil {
return fmt.Errorf("failed to verify checksum: %w", err)
}
if m.Checksum != expectedChecksum {
return fmt.Errorf("%w: expected %s, got %s", ErrChecksumMismatch, expectedChecksum, m.Checksum)
}
}
return nil
}
// ValidateInstanceMetadata validates instance metadata.
func ValidateInstanceMetadata(im *InstanceMetadata) error {
// Address is required
if im.Address == "" {
return &ValidationError{Field: "address", Message: "instance address is required"}
}
// Weight should be 0-100
if im.Weight < 0 || im.Weight > 100 {
return &ValidationError{Field: "weight", Message: "instance weight must be between 0 and 100"}
}
// Validate deployment metadata if present
if im.Deployment != nil {
if im.Deployment.DeploymentID == "" {
return &ValidationError{Field: "deployment.deployment_id", Message: "deployment ID is required"}
}
if im.Deployment.TrafficPercent < 0 || im.Deployment.TrafficPercent > 100 {
return &ValidationError{Field: "deployment.traffic_percent", Message: "traffic percent must be between 0 and 100"}
}
}
return nil
}
// ValidateRoutingConfig validates routing configuration.
func ValidateRoutingConfig(rc *RoutingConfig) error {
// Validate mount strategy
if rc.Strategy != "" && !rc.Strategy.IsValid() {
return &ValidationError{Field: "routing.strategy", Message: fmt.Sprintf("invalid mount strategy: %s", rc.Strategy)}
}
// Custom strategy requires base path
if rc.Strategy == MountStrategyCustom && rc.BasePath == "" {
return &ValidationError{Field: "routing.base_path", Message: "base path is required for custom mount strategy"}
}
// Subdomain strategy requires subdomain
if rc.Strategy == MountStrategySubdomain && rc.Subdomain == "" {
return &ValidationError{Field: "routing.subdomain", Message: "subdomain is required for subdomain mount strategy"}
}
// Priority should be 0-100
if rc.Priority < 0 || rc.Priority > 100 {
return &ValidationError{Field: "routing.priority", Message: "routing priority must be between 0 and 100"}
}
return nil
}
// GetSchema retrieves a schema descriptor by type.
func (m *SchemaManifest) GetSchema(schemaType SchemaType) (*SchemaDescriptor, bool) {
for i := range m.Schemas {
if m.Schemas[i].Type == schemaType {
return &m.Schemas[i], true
}
}
return nil, false
}
// HasCapability checks if the manifest includes a specific capability.
func (m *SchemaManifest) HasCapability(capability string) bool {
return slices.Contains(m.Capabilities, capability)
}
// Clone creates a deep copy of the manifest.
func (m *SchemaManifest) Clone() *SchemaManifest {
clone := &SchemaManifest{
Version: m.Version,
ServiceName: m.ServiceName,
ServiceVersion: m.ServiceVersion,
InstanceID: m.InstanceID,
Schemas: make([]SchemaDescriptor, len(m.Schemas)),
Capabilities: make([]string, len(m.Capabilities)),
Endpoints: m.Endpoints,
Routing: m.Routing,
UpdatedAt: m.UpdatedAt,
Checksum: m.Checksum,
RoutesChecksum: m.RoutesChecksum,
}
copy(clone.Schemas, m.Schemas)
copy(clone.Capabilities, m.Capabilities)
if len(m.RouteTable) > 0 {
clone.RouteTable = make([]RouteDescriptor, len(m.RouteTable))
copy(clone.RouteTable, m.RouteTable)
}
return clone
}
// ToJSON serializes the manifest to JSON.
func (m *SchemaManifest) ToJSON() ([]byte, error) {
return json.Marshal(m)
}
// ToPrettyJSON serializes the manifest to pretty-printed JSON.
func (m *SchemaManifest) ToPrettyJSON() ([]byte, error) {
return json.MarshalIndent(m, "", " ")
}
// FromJSON deserializes a manifest from JSON.
func FromJSON(data []byte) (*SchemaManifest, error) {
var manifest SchemaManifest
err := json.Unmarshal(data, &manifest)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrInvalidManifest, err)
}
return &manifest, nil
}
// ValidateSchemaDescriptor validates a schema descriptor.
func ValidateSchemaDescriptor(sd *SchemaDescriptor) error {
// Check schema type
if !sd.Type.IsValid() {
return fmt.Errorf("%w: %s", ErrUnsupportedType, sd.Type)
}
// Check spec version
if sd.SpecVersion == "" {
return &ValidationError{Field: "spec_version", Message: "spec version is required"}
}
// Validate location
err := sd.Location.Validate()
if err != nil {
return err
}
// For inline schemas, InlineSchema must be present
if sd.Location.Type == LocationTypeInline && sd.InlineSchema == nil {
return &ValidationError{Field: "inline_schema", Message: "inline schema is required for inline location type"}
}
// Check hash
if sd.Hash == "" {
return &ValidationError{Field: "hash", Message: "schema hash is required"}
}
// Validate hash format (should be 64 hex characters for SHA256)
if len(sd.Hash) != 64 {
return &ValidationError{Field: "hash", Message: "invalid hash format (expected 64 hex characters)"}
}
// Check content type
if sd.ContentType == "" {
return &ValidationError{Field: "content_type", Message: "content type is required"}
}
return nil
}
// CalculateManifestChecksum calculates the SHA256 checksum of a manifest
// by combining all schema hashes in a deterministic order.
func CalculateManifestChecksum(manifest *SchemaManifest) (string, error) {
if len(manifest.Schemas) == 0 {
// Empty manifest has empty checksum
return "", nil
}
// Sort schemas by type for deterministic hashing
sortedSchemas := make([]SchemaDescriptor, len(manifest.Schemas))
copy(sortedSchemas, manifest.Schemas)
sort.Slice(sortedSchemas, func(i, j int) bool {
return sortedSchemas[i].Type < sortedSchemas[j].Type
})
// Concatenate all schema hashes
var (
combined string
combinedSb278 strings.Builder
)
for _, schema := range sortedSchemas {
combinedSb278.WriteString(schema.Hash)
}
combined += combinedSb278.String()
// Calculate SHA256 of combined hashes
hash := sha256.Sum256([]byte(combined))
return hex.EncodeToString(hash[:]), nil
}
// CalculateSchemaChecksum calculates the SHA256 checksum of a schema.
func CalculateSchemaChecksum(schema any) (string, error) {
// Serialize to canonical JSON (map keys are sorted by json.Marshal)
data, err := json.Marshal(schema)
if err != nil {
return "", fmt.Errorf("failed to serialize schema: %w", err)
}
// Calculate SHA256
hash := sha256.Sum256(data)
return hex.EncodeToString(hash[:]), nil
}
// UpdateRoutesChecksum recalculates the routes checksum based on the route table
// and routing configuration. Services SHOULD call this after building their route table.
func (m *SchemaManifest) UpdateRoutesChecksum() error {
checksum, err := CalculateRoutesChecksum(m)
if err != nil {
return fmt.Errorf("failed to calculate routes checksum: %w", err)
}
m.RoutesChecksum = checksum
return nil
}
// CalculateRoutesChecksum calculates a SHA256 hash of the route-affecting fields:
// routing config (strategy, base_path, subdomain, rewrite, strip_prefix) and
// sorted route table entries (path + methods + protocol).
// This hash is used by gateways to detect whether route remounting is needed.
func CalculateRoutesChecksum(manifest *SchemaManifest) (string, error) {
// Build canonical representation of route-affecting fields
type routeEntry struct {
Path string `json:"path"`
Methods []string `json:"methods,omitempty"`
Protocol string `json:"protocol"`
}
type routeCanonical struct {
Strategy string `json:"strategy"`
BasePath string `json:"base_path"`
Subdomain string `json:"subdomain"`
Rewrite []PathRewrite `json:"rewrite"`
StripPrefix bool `json:"strip_prefix"`
Routes []routeEntry `json:"routes"`
Health string `json:"health"`
GraphQL string `json:"graphql"`
OpenAPI string `json:"openapi"`
AsyncAPI string `json:"asyncapi"`
}
// Sort route table entries for deterministic hashing
sortedRoutes := make([]routeEntry, len(manifest.RouteTable))
for i, r := range manifest.RouteTable {
// Sort methods within each route for determinism
methods := make([]string, len(r.Methods))
copy(methods, r.Methods)
sort.Strings(methods)
sortedRoutes[i] = routeEntry{
Path: r.Path,
Methods: methods,
Protocol: r.Protocol,
}
}
sort.Slice(sortedRoutes, func(i, j int) bool {
if sortedRoutes[i].Path != sortedRoutes[j].Path {
return sortedRoutes[i].Path < sortedRoutes[j].Path
}
return sortedRoutes[i].Protocol < sortedRoutes[j].Protocol
})
canonical := routeCanonical{
Strategy: string(manifest.Routing.Strategy),
BasePath: manifest.Routing.BasePath,
Subdomain: manifest.Routing.Subdomain,
Rewrite: manifest.Routing.Rewrite,
StripPrefix: manifest.Routing.StripPrefix,
Routes: sortedRoutes,
Health: manifest.Endpoints.Health,
GraphQL: manifest.Endpoints.GraphQL,
OpenAPI: manifest.Endpoints.OpenAPI,
AsyncAPI: manifest.Endpoints.AsyncAPI,
}
data, err := json.Marshal(canonical)
if err != nil {
return "", fmt.Errorf("failed to serialize route canonical form: %w", err)
}
hash := sha256.Sum256(data)
return hex.EncodeToString(hash[:]), nil
}
// ManifestDiff represents the difference between two manifests.
type ManifestDiff struct {
// SchemasAdded are schemas present in new but not in old
SchemasAdded []SchemaDescriptor
// SchemasRemoved are schemas present in old but not in new
SchemasRemoved []SchemaDescriptor
// SchemasChanged are schemas present in both but with different hashes
SchemasChanged []SchemaChangeDiff
// CapabilitiesAdded are new capabilities
CapabilitiesAdded []string
// CapabilitiesRemoved are removed capabilities
CapabilitiesRemoved []string
// EndpointsChanged indicates if endpoints changed
EndpointsChanged bool
// RoutingChanged indicates if routing configuration changed
RoutingChanged bool
// RoutesChecksumChanged indicates the route table hash changed.
// Gateway implementations SHOULD use this to decide whether to remount routes.
RoutesChecksumChanged bool
}
// SchemaChangeDiff represents a changed schema.
type SchemaChangeDiff struct {
Type SchemaType
OldHash string
NewHash string
}
// HasChanges returns true if there are any changes.
func (d *ManifestDiff) HasChanges() bool {
return len(d.SchemasAdded) > 0 ||
len(d.SchemasRemoved) > 0 ||
len(d.SchemasChanged) > 0 ||
len(d.CapabilitiesAdded) > 0 ||
len(d.CapabilitiesRemoved) > 0 ||
d.EndpointsChanged ||
d.RoutingChanged ||
d.RoutesChecksumChanged
}
// HasRouteChanges returns true only if route-affecting changes were detected.
// Gateway implementations SHOULD use this to decide whether to remount routes.
// This prevents unnecessary route remounts that cause intermittent 404s.
func (d *ManifestDiff) HasRouteChanges() bool {
return len(d.SchemasAdded) > 0 ||
len(d.SchemasRemoved) > 0 ||
d.RoutingChanged ||
d.RoutesChecksumChanged
}
// DiffManifests compares two manifests and returns the differences.
func DiffManifests(old, newManifest *SchemaManifest) *ManifestDiff {
diff := &ManifestDiff{}
// Build maps for easier comparison
oldSchemas := make(map[SchemaType]SchemaDescriptor)
for _, s := range old.Schemas {
oldSchemas[s.Type] = s
}
newSchemas := make(map[SchemaType]SchemaDescriptor)
for _, s := range newManifest.Schemas {
newSchemas[s.Type] = s
}
// Find added and changed schemas
for schemaType, newSchema := range newSchemas {
if oldSchema, exists := oldSchemas[schemaType]; exists {
// Schema exists in both, check if changed
if oldSchema.Hash != newSchema.Hash {
diff.SchemasChanged = append(diff.SchemasChanged, SchemaChangeDiff{
Type: schemaType,
OldHash: oldSchema.Hash,
NewHash: newSchema.Hash,
})
}
} else {
// Schema is new
diff.SchemasAdded = append(diff.SchemasAdded, newSchema)
}
}
// Find removed schemas
for schemaType, oldSchema := range oldSchemas {
if _, exists := newSchemas[schemaType]; !exists {
diff.SchemasRemoved = append(diff.SchemasRemoved, oldSchema)
}
}
// Compare capabilities
oldCaps := make(map[string]bool)
for _, c := range old.Capabilities {
oldCaps[c] = true
}
newCaps := make(map[string]bool)
for _, c := range newManifest.Capabilities {
newCaps[c] = true
}
for cap := range newCaps {
if !oldCaps[cap] {
diff.CapabilitiesAdded = append(diff.CapabilitiesAdded, cap)
}
}
for cap := range oldCaps {
if !newCaps[cap] {
diff.CapabilitiesRemoved = append(diff.CapabilitiesRemoved, cap)
}
}
// Compare endpoints (simple comparison)
if old.Endpoints != newManifest.Endpoints {
diff.EndpointsChanged = true
}
// Compare routing configuration
if old.Routing.Strategy != newManifest.Routing.Strategy ||
old.Routing.BasePath != newManifest.Routing.BasePath ||
old.Routing.Subdomain != newManifest.Routing.Subdomain ||
old.Routing.StripPrefix != newManifest.Routing.StripPrefix ||
old.Routing.Priority != newManifest.Routing.Priority {
diff.RoutingChanged = true
}
// Compare routes checksum (fast path for route change detection)
if old.RoutesChecksum != newManifest.RoutesChecksum {
diff.RoutesChecksumChanged = true
}
return diff
}