appcore-gateway 2.0.0-alpha.2

Multi-tenant Gateway capability for the AppCore Runtime.
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
// =============================================================================
//        #######
//     ###       ###     F: resolver.rs
//    ##   ## ##   ##    P: AppCore-Runtime
//         ## ##
//                       C: 2026/07/26 08:53:09 by dnettoRaw
//    ##   ## ##   ##    U: 2026/08/26 00:00:00 by dnettoRaw
//      ###########      S: 1.0.2-rc
// =============================================================================

//! Deterministic tenant-local capability worker selection.

use crate::config::{MAX_GATEWAY_AFFINITY_KEY_BYTES, MAX_GATEWAY_WORKER_INFLIGHT};
use crate::connection::WorkerConnectionKey;
use crate::registry::CapabilityRegistry;
use crate::tenant::TenantState;
use appcore_types::CapabilityName;
use std::cmp::Ordering;
use std::collections::HashSet;
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use std::sync::Arc;
use std::time::Duration;

/// Stable V1 strategy used to resolve one registered worker.
///
/// This exhaustive enum is frozen with the `FirstAvailable` contract. Use
/// [`WorkerSelectionPolicy`] for opt-in health and admission-aware selection.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SelectionPolicy {
    /// Picks the first candidate in stable worker-identity order.
    #[default]
    FirstAvailable,
}

/// Opt-in strategy used to choose one eligible live worker.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum WorkerSelectionPolicy {
    /// Picks the first candidate in stable worker-identity order.
    #[default]
    FirstAvailable,
    /// Advances a bounded tenant-local cursor over stable candidate order.
    RoundRobin,
    /// Chooses the smallest admitted-route count and queue depth.
    LeastInflight,
    /// Distributes using fixed heartbeat-freshness weights.
    HealthWeighted,
    /// Uses stateless tenant-local rendezvous hashing.
    Affinity,
}

/// Bounded inputs used by health, admission and affinity-aware selection.
#[derive(Debug, Clone, Copy)]
pub struct WorkerSelectionInput<'a> {
    now_ms: u64,
    heartbeat_timeout: Duration,
    max_inflight: u64,
    affinity_key: Option<&'a str>,
}

impl<'a> WorkerSelectionInput<'a> {
    /// Creates selection input with the fixed Gateway per-worker route limit.
    pub fn new(now_ms: u64, heartbeat_timeout: Duration) -> Self {
        Self {
            now_ms,
            heartbeat_timeout,
            max_inflight: MAX_GATEWAY_WORKER_INFLIGHT,
            affinity_key: None,
        }
    }

    /// Applies a smaller positive per-worker limit for this selection.
    pub fn with_max_inflight(mut self, max_inflight: u64) -> Self {
        self.max_inflight = max_inflight;
        self
    }

    /// Supplies a bounded request affinity key. The resolver never stores it.
    pub fn with_affinity(mut self, affinity_key: &'a str) -> Self {
        self.affinity_key = Some(affinity_key);
        self
    }
}

/// Controlled reason why no worker could be selected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum WorkerSelectionError {
    /// No registered worker advertises the requested capability.
    #[error("capability has no registered worker")]
    CapabilityUnavailable,
    /// Registered workers are disconnected or outside the health window.
    #[error("capability has no healthy worker")]
    NoHealthyWorker,
    /// Every healthy worker reached its route or outbound-queue limit.
    #[error("all healthy workers are at capacity")]
    AtCapacity,
    /// Affinity policy requires a non-empty bounded key.
    #[error("affinity policy requires a valid bounded key")]
    InvalidAffinity,
    /// Health and in-flight bounds must be positive and within Runtime limits.
    #[error("worker selection limits are invalid")]
    InvalidLimits,
}

/// Resolves worker targets for capability requests within one tenant partition.
#[derive(Debug, Clone)]
pub struct CapabilityResolver {
    policy: WorkerSelectionPolicy,
    cursor: Arc<AtomicU64>,
}

impl Default for CapabilityResolver {
    fn default() -> Self {
        Self {
            policy: WorkerSelectionPolicy::FirstAvailable,
            cursor: Arc::new(AtomicU64::new(0)),
        }
    }
}

impl CapabilityResolver {
    /// Creates a resolver with the compatible `FirstAvailable` policy.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a resolver using one explicit live-worker selection policy.
    pub fn with_policy(policy: WorkerSelectionPolicy) -> Self {
        Self {
            policy,
            cursor: Arc::new(AtomicU64::new(0)),
        }
    }

    /// Returns the configured selection policy.
    pub fn policy(&self) -> WorkerSelectionPolicy {
        self.policy
    }

    /// Resolves from registry data alone.
    ///
    /// This compatible planner cannot evaluate live health or admission. Use
    /// [`Self::select`] before dispatch when those guarantees are required.
    pub fn resolve(
        &self,
        capability: &CapabilityName,
        registry: &CapabilityRegistry,
    ) -> Option<WorkerConnectionKey> {
        let registered = registry.resolve(capability)?;
        match self.policy {
            WorkerSelectionPolicy::FirstAvailable
            | WorkerSelectionPolicy::LeastInflight
            | WorkerSelectionPolicy::HealthWeighted => registered
                .iter()
                .min_by(|left, right| compare_worker_keys(left, right))
                .cloned(),
            WorkerSelectionPolicy::RoundRobin => {
                let mut candidates = registered.iter().collect::<Vec<_>>();
                candidates.sort_by(|left, right| compare_worker_keys(left, right));
                if candidates.is_empty() {
                    return None;
                }
                Some((*select_cursor(&self.cursor, &candidates)).clone())
            }
            WorkerSelectionPolicy::Affinity => None,
        }
    }

    /// Selects one live, healthy and admitted worker from a tenant partition.
    pub fn select(
        &self,
        capability: &CapabilityName,
        tenant: &TenantState,
        input: WorkerSelectionInput<'_>,
    ) -> Result<WorkerConnectionKey, WorkerSelectionError> {
        validate_input(self.policy, input)?;
        let registered = tenant
            .registry
            .resolve(capability)
            .ok_or(WorkerSelectionError::CapabilityUnavailable)?;
        let candidates = healthy_candidates(registered, tenant, input);
        let selected = match self.policy {
            WorkerSelectionPolicy::FirstAvailable => {
                select_best(candidates, input.max_inflight, |candidate, current| {
                    compare_worker_keys(candidate.key, current.key).is_lt()
                })?
            }
            WorkerSelectionPolicy::LeastInflight => {
                select_best(candidates, input.max_inflight, |candidate, current| {
                    compare_candidate_load(candidate, current).is_lt()
                })?
            }
            WorkerSelectionPolicy::Affinity => {
                select_best(candidates, input.max_inflight, |candidate, current| {
                    compare_candidate_affinity(candidate, current, capability, tenant, input)
                        .is_gt()
                })?
            }
            WorkerSelectionPolicy::RoundRobin => self.choose_buffered(
                candidates,
                input.max_inflight,
                BufferedSelectionPolicy::RoundRobin,
            )?,
            WorkerSelectionPolicy::HealthWeighted => self.choose_buffered(
                candidates,
                input.max_inflight,
                BufferedSelectionPolicy::HealthWeighted,
            )?,
        };
        Ok(selected.key.clone())
    }

    fn choose_buffered<'a>(
        &self,
        candidates: impl Iterator<Item = Candidate<'a>>,
        max_inflight: u64,
        policy: BufferedSelectionPolicy,
    ) -> Result<Candidate<'a>, WorkerSelectionError> {
        let mut saw_healthy = false;
        let mut eligible = Vec::with_capacity(candidates.size_hint().1.unwrap_or(0));
        for candidate in candidates {
            saw_healthy = true;
            if candidate.is_eligible(max_inflight) {
                eligible.push(candidate);
            }
        }
        if eligible.is_empty() {
            return Err(empty_selection_error(saw_healthy));
        }
        eligible.sort_by(|left, right| compare_worker_keys(left.key, right.key));
        Ok(match policy {
            BufferedSelectionPolicy::RoundRobin => *select_cursor(&self.cursor, &eligible),
            BufferedSelectionPolicy::HealthWeighted => {
                *select_health_weighted(&self.cursor, &eligible)
            }
        })
    }
}

fn healthy_candidates<'a>(
    registered: &'a HashSet<WorkerConnectionKey>,
    tenant: &'a TenantState,
    input: WorkerSelectionInput<'_>,
) -> impl Iterator<Item = Candidate<'a>> + 'a {
    let now_ms = input.now_ms;
    let heartbeat_timeout = input.heartbeat_timeout;
    registered.iter().filter_map(move |key| {
        if key.tenant_id != tenant.tenant_id {
            return None;
        }
        let worker = tenant.get_worker(&key.installation_id, &key.core_id)?;
        worker
            .is_open_and_healthy(now_ms, heartbeat_timeout)
            .then(|| Candidate::from_worker(worker, now_ms, heartbeat_timeout))
    })
}

fn select_best<'a>(
    candidates: impl Iterator<Item = Candidate<'a>>,
    max_inflight: u64,
    is_better: impl Fn(&Candidate<'a>, &Candidate<'a>) -> bool,
) -> Result<Candidate<'a>, WorkerSelectionError> {
    let mut saw_healthy = false;
    let mut selected = None;
    for candidate in candidates {
        saw_healthy = true;
        if !candidate.is_eligible(max_inflight) {
            continue;
        }
        if selected
            .as_ref()
            .is_none_or(|current| is_better(&candidate, current))
        {
            selected = Some(candidate);
        }
    }
    selected.ok_or_else(|| empty_selection_error(saw_healthy))
}

fn compare_candidate_load(left: &Candidate<'_>, right: &Candidate<'_>) -> Ordering {
    left.inflight
        .cmp(&right.inflight)
        .then_with(|| left.queue_depth.cmp(&right.queue_depth))
        .then_with(|| compare_worker_keys(left.key, right.key))
}

fn compare_candidate_affinity(
    left: &Candidate<'_>,
    right: &Candidate<'_>,
    capability: &CapabilityName,
    tenant: &TenantState,
    input: WorkerSelectionInput<'_>,
) -> Ordering {
    affinity_score(
        tenant.tenant_id.as_str(),
        capability.as_str(),
        input.affinity_key.unwrap_or_default(),
        left.key,
    )
    .cmp(&affinity_score(
        tenant.tenant_id.as_str(),
        capability.as_str(),
        input.affinity_key.unwrap_or_default(),
        right.key,
    ))
    .then_with(|| compare_worker_keys(right.key, left.key))
}

fn empty_selection_error(saw_healthy: bool) -> WorkerSelectionError {
    if saw_healthy {
        WorkerSelectionError::AtCapacity
    } else {
        WorkerSelectionError::NoHealthyWorker
    }
}

#[derive(Clone, Copy)]
enum BufferedSelectionPolicy {
    RoundRobin,
    HealthWeighted,
}

#[derive(Debug, Clone, Copy)]
struct Candidate<'a> {
    key: &'a WorkerConnectionKey,
    inflight: u64,
    queue_depth: usize,
    queue_remaining: usize,
    health_weight: u64,
}

impl<'a> Candidate<'a> {
    fn from_worker(
        worker: &'a crate::WorkerConnection,
        now_ms: u64,
        heartbeat_timeout: Duration,
    ) -> Self {
        let timeout_ms = duration_ms(heartbeat_timeout);
        let age_ms = now_ms.saturating_sub(worker.last_heartbeat());
        let remaining_ms = timeout_ms.saturating_sub(age_ms);
        let health_weight = 1_u64.saturating_add(
            remaining_ms
                .saturating_mul(15)
                .checked_div(timeout_ms)
                .unwrap_or(0),
        );
        Self {
            key: &worker.key,
            inflight: worker.inflight(),
            queue_depth: worker.outbound_queue_depth(),
            queue_remaining: worker.outbound_queue_remaining(),
            health_weight,
        }
    }

    fn is_eligible(self, max_inflight: u64) -> bool {
        self.inflight < max_inflight && self.queue_remaining > 0
    }
}

fn validate_input(
    policy: WorkerSelectionPolicy,
    input: WorkerSelectionInput<'_>,
) -> Result<(), WorkerSelectionError> {
    if input.heartbeat_timeout.is_zero()
        || input.max_inflight == 0
        || input.max_inflight > MAX_GATEWAY_WORKER_INFLIGHT
    {
        return Err(WorkerSelectionError::InvalidLimits);
    }
    if policy == WorkerSelectionPolicy::Affinity {
        let affinity = input
            .affinity_key
            .filter(|value| !value.is_empty())
            .filter(|value| value.len() <= MAX_GATEWAY_AFFINITY_KEY_BYTES)
            .filter(|value| !value.chars().any(char::is_control));
        if affinity.is_none() {
            return Err(WorkerSelectionError::InvalidAffinity);
        }
    }
    Ok(())
}

fn select_cursor<'a, T>(cursor: &AtomicU64, candidates: &'a [T]) -> &'a T {
    let ticket = cursor.fetch_add(1, AtomicOrdering::Relaxed);
    let index = usize::try_from(ticket).unwrap_or(usize::MAX) % candidates.len();
    &candidates[index]
}

fn select_health_weighted<'a, 'worker>(
    cursor: &AtomicU64,
    candidates: &'a [Candidate<'worker>],
) -> &'a Candidate<'worker> {
    let total = candidates.iter().fold(0_u64, |sum, candidate| {
        sum.saturating_add(candidate.health_weight)
    });
    let mut slot = cursor.fetch_add(1, AtomicOrdering::Relaxed) % total.max(1);
    for candidate in candidates {
        if slot < candidate.health_weight {
            return candidate;
        }
        slot = slot.saturating_sub(candidate.health_weight);
    }
    &candidates[0]
}

fn affinity_score(
    tenant: &str,
    capability: &str,
    affinity: &str,
    worker: &WorkerConnectionKey,
) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    for value in [
        tenant,
        capability,
        affinity,
        worker.tenant_id.as_str(),
        worker.installation_id.as_str(),
        worker.core_id.as_str(),
    ] {
        for byte in (value.len() as u64)
            .to_le_bytes()
            .iter()
            .chain(value.as_bytes())
        {
            hash ^= u64::from(*byte);
            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        }
    }
    hash
}

fn compare_worker_keys(left: &WorkerConnectionKey, right: &WorkerConnectionKey) -> Ordering {
    left.tenant_id
        .as_str()
        .cmp(right.tenant_id.as_str())
        .then_with(|| {
            left.installation_id
                .as_str()
                .cmp(right.installation_id.as_str())
        })
        .then_with(|| left.core_id.as_str().cmp(right.core_id.as_str()))
}

fn duration_ms(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

#[cfg(test)]
#[path = "resolver_tests.rs"]
mod tests;