use std::sync::Arc;
use graphile_worker_database::{Database, Schema};
use graphile_worker_extensions::ReadOnlyExtensions;
use graphile_worker_job::Job;
use serde_json::Value;
use crate::{SharedTaskDetails, WorkerContextBuilder};
#[derive(Clone, Debug)]
pub struct WorkerContext {
pub(crate) payload: Option<Value>,
pub(crate) database: Database,
pub(crate) schema: Schema,
pub(crate) job: Arc<Job>,
pub(crate) worker_id: String,
pub(crate) extensions: ReadOnlyExtensions,
pub(crate) task_details: SharedTaskDetails,
pub(crate) use_local_time: bool,
}
impl WorkerContext {
pub fn builder() -> WorkerContextBuilder {
WorkerContextBuilder::default()
}
pub fn from_shared_job(
job: Arc<Job>,
database: impl Into<Database>,
schema: impl Into<Schema>,
worker_id: String,
extensions: ReadOnlyExtensions,
task_details: SharedTaskDetails,
use_local_time: bool,
) -> Self {
Self {
payload: None,
database: database.into(),
schema: schema.into(),
job,
worker_id,
extensions,
task_details,
use_local_time,
}
}
pub fn payload(&self) -> &Value {
self.payload.as_ref().unwrap_or_else(|| self.job.payload())
}
pub fn database(&self) -> &Database {
&self.database
}
#[cfg(feature = "driver-sqlx")]
pub fn try_pg_pool(&self) -> Option<&sqlx::PgPool> {
self.database
.downcast_ref::<graphile_worker_database::sqlx::SqlxDatabase>()
.map(|database| database.pool())
}
#[cfg(feature = "driver-sqlx")]
pub fn pg_pool(&self) -> &sqlx::PgPool {
self.try_pg_pool()
.expect("WorkerContext does not use the SQLx database driver")
}
pub fn schema(&self) -> &Schema {
&self.schema
}
pub fn job(&self) -> &Job {
self.job.as_ref()
}
pub fn worker_id(&self) -> &str {
&self.worker_id
}
pub fn extensions(&self) -> &ReadOnlyExtensions {
&self.extensions
}
pub fn task_details(&self) -> &SharedTaskDetails {
&self.task_details
}
pub fn use_local_time(&self) -> bool {
self.use_local_time
}
pub fn get_ext<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.extensions.get()
}
}