rskit-discovery 0.2.0-alpha.2

Service discovery with load balancing strategies
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
//! Service discovery configuration.
//!
//! Mirrors gokit's `discovery.Config` — all three kits use the same config shape
//! so services are structurally identical regardless of language.

use std::collections::HashMap;

use rskit_errors::{AppError, AppResult};
use rskit_util::time::parse_duration;
use serde::Deserialize;

/// Top-level discovery configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct DiscoveryConfig {
    /// Whether discovery is active.
    pub enabled: bool,
    /// Discovery backend: `"consul"`, `"static"`, etc.
    pub provider: String,
    /// Provider address (e.g. `"localhost:8500"` for Consul). Generic —
    /// every remote provider needs an address.
    pub addr: String,
    /// URI scheme for the provider connection (`"http"`, `"https"`).
    pub scheme: String,
    /// Auth token for the discovery provider.
    pub token: String,
    /// Self-registration settings.
    pub registration: RegistrationConfig,
    /// Health check settings for registered services.
    pub health: HealthConfig,
    /// How long discovered endpoints are cached (e.g. `"30s"`).
    pub cache_ttl: String,
    /// Remote services this application depends on.
    #[serde(default)]
    pub services: Vec<DiscoveredService>,
    /// Static endpoint fallback (used by the static provider or when the backend is unavailable).
    #[serde(default)]
    pub static_endpoints: Vec<StaticEndpoint>,
    /// Exotic provider-specific settings (e.g. datacenter, TLS, pool for Consul).
    /// Generic fields like addr/scheme/token are on the config directly.
    #[serde(default)]
    pub provider_options: toml::Table,
}

impl Default for DiscoveryConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            provider: "static".to_string(),
            addr: String::new(),
            scheme: "http".to_string(),
            token: String::new(),
            registration: RegistrationConfig::default(),
            health: HealthConfig::default(),
            cache_ttl: "30s".to_string(),
            services: Vec::new(),
            static_endpoints: Vec::new(),
            provider_options: toml::Table::new(),
        }
    }
}

impl DiscoveryConfig {
    /// Apply sensible defaults to zero-valued fields.
    pub fn apply_defaults(&mut self) {
        if self.provider.is_empty() {
            self.provider = "static".to_string();
        }
        if self.scheme.is_empty() {
            self.scheme = "http".to_string();
        }
        self.registration.apply_defaults();
        self.health.apply_defaults();
    }

    /// Validate that required fields are present.
    pub fn validate(&self) -> AppResult<()> {
        if !self.enabled {
            return Ok(());
        }
        if self.registration.enabled {
            if self.registration.service_name.is_empty() {
                return Err(AppError::invalid_input(
                    "discovery.registration.service_name",
                    "service name is required",
                ));
            }
            if self.registration.service_port == 0 {
                return Err(AppError::invalid_input(
                    "discovery.registration.service_port",
                    "service port must be greater than zero",
                ));
            }
        }
        Ok(())
    }

    /// Build a [`ServiceInstance`](crate::instance::ServiceInstance) from the registration config.
    pub fn build_instance(&self) -> crate::instance::ServiceInstance {
        let reg = &self.registration;
        let id = if reg.service_id.is_empty() {
            reg.service_name.clone()
        } else {
            reg.service_id.clone()
        };
        crate::instance::ServiceInstance {
            id,
            name: reg.service_name.clone(),
            address: reg.service_address.clone(),
            port: reg.service_port,
            healthy: true,
            weight: 1,
            tags: reg.tags.clone(),
            metadata: reg.metadata.clone(),
        }
    }
}

/// Self-registration settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct RegistrationConfig {
    /// Toggle self-registration.
    pub enabled: bool,
    /// When true (the default), the service will retry with backoff
    /// and fail to start if registration cannot be completed — appropriate for staging/production.
    /// When false, logs a warning and continues in degraded mode — convenient for local development.
    pub required: bool,
    /// Number of registration retries before giving up. Defaults to 3.
    pub max_retries: u32,
    /// Base interval between retries (e.g. `"2s"`). Doubles each retry.
    pub retry_interval: String,
    /// Name used when registering.
    pub service_name: String,
    /// Unique instance ID; defaults to `service_name` if empty.
    pub service_id: String,
    /// Address advertised to other services.
    pub service_address: String,
    /// Port advertised to other services.
    pub service_port: u16,
    /// Metadata tags attached to the registration.
    #[serde(default)]
    pub tags: Vec<String>,
    /// Arbitrary key-value metadata.
    #[serde(default)]
    pub metadata: HashMap<String, String>,
}

impl Default for RegistrationConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            required: true,
            max_retries: 3,
            retry_interval: "2s".to_string(),
            service_name: String::new(),
            service_id: String::new(),
            service_address: String::new(),
            service_port: 0,
            tags: Vec::new(),
            metadata: HashMap::new(),
        }
    }
}

impl RegistrationConfig {
    /// Apply defaults to zero-valued fields.
    pub fn apply_defaults(&mut self) {
        if self.service_id.is_empty() && !self.service_name.is_empty() {
            self.service_id = self.service_name.clone();
        }
        if self.max_retries == 0 {
            self.max_retries = 3;
        }
        if self.retry_interval.is_empty() {
            self.retry_interval = "2s".to_string();
        }
    }

    /// Parse the retry interval as a [`Duration`](std::time::Duration).
    pub fn retry_duration(&self) -> AppResult<std::time::Duration> {
        parse_duration(&self.retry_interval).ok_or_else(|| {
            AppError::invalid_input(
                "discovery.registration.retry_interval",
                format!("invalid duration '{}'", self.retry_interval),
            )
        })
    }
}

/// Health check configuration for registered services.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct HealthConfig {
    /// Toggle health checks.
    pub enabled: bool,
    /// Health check type: `"http"`, `"grpc"`, `"tcp"`, or `"ttl"`.
    #[serde(rename = "type")]
    pub check_type: String,
    /// HTTP path for health checks.
    pub path: String,
    /// How often health is polled (e.g. `"10s"`).
    pub interval: String,
    /// Timeout for a single health check.
    pub timeout: String,
    /// Remove service after being critical for this duration.
    pub deregister_after: String,
}

impl Default for HealthConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            check_type: "http".to_string(),
            path: "/health".to_string(),
            interval: "10s".to_string(),
            timeout: "5s".to_string(),
            deregister_after: "1m".to_string(),
        }
    }
}

impl HealthConfig {
    /// Apply defaults to zero-valued fields.
    pub fn apply_defaults(&mut self) {
        if self.check_type.is_empty() {
            self.check_type = "http".to_string();
        }
        if self.path.is_empty() {
            self.path = "/health".to_string();
        }
        if self.interval.is_empty() {
            self.interval = "10s".to_string();
        }
        if self.timeout.is_empty() {
            self.timeout = "5s".to_string();
        }
        if self.deregister_after.is_empty() {
            self.deregister_after = "1m".to_string();
        }
    }
}

/// A remote service this application depends on.
#[derive(Debug, Clone, Deserialize)]
pub struct DiscoveredService {
    /// Logical service name (e.g. `"ssm-ingestion"`).
    pub name: String,
    /// Protocol: `"grpc"` or `"http"`.
    #[serde(default = "default_protocol")]
    pub protocol: String,
}

/// A statically configured endpoint (fallback or static provider).
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct StaticEndpoint {
    /// Logical service name.
    pub name: String,
    /// Host or IP address.
    pub address: String,
    /// Port.
    pub port: u16,
    /// Protocol: `"grpc"` or `"http"`.
    pub protocol: String,
    /// Tags for filtering.
    #[serde(default)]
    pub tags: Vec<String>,
    /// Arbitrary key-value metadata.
    #[serde(default)]
    pub metadata: HashMap<String, String>,
    /// Weight for load balancing.
    pub weight: u32,
    /// Whether this endpoint is healthy.
    pub healthy: bool,
}

impl Default for StaticEndpoint {
    fn default() -> Self {
        Self {
            name: String::new(),
            address: String::new(),
            port: 0,
            protocol: "grpc".to_string(),
            tags: Vec::new(),
            metadata: HashMap::new(),
            weight: 1,
            healthy: true,
        }
    }
}

fn default_protocol() -> String {
    "grpc".to_string()
}

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

    #[test]
    fn discovery_defaults_are_static_and_disabled() {
        let cfg = DiscoveryConfig::default();

        assert!(!cfg.enabled);
        assert_eq!(cfg.provider, "static");
        assert_eq!(cfg.scheme, "http");
        assert_eq!(cfg.cache_ttl, "30s");
        assert!(cfg.services.is_empty());
        assert!(cfg.static_endpoints.is_empty());
    }

    #[test]
    fn apply_defaults_fills_nested_zero_values_without_overwriting_explicit_values() {
        let mut cfg = DiscoveryConfig {
            provider: String::new(),
            scheme: String::new(),
            registration: RegistrationConfig {
                service_name: "svc".to_string(),
                max_retries: 0,
                retry_interval: String::new(),
                ..Default::default()
            },
            health: HealthConfig {
                check_type: String::new(),
                path: String::new(),
                interval: String::new(),
                timeout: String::new(),
                deregister_after: String::new(),
                ..Default::default()
            },
            ..Default::default()
        };

        cfg.apply_defaults();

        assert_eq!(cfg.provider, "static");
        assert_eq!(cfg.scheme, "http");
        assert_eq!(cfg.registration.service_id, "svc");
        assert_eq!(cfg.registration.max_retries, 3);
        assert_eq!(cfg.registration.retry_interval, "2s");
        assert_eq!(cfg.health.check_type, "http");
        assert_eq!(cfg.health.path, "/health");
        assert_eq!(cfg.health.interval, "10s");
        assert_eq!(cfg.health.timeout, "5s");
        assert_eq!(cfg.health.deregister_after, "1m");
    }

    #[test]
    fn validate_ignores_disabled_registration_but_rejects_missing_enabled_fields() {
        let disabled = DiscoveryConfig {
            enabled: false,
            registration: RegistrationConfig {
                enabled: true,
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(disabled.validate().is_ok());

        let missing_name = DiscoveryConfig {
            enabled: true,
            registration: RegistrationConfig {
                enabled: true,
                service_port: 8080,
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(
            missing_name
                .validate()
                .unwrap_err()
                .to_string()
                .contains("service name")
        );

        let missing_port = DiscoveryConfig {
            enabled: true,
            registration: RegistrationConfig {
                enabled: true,
                service_name: "svc".to_string(),
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(
            missing_port
                .validate()
                .unwrap_err()
                .to_string()
                .contains("port")
        );
    }

    #[test]
    fn build_instance_uses_service_name_as_default_id_and_preserves_metadata() {
        let mut metadata = HashMap::new();
        metadata.insert("zone".to_string(), "a".to_string());
        let cfg = DiscoveryConfig {
            registration: RegistrationConfig {
                service_name: "api".to_string(),
                service_address: "127.0.0.1".to_string(),
                service_port: 8080,
                tags: vec!["blue".to_string()],
                metadata: metadata.clone(),
                ..Default::default()
            },
            ..Default::default()
        };

        let instance = cfg.build_instance();

        assert_eq!(instance.id, "api");
        assert_eq!(instance.name, "api");
        assert_eq!(instance.address, "127.0.0.1");
        assert_eq!(instance.port, 8080);
        assert_eq!(instance.tags, vec!["blue"]);
        assert_eq!(instance.metadata, metadata);
    }

    #[test]
    fn retry_duration_accepts_valid_values_and_rejects_invalid_values() {
        let valid = RegistrationConfig {
            retry_interval: "250ms".to_string(),
            ..Default::default()
        };
        assert_eq!(
            valid.retry_duration().unwrap(),
            std::time::Duration::from_millis(250)
        );

        let invalid = RegistrationConfig {
            retry_interval: "soon".to_string(),
            ..Default::default()
        };
        assert!(
            invalid
                .retry_duration()
                .unwrap_err()
                .to_string()
                .contains("invalid duration")
        );
    }

    #[test]
    fn serde_defaults_fill_protocol_and_static_endpoint_fields() {
        #[derive(Deserialize)]
        struct Wrapper {
            services: Vec<DiscoveredService>,
            endpoint: StaticEndpoint,
        }

        let parsed: Wrapper = toml::from_str(
            r#"
            [[services]]
            name = "users"

            [endpoint]
            name = "users"
            address = "127.0.0.1"
            "#,
        )
        .unwrap();

        assert_eq!(parsed.services[0].protocol, "grpc");
        assert_eq!(parsed.endpoint.port, 0);
        assert_eq!(parsed.endpoint.protocol, "grpc");
        assert_eq!(parsed.endpoint.weight, 1);
        assert!(parsed.endpoint.healthy);
    }
}