awa-worker 0.6.0-alpha.4

Worker runtime for the Awa job queue
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
pub use crate::runtime::ProgressState;
use crate::storage::RuntimeStorage;
use awa_model::{AwaError, CallbackConfig, JobRow, QueueStorage};
use sqlx::PgPool;
use std::any::Any;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

/// Proof that this job registered an external callback in the database.
///
/// The public `id` can be sent to the external system. `#[non_exhaustive]`
/// keeps external callers from constructing this type directly.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CallbackGuard {
    pub id: uuid::Uuid,
}

impl CallbackGuard {
    fn new(id: uuid::Uuid) -> Self {
        Self { id }
    }

    /// Return the callback UUID persisted for this job.
    pub fn id(&self) -> uuid::Uuid {
        self.id
    }

    #[cfg(feature = "__python-bridge")]
    #[doc(hidden)]
    pub fn from_bridge_token(id: uuid::Uuid) -> Self {
        Self::new(id)
    }
}

#[doc(hidden)]
pub type CallbackToken = CallbackGuard;

/// Context passed to worker handlers during job execution.
///
/// Provides access to the job metadata, shared state (e.g., service dependencies),
/// callback registration, and structured progress reporting.
pub struct JobContext {
    /// The raw job row from the database.
    pub job: JobRow,
    /// Cancellation flag — set to true when shutdown or deadline is signalled.
    cancelled: Arc<AtomicBool>,
    /// Shared state map for dependency injection.
    state: Arc<HashMap<std::any::TypeId, Box<dyn Any + Send + Sync>>>,
    /// Database pool for callback registration and progress flush.
    pool: PgPool,
    /// Active runtime storage backend.
    storage: RuntimeStorage,
    /// Shared progress buffer — written by handler, read by heartbeat service.
    progress: Arc<std::sync::Mutex<ProgressState>>,
}

impl JobContext {
    pub(crate) fn new(
        job: JobRow,
        cancelled: Arc<AtomicBool>,
        state: Arc<HashMap<std::any::TypeId, Box<dyn Any + Send + Sync>>>,
        pool: PgPool,
        storage: RuntimeStorage,
        progress: Arc<std::sync::Mutex<ProgressState>>,
    ) -> Self {
        Self {
            job,
            cancelled,
            state,
            pool,
            storage,
            progress,
        }
    }

    #[doc(hidden)]
    pub fn new_for_testing(
        job: JobRow,
        cancelled: Arc<AtomicBool>,
        state: Arc<HashMap<std::any::TypeId, Box<dyn Any + Send + Sync>>>,
        pool: PgPool,
        progress: Arc<std::sync::Mutex<ProgressState>>,
    ) -> Self {
        Self::new(
            job,
            cancelled,
            state,
            pool,
            RuntimeStorage::Canonical,
            progress,
        )
    }

    /// Check if this job's execution has been cancelled (shutdown or deadline).
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::SeqCst)
    }

    /// Clone the shared cancellation flag for language bridges.
    pub fn cancellation_flag(&self) -> Arc<AtomicBool> {
        self.cancelled.clone()
    }

    /// Signal cancellation for this job.
    pub fn cancel(&self) {
        self.cancelled.store(true, Ordering::SeqCst);
    }

    /// Extract a shared state value by type.
    ///
    /// State values are registered via `Client::builder().state(value)`.
    /// Register the concrete type you want to extract:
    ///
    /// ```ignore
    /// // Register with the type you'll extract:
    /// let deps = Arc::new(MyDeps::new());
    /// Client::builder(pool)
    ///     .state(deps.clone())  // stores Arc<MyDeps>
    ///     .build()?;
    ///
    /// // In handler — extract the same type:
    /// let deps = ctx.extract::<Arc<MyDeps>>().unwrap();
    /// ```
    pub fn extract<T: Any + Send + Sync + Clone>(&self) -> Option<T> {
        self.state
            .get(&std::any::TypeId::of::<T>())
            .and_then(|v| v.downcast_ref::<T>())
            .cloned()
    }

    /// Get a reference to the database pool.
    pub fn pool(&self) -> &PgPool {
        &self.pool
    }

    /// Get the active queue-storage backend for this job, if any.
    pub fn queue_storage_store(&self) -> Option<Arc<QueueStorage>> {
        self.storage.queue_storage_store()
    }

    /// Register a callback for this job, writing the callback_id to the database
    /// immediately.
    ///
    /// Call this BEFORE sending the callback_id to the external system to avoid
    /// the race condition where the external system fires before the DB knows
    /// about the callback.
    ///
    /// Returns a `CallbackGuard` whose `id` should be included in the URL or
    /// payload sent to the external system.
    pub async fn register_callback(&self, timeout: Duration) -> Result<CallbackGuard, AwaError> {
        let callback_id = match &self.storage {
            RuntimeStorage::Canonical => {
                awa_model::admin::register_callback(
                    &self.pool,
                    self.job.id,
                    self.job.run_lease,
                    timeout,
                )
                .await?
            }
            RuntimeStorage::QueueStorage(runtime) => {
                runtime
                    .store
                    .register_callback(&self.pool, self.job.id, self.job.run_lease, timeout)
                    .await?
            }
        };
        Ok(CallbackGuard::new(callback_id))
    }

    /// Register a callback with CEL expressions for automatic resolution.
    ///
    /// See [`CallbackConfig`] for expression semantics.
    pub async fn register_callback_with_config(
        &self,
        timeout: Duration,
        config: &CallbackConfig,
    ) -> Result<CallbackGuard, AwaError> {
        let callback_id = match &self.storage {
            RuntimeStorage::Canonical => {
                awa_model::admin::register_callback_with_config(
                    &self.pool,
                    self.job.id,
                    self.job.run_lease,
                    timeout,
                    config,
                )
                .await?
            }
            RuntimeStorage::QueueStorage(runtime) => {
                runtime
                    .store
                    .register_callback_with_config(
                        &self.pool,
                        self.job.id,
                        self.job.run_lease,
                        timeout,
                        config,
                    )
                    .await?
            }
        };
        Ok(CallbackGuard::new(callback_id))
    }

    /// Wait for an external callback to resolve, then resume with the payload.
    ///
    /// This enables sequential callbacks: the handler can register a callback,
    /// wait for it, process the result, register another callback, wait again,
    /// and so on — all within a single handler invocation.
    ///
    /// The handler's async task suspends while waiting. The job transitions to
    /// `waiting_external`. When `resume_external(callback_id, payload)` is
    /// called, the job transitions back to `running` and this method returns
    /// the payload.
    ///
    /// The handler holds its permit (worker slot) during the wait. For very
    /// long waits, consider whether the single-shot `WaitForCallback` pattern
    /// (which releases the permit) is more appropriate.
    ///
    /// ```ignore
    /// let token = ctx.register_callback(Duration::from_secs(3600)).await?;
    /// send_to_external_system(token.id());
    /// let payload = ctx.wait_for_callback(token).await?;
    /// // Handler resumes here with the external system's response
    /// ```
    pub async fn wait_for_callback(
        &self,
        guard: CallbackGuard,
    ) -> Result<serde_json::Value, AwaError> {
        use awa_model::admin::CallbackPollResult;

        let callback_id = guard.id();

        let entered = match &self.storage {
            RuntimeStorage::Canonical => {
                awa_model::admin::enter_callback_wait(
                    &self.pool,
                    self.job.id,
                    self.job.run_lease,
                    callback_id,
                )
                .await?
            }
            RuntimeStorage::QueueStorage(runtime) => {
                runtime
                    .store
                    .enter_callback_wait(&self.pool, self.job.id, self.job.run_lease, callback_id)
                    .await?
            }
        };

        let check_state = || async {
            match &self.storage {
                RuntimeStorage::Canonical => {
                    awa_model::admin::check_callback_state(&self.pool, self.job.id, callback_id)
                        .await
                }
                RuntimeStorage::QueueStorage(runtime) => {
                    runtime
                        .store
                        .check_callback_state(&self.pool, self.job.id, callback_id)
                        .await
                }
            }
        };

        if !entered {
            match check_state().await? {
                CallbackPollResult::Resolved(payload) => return Ok(payload),
                CallbackPollResult::Pending => { /* Already in waiting_external */ }
                CallbackPollResult::Stale {
                    token,
                    current,
                    state,
                } => {
                    return Err(AwaError::Validation(format!(
                        "wait_for_callback: token {token} is stale; current callback is {current} in state {state:?}"
                    )));
                }
                CallbackPollResult::UnexpectedState { token, state } => {
                    return Err(AwaError::Validation(format!(
                        "wait_for_callback: job is not waiting on callback {token}; state={state:?}"
                    )));
                }
                CallbackPollResult::NotFound => {
                    return Err(AwaError::Validation(
                        "job not found during callback wait".into(),
                    ));
                }
            }
        }

        loop {
            if self.is_cancelled() {
                return Err(AwaError::Validation(
                    "job cancelled while waiting for callback".into(),
                ));
            }

            match check_state().await? {
                CallbackPollResult::Resolved(payload) => return Ok(payload),
                CallbackPollResult::Pending => {
                    tokio::time::sleep(Duration::from_millis(200)).await;
                }
                CallbackPollResult::Stale {
                    token,
                    current,
                    state,
                } => {
                    return Err(AwaError::Validation(format!(
                        "wait_for_callback: token {token} is stale; current callback is {current} in state {state:?}"
                    )));
                }
                CallbackPollResult::UnexpectedState { token, state } => {
                    return Err(AwaError::Validation(format!(
                        "job left wait_for_callback unexpectedly for token {token}: state={state:?}"
                    )));
                }
                CallbackPollResult::NotFound => {
                    return Err(AwaError::Validation(
                        "job not found during callback wait".into(),
                    ));
                }
            }
        }
    }

    /// Set structured progress (0-100 with message). Sync — writes to in-memory buffer.
    ///
    /// `percent` is clamped to 0-100. For progress without a message, pass `""`.
    pub fn set_progress(&self, percent: u8, message: &str) {
        let mut guard = self.progress.lock().expect("progress lock poisoned");
        guard.set_progress(percent, Some(message));
    }

    /// Shallow-merge keys into progress.metadata for checkpointing. Sync.
    ///
    /// `updates` must be a JSON object. Top-level keys overwrite; nested objects
    /// are replaced, not deep-merged.
    pub fn update_metadata(&self, updates: serde_json::Value) -> Result<(), AwaError> {
        let obj = updates
            .as_object()
            .ok_or_else(|| AwaError::Validation("update_metadata requires a JSON object".into()))?;

        let mut guard = self.progress.lock().expect("progress lock poisoned");
        if !guard.merge_metadata(obj) {
            return Err(AwaError::Validation(
                "progress.metadata is not a JSON object; cannot merge".into(),
            ));
        }
        Ok(())
    }

    /// Force immediate flush of pending progress to DB. For critical checkpoints.
    ///
    /// Does not return success until the progress has been durably written
    /// or the job is no longer in running state (rescued/cancelled).
    pub async fn flush_progress(&self) -> Result<(), AwaError> {
        let (snapshot, target_generation) = {
            let guard = self.progress.lock().expect("progress lock poisoned");
            match guard.pending_snapshot() {
                Some(pair) => pair,
                None => return Ok(()),
            }
        };

        match &self.storage {
            RuntimeStorage::Canonical => {
                let result = sqlx::query(
                    r#"
                    UPDATE awa.jobs_hot
                    SET progress = $2
                    WHERE id = $1 AND state = 'running' AND run_lease = $3
                    "#,
                )
                .bind(self.job.id)
                .bind(&snapshot)
                .bind(self.job.run_lease)
                .execute(&self.pool)
                .await?;

                if result.rows_affected() == 0 {
                    return Ok(());
                }
            }
            RuntimeStorage::QueueStorage(runtime) => {
                runtime
                    .store
                    .flush_progress(
                        &self.pool,
                        self.job.id,
                        self.job.run_lease,
                        snapshot.clone(),
                    )
                    .await?;
            }
        }

        let mut guard = self.progress.lock().expect("progress lock poisoned");
        guard.ack(target_generation);

        Ok(())
    }

    /// Get a clone of the shared progress state Arc (for Python bridge).
    pub fn progress_buffer(&self) -> Arc<std::sync::Mutex<ProgressState>> {
        self.progress.clone()
    }
}