cf-gears-toolkit 0.16.0

Core ToolKit library
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
//! Tests for `OoP` self-registration and dependency resolution.

use super::*;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

use async_trait::async_trait;
use cf_system_sdks::directory::{
    DirectoryClient, DirectoryInvalidArgument, DirectoryPermissionDenied, ServiceEndpoint,
    ServiceInstanceInfo,
};

use crate::runtime::{DependencyChecker, PresenceManager, ReportedStateSource};

/// Wrap a stub directory in a per-process presence manager (a fresh, ready
/// `DependencyChecker` so registrations report `Serving`). The manager's
/// renewal loop is not spawned here, so these tests exercise the *writer*
/// (register + re-register on update); heartbeat/renewal is covered by
/// `presence_manager_tests`.
fn manager(stub: Arc<StubDirectory>) -> Arc<PresenceManager> {
    PresenceManager::new(
        stub as Arc<dyn DirectoryClient>,
        ReportedStateSource::Dependencies(Arc::new(DependencyChecker::new())),
        Duration::from_secs(5),
    )
}

/// The rejection a [`StubDirectory`] returns from `register`.
#[derive(Clone, Copy)]
enum Rejection {
    /// A mis-configured label / endpoint URI (gRPC `InvalidArgument`). Permanent.
    InvalidArgument,
    /// An authorization denial, or a service-name conflict *pinned* to another
    /// gear by the ownership map (gRPC `PermissionDenied`). Permanent.
    PermissionDenied,
    /// A *recoverable* gRPC service-name conflict — the name is currently
    /// advertised by another gear (gRPC `FailedPrecondition`). It clears when
    /// that gear deregisters, so the client surfaces it as a transient error and
    /// retries with backoff.
    Conflict,
}

/// Stub directory: fails `register`/`resolve` a configurable number of times,
/// then succeeds; records register calls and heartbeats. While `rejecting` is
/// set, `register` always returns the permanent `reject_kind` rejection;
/// [`stop_rejecting`](StubDirectory::stop_rejecting) clears it to model the
/// conflict later resolving.
struct StubDirectory {
    fail_register: AtomicUsize,
    register_calls: AtomicUsize,
    /// Registrations that reached the `Ok` path (i.e. actually succeeded), as
    /// distinct from `register_calls` (attempts, counted before the reject check).
    register_ok: AtomicUsize,
    heartbeats: AtomicUsize,
    fail_resolve: AtomicUsize,
    reject_kind: Option<Rejection>,
    rejecting: AtomicBool,
    /// While set, `register` waits for `released` after counting the call.
    holding: AtomicBool,
    released: tokio::sync::Notify,
}

impl StubDirectory {
    fn new(fail_register: usize, fail_resolve: usize) -> Self {
        Self {
            fail_register: AtomicUsize::new(fail_register),
            register_calls: AtomicUsize::new(0),
            register_ok: AtomicUsize::new(0),
            heartbeats: AtomicUsize::new(0),
            fail_resolve: AtomicUsize::new(fail_resolve),
            reject_kind: None,
            rejecting: AtomicBool::new(false),
            holding: AtomicBool::new(false),
            released: tokio::sync::Notify::new(),
        }
    }

    /// A directory that rejects every registration with `kind` while `rejecting`
    /// is set (as the gRPC front-end does for a mis-configured label / endpoint
    /// URI, an authorization denial, or a service-name conflict).
    fn rejecting(kind: Rejection) -> Self {
        Self {
            reject_kind: Some(kind),
            rejecting: AtomicBool::new(true),
            ..Self::new(0, 0)
        }
    }

    /// Stop rejecting: subsequent registrations succeed, modelling the
    /// conflicting owner deregistering (or an authz fix landing).
    fn stop_rejecting(&self) {
        self.rejecting.store(false, Ordering::SeqCst);
    }
}

#[async_trait]
impl DirectoryClient for StubDirectory {
    async fn resolve_grpc_service(&self, _service: &str) -> anyhow::Result<ServiceEndpoint> {
        Ok(ServiceEndpoint::new("http://grpc"))
    }

    async fn resolve_rest_service(&self, gear: &str) -> anyhow::Result<ServiceEndpoint> {
        if self.fail_resolve.load(Ordering::SeqCst) > 0 {
            self.fail_resolve.fetch_sub(1, Ordering::SeqCst);
            anyhow::bail!("not yet available");
        }
        Ok(ServiceEndpoint::new(format!("http://{gear}:8080")))
    }

    async fn list_instances(&self, _gear: &str) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
        Ok(vec![])
    }

    async fn list_all_instances(&self) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
        Ok(vec![])
    }

    async fn register_instance(&self, _info: RegisterInstanceInfo) -> anyhow::Result<()> {
        self.register_calls.fetch_add(1, Ordering::SeqCst);
        if self.holding.load(Ordering::SeqCst) {
            self.released.notified().await;
        }
        if self.rejecting.load(Ordering::SeqCst) {
            match self.reject_kind {
                Some(Rejection::InvalidArgument) => {
                    return Err(DirectoryInvalidArgument::new("bad label").into());
                }
                Some(Rejection::PermissionDenied) => {
                    return Err(DirectoryPermissionDenied::new("peer not authorized").into());
                }
                Some(Rejection::Conflict) => {
                    // A gRPC service-name conflict is `FailedPrecondition`, which
                    // `call_error` leaves as an opaque transient error — so the
                    // presence loop retries it with backoff rather than treating
                    // it as a permanent rejection.
                    anyhow::bail!(
                        "directory register_instance failed: gRPC FailedPrecondition: \
                         a gRPC service name in this registration is already owned by another gear"
                    );
                }
                None => {}
            }
        }
        if self.fail_register.load(Ordering::SeqCst) > 0 {
            self.fail_register.fetch_sub(1, Ordering::SeqCst);
            anyhow::bail!("directory unavailable");
        }
        self.register_ok.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }

    async fn deregister_instance(&self, _gear: &str, _instance: &str) -> anyhow::Result<()> {
        Ok(())
    }

    async fn send_heartbeat(&self, _gear: &str, _instance: &str) -> anyhow::Result<()> {
        self.heartbeats.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }
}

fn info() -> RegisterInstanceInfo {
    RegisterInstanceInfo::new("billing", "i-1")
        .with_version("1.0.0")
        .with_rest_endpoint(ServiceEndpoint::new("http://billing:8080"))
        .with_openapi_spec_hash("a".repeat(64))
}

#[test]
fn backoff_doubles_and_caps() {
    assert_eq!(
        next_backoff(Duration::from_millis(100)),
        Duration::from_millis(200)
    );
    assert_eq!(
        next_backoff(Duration::from_millis(200)),
        Duration::from_millis(400)
    );
    assert_eq!(next_backoff(Duration::from_secs(20)), MAX_BACKOFF);
    assert_eq!(next_backoff(MAX_BACKOFF), MAX_BACKOFF);
}

#[tokio::test]
async fn registration_retries_until_success() {
    let cancel = CancellationToken::new();
    let ok = register_once_with_backoff(
        &manager(Arc::new(StubDirectory::new(2, 0))),
        &info(),
        &cancel,
    )
    .await;
    assert!(ok);
}

#[tokio::test]
async fn registration_keeps_loop_alive_on_permanent_rejection() {
    // A DirectoryInvalidArgument is permanent: the backoff retry must give up
    // after a single attempt rather than retrying a request that can never
    // succeed, yet still return `true` so the presence loop keeps running.
    let stub = Arc::new(StubDirectory::rejecting(Rejection::InvalidArgument));
    let cancel = CancellationToken::new();
    let ok = register_once_with_backoff(&manager(Arc::clone(&stub)), &info(), &cancel).await;
    assert!(ok, "a permanent rejection must not stop the presence loop");
    assert_eq!(
        stub.register_calls.load(Ordering::SeqCst),
        1,
        "a permanent rejection must not be retried"
    );
}

#[tokio::test]
async fn registration_does_not_retry_permission_denied() {
    // A DirectoryPermissionDenied (an authorization denial) is just as permanent
    // as an invalid argument: retrying the identical request can never turn the
    // "no" into a "yes", so the backoff retry must give up after a single attempt
    // (regression: it previously fell into the generic transient branch and
    // retried forever at `warn!`), yet still keep the presence loop alive.
    let stub = Arc::new(StubDirectory::rejecting(Rejection::PermissionDenied));
    let cancel = CancellationToken::new();
    let ok = register_once_with_backoff(&manager(Arc::clone(&stub)), &info(), &cancel).await;
    assert!(ok, "a permanent rejection must not stop the presence loop");
    assert_eq!(
        stub.register_calls.load(Ordering::SeqCst),
        1,
        "a permission-denied rejection must not be retried"
    );
}

#[tokio::test]
async fn registration_returns_false_when_cancelled() {
    let cancel = CancellationToken::new();
    cancel.cancel();
    let ok = register_once_with_backoff(
        &manager(Arc::new(StubDirectory::new(1000, 0))),
        &info(),
        &cancel,
    )
    .await;
    assert!(!ok, "cancelled registration must return false");
}

#[tokio::test]
async fn presence_loop_registers_once_and_waits_for_cancel() {
    let stub = Arc::new(StubDirectory::new(0, 0));
    let cancel = CancellationToken::new();

    let task = tokio::spawn(presence_loop(
        manager(Arc::clone(&stub)),
        info(),
        cancel.clone(),
    ));
    while stub.register_ok.load(Ordering::SeqCst) == 0 {
        tokio::task::yield_now().await;
    }

    assert_eq!(
        stub.register_calls.load(Ordering::SeqCst),
        1,
        "the writer registers exactly once"
    );
    assert_eq!(
        stub.heartbeats.load(Ordering::SeqCst),
        0,
        "the writer never heartbeats; the presence manager owns renewal"
    );
    assert!(
        !task.is_finished(),
        "the writer stays alive (for OpenAPI updates) until cancel"
    );

    cancel.cancel();
    task.await.unwrap();
}

/// An `OpenAPI`-document update re-registers through the manager (which then
/// renews the record carrying the new document); the writer sends no heartbeats.
#[tokio::test]
async fn an_openapi_update_re_registers_through_the_manager() {
    let stub = Arc::new(StubDirectory::new(0, 0));
    let cancel = CancellationToken::new();
    let (updates, rx) = tokio::sync::watch::channel(info());
    let task = tokio::spawn(presence_loop_with_updates(
        manager(Arc::clone(&stub)),
        rx,
        cancel.clone(),
    ));
    while stub.register_ok.load(Ordering::SeqCst) == 0 {
        tokio::task::yield_now().await;
    }

    updates.send_replace(info().with_openapi_spec_hash("b".repeat(64)));
    while stub.register_ok.load(Ordering::SeqCst) < 2 {
        tokio::task::yield_now().await;
    }

    assert_eq!(
        stub.register_calls.load(Ordering::SeqCst),
        2,
        "the document update re-registers exactly once"
    );
    assert_eq!(
        stub.heartbeats.load(Ordering::SeqCst),
        0,
        "renewal (heartbeats) is the manager's job, not the writer's"
    );

    cancel.cancel();
    task.await.unwrap();
}

#[tokio::test]
async fn presence_loop_survives_permanent_rejection() {
    // A permanent DirectoryInvalidArgument must NOT tear the writer down: it
    // stays alive (so OpenAPI updates can still re-register) while the manager
    // keeps renewing any registration that landed. Only cancellation stops it.
    let stub = Arc::new(StubDirectory::rejecting(Rejection::InvalidArgument));
    let cancel = CancellationToken::new();

    let task = tokio::spawn(presence_loop(
        manager(Arc::clone(&stub)),
        info(),
        cancel.clone(),
    ));

    // Let the single (permanent) registration attempt happen.
    for _ in 0..10 {
        if stub.register_calls.load(Ordering::SeqCst) >= 1 {
            break;
        }
        tokio::task::yield_now().await;
    }

    assert!(
        !task.is_finished(),
        "a permanent rejection must not stop the writer"
    );
    assert_eq!(
        stub.register_calls.load(Ordering::SeqCst),
        1,
        "a permanent rejection is not retried"
    );

    cancel.cancel();
    task.await.unwrap();
}

#[tokio::test(start_paused = true)]
async fn presence_loop_recovers_when_conflict_clears() {
    // A gear denied on a *recoverable* gRPC service-name conflict
    // (`FailedPrecondition`, surfaced as a transient error) keeps retrying the
    // initial registration with backoff — it is NOT treated as a permanent
    // rejection. Once the conflict clears (the owning gear deregisters) the next
    // retry succeeds, so the instance becomes discoverable without a restart.
    // Driven on virtual time so the backoff costs no wall clock.
    let stub = Arc::new(StubDirectory::rejecting(Rejection::Conflict));
    let cancel = CancellationToken::new();

    let task = tokio::spawn(presence_loop(
        manager(Arc::clone(&stub)),
        info(),
        cancel.clone(),
    ));

    // Let the initial attempt run and fail; the loop parks on its backoff sleep.
    // No time has advanced, so exactly one attempt has happened.
    for _ in 0..10 {
        if stub.register_calls.load(Ordering::SeqCst) >= 1 {
            break;
        }
        tokio::task::yield_now().await;
    }
    assert_eq!(
        stub.register_calls.load(Ordering::SeqCst),
        1,
        "the initial registration is rejected but the loop keeps retrying"
    );
    assert_eq!(
        stub.register_ok.load(Ordering::SeqCst),
        0,
        "while rejecting, no registration reaches the Ok path"
    );

    // The conflicting owner deregisters; the directory now accepts.
    stub.stop_rejecting();

    // Advance past the (capped) backoff so the pending retry fires — this time it
    // must actually *succeed*. Asserting the Ok path (not just another attempt,
    // which `register_calls` counts before the reject check) is what proves
    // `stop_rejecting` took effect and the instance recovered.
    tokio::time::advance(MAX_BACKOFF + Duration::from_secs(1)).await;
    for _ in 0..10 {
        if stub.register_ok.load(Ordering::SeqCst) >= 1 {
            break;
        }
        tokio::task::yield_now().await;
    }
    assert_eq!(
        stub.register_ok.load(Ordering::SeqCst),
        1,
        "once the conflict clears the retry must succeed, not merely re-attempt"
    );

    cancel.cancel();
    task.await.unwrap();
}

// Dependency resolution moved to the proxy-wiring phase (typed
// `#[toolkit::consumes]` clients feeding the shared `DependencyChecker`); the
// former `resolve_one_dep`/`resolve_deps`/`ResolvedRestEndpoints` stopgap and
// its tests were retired. Consumer-wiring resolution is covered by
// `host_runtime` proxy-wiring tests and the api-contracts example E2E tests.