-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.go
More file actions
1782 lines (1301 loc) · 55.4 KB
/
types.go
File metadata and controls
1782 lines (1301 loc) · 55.4 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
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package farp
import "fmt"
// SchemaType represents supported schema/protocol types.
type SchemaType string
const (
// SchemaTypeOpenAPI represents OpenAPI/Swagger specifications.
SchemaTypeOpenAPI SchemaType = "openapi"
// SchemaTypeAsyncAPI represents AsyncAPI specifications.
SchemaTypeAsyncAPI SchemaType = "asyncapi"
// SchemaTypeGRPC represents gRPC protocol buffer definitions.
SchemaTypeGRPC SchemaType = "grpc"
// SchemaTypeGraphQL represents GraphQL Schema Definition Language.
SchemaTypeGraphQL SchemaType = "graphql"
// SchemaTypeORPC represents oRPC (OpenAPI-based RPC) specifications.
SchemaTypeORPC SchemaType = "orpc"
// SchemaTypeThrift represents Apache Thrift IDL (future support).
SchemaTypeThrift SchemaType = "thrift"
// SchemaTypeAvro represents Apache Avro schemas (future support).
SchemaTypeAvro SchemaType = "avro"
// SchemaTypeCustom represents custom/proprietary schema types.
SchemaTypeCustom SchemaType = "custom"
)
// IsValid checks if the schema type is valid.
func (st SchemaType) IsValid() bool {
switch st {
case SchemaTypeOpenAPI, SchemaTypeAsyncAPI, SchemaTypeGRPC,
SchemaTypeGraphQL, SchemaTypeORPC, SchemaTypeThrift, SchemaTypeAvro, SchemaTypeCustom:
return true
default:
return false
}
}
// String returns the string representation of the schema type.
func (st SchemaType) String() string {
return string(st)
}
// LocationType represents how schemas can be retrieved.
type LocationType string
const (
// LocationTypeHTTP means fetch schema via HTTP GET.
LocationTypeHTTP LocationType = "http"
// LocationTypeRegistry means fetch schema from backend KV store.
LocationTypeRegistry LocationType = "registry"
// LocationTypeInline means schema is embedded in the manifest.
LocationTypeInline LocationType = "inline"
)
// IsValid checks if the location type is valid.
func (lt LocationType) IsValid() bool {
switch lt {
case LocationTypeHTTP, LocationTypeRegistry, LocationTypeInline:
return true
default:
return false
}
}
// String returns the string representation of the location type.
func (lt LocationType) String() string {
return string(lt)
}
// SchemaManifest describes all API contracts for a service instance.
type SchemaManifest struct {
// Version of the FARP protocol (semver)
Version string `json:"version"`
// Service identity
ServiceName string `json:"service_name"`
ServiceVersion string `json:"service_version"`
InstanceID string `json:"instance_id"`
// Instance metadata
Instance *InstanceMetadata `json:"instance,omitempty"`
// Schemas exposed by this instance
Schemas []SchemaDescriptor `json:"schemas"`
// Capabilities/protocols supported (e.g., ["rest", "grpc", "websocket"])
Capabilities []string `json:"capabilities"`
// Endpoints for introspection and health
Endpoints SchemaEndpoints `json:"endpoints"`
// Routing configuration for gateway federation
Routing RoutingConfig `json:"routing"`
// Authentication configuration
Auth AuthConfig `json:"auth,omitempty"`
// Webhook for bidirectional communication
Webhook WebhookConfig `json:"webhook,omitempty"`
// Service operational hints (non-binding)
Hints *ServiceHints `json:"hints,omitempty"`
// Route table: pre-computed list of routes the service exposes.
// When present, gateways can use this directly instead of parsing schemas.
// This enables fast route-change detection without schema fetching.
RouteTable []RouteDescriptor `json:"route_table,omitempty"`
// Change tracking
UpdatedAt int64 `json:"updated_at"` // Unix timestamp
Checksum string `json:"checksum"` // SHA256 of all schemas combined
// RoutesChecksum is a SHA256 hash of the computed route table.
// It covers: route paths, methods, mount strategy, base path, rewrite rules.
// Gateways SHOULD compare this value before remounting routes.
// If unchanged, the gateway MUST skip route remounting to avoid intermittent 404s.
RoutesChecksum string `json:"routes_checksum,omitempty"`
}
// SchemaDescriptor describes a single API schema/contract.
type SchemaDescriptor struct {
// Type of schema (openapi, asyncapi, grpc, graphql, etc.)
Type SchemaType `json:"type"`
// Specification version (e.g., "3.1.0" for OpenAPI, "3.0.0" for AsyncAPI)
SpecVersion string `json:"spec_version"`
// How to retrieve the schema
Location SchemaLocation `json:"location"`
// Content type (e.g., "application/json", "application/x-protobuf")
ContentType string `json:"content_type"`
// Optional: Inline schema for small schemas (< 100KB recommended)
InlineSchema any `json:"inline_schema,omitempty"`
// Integrity validation
Hash string `json:"hash"` // SHA256 of schema content
Size int64 `json:"size"` // Size in bytes
// Schema compatibility metadata
Compatibility *SchemaCompatibility `json:"compatibility,omitempty"`
// Protocol-specific metadata
Metadata *ProtocolMetadata `json:"metadata,omitempty"`
}
// SchemaLocation describes where and how to fetch a schema.
type SchemaLocation struct {
// Location type (http, registry, inline)
Type LocationType `json:"type"`
// HTTP URL (if Type == HTTP)
// Example: "http://user-service:8080/openapi.json"
URL string `json:"url,omitempty"`
// Registry path in backend KV store (if Type == Registry)
// Example: "/schemas/user-service/v1/openapi"
RegistryPath string `json:"registry_path,omitempty"`
// HTTP headers for authentication (if Type == HTTP)
// Example: {"Authorization": "Bearer token"}
Headers map[string]string `json:"headers,omitempty"`
}
// Validate checks if the schema location is valid.
func (sl *SchemaLocation) Validate() error {
if !sl.Type.IsValid() {
return fmt.Errorf("%w: invalid location type: %s", ErrInvalidLocation, sl.Type)
}
switch sl.Type {
case LocationTypeHTTP:
if sl.URL == "" {
return fmt.Errorf("%w: URL required for HTTP location", ErrInvalidLocation)
}
case LocationTypeRegistry:
if sl.RegistryPath == "" {
return fmt.Errorf("%w: registry path required for registry location", ErrInvalidLocation)
}
case LocationTypeInline:
// No additional validation needed for inline
}
return nil
}
// SchemaEndpoints provides URLs for service introspection.
type SchemaEndpoints struct {
// Health check endpoint (required)
// Example: "/health" or "/healthz"
Health string `json:"health"`
// Prometheus metrics endpoint (optional)
// Example: "/metrics"
Metrics string `json:"metrics,omitempty"`
// OpenAPI spec endpoint (optional)
// Example: "/openapi.json"
OpenAPI string `json:"openapi,omitempty"`
// AsyncAPI spec endpoint (optional)
// Example: "/asyncapi.json"
AsyncAPI string `json:"asyncapi,omitempty"`
// Whether gRPC server reflection is enabled
GRPCReflection bool `json:"grpc_reflection,omitempty"`
// GraphQL introspection endpoint (optional)
// Example: "/graphql"
GraphQL string `json:"graphql,omitempty"`
// Documentation URL for human-readable API docs
// Example: "https://docs.example.com/user-service"
Documentation string `json:"documentation,omitempty"`
// Changelog URL for API change history
// Example: "https://docs.example.com/user-service/changelog"
Changelog string `json:"changelog,omitempty"`
}
// Capability represents a protocol capability.
type Capability string
const (
// CapabilityREST indicates REST API support.
CapabilityREST Capability = "rest"
// CapabilityGRPC indicates gRPC support.
CapabilityGRPC Capability = "grpc"
// CapabilityWebSocket indicates WebSocket support.
CapabilityWebSocket Capability = "websocket"
// CapabilitySSE indicates Server-Sent Events support.
CapabilitySSE Capability = "sse"
// CapabilityGraphQL indicates GraphQL support.
CapabilityGraphQL Capability = "graphql"
// CapabilityMQTT indicates MQTT support.
CapabilityMQTT Capability = "mqtt"
// CapabilityAMQP indicates AMQP support.
CapabilityAMQP Capability = "amqp"
)
// String returns the string representation of the capability.
func (c Capability) String() string {
return string(c)
}
// InstanceMetadata provides information about a service instance.
type InstanceMetadata struct {
// Instance address (host:port)
Address string `json:"address"`
// Instance region/zone/datacenter
Region string `json:"region,omitempty"`
Zone string `json:"zone,omitempty"`
// Instance labels for selection
Labels map[string]string `json:"labels,omitempty"`
// Instance weight for load balancing (0-100, default: 100)
Weight int `json:"weight,omitempty"`
// Instance status
Status InstanceStatus `json:"status"`
// Instance role in deployment
Role InstanceRole `json:"role,omitempty"`
// Canary/blue-green deployment metadata
Deployment *DeploymentMetadata `json:"deployment,omitempty"`
// Instance start time
StartedAt int64 `json:"started_at"` // Unix timestamp
// Expected schema checksum (for validation)
ExpectedSchemaChecksum string `json:"expected_schema_checksum,omitempty"`
}
// InstanceStatus represents the status of a service instance.
type InstanceStatus string
const (
// InstanceStatusStarting indicates the instance is starting.
InstanceStatusStarting InstanceStatus = "starting"
// InstanceStatusHealthy indicates the instance is healthy.
InstanceStatusHealthy InstanceStatus = "healthy"
// InstanceStatusDegraded indicates the instance is degraded.
InstanceStatusDegraded InstanceStatus = "degraded"
// InstanceStatusUnhealthy indicates the instance is unhealthy.
InstanceStatusUnhealthy InstanceStatus = "unhealthy"
// InstanceStatusDraining indicates the instance is draining connections.
InstanceStatusDraining InstanceStatus = "draining"
// InstanceStatusStopping indicates the instance is stopping.
InstanceStatusStopping InstanceStatus = "stopping"
)
// String returns the string representation of the instance status.
func (is InstanceStatus) String() string {
return string(is)
}
// InstanceRole represents the role of an instance in a deployment.
type InstanceRole string
const (
// InstanceRolePrimary indicates the instance is primary/production.
InstanceRolePrimary InstanceRole = "primary"
// InstanceRoleCanary indicates the instance is a canary deployment.
InstanceRoleCanary InstanceRole = "canary"
// InstanceRoleBlue indicates the instance is part of blue deployment.
InstanceRoleBlue InstanceRole = "blue"
// InstanceRoleGreen indicates the instance is part of green deployment.
InstanceRoleGreen InstanceRole = "green"
// InstanceRoleShadow indicates the instance is a shadow deployment.
InstanceRoleShadow InstanceRole = "shadow"
)
// String returns the string representation of the instance role.
func (ir InstanceRole) String() string {
return string(ir)
}
// DeploymentMetadata provides information about a deployment.
type DeploymentMetadata struct {
// Deployment ID
DeploymentID string `json:"deployment_id"`
// Deployment strategy
Strategy DeploymentStrategy `json:"strategy"`
// Traffic percentage (0-100)
TrafficPercent int `json:"traffic_percent,omitempty"`
// Deployment stage
Stage string `json:"stage,omitempty"` // "canary", "rollout", "stable"
// Deployment time
DeployedAt int64 `json:"deployed_at"`
}
// DeploymentStrategy represents the deployment strategy.
type DeploymentStrategy string
const (
// DeploymentStrategyRolling indicates a rolling update deployment.
DeploymentStrategyRolling DeploymentStrategy = "rolling"
// DeploymentStrategyCanary indicates a canary deployment.
DeploymentStrategyCanary DeploymentStrategy = "canary"
// DeploymentStrategyBlueGreen indicates a blue-green deployment.
DeploymentStrategyBlueGreen DeploymentStrategy = "blue_green"
// DeploymentStrategyShadow indicates a shadow deployment.
DeploymentStrategyShadow DeploymentStrategy = "shadow"
// DeploymentStrategyRecreate indicates a recreate deployment.
DeploymentStrategyRecreate DeploymentStrategy = "recreate"
)
// String returns the string representation of the deployment strategy.
func (ds DeploymentStrategy) String() string {
return string(ds)
}
// RoutingConfig provides gateway route mounting configuration.
type RoutingConfig struct {
// Mounting strategy
Strategy MountStrategy `json:"strategy"`
// Base path for mounting (used with path-based strategies)
BasePath string `json:"base_path,omitempty"`
// Subdomain for mounting (used with subdomain strategy)
Subdomain string `json:"subdomain,omitempty"`
// Path rewriting rules
Rewrite []PathRewrite `json:"rewrite,omitempty"`
// Strip prefix before forwarding to service
StripPrefix bool `json:"strip_prefix,omitempty"`
// Priority for conflict resolution (higher = higher priority)
Priority int `json:"priority,omitempty"`
// Tags for route grouping and filtering
Tags []string `json:"tags,omitempty"`
// Default middleware applied to all routes for this service
Middleware []MiddlewareDeclaration `json:"middleware,omitempty"`
// API versioning strategy
Versioning *APIVersioningConfig `json:"versioning,omitempty"`
// Path include/exclude rules for controlling which routes are published
// to the gateway. Rules are evaluated in order; first match wins.
// Paths not matching any rule are included by default.
// Supports glob patterns: "*" matches one segment, "**" matches zero or more.
PathRules []PathRule `json:"path_rules,omitempty"`
}
// PathRule defines an include or exclude rule for API paths.
type PathRule struct {
// Glob pattern to match against paths.
// Examples: "/api/v1/*", "/internal/**", "/health", "/api/users/*"
// "*" matches a single path segment, "**" matches zero or more segments.
Pattern string `json:"pattern"`
// Action to take when the pattern matches: "include" or "exclude".
Action PathRuleAction `json:"action"`
}
// PathRuleAction is the action for a path rule.
type PathRuleAction string
const (
// PathRuleInclude includes matching paths in published schemas.
PathRuleInclude PathRuleAction = "include"
// PathRuleExclude excludes matching paths from published schemas.
PathRuleExclude PathRuleAction = "exclude"
)
// MountStrategy defines how routes are mounted in the gateway.
type MountStrategy string
const (
// MountStrategyRoot merges service routes to gateway root (no prefix).
MountStrategyRoot MountStrategy = "root"
// MountStrategyInstance mounts under /instance-id/*.
MountStrategyInstance MountStrategy = "instance"
// MountStrategyService mounts under /service-name/* (default).
MountStrategyService MountStrategy = "service"
// MountStrategyVersioned mounts under /service-name/version/*.
MountStrategyVersioned MountStrategy = "versioned"
// MountStrategyCustom mounts under custom base path.
MountStrategyCustom MountStrategy = "custom"
// MountStrategySubdomain mounts on subdomain: service.gateway.com.
MountStrategySubdomain MountStrategy = "subdomain"
)
// String returns the string representation of the mount strategy.
func (ms MountStrategy) String() string {
return string(ms)
}
// IsValid checks if the mount strategy is valid.
func (ms MountStrategy) IsValid() bool {
switch ms {
case MountStrategyRoot, MountStrategyInstance, MountStrategyService,
MountStrategyVersioned, MountStrategyCustom, MountStrategySubdomain:
return true
default:
return false
}
}
// PathRewrite defines a path rewriting rule.
type PathRewrite struct {
// Pattern to match (regex)
Pattern string `json:"pattern"`
// Replacement string
Replacement string `json:"replacement"`
}
// AuthConfig provides authentication and authorization configuration.
type AuthConfig struct {
// Authentication schemes supported by service
Schemes []AuthScheme `json:"schemes"`
// Required permissions/scopes
RequiredScopes []string `json:"required_scopes,omitempty"`
// Access control rules
AccessControl []AccessRule `json:"access_control,omitempty"`
// Token validation endpoint
TokenValidationURL string `json:"token_validation_url,omitempty"`
// Public (unauthenticated) routes
PublicRoutes []string `json:"public_routes,omitempty"`
}
// AuthScheme describes an authentication scheme.
type AuthScheme struct {
// Scheme type
Type AuthType `json:"type"`
// Scheme configuration (varies by type)
Config map[string]any `json:"config,omitempty"`
}
// AuthType represents an authentication type.
type AuthType string
const (
// AuthTypeBearer indicates Bearer token authentication (JWT, opaque).
AuthTypeBearer AuthType = "bearer"
// AuthTypeAPIKey indicates API key authentication.
AuthTypeAPIKey AuthType = "apikey"
// AuthTypeBasic indicates Basic authentication.
AuthTypeBasic AuthType = "basic"
// AuthTypeMTLS indicates Mutual TLS authentication.
AuthTypeMTLS AuthType = "mtls"
// AuthTypeOAuth2 indicates OAuth 2.0 authentication.
AuthTypeOAuth2 AuthType = "oauth2"
// AuthTypeOIDC indicates OpenID Connect authentication.
AuthTypeOIDC AuthType = "oidc"
// AuthTypeCustom indicates custom authentication scheme.
AuthTypeCustom AuthType = "custom"
)
// String returns the string representation of the auth type.
func (at AuthType) String() string {
return string(at)
}
// AccessRule defines an access control rule.
type AccessRule struct {
// Path pattern (glob or regex)
Path string `json:"path"`
// HTTP methods
Methods []string `json:"methods"`
// Required roles
Roles []string `json:"roles,omitempty"`
// Required permissions
Permissions []string `json:"permissions,omitempty"`
// Allow anonymous access
AllowAnonymous bool `json:"allow_anonymous,omitempty"`
}
// WebhookConfig provides bidirectional communication configuration.
type WebhookConfig struct {
// Webhook endpoint on service for gateway notifications
ServiceWebhook string `json:"service_webhook,omitempty"`
// Webhook endpoint on gateway for service notifications
GatewayWebhook string `json:"gateway_webhook,omitempty"`
// Webhook secret for HMAC signature verification
Secret string `json:"secret,omitempty"`
// Event types service wants to receive from gateway
SubscribeEvents []WebhookEventType `json:"subscribe_events,omitempty"`
// Event types service will send to gateway
PublishEvents []WebhookEventType `json:"publish_events,omitempty"`
// Retry configuration
Retry RetryConfig `json:"retry,omitempty"`
// HTTP-based communication routes (alternative to push webhooks)
HTTPRoutes *HTTPCommunicationRoutes `json:"http_routes,omitempty"`
}
// HTTPCommunicationRoutes defines HTTP communication routes.
type HTTPCommunicationRoutes struct {
// Service exposes these routes for gateway to call
ServiceRoutes []CommunicationRoute `json:"service_routes,omitempty"`
// Gateway exposes these routes for service to call
GatewayRoutes []CommunicationRoute `json:"gateway_routes,omitempty"`
// Polling configuration if HTTP polling is used
Polling *PollingConfig `json:"polling,omitempty"`
}
// CommunicationRoute defines a communication route.
type CommunicationRoute struct {
// Route identifier
ID string `json:"id"`
// Route path
Path string `json:"path"`
// HTTP method
Method string `json:"method"`
// Route purpose/type
Type CommunicationRouteType `json:"type"`
// Description
Description string `json:"description,omitempty"`
// Request schema (JSON Schema, OpenAPI schema, etc.)
RequestSchema any `json:"request_schema,omitempty"`
// Response schema
ResponseSchema any `json:"response_schema,omitempty"`
// Authentication required
AuthRequired bool `json:"auth_required"`
// Idempotent operation
Idempotent bool `json:"idempotent"`
// Expected timeout
Timeout string `json:"timeout,omitempty"`
}
// CommunicationRouteType defines the type of communication route.
type CommunicationRouteType string
const (
// RouteTypeControl indicates control plane operations.
RouteTypeControl CommunicationRouteType = "control"
// RouteTypeAdmin indicates admin operations.
RouteTypeAdmin CommunicationRouteType = "admin"
// RouteTypeManagement indicates management operations.
RouteTypeManagement CommunicationRouteType = "management"
// RouteTypeLifecycleStart indicates lifecycle start hook.
RouteTypeLifecycleStart CommunicationRouteType = "lifecycle.start"
// RouteTypeLifecycleStop indicates lifecycle stop hook.
RouteTypeLifecycleStop CommunicationRouteType = "lifecycle.stop"
// RouteTypeLifecycleReload indicates lifecycle reload hook.
RouteTypeLifecycleReload CommunicationRouteType = "lifecycle.reload"
// RouteTypeConfigUpdate indicates config update.
RouteTypeConfigUpdate CommunicationRouteType = "config.update"
// RouteTypeConfigQuery indicates config query.
RouteTypeConfigQuery CommunicationRouteType = "config.query"
// RouteTypeEventPoll indicates event polling.
RouteTypeEventPoll CommunicationRouteType = "event.poll"
// RouteTypeEventAck indicates event acknowledgment.
RouteTypeEventAck CommunicationRouteType = "event.ack"
// RouteTypeHealthCheck indicates health check.
RouteTypeHealthCheck CommunicationRouteType = "health.check"
// RouteTypeStatusQuery indicates status query.
RouteTypeStatusQuery CommunicationRouteType = "status.query"
// RouteTypeSchemaQuery indicates schema query.
RouteTypeSchemaQuery CommunicationRouteType = "schema.query"
// RouteTypeSchemaValidate indicates schema validation.
RouteTypeSchemaValidate CommunicationRouteType = "schema.validate"
// RouteTypeMetricsQuery indicates metrics query.
RouteTypeMetricsQuery CommunicationRouteType = "metrics.query"
// RouteTypeTracingExport indicates tracing export.
RouteTypeTracingExport CommunicationRouteType = "tracing.export"
// RouteTypeCustom indicates custom route type.
RouteTypeCustom CommunicationRouteType = "custom"
)
// String returns the string representation of the communication route type.
func (crt CommunicationRouteType) String() string {
return string(crt)
}
// PollingConfig defines polling configuration.
type PollingConfig struct {
// Polling interval
Interval string `json:"interval"` // Duration string
// Polling timeout
Timeout string `json:"timeout,omitempty"`
// Long polling support
LongPolling bool `json:"long_polling,omitempty"`
// Long polling timeout
LongPollingTimeout string `json:"long_polling_timeout,omitempty"`
}
// WebhookEventType defines types of webhook events.
type WebhookEventType string
const (
// EventSchemaUpdated indicates schema was updated.
EventSchemaUpdated WebhookEventType = "schema.updated"
// EventHealthChanged indicates health status changed.
EventHealthChanged WebhookEventType = "health.changed"
// EventInstanceScaling indicates instance scaling event.
EventInstanceScaling WebhookEventType = "instance.scaling"
// EventMaintenanceMode indicates maintenance mode event.
EventMaintenanceMode WebhookEventType = "maintenance.mode"
// EventRateLimitChanged indicates rate limit changed.
EventRateLimitChanged WebhookEventType = "ratelimit.changed"
// EventCircuitBreakerOpen indicates circuit breaker opened.
EventCircuitBreakerOpen WebhookEventType = "circuit.breaker.open"
// EventCircuitBreakerClosed indicates circuit breaker closed.
EventCircuitBreakerClosed WebhookEventType = "circuit.breaker.closed"
// EventConfigUpdated indicates config was updated.
EventConfigUpdated WebhookEventType = "config.updated"
// EventTrafficShift indicates traffic shift event.
EventTrafficShift WebhookEventType = "traffic.shift"
// EventRoutesChanging indicates routes are about to change (pre-notification).
// Gateways can use this to prepare for the route swap.
EventRoutesChanging WebhookEventType = "routes.changing"
// EventRoutesChanged indicates routes have been changed/swapped.
EventRoutesChanged WebhookEventType = "routes.changed"
// EventRoutesDraining indicates old routes are draining connections.
EventRoutesDraining WebhookEventType = "routes.draining"
// EventGatewayShutdown indicates the gateway is shutting down.
// Services receive this as a fire-and-forget notification so they can
// adjust behavior (e.g., buffer events, switch to fallback, re-discover).
EventGatewayShutdown WebhookEventType = "gateway.shutdown"
)
// String returns the string representation of the webhook event type.
func (wet WebhookEventType) String() string {
return string(wet)
}
// WebhookEvent is the payload sent to service webhook endpoints.
type WebhookEvent struct {
// Type of event
Type WebhookEventType `json:"type"`
// Timestamp of the event (Unix seconds)
Timestamp int64 `json:"timestamp"`
// Source identifier (e.g., gateway instance ID)
Source string `json:"source,omitempty"`
// Optional data payload specific to the event type
Data map[string]any `json:"data,omitempty"`
}
// RetryConfig defines retry configuration.
type RetryConfig struct {
// Maximum retry attempts
MaxAttempts int `json:"max_attempts"`
// Initial retry delay
InitialDelay string `json:"initial_delay"` // Duration string
// Maximum retry delay
MaxDelay string `json:"max_delay"`
// Backoff multiplier
Multiplier float64 `json:"multiplier"`
// Retryable HTTP status codes (default: [502, 503, 504])
RetryableStatusCodes []int `json:"retryable_status_codes,omitempty"`
// Retryable HTTP methods (default: GET, HEAD, OPTIONS)
RetryableMethods []string `json:"retryable_methods,omitempty"`
// Retry on connection errors (timeouts, refused, reset)
RetryOnConnectionError bool `json:"retry_on_connection_error,omitempty"`
// Per-attempt timeout (overrides global timeout for each retry)
PerAttemptTimeout string `json:"per_attempt_timeout,omitempty"`
}
// SchemaCompatibility provides schema compatibility metadata.
type SchemaCompatibility struct {
// Compatibility mode
Mode CompatibilityMode `json:"mode"`
// Previous schema versions (for lineage tracking)
PreviousVersions []string `json:"previous_versions,omitempty"`
// Breaking changes from previous version
BreakingChanges []BreakingChange `json:"breaking_changes,omitempty"`
// Deprecation notices
Deprecations []Deprecation `json:"deprecations,omitempty"`
}
// CompatibilityMode defines schema compatibility guarantees.
type CompatibilityMode string
const (
// CompatibilityBackward indicates new schema can read data written by old schema.
CompatibilityBackward CompatibilityMode = "backward"
// CompatibilityForward indicates old schema can read data written by new schema.
CompatibilityForward CompatibilityMode = "forward"
// CompatibilityFull indicates both backward and forward compatible.
CompatibilityFull CompatibilityMode = "full"
// CompatibilityNone indicates breaking changes, no compatibility guaranteed.
CompatibilityNone CompatibilityMode = "none"
// CompatibilityBackwardTransitive indicates transitive backward compatibility across N versions.
CompatibilityBackwardTransitive CompatibilityMode = "backward_transitive"
// CompatibilityForwardTransitive indicates transitive forward compatibility across N versions.
CompatibilityForwardTransitive CompatibilityMode = "forward_transitive"
)
// String returns the string representation of the compatibility mode.
func (cm CompatibilityMode) String() string {
return string(cm)
}
// BreakingChange describes a breaking change in a schema.
type BreakingChange struct {
// Type of breaking change
Type ChangeType `json:"type"`
// Path in schema (e.g., "/paths/users/get", "User.email")
Path string `json:"path"`
// Human-readable description
Description string `json:"description"`
// Severity level
Severity ChangeSeverity `json:"severity"`
// Migration instructions
Migration string `json:"migration,omitempty"`
}
// ChangeType defines types of schema changes.
type ChangeType string
const (
// ChangeTypeFieldRemoved indicates a field was removed.
ChangeTypeFieldRemoved ChangeType = "field_removed"
// ChangeTypeFieldTypeChanged indicates a field type was changed.
ChangeTypeFieldTypeChanged ChangeType = "field_type_changed"
// ChangeTypeFieldRequired indicates a field became required.
ChangeTypeFieldRequired ChangeType = "field_required"
// ChangeTypeEndpointRemoved indicates an endpoint was removed.
ChangeTypeEndpointRemoved ChangeType = "endpoint_removed"
// ChangeTypeEndpointChanged indicates an endpoint was changed.
ChangeTypeEndpointChanged ChangeType = "endpoint_changed"
// ChangeTypeEnumValueRemoved indicates an enum value was removed.
ChangeTypeEnumValueRemoved ChangeType = "enum_value_removed"
// ChangeTypeMethodRemoved indicates a method was removed.
ChangeTypeMethodRemoved ChangeType = "method_removed"
)
// String returns the string representation of the change type.
func (ct ChangeType) String() string {
return string(ct)
}
// ChangeSeverity defines the severity of a schema change.
type ChangeSeverity string
const (
// SeverityCritical indicates immediate breakage.
SeverityCritical ChangeSeverity = "critical"
// SeverityHigh indicates likely breakage.
SeverityHigh ChangeSeverity = "high"
// SeverityMedium indicates possible breakage.
SeverityMedium ChangeSeverity = "medium"
// SeverityLow indicates minimal risk.
SeverityLow ChangeSeverity = "low"
)
// String returns the string representation of the change severity.
func (cs ChangeSeverity) String() string {
return string(cs)
}
// Deprecation describes a deprecated schema element.
type Deprecation struct {
// Path in schema
Path string `json:"path"`
// Deprecation date (ISO 8601)
DeprecatedAt string `json:"deprecated_at"`
// Planned removal date (ISO 8601)
RemovalDate string `json:"removal_date,omitempty"`
// Replacement recommendation
Replacement string `json:"replacement,omitempty"`
// Migration guide
Migration string `json:"migration,omitempty"`
// Reason for deprecation
Reason string `json:"reason,omitempty"`
}
// ServiceHints provides operational hints for the gateway.
// All hints are non-binding — gateways may choose to honor or ignore them.
type ServiceHints struct {
// Recommended timeout for operations
RecommendedTimeout string `json:"recommended_timeout,omitempty"`
// Expected latency profile
ExpectedLatency *LatencyProfile `json:"expected_latency,omitempty"`
// Scaling characteristics
Scaling *ScalingProfile `json:"scaling,omitempty"`
// Dependencies on other services
Dependencies []ServiceDependency `json:"dependencies,omitempty"`
// Rate limiting configuration (service-level default)
RateLimit *RateLimitConfig `json:"rate_limit,omitempty"`
// Circuit breaker configuration
CircuitBreaker *CircuitBreakerConfig `json:"circuit_breaker,omitempty"`
// CORS configuration (service-level default)
CORS *CORSConfig `json:"cors,omitempty"`
// Retry policy configuration
RetryPolicy *RetryConfig `json:"retry_policy,omitempty"`
// Observability configuration (tracing, metrics)
Observability *ObservabilityConfig `json:"observability,omitempty"`
// Graceful shutdown configuration
GracefulShutdown *GracefulShutdownConfig `json:"graceful_shutdown,omitempty"`
// Response caching configuration (service-level default)
Cache *CacheConfig `json:"cache,omitempty"`
// Load balancing configuration
LoadBalancing *LoadBalancingConfig `json:"load_balancing,omitempty"`
// Request/response transformation hints
Transformations *TransformationConfig `json:"transformations,omitempty"`
}
// LatencyProfile describes expected latency characteristics.
type LatencyProfile struct {
// Median latency
P50 string `json:"p50,omitempty"` // e.g., "10ms"
// 95th percentile
P95 string `json:"p95,omitempty"` // e.g., "50ms"
// 99th percentile
P99 string `json:"p99,omitempty"` // e.g., "100ms"
// 99.9th percentile
P999 string `json:"p999,omitempty"` // e.g., "500ms"