camel-function 0.11.0

Function runtime service for out-of-process function execution
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
use crate::config::FunctionConfig;
use crate::pool::{RunnerPool, RunnerPoolKey, RunnerState};
use crate::provider::{FunctionProvider, HealthReport};
use camel_api::Exchange;
use camel_api::function::*;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

pub(crate) struct DefaultFunctionInvoker {
    pub(crate) pool: Arc<RunnerPool>,
    pub(crate) provider: Arc<dyn FunctionProvider>,
    pub(crate) config: FunctionConfig,
    pub(crate) pending: Mutex<Vec<(FunctionDefinition, Option<String>)>>,
    pub(crate) staging: Mutex<HashMap<u64, StagedEntries>>,
    pub(crate) function_timeouts: Mutex<HashMap<FunctionId, u64>>,
    pub(crate) next_generation: AtomicU64,
    pub(crate) current_generation: AtomicU64,
    pub(crate) started: AtomicBool,
    pub(crate) register_lock: tokio::sync::Mutex<()>,
}

type StagedEntries = Vec<(FunctionDefinition, Option<String>)>;

impl DefaultFunctionInvoker {
    pub(crate) fn new(
        pool: Arc<RunnerPool>,
        provider: Arc<dyn FunctionProvider>,
        config: FunctionConfig,
    ) -> Self {
        Self {
            pool,
            provider,
            config,
            pending: Mutex::new(Vec::new()),
            staging: Mutex::new(HashMap::new()),
            function_timeouts: Mutex::new(HashMap::new()),
            next_generation: AtomicU64::new(0),
            current_generation: AtomicU64::new(0),
            started: AtomicBool::new(false),
            register_lock: tokio::sync::Mutex::new(()),
        }
    }

    pub(crate) async fn wait_until_healthy(
        &self,
        handle: &crate::pool::RunnerHandle,
    ) -> Result<(), FunctionInvocationError> {
        let deadline = tokio::time::Instant::now() + self.config.boot_timeout;
        loop {
            if tokio::time::Instant::now() > deadline {
                return Err(FunctionInvocationError::RunnerUnavailable {
                    reason: "boot timeout".into(),
                });
            }
            match self.provider.health(handle).await {
                Ok(HealthReport::Healthy) => {
                    *handle.state.lock().expect("state") = RunnerState::Healthy; // allow-unwrap
                    return Ok(());
                }
                Ok(HealthReport::Unhealthy(reason)) => {
                    *handle.state.lock().expect("state") = RunnerState::Unhealthy {
                        // allow-unwrap
                        since: std::time::Instant::now(),
                        reason,
                    };
                    tokio::time::sleep(self.config.health_interval).await;
                }
                Err(e) => {
                    return Err(FunctionInvocationError::RunnerUnavailable {
                        reason: e.to_string(),
                    });
                }
            }
        }
    }
}

impl FunctionInvokerSync for DefaultFunctionInvoker {
    fn stage_pending(&self, def: FunctionDefinition, route_id: Option<&str>, generation: u64) {
        let rid = route_id.map(ToOwned::to_owned);
        if !self.started.load(Ordering::SeqCst) {
            self.pending.lock().expect("pending").push((def, rid)); // allow-unwrap
            return;
        }
        let mut staging = self.staging.lock().expect("staging"); // allow-unwrap
        let entry = staging.entry(generation).or_default();
        let did = def.id.clone();
        let rid_owned = rid.clone();
        entry
            .retain(|(existing, existing_rid)| !(existing.id == did && existing_rid == &rid_owned));
        entry.push((def, rid_owned));
    }

    fn discard_staging(&self, generation: u64) {
        self.staging.lock().expect("staging").remove(&generation); // allow-unwrap
    }

    fn begin_reload(&self) -> u64 {
        let generation = self.next_generation.fetch_add(1, Ordering::SeqCst) + 1;
        self.current_generation.store(generation, Ordering::SeqCst);
        self.staging
            .lock()
            .expect("staging") // allow-unwrap
            .entry(generation)
            .or_default();
        generation
    }

    fn function_refs_for_route(&self, route_id: &str) -> Vec<(FunctionId, Option<String>)> {
        self.pool
            .function_to_key
            .iter()
            .filter(|kv| kv.key().1.as_deref() == Some(route_id))
            .map(|kv| kv.key().clone())
            .collect()
    }

    fn staged_refs_for_route(
        &self,
        route_id: &str,
        generation: u64,
    ) -> Vec<(FunctionId, Option<String>)> {
        let staging = self.staging.lock().expect("staging"); // allow-unwrap
        staging
            .get(&generation)
            .map(|entries| {
                entries
                    .iter()
                    .filter(|(_, rid)| rid.as_deref() == Some(route_id))
                    .map(|(def, rid)| (def.id.clone(), rid.clone()))
                    .collect()
            })
            .unwrap_or_default()
    }

    fn staged_defs_for_route(
        &self,
        route_id: &str,
        generation: u64,
    ) -> Vec<(FunctionDefinition, Option<String>)> {
        let staging = self.staging.lock().expect("staging"); // allow-unwrap
        staging
            .get(&generation)
            .map(|entries| {
                entries
                    .iter()
                    .filter(|(_, rid)| rid.as_deref() == Some(route_id))
                    .map(|(def, rid)| (def.clone(), rid.clone()))
                    .collect()
            })
            .unwrap_or_default()
    }
}

#[async_trait::async_trait]
impl FunctionInvoker for DefaultFunctionInvoker {
    async fn register(
        &self,
        def: FunctionDefinition,
        route_id: Option<&str>,
    ) -> Result<(), FunctionInvocationError> {
        let key = RunnerPoolKey {
            runtime: def.runtime.clone(),
        };
        let _guard = self.register_lock.lock().await;
        let handle = {
            let existing = self.pool.handles.get(&key).map(|h| h.clone());
            match existing {
                Some(h) => h,
                None => {
                    let spawned = self.provider.spawn(&key).await.map_err(|e| {
                        FunctionInvocationError::RunnerUnavailable {
                            reason: e.to_string(),
                        }
                    })?;
                    self.wait_until_healthy(&spawned).await?;
                    self.pool
                        .handles
                        .entry(key.clone())
                        .or_insert(spawned)
                        .clone()
                }
            }
        };
        self.provider
            .register(&handle, &def)
            .await
            .map_err(|e| FunctionInvocationError::Transport(e.to_string()))?;
        let ref_key = (def.id.clone(), route_id.map(ToOwned::to_owned));
        self.pool
            .ref_counts
            .entry(ref_key.clone())
            .and_modify(|c| *c += 1)
            .or_insert(1);
        self.function_timeouts
            .lock()
            .expect("function_timeouts") // allow-unwrap
            .insert(def.id.clone(), def.timeout_ms);
        self.pool.function_to_key.insert(ref_key, key);
        Ok(())
    }

    async fn unregister(
        &self,
        id: &FunctionId,
        route_id: Option<&str>,
    ) -> Result<(), FunctionInvocationError> {
        let key = (id.clone(), route_id.map(ToOwned::to_owned));
        let mut should_unregister = false;
        if let Some(mut c) = self.pool.ref_counts.get_mut(&key) {
            if *c > 1 {
                *c -= 1;
            } else {
                should_unregister = true;
            }
        }
        if should_unregister {
            self.pool.ref_counts.remove(&key);
        }
        if should_unregister && let Some((_, pool_key)) = self.pool.function_to_key.remove(&key) {
            let still_used_by_other_route =
                self.pool.function_to_key.iter().any(|kv| kv.key().0 == *id);
            if !still_used_by_other_route {
                self.function_timeouts
                    .lock()
                    .expect("function_timeouts") // allow-unwrap
                    .remove(id);
                if let Some(handle) = self.pool.handles.get(&pool_key) {
                    self.provider
                        .unregister(&handle, id)
                        .await
                        .map_err(|e| FunctionInvocationError::Transport(e.to_string()))?;
                }
                let still_used = self
                    .pool
                    .function_to_key
                    .iter()
                    .any(|kv| kv.value() == &pool_key);
                if !still_used && let Some((_, handle)) = self.pool.handles.remove(&pool_key) {
                    handle.cancel.cancel();
                    self.provider
                        .shutdown(handle)
                        .await
                        .map_err(|e| FunctionInvocationError::Transport(e.to_string()))?;
                }
            }
        }
        Ok(())
    }

    async fn invoke(
        &self,
        id: &FunctionId,
        exchange: &Exchange,
    ) -> Result<ExchangePatch, FunctionInvocationError> {
        tracing::debug!(function_id = %id, "invoking registered function");
        let key = self
            .pool
            .function_to_key
            .iter()
            .find(|kv| kv.key().0 == *id)
            .map(|kv| kv.value().clone())
            .ok_or_else(|| FunctionInvocationError::NotRegistered {
                function_id: id.clone(),
            })?;
        let handle = self
            .pool
            .handles
            .get(&key)
            .map(|h| h.clone())
            .ok_or_else(|| FunctionInvocationError::RunnerUnavailable {
                reason: "missing handle".into(),
            })?;
        let state = handle.state.lock().expect("state").clone(); // allow-unwrap
        match state {
            RunnerState::Failed { reason } => {
                return Err(FunctionInvocationError::RunnerUnavailable { reason });
            }
            RunnerState::Unhealthy { reason, .. } => {
                return Err(FunctionInvocationError::RunnerUnavailable { reason });
            }
            _ => {}
        }
        let timeout = std::time::Duration::from_millis(
            self.function_timeouts
                .lock()
                .expect("function_timeouts") // allow-unwrap
                .get(id)
                .copied()
                .unwrap_or(self.config.default_timeout_ms),
        );
        let timeout_ms = timeout.as_millis() as u64;
        tokio::time::timeout(
            timeout,
            self.provider.invoke(&handle, id, exchange, timeout),
        )
        .await
        .map_err(|_| FunctionInvocationError::Timeout {
            function_id: id.clone(),
            timeout_ms,
        })?
        .map_err(|e| FunctionInvocationError::Transport(e.to_string()))
    }

    async fn prepare_reload(
        &self,
        diff: FunctionDiff,
        generation: u64,
    ) -> Result<PrepareToken, FunctionInvocationError> {
        let current_gen = self.current_generation.load(Ordering::SeqCst);
        if generation != current_gen {
            self.discard_staging(generation);
            return Err(FunctionInvocationError::Transport(format!(
                "stale generation: expected {}, got {}",
                current_gen, generation
            )));
        }

        {
            let mut staging = self.staging.lock().expect("staging"); // allow-unwrap
            let before = staging.len();
            staging.retain(|g, _| *g >= current_gen);
            let purged = before - staging.len();
            if purged > 0 {
                tracing::info!(purged, "hot-reload: purged stale staging buffers");
            }
        }

        let mut token = PrepareToken::default();
        for (def, route_id) in &diff.added {
            match self.register(def.clone(), route_id.as_deref()).await {
                Ok(()) => {
                    token.registered.push((def.clone(), route_id.clone()));
                }
                Err(e) => {
                    for (reg_def, reg_rid) in &token.registered {
                        if let Err(unreg_err) =
                            self.unregister(&reg_def.id, reg_rid.as_deref()).await
                        {
                            tracing::warn!(
                                function_id = %reg_def.id,
                                error = %unreg_err,
                                "hot-reload: failed to unregister during prepare rollback"
                            );
                        }
                    }
                    self.staging.lock().expect("staging").remove(&generation); // allow-unwrap
                    return Err(e);
                }
            }
        }
        Ok(token)
    }

    async fn finalize_reload(
        &self,
        diff: &FunctionDiff,
        generation: u64,
    ) -> Result<(), FunctionInvocationError> {
        for (id, route_id) in &diff.removed {
            self.unregister(id, route_id.as_deref()).await?;
        }
        self.staging.lock().expect("staging").remove(&generation); // allow-unwrap
        Ok(())
    }

    async fn rollback_reload(
        &self,
        token: PrepareToken,
        generation: u64,
    ) -> Result<(), FunctionInvocationError> {
        for (def, route_id) in &token.registered {
            if let Err(e) = self.unregister(&def.id, route_id.as_deref()).await {
                tracing::warn!(
                    function_id = %def.id,
                    error = %e,
                    "hot-reload: failed to unregister during rollback"
                );
            }
        }
        self.staging.lock().expect("staging").remove(&generation); // allow-unwrap
        Ok(())
    }

    async fn commit_staged(&self) -> Result<(), FunctionInvocationError> {
        let entries = self.staging.lock().expect("staging").remove(&0); // allow-unwrap
        if let Some(entries) = entries {
            let mut committed: Vec<(FunctionId, Option<String>)> = Vec::new();
            for (def, route_id) in entries {
                match self.register(def.clone(), route_id.as_deref()).await {
                    Ok(()) => committed.push((def.id, route_id)),
                    Err(e) => {
                        for (id, rid) in committed.iter().rev() {
                            let _ = self.unregister(id, rid.as_deref()).await;
                        }
                        return Err(e);
                    }
                }
            }
        }
        Ok(())
    }
}