1use serde::{Serialize, de::DeserializeOwned};
2
3use crate::{JobId, OxanusError, Storage, job_envelope::JobMeta};
4
5#[derive(Clone)]
6pub struct Context<T: Clone + Send + Sync> {
7 pub ctx: T,
8 pub meta: JobMeta,
9 pub state: JobState,
10}
11
12impl<T: Clone + Send + Sync> Context<T> {
13 pub fn value(v: T) -> ContextValue<T> {
14 ContextValue(v)
15 }
16}
17
18#[derive(Debug, Clone)]
19pub struct ContextValue<T: Clone + Send + Sync>(pub(crate) T);
20
21#[derive(Clone)]
22pub struct JobState {
23 storage: Storage,
24 job_id: JobId,
25 value: Option<serde_json::Value>,
26}
27
28impl JobState {
29 pub(crate) fn new(storage: Storage, job_id: JobId, value: Option<serde_json::Value>) -> Self {
30 Self {
31 storage,
32 job_id,
33 value,
34 }
35 }
36
37 pub async fn update(&self, state: impl Serialize) -> Result<(), OxanusError> {
38 self.storage
39 .internal
40 .update_state(
41 &self.job_id,
42 serde_json::to_value(state).map_err(OxanusError::JobStateJsonError)?,
43 )
44 .await?;
45 Ok(())
46 }
47
48 pub async fn get<S: DeserializeOwned>(&self) -> Result<Option<S>, OxanusError> {
49 Ok(match self.value.clone() {
50 Some(state) => {
51 Some(serde_json::from_value(state).map_err(OxanusError::JobStateJsonError)?)
52 }
53 None => None,
54 })
55 }
56}