pgqueuer-hs 0.0.1.0 → 0.1.0.0
raw patch · API changes only · 31 files changed · show whitespace changes · browse pgqueuer-hs-0.1.0.0
+5270/−1111 lines, 31 filesdep +asyncdep +case-insensitivedep +contravariantPVP ok
Dependencies added: async, case-insensitive, contravariant, cron, hasql, hasql-pool, hs-opentelemetry-api, hs-opentelemetry-propagator-w3c, http-types, mtl, random, stm, testcontainers, unliftio, unordered-containers, vector
API changes (from Hackage documentation)
40 removed, 287 added, 5 changed
version bump matches the API change (PVP)
- PGQueuer: retryJob :: QueueManager -> Job -> NominalDiffTime -> Maybe Value -> IO ()
- PGQueuer.Query: retryJob :: Connection -> DBSettings -> Job -> NominalDiffTime -> Maybe Value -> IO ()
- PGQueuer.Types: instance GHC.Enum.Bounded PGQueuer.Types.JobStatus
- PGQueuer.Types: instance GHC.Enum.Bounded PGQueuer.Types.OnFailure
- PGQueuer.Types: instance GHC.Enum.Bounded PGQueuer.Types.Operation
- PGQueuer.Types: instance GHC.Enum.Enum PGQueuer.Types.JobStatus
- PGQueuer.Types: instance GHC.Enum.Enum PGQueuer.Types.OnFailure
- PGQueuer.Types: instance GHC.Enum.Enum PGQueuer.Types.Operation
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.Channel
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.CronExpression
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.Entrypoint
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.EntrypointExecutionParameter
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.Event
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.Job
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.JobId
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.JobStatus
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.LogEntry
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.LogStatistics
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.OnFailure
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.Operation
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.QueueStatistics
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.Schedule
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.ScheduleId
- PGQueuer.Types: instance GHC.Generics.Generic PGQueuer.Types.TracebackRecord
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.Channel
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.CronExpression
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.Entrypoint
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.EntrypointExecutionParameter
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.Event
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.Job
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.JobId
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.JobStatus
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.LogEntry
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.LogStatistics
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.OnFailure
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.Operation
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.QueueStatistics
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.Schedule
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.ScheduleId
- PGQueuer.Types: instance GHC.Show.Show PGQueuer.Types.TracebackRecord
+ PGQueuer: (<~~) :: JobNode -> [JobTree] -> JobTree
+ PGQueuer: JobNode :: Entrypoint -> Maybe ByteString -> Int -> Maybe NominalDiffTime -> Maybe Text -> Maybe Value -> Maybe Value -> JobNode
+ PGQueuer: JobTree :: JobNode -> [JobTree] -> JobTree
+ PGQueuer: [jnDedupeKey] :: JobNode -> Maybe Text
+ PGQueuer: [jnEntrypoint] :: JobNode -> Entrypoint
+ PGQueuer: [jnExecuteAfter] :: JobNode -> Maybe NominalDiffTime
+ PGQueuer: [jnHeaders] :: JobNode -> Maybe Value
+ PGQueuer: [jnParentState] :: JobNode -> Maybe Value
+ PGQueuer: [jnPayload] :: JobNode -> Maybe ByteString
+ PGQueuer: [jnPriority] :: JobNode -> Int
+ PGQueuer: data JobNode
+ PGQueuer: data JobTree
+ PGQueuer: infixr 5 <~~
+ PGQueuer: insertJobTree :: QueueManager -> JobTree -> IO ()
+ PGQueuer: registerSchedule :: QueueManager -> CronExpression -> Entrypoint -> IO ()
+ PGQueuer: retryJobs :: QueueManager -> [(JobId, UTCTime, Int32)] -> IO ()
+ PGQueuer: setupSchema :: QueueManager -> IO ()
+ PGQueuer: type EntrypointHandler = Job -> IO ()
+ PGQueuer.Backend.Hasql: HasqlDb :: ReaderT HasqlDbEnv IO a -> HasqlDb a
+ PGQueuer.Backend.Hasql: HasqlDbEnv :: Pool -> DBSettings -> HasqlDbEnv
+ PGQueuer.Backend.Hasql: [hdbPool] :: HasqlDbEnv -> Pool
+ PGQueuer.Backend.Hasql: [hdbSettings] :: HasqlDbEnv -> DBSettings
+ PGQueuer.Backend.Hasql: [unHasqlDb] :: HasqlDb a -> ReaderT HasqlDbEnv IO a
+ PGQueuer.Backend.Hasql: data HasqlDbEnv
+ PGQueuer.Backend.Hasql: instance Control.Monad.IO.Class.MonadIO PGQueuer.Backend.Hasql.HasqlDb
+ PGQueuer.Backend.Hasql: instance Control.Monad.Reader.Class.MonadReader PGQueuer.Backend.Hasql.HasqlDbEnv PGQueuer.Backend.Hasql.HasqlDb
+ PGQueuer.Backend.Hasql: instance GHC.Internal.Base.Applicative PGQueuer.Backend.Hasql.HasqlDb
+ PGQueuer.Backend.Hasql: instance GHC.Internal.Base.Functor PGQueuer.Backend.Hasql.HasqlDb
+ PGQueuer.Backend.Hasql: instance GHC.Internal.Base.Monad PGQueuer.Backend.Hasql.HasqlDb
+ PGQueuer.Backend.Hasql: instance PGQueuer.Core.Monad.MonadPGQueuer PGQueuer.Backend.Hasql.HasqlDb
+ PGQueuer.Backend.Hasql: mkHasqlDbEnv :: ByteString -> DBSettings -> IO HasqlDbEnv
+ PGQueuer.Backend.Hasql: newtype HasqlDb a
+ PGQueuer.Backend.Hasql: releaseHasqlDbEnv :: HasqlDbEnv -> IO ()
+ PGQueuer.Backend.Hasql: runHasqlDb :: HasqlDbEnv -> HasqlDb a -> IO a
+ PGQueuer.Backend.Hasql.Statements: dequeueStmt :: DBSettings -> Int -> Statement (Int32, UUID, Maybe Int64, Vector Text, Vector Int64) (Vector Job)
+ PGQueuer.Backend.Hasql.Statements: enqueueStmt :: DBSettings -> Statement (Vector Int32, Vector Text, Vector (Maybe ByteString), Vector (Maybe Text), Vector (Maybe Text), Vector (Maybe ByteString), Vector (Maybe Int32), Vector (Maybe ByteString), Vector Text) (Vector Int32)
+ PGQueuer.Backend.Hasql.Statements: fetchSchedulesStmt :: Statement () (Vector (Int32, Text, Text, UTCTime, UTCTime, UTCTime, UTCTime, Maybe UTCTime, Text))
+ PGQueuer.Backend.Hasql.Statements: getEarliestNextRunStmt :: Statement () (Maybe UTCTime)
+ PGQueuer.Backend.Hasql.Statements: insertScheduleStmt :: Statement (Text, Text) ()
+ PGQueuer.Backend.Hasql.Statements: logJobsStmt :: DBSettings -> Statement (Vector Int32, Vector Text, Vector (Maybe ByteString)) ()
+ PGQueuer.Backend.Hasql.Statements: mergedChildResultsStmt :: DBSettings -> Statement Int32 (Vector Value)
+ PGQueuer.Backend.Hasql.Statements: retryJobsStmt :: DBSettings -> Statement (Vector UTCTime, Vector Int32, Vector Int32) ()
+ PGQueuer.Backend.Hasql.Statements: setScheduleQueuedStmt :: Statement (UTCTime, Int32) ()
+ PGQueuer.Backend.Hasql.Statements: tableStatsStmt :: Statement Text (Int64, Int64, Int64)
+ PGQueuer.Backend.Hasql.Statements: updateHeartbeatStmt :: DBSettings -> Statement (Vector Int32) ()
+ PGQueuer.Backend.Hasql.Statements: walLsnStmt :: Statement () Int64
+ PGQueuer.Backend.Simple: SimpleDb :: ReaderT SimpleDbEnv IO a -> SimpleDb a
+ PGQueuer.Backend.Simple: SimpleDbEnv :: Connection -> DBSettings -> SimpleDbEnv
+ PGQueuer.Backend.Simple: [sdbConnection] :: SimpleDbEnv -> Connection
+ PGQueuer.Backend.Simple: [sdbSettings] :: SimpleDbEnv -> DBSettings
+ PGQueuer.Backend.Simple: [unSimpleDb] :: SimpleDb a -> ReaderT SimpleDbEnv IO a
+ PGQueuer.Backend.Simple: data SimpleDbEnv
+ PGQueuer.Backend.Simple: instance Control.Monad.IO.Class.MonadIO PGQueuer.Backend.Simple.SimpleDb
+ PGQueuer.Backend.Simple: instance Control.Monad.Reader.Class.MonadReader PGQueuer.Backend.Simple.SimpleDbEnv PGQueuer.Backend.Simple.SimpleDb
+ PGQueuer.Backend.Simple: instance GHC.Internal.Base.Applicative PGQueuer.Backend.Simple.SimpleDb
+ PGQueuer.Backend.Simple: instance GHC.Internal.Base.Functor PGQueuer.Backend.Simple.SimpleDb
+ PGQueuer.Backend.Simple: instance GHC.Internal.Base.Monad PGQueuer.Backend.Simple.SimpleDb
+ PGQueuer.Backend.Simple: instance PGQueuer.Core.Monad.MonadPGQueuer PGQueuer.Backend.Simple.SimpleDb
+ PGQueuer.Backend.Simple: mkSimpleDbEnv :: Connection -> SimpleDbEnv
+ PGQueuer.Backend.Simple: newtype SimpleDb a
+ PGQueuer.Backend.Simple: runSimpleDb :: SimpleDbEnv -> SimpleDb a -> IO a
+ PGQueuer.Core.Monad: class Monad m => MonadPGQueuer (m :: Type -> Type)
+ PGQueuer.Core.Monad: dequeue :: MonadPGQueuer m => Int -> [EntrypointExecutionParameter] -> UUID -> Maybe Int -> Int -> m [Job]
+ PGQueuer.Core.Monad: enqueue :: MonadPGQueuer m => Entrypoint -> Maybe ByteString -> Int -> Maybe NominalDiffTime -> Maybe Text -> Maybe Value -> Maybe JobId -> Maybe Value -> JobStatus -> m [JobId]
+ PGQueuer.Core.Monad: fetchSchedules :: MonadPGQueuer m => m [Schedule]
+ PGQueuer.Core.Monad: getEarliestNextRun :: MonadPGQueuer m => m (Maybe UTCTime)
+ PGQueuer.Core.Monad: insertSchedule :: MonadPGQueuer m => CronExpression -> Entrypoint -> m ()
+ PGQueuer.Core.Monad: logJobs :: MonadPGQueuer m => [(JobId, JobStatus, Maybe Value)] -> m ()
+ PGQueuer.Core.Monad: mergedChildResults :: MonadPGQueuer m => JobId -> m [Value]
+ PGQueuer.Core.Monad: retryJobs :: MonadPGQueuer m => [(JobId, UTCTime, Int32)] -> m ()
+ PGQueuer.Core.Monad: setScheduleQueued :: MonadPGQueuer m => ScheduleId -> UTCTime -> m ()
+ PGQueuer.Core.Monad: updateHeartbeat :: MonadPGQueuer m => [JobId] -> m ()
+ PGQueuer.Core.Monad: withTransaction :: MonadPGQueuer m => m a -> m a
+ PGQueuer.Query: fetchSchedules :: Connection -> DBSettings -> IO [Schedule]
+ PGQueuer.Query: getEarliestNextRun :: Connection -> DBSettings -> IO (Maybe UTCTime)
+ PGQueuer.Query: insertSchedule :: Connection -> DBSettings -> CronExpression -> Entrypoint -> IO ()
+ PGQueuer.Query: retryJobs :: Connection -> DBSettings -> [(JobId, UTCTime, Int32)] -> IO ()
+ PGQueuer.Query: setScheduleQueued :: Connection -> DBSettings -> ScheduleId -> UTCTime -> IO ()
+ PGQueuer.Settings: instance GHC.Classes.Eq PGQueuer.Settings.DBSettings
+ PGQueuer.Settings: instance GHC.Internal.Show.Show PGQueuer.Settings.DBSettings
+ PGQueuer.Tracing: injectOtelContext :: IO (Maybe Value)
+ PGQueuer.Tracing: withJobSpan :: Entrypoint -> JobId -> Maybe Value -> IO a -> IO a
+ PGQueuer.Types: CancellationEvent :: Channel -> UTCTime -> [JobId] -> Event
+ PGQueuer.Types: Constant :: NominalDiffTime -> BackoffStrategy
+ PGQueuer.Types: CronExpression :: Text -> CronExpression
+ PGQueuer.Types: Delete :: Operation
+ PGQueuer.Types: EqualJitter :: Jitter
+ PGQueuer.Types: Exponential :: NominalDiffTime -> NominalDiffTime -> BackoffStrategy
+ PGQueuer.Types: FullJitter :: Jitter
+ PGQueuer.Types: HealthCheckEvent :: Channel -> UTCTime -> UUID -> Event
+ PGQueuer.Types: Held :: JobStatus
+ PGQueuer.Types: Insert :: Operation
+ PGQueuer.Types: JobPermanentException :: Text -> JobPermanentException
+ PGQueuer.Types: JobRetryableException :: Text -> JobRetryableException
+ PGQueuer.Types: Linear :: NominalDiffTime -> NominalDiffTime -> BackoffStrategy
+ PGQueuer.Types: LogEntry :: UTCTime -> JobId -> JobStatus -> Int -> Entrypoint -> Maybe Value -> Bool -> Maybe JobId -> LogEntry
+ PGQueuer.Types: LogStatistics :: Int -> UTCTime -> Entrypoint -> Int -> JobStatus -> LogStatistics
+ PGQueuer.Types: NoJitter :: Jitter
+ PGQueuer.Types: Schedule :: ScheduleId -> CronExpression -> Entrypoint -> UTCTime -> UTCTime -> UTCTime -> UTCTime -> Maybe UTCTime -> JobStatus -> Schedule
+ PGQueuer.Types: TableChangedEvent :: Channel -> UTCTime -> Operation -> Text -> Event
+ PGQueuer.Types: TracebackRecord :: JobId -> UTCTime -> Text -> Text -> Text -> TracebackRecord
+ PGQueuer.Types: Truncate :: Operation
+ PGQueuer.Types: Update :: Operation
+ PGQueuer.Types: [backoffBase] :: BackoffStrategy -> NominalDiffTime
+ PGQueuer.Types: [backoffCap] :: BackoffStrategy -> NominalDiffTime
+ PGQueuer.Types: [backoffDelay] :: BackoffStrategy -> NominalDiffTime
+ PGQueuer.Types: [eventChannel] :: Event -> Channel
+ PGQueuer.Types: [eventId] :: Event -> UUID
+ PGQueuer.Types: [eventIds] :: Event -> [JobId]
+ PGQueuer.Types: [eventOperation] :: Event -> Operation
+ PGQueuer.Types: [eventSentAt] :: Event -> UTCTime
+ PGQueuer.Types: [eventTable] :: Event -> Text
+ PGQueuer.Types: [jobParentId] :: Job -> Maybe JobId
+ PGQueuer.Types: [jobParentState] :: Job -> Maybe Value
+ PGQueuer.Types: [logAggregated] :: LogEntry -> Bool
+ PGQueuer.Types: [logCreated] :: LogEntry -> UTCTime
+ PGQueuer.Types: [logEntrypoint] :: LogEntry -> Entrypoint
+ PGQueuer.Types: [logJobId] :: LogEntry -> JobId
+ PGQueuer.Types: [logParentId] :: LogEntry -> Maybe JobId
+ PGQueuer.Types: [logPriority] :: LogEntry -> Int
+ PGQueuer.Types: [logStatsCount] :: LogStatistics -> Int
+ PGQueuer.Types: [logStatsCreated] :: LogStatistics -> UTCTime
+ PGQueuer.Types: [logStatsEntrypoint] :: LogStatistics -> Entrypoint
+ PGQueuer.Types: [logStatsPriority] :: LogStatistics -> Int
+ PGQueuer.Types: [logStatsStatus] :: LogStatistics -> JobStatus
+ PGQueuer.Types: [logStatus] :: LogEntry -> JobStatus
+ PGQueuer.Types: [logTraceback] :: LogEntry -> Maybe Value
+ PGQueuer.Types: [paramBackoffStrategy] :: EntrypointExecutionParameter -> BackoffStrategy
+ PGQueuer.Types: [paramJitter] :: EntrypointExecutionParameter -> Jitter
+ PGQueuer.Types: [paramMaxAttempts] :: EntrypointExecutionParameter -> Int
+ PGQueuer.Types: [scheduleCreated] :: Schedule -> UTCTime
+ PGQueuer.Types: [scheduleEntrypoint] :: Schedule -> Entrypoint
+ PGQueuer.Types: [scheduleExpression] :: Schedule -> CronExpression
+ PGQueuer.Types: [scheduleHeartbeat] :: Schedule -> UTCTime
+ PGQueuer.Types: [scheduleId] :: Schedule -> ScheduleId
+ PGQueuer.Types: [scheduleLastRun] :: Schedule -> Maybe UTCTime
+ PGQueuer.Types: [scheduleNextRun] :: Schedule -> UTCTime
+ PGQueuer.Types: [scheduleStatus] :: Schedule -> JobStatus
+ PGQueuer.Types: [scheduleUpdated] :: Schedule -> UTCTime
+ PGQueuer.Types: [traceExceptionMessage] :: TracebackRecord -> Text
+ PGQueuer.Types: [traceExceptionType] :: TracebackRecord -> Text
+ PGQueuer.Types: [traceJobId] :: TracebackRecord -> JobId
+ PGQueuer.Types: [traceTimestamp] :: TracebackRecord -> UTCTime
+ PGQueuer.Types: [traceTraceback] :: TracebackRecord -> Text
+ PGQueuer.Types: data BackoffStrategy
+ PGQueuer.Types: data Event
+ PGQueuer.Types: data Jitter
+ PGQueuer.Types: data LogEntry
+ PGQueuer.Types: data LogStatistics
+ PGQueuer.Types: data Operation
+ PGQueuer.Types: data Schedule
+ PGQueuer.Types: data TracebackRecord
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.BackoffStrategy
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.Channel
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.CronExpression
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.Entrypoint
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.EntrypointExecutionParameter
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.Event
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.Jitter
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.JobId
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.JobStatus
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.LogStatistics
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.OnFailure
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.Operation
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.QueueStatistics
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.ScheduleId
+ PGQueuer.Types: instance Data.Aeson.Types.FromJSON.FromJSON PGQueuer.Types.TracebackRecord
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.BackoffStrategy
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.Channel
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.CronExpression
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.Entrypoint
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.EntrypointExecutionParameter
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.Event
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.Jitter
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.JobId
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.JobStatus
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.LogStatistics
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.OnFailure
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.Operation
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.QueueStatistics
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.ScheduleId
+ PGQueuer.Types: instance Data.Aeson.Types.ToJSON.ToJSON PGQueuer.Types.TracebackRecord
+ PGQueuer.Types: instance GHC.Classes.Eq PGQueuer.Types.BackoffStrategy
+ PGQueuer.Types: instance GHC.Classes.Eq PGQueuer.Types.Jitter
+ PGQueuer.Types: instance GHC.Classes.Eq PGQueuer.Types.JobPermanentException
+ PGQueuer.Types: instance GHC.Classes.Eq PGQueuer.Types.JobRetryableException
+ PGQueuer.Types: instance GHC.Internal.Enum.Bounded PGQueuer.Types.JobStatus
+ PGQueuer.Types: instance GHC.Internal.Enum.Bounded PGQueuer.Types.OnFailure
+ PGQueuer.Types: instance GHC.Internal.Enum.Bounded PGQueuer.Types.Operation
+ PGQueuer.Types: instance GHC.Internal.Enum.Enum PGQueuer.Types.JobStatus
+ PGQueuer.Types: instance GHC.Internal.Enum.Enum PGQueuer.Types.OnFailure
+ PGQueuer.Types: instance GHC.Internal.Enum.Enum PGQueuer.Types.Operation
+ PGQueuer.Types: instance GHC.Internal.Exception.Type.Exception PGQueuer.Types.JobPermanentException
+ PGQueuer.Types: instance GHC.Internal.Exception.Type.Exception PGQueuer.Types.JobRetryableException
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.BackoffStrategy
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.Channel
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.CronExpression
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.Entrypoint
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.EntrypointExecutionParameter
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.Event
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.Jitter
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.Job
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.JobId
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.JobStatus
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.LogEntry
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.LogStatistics
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.OnFailure
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.Operation
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.QueueStatistics
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.Schedule
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.ScheduleId
+ PGQueuer.Types: instance GHC.Internal.Generics.Generic PGQueuer.Types.TracebackRecord
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.BackoffStrategy
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.Channel
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.CronExpression
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.Entrypoint
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.EntrypointExecutionParameter
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.Event
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.Jitter
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.Job
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.JobId
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.JobPermanentException
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.JobRetryableException
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.JobStatus
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.LogEntry
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.LogStatistics
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.OnFailure
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.Operation
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.QueueStatistics
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.Schedule
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.ScheduleId
+ PGQueuer.Types: instance GHC.Internal.Show.Show PGQueuer.Types.TracebackRecord
+ PGQueuer.Types: newtype CronExpression
+ PGQueuer.Types: newtype JobPermanentException
+ PGQueuer.Types: newtype JobRetryableException
+ PGQueuer.Types: textToJobStatus :: Text -> Maybe JobStatus
+ PGQueuer.Worker.Backoff: Constant :: NominalDiffTime -> BackoffStrategy
+ PGQueuer.Worker.Backoff: EqualJitter :: Jitter
+ PGQueuer.Worker.Backoff: Exponential :: NominalDiffTime -> NominalDiffTime -> BackoffStrategy
+ PGQueuer.Worker.Backoff: FullJitter :: Jitter
+ PGQueuer.Worker.Backoff: Linear :: NominalDiffTime -> NominalDiffTime -> BackoffStrategy
+ PGQueuer.Worker.Backoff: NoJitter :: Jitter
+ PGQueuer.Worker.Backoff: [backoffBase] :: BackoffStrategy -> NominalDiffTime
+ PGQueuer.Worker.Backoff: [backoffCap] :: BackoffStrategy -> NominalDiffTime
+ PGQueuer.Worker.Backoff: [backoffDelay] :: BackoffStrategy -> NominalDiffTime
+ PGQueuer.Worker.Backoff: applyJitter :: Jitter -> NominalDiffTime -> IO NominalDiffTime
+ PGQueuer.Worker.Backoff: calculateBackoff :: BackoffStrategy -> Int -> NominalDiffTime
+ PGQueuer.Worker.Backoff: data BackoffStrategy
+ PGQueuer.Worker.Backoff: data Jitter
+ PGQueuer.Worker.Buffer: BufferConfig :: !Int -> !Int -> BufferConfig
+ PGQueuer.Worker.Buffer: [bcFlushInterval] :: BufferConfig -> !Int
+ PGQueuer.Worker.Buffer: [bcMaxSize] :: BufferConfig -> !Int
+ PGQueuer.Worker.Buffer: add :: TimedOverflowBuffer a -> a -> IO ()
+ PGQueuer.Worker.Buffer: data BufferConfig
+ PGQueuer.Worker.Buffer: data TimedOverflowBuffer a
+ PGQueuer.Worker.Buffer: defaultBufferConfig :: BufferConfig
+ PGQueuer.Worker.Buffer: flushBuffer :: TimedOverflowBuffer a -> IO ()
+ PGQueuer.Worker.Buffer: instance GHC.Classes.Eq PGQueuer.Worker.Buffer.BufferConfig
+ PGQueuer.Worker.Buffer: instance GHC.Internal.Show.Show PGQueuer.Worker.Buffer.BufferConfig
+ PGQueuer.Worker.Buffer: mkHeartbeatBuffer :: BufferConfig -> ([JobId] -> IO ()) -> IO HeartbeatBuffer
+ PGQueuer.Worker.Buffer: mkJobStatusLogBuffer :: BufferConfig -> ([(JobId, JobStatus, Maybe Value)] -> IO ()) -> IO JobStatusLogBuffer
+ PGQueuer.Worker.Buffer: mkRetryBuffer :: BufferConfig -> ([(JobId, UTCTime, Int32)] -> IO ()) -> IO RetryBuffer
+ PGQueuer.Worker.Buffer: newBuffer :: BufferConfig -> ([a] -> IO ()) -> IO (TimedOverflowBuffer a)
+ PGQueuer.Worker.Buffer: type HeartbeatBuffer = TimedOverflowBuffer JobId
+ PGQueuer.Worker.Buffer: type JobStatusLogBuffer = TimedOverflowBuffer (JobId, JobStatus, Maybe Value)
+ PGQueuer.Worker.Buffer: type RetryBuffer = TimedOverflowBuffer (JobId, UTCTime, Int32)
+ PGQueuer.Worker.Buffer: withBuffer :: BufferConfig -> ([a] -> IO ()) -> (TimedOverflowBuffer a -> IO b) -> IO b
+ PGQueuer.Worker.Cron: calculateNextRunTime :: CronExpression -> UTCTime -> Either String UTCTime
+ PGQueuer.Worker.Cron: runCronScheduler :: Connection -> DBSettings -> IO ()
+ PGQueuer.Workflow: (<~~) :: JobNode -> [JobTree] -> JobTree
+ PGQueuer.Workflow: JobNode :: Entrypoint -> Maybe ByteString -> Int -> Maybe NominalDiffTime -> Maybe Text -> Maybe Value -> Maybe Value -> JobNode
+ PGQueuer.Workflow: JobTree :: JobNode -> [JobTree] -> JobTree
+ PGQueuer.Workflow: [jnDedupeKey] :: JobNode -> Maybe Text
+ PGQueuer.Workflow: [jnEntrypoint] :: JobNode -> Entrypoint
+ PGQueuer.Workflow: [jnExecuteAfter] :: JobNode -> Maybe NominalDiffTime
+ PGQueuer.Workflow: [jnHeaders] :: JobNode -> Maybe Value
+ PGQueuer.Workflow: [jnParentState] :: JobNode -> Maybe Value
+ PGQueuer.Workflow: [jnPayload] :: JobNode -> Maybe ByteString
+ PGQueuer.Workflow: [jnPriority] :: JobNode -> Int
+ PGQueuer.Workflow: data JobNode
+ PGQueuer.Workflow: data JobTree
+ PGQueuer.Workflow: infixr 5 <~~
+ PGQueuer.Workflow: insertJobTree :: MonadPGQueuer m => JobTree -> m ()
+ PGQueuer.Workflow: instance GHC.Classes.Eq PGQueuer.Workflow.JobNode
+ PGQueuer.Workflow: instance GHC.Classes.Eq PGQueuer.Workflow.JobTree
+ PGQueuer.Workflow: instance GHC.Internal.Show.Show PGQueuer.Workflow.JobNode
+ PGQueuer.Workflow: instance GHC.Internal.Show.Show PGQueuer.Workflow.JobTree
- PGQueuer: workerLoop :: QueueManager -> [EntrypointExecutionParameter] -> IO ()
+ PGQueuer: workerLoop :: QueueManager -> BufferConfig -> [EntrypointExecutionParameter] -> IO ()
- PGQueuer.Query: enqueueMultiple :: Connection -> DBSettings -> [Entrypoint] -> [Maybe ByteString] -> [Int] -> [Maybe NominalDiffTime] -> [Maybe Text] -> [Maybe Value] -> IO [JobId]
+ PGQueuer.Query: enqueueMultiple :: Connection -> DBSettings -> [Entrypoint] -> [Maybe ByteString] -> [Int] -> [Maybe NominalDiffTime] -> [Maybe Text] -> [Maybe Value] -> [Maybe JobId] -> [Maybe Value] -> [JobStatus] -> IO [JobId]
- PGQueuer.Query: enqueueSingle :: Connection -> DBSettings -> Entrypoint -> Maybe ByteString -> Int -> Maybe NominalDiffTime -> Maybe Text -> Maybe Value -> IO [JobId]
+ PGQueuer.Query: enqueueSingle :: Connection -> DBSettings -> Entrypoint -> Maybe ByteString -> Int -> Maybe NominalDiffTime -> Maybe Text -> Maybe Value -> Maybe JobId -> Maybe Value -> JobStatus -> IO [JobId]
- PGQueuer.Types: EntrypointExecutionParameter :: Entrypoint -> Int -> EntrypointExecutionParameter
+ PGQueuer.Types: EntrypointExecutionParameter :: Entrypoint -> Int -> Int -> BackoffStrategy -> Jitter -> EntrypointExecutionParameter
- PGQueuer.Types: Job :: JobId -> Int -> UTCTime -> UTCTime -> UTCTime -> UTCTime -> JobStatus -> Entrypoint -> Maybe ByteString -> Int -> Maybe UUID -> Maybe Value -> Job
+ PGQueuer.Types: Job :: JobId -> Int -> UTCTime -> UTCTime -> UTCTime -> UTCTime -> JobStatus -> Entrypoint -> Maybe ByteString -> Int -> Maybe UUID -> Maybe Value -> Maybe JobId -> Maybe Value -> Job
Files
- CHANGELOG.md +74/−6
- CONTRIBUTING.md +129/−0
- README.md +231/−66
- bench/Main.hs +376/−0 · folded
- pgqueuer-hs.cabal +125/−7
- src/PGQueuer.hs +238/−39
- src/PGQueuer/Backend/Hasql.hs +245/−0
- src/PGQueuer/Backend/Hasql/Statements.hs +595/−0
- src/PGQueuer/Backend/Simple.hs +159/−0
- src/PGQueuer/Core/Monad.hs +110/−0
- src/PGQueuer/Listener.hs +19/−8
- src/PGQueuer/Query.hs +180/−53
- src/PGQueuer/Schema.hs +48/−12
- src/PGQueuer/Settings.hs +33/−10
- src/PGQueuer/Tracing.hs +92/−0
- src/PGQueuer/Types.hs +259/−53
- src/PGQueuer/Worker/Backoff.hs +54/−0
- src/PGQueuer/Worker/Buffer.hs +315/−0
- src/PGQueuer/Worker/Cron.hs +90/−0
- src/PGQueuer/Workflow.hs +87/−0
- test/Spec.hs +46/−2 · folded
- test/Tests/BackoffSpec.hs +45/−0 · folded
- test/Tests/BufferSpec.hs +74/−0 · folded
- test/Tests/CoreSpec.hs +379/−0 · folded
- test/Tests/CronSpec.hs +44/−0 · folded
- test/Tests/HasqlSpec.hs +39/−0 · folded
- test/Tests/PGQueuer.hs +50/−42 · folded
- test/Tests/SimpleSpec.hs +41/−0 · folded
- test/Tests/TestContainer.hs +121/−0 · folded
- test/Tests/TypesSpec.hs +111/−0 · folded
- test/Tests/WorkflowSpec.hs +48/−0 · folded
CHANGELOG.md view
@@ -1,11 +1,79 @@-# Changelog for `pgqueuer-hs`+# Changelog -All notable changes to this project will be documented in this file.+All notable changes to `pgqueuer-hs` will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),-and this project adheres to the-[Haskell Package Versioning Policy](https://pvp.haskell.org/).+and this project adheres to the [Haskell Package Versioning Policy (PVP)](https://pvp.haskell.org/). -## Unreleased+## [0.1.0.0] - 2026-11-14 -## 0.1.0.0 - YYYY-MM-DD+### Added+- **Testcontainers Integration**:+ - Native containerized PostgreSQL 16 testing (`Tests.TestContainer`) with ephemeral port allocation, active socket readiness probing, and dynamic connection string resolution.+ - Automatic fallback to local database when Docker/Podman is not running.+- **Multi-Snapshot CI Matrix**:+ - Added support for multiple Stackage LTS resolvers (`stack-lts-24.52.yaml`, `stack-lts-23.28.yaml`, `stack-lts-22.44.yaml`, `stack-lts-21.25.yaml`).+ - Added dynamic matrix discovery using `freckle/stack-action/generate-matrix@v5`.+- **Comprehensive Unit & Integration Test Suites**:+ - `Tests.TypesSpec`: Bidirectional roundtrips for `JobStatus`, `OnFailure`, `BackoffStrategy`, `Jitter`, and JSON serialization.+ - `Tests.BufferSpec`: Concurrency, overflow triggering, timer flush, and graceful shutdown tests for `TimedOverflowBuffer`.+ - `Tests.CronSpec`: Cron expression parsing and next run calculation tests.+ - `Tests.WorkflowSpec`: Hierarchical DAG tree construction and invariant verification.+ - `Tests.BackoffSpec`: Backoff interval calculation and jitter distribution bounds.+ - `Tests.CoreSpec`, `Tests.SimpleSpec`, `Tests.HasqlSpec`: 100% behavioral parity verification across `SimpleDb` and `HasqlDb`.+- **Runnable Example Executables**:+ - Added `hasql-worker` (`example/app/05-hasql-worker.hs`) showcasing the high-performance compiled binary Hasql backend with connection pooling.+ - Added `cron-pipeline` (`example/app/06-cron-pipeline.hs`) demonstrating recurring cron job scheduling and worker dispatch.+- **Workflow Automation & Developer Tooling**:+ - Added `Makefile` with targets for `build`, `test`, `bench`, `lint`, `format`, `format-check`, `check`, `docs`, `clean`, `db-up`, `db-down`.+ - Added `.hlint.yaml` configuration preventing dangerous partial functions (`head`, `tail`, `fromJust`, `read`, `undefined`, etc.).+ - Added automated Hackage publication pipeline (`.github/workflows/publish-hackage.yml`).+ - Added `cabal.project` linking root and example packages.++### Fixed+- **Haddock Documentation Warnings**:+ - Achieved 100% Haddock documentation coverage across all library modules.+ - Disambiguated identifier type/value links (`'t:JobId'`, `'t:Job'`, `'t:SimpleDb'`, `'t:HasqlDb'`, `'t:TimedOverflowBuffer'`, `'t:DBSettings'`).+ - Fixed out-of-scope identifier link warnings.+- **Codebase Cleanup & Housekeeping**:+ - Removed obsolete duplicate files (`agent.md`, `fourmolu.yml`, `example/test/Spec.hs`).+ - Streamlined `enqueueSingle` to use direct single-element lists without custom list shadows.+ - Pruned unused dependencies (`tasty-bench`, `tasty`) from benchmark harness.+ - Extended Fourmolu formatting to cover `bench/` and `example/`.+- **Fourmolu Formatting**:+ - Cleaned and formatted all source trees (`src`, `test`, `bench`, `example`) conforming strictly to `fourmolu.yaml`.+- **Database Engine Compatibility**:+ - Made `start-db.sh` and Makefile auto-detect both `podman` and `docker` with health-check readiness polling.+ - Fixed resilient scraper example's admin retry loop with real timestamp and attempt tracking.++---++## [0.0.1.0] - 2026-11-08++### Added+- **Core Architecture (`PGQueuer`)**:+ - High-level `QueueManager` API (`createQueueManager`, `withQueueManager`) for lifecycle and connection management.+ - Dual backend abstraction via `MonadPGQueuer`:+ - `SimpleDb`: Reference driver built on `postgresql-simple`.+ - `HasqlDb`: Zero-allocation high-performance driver using compiled binary prepared statements and `hasql-pool`.+- **Lock-Free Concurrency**:+ - Dequeue engine utilizing PostgreSQL `FOR UPDATE SKIP LOCKED` for zero-contention job claims across horizontal worker instances.+ - Per-entrypoint concurrency limits and optional global concurrency limits.+- **STM Timed Overflow Buffering (`PGQueuer.Worker.Buffer`)**:+ - Decoupled database write logging and heartbeat updates via `TimedOverflowBuffer`.+ - Bulk flushing triggered by buffer capacity overflow or timer expiration.+- **Retry Policies & Jitter Algorithms (`PGQueuer.Worker.Backoff`)**:+ - Mathematical backoff strategies: `Exponential`, `Linear`, `Constant`.+ - Anti-thundering-herd jitter implementations: `NoJitter`, `FullJitter`, `EqualJitter`.+ - Transient exception hierarchy: `JobRetryableException` and `JobPermanentException`.+- **DAG Workflow Dependencies (`PGQueuer.Workflow`)**:+ - Tree-structured job execution (`JobTree`, `JobNode`, `<~~`).+ - Automatic atomic hold on parent jobs until all child jobs complete with rollup of child outputs.+- **Distributed Cron Scheduling (`PGQueuer.Worker.Cron`)**:+ - 5-field cron recurring job registration (`CronExpression`) stored directly in PostgreSQL.+ - Lock-free schedule acquisition with `calculateNextRunTime` dispatch.+- **OpenTelemetry Observability (`PGQueuer.Tracing`)**:+ - Conditional OpenTelemetry integration (`-f otel`) supporting W3C trace context propagation in job headers.+- **Database Schema Management (`PGQueuer.Schema`)**:+ - Full automated DDL installation (`installSchema`, `uninstallSchema`, `verifyStructure`).+ - Triggers and functions emitting asynchronous pub/sub events via `LISTEN`/`NOTIFY`.
+ CONTRIBUTING.md view
@@ -0,0 +1,129 @@+# Contributing to pgqueuer-hs++Thank you for your interest in contributing to `pgqueuer-hs`! We welcome bug reports, feature proposals, documentation improvements, and pull requests.++---++## Development Setup++### Prerequisites+* **GHC**: 9.4, 9.6, 9.8, or 9.10++* **Stack**: 2.15+ or **Cabal**: 3.10++* **PostgreSQL**: 14+ (or Docker / Podman to run the local container)+* **Fourmolu**: 0.14++* **HLint**: 3.8+++### Building the Project++Clone the repository and build:++```bash+git clone https://github.com/tusharad/pgqueuer-hs.git+cd pgqueuer-hs++# Using Stack+make build++# Or using Cabal+cabal build+```++---++## Local Database Setup++Integration tests and example applications connect to a PostgreSQL instance. You can launch a containerized test instance using:++```bash+make db-up+```++This starts a PostgreSQL 16 container named `queue-db` with healthcheck polling. To stop and clean it up:++```bash+make db-down+```++---++## Running Tests++Run the full test suite (including unit tests, cron tests, buffer flusher tests, and database integration tests):++```bash+make test+```++Or with Cabal:++```bash+cabal test+```++---++## Code Style & Formatting++We maintain strict consistency using Fourmolu and HLint:++* **Format code**:+ ```bash+ make format+ ```+* **Verify formatting**:+ ```bash+ make format-check+ ```+* **Static analysis**:+ ```bash+ make lint+ ```++---++## Pre-Release Validation++Before submitting a pull request or cutting a new release, execute the pre-release validation suite:++```bash+make release-check+```++This verifies:+1. Fourmolu formatting compliance (`make format-check`)+2. HLint linting with zero warnings (`make lint`)+3. Cabal package metadata validity (`cabal check`)+4. Full test suite execution (`make test`)+5. Hackage source distribution tarball generation (`cabal sdist`)+6. Hackage documentation tarball creation (`cabal haddock --haddock-for-hackage --enable-doc`)++---++## Publishing to Hackage++This repository contains a GitHub Actions workflow (`.github/workflows/publish-hackage.yml`) for automated Hackage releases.++### Automated Release via GitHub Actions+1. Ensure `CHANGELOG.md` and `package.yaml` have the updated version number according to the [Haskell Package Versioning Policy (PVP)](https://pvp.haskell.org/).+2. Run `make release-check` to verify all builds, tests, and tarballs succeed locally.+3. Commit and push changes to `main`.+4. Create and push a git tag prefixed with `v` (e.g. `v0.1.0.0`):+ ```bash+ git tag -a v0.1.0.0 -m "Release v0.1.0.0"+ git push origin v0.1.0.0+ ```+5. The GitHub Actions runner will automatically build the source tarball and Haddock archive and upload them to Hackage using repository secret `HACKAGE_TOKEN` (or `HACKAGE_USERNAME` and `HACKAGE_PASSWORD`).++### Manual Release (Fallback)+If publishing manually via Cabal:++```bash+# 1. Build distribution tarball and documentation+make sdist+make docs-hackage++# 2. Upload package and documentation to Hackage+cabal upload --publish -t "${HACKAGE_TOKEN}" dist-newstyle/sdist/pgqueuer-hs-*.tar.gz+cabal upload --publish -d -t "${HACKAGE_TOKEN}" dist-newstyle/pgqueuer-hs-*-docs.tar.gz+```+
README.md view
@@ -1,114 +1,279 @@-# pgqueuer-hs: PostgreSQL-powered job queues for Haskell+# pgqueuer-hs -A PostgreSQL-powered job queue library. fully compatible Haskell implementation of [pgqueuer](https://github.com/janbjorge/pgqueuer).+[](https://hackage.haskell.org/package/pgqueuer-hs)+[](https://www.haskell.org/ghc/)+[](LICENSE)+[](https://github.com/tusharad/pgqueuer-hs/actions/workflows/haskell.yaml) +A high-performance, transactional PostgreSQL-backed background job queue for Haskell, fully compatible with [pgqueuer](https://github.com/janbjorge/pgqueuer).++---+ ## Overview -Your PostgreSQL database is already a job queue.+**Your PostgreSQL database is already a distributed job queue.** -`pgqueuer-hs` turns PostgreSQL into a fast, reliable background job processor. Jobs live in the same database as your application data. One stack, full ACID guarantees, and no separate message broker to run.+`pgqueuer-hs` turns PostgreSQL into a fast, resilient, horizontally scalable background job processor. Jobs reside directly inside your PostgreSQL database with full ACID guarantees. -### Key Features+- **No separate message broker**: Eliminate the operational overhead of running RabbitMQ, Redis, or Kafka for background tasks.+- **Transactional enqueuing**: Enqueue jobs in the exact same database transaction as your business domain data. If your transaction rolls back, the job is never scheduled.+- **Zero-allocation binary protocol**: Support for both `postgresql-simple` and compiled `hasql` prepared statements with connection pooling.+- **Cross-language compatible**: Process jobs enqueued by Python `pgqueuer` services in Haskell, or vice versa. -- **PostgreSQL-Native**: Jobs stored directly in PostgreSQL with ACID guarantees-- **Transactional Enqueue**: Enqueue jobs in the same transaction as your application data-- **Safe Concurrency**: `FOR UPDATE SKIP LOCKED` prevents duplicate processing-- **Per-Entrypoint Limits**: Configure concurrency limits per job type-- **Global Limits**: Optional global concurrency control across all entrypoints-- **Instant Dispatch**: `LISTEN/NOTIFY` wakes workers immediately when jobs arrive-- **Deferred Jobs**: Schedule job execution with `execute_after`-- **Deduplication**: Prevent duplicate jobs with `dedupe_key`-- **Cross-Language Compatible**: Jobs created in Python can be processed by Haskell (and vice versa)-- **Job Tracking**: Complete logging of job status transitions-- **Error Handling**: Failed jobs can be retried or held for manual inspection+--- -## Database Schema+## Architecture -The Haskell port uses the **exact same schema** as Python pgqueuer:+```mermaid+flowchart TD+ subgraph Producers ["Producers / Applications"]+ P1["App Transaction (PostgreSQL)"]+ P2["Cron Scheduler (PGQueuer)"]+ P3["DAG Workflow Root"]+ end -## Examples+ subgraph Postgres ["PostgreSQL 14+"]+ Q["pgqueuer (Active Ledger)\nFOR UPDATE SKIP LOCKED"]+ L["pgqueuer_log (Unlogged Table)\nAudit & Telemetry"]+ S["pgqueuer_schedules\nDistributed Cron"]+ T["Triggers & LISTEN/NOTIFY\nInstant Dispatch"]+ end -Fully working examples are available in `./example` directory+ subgraph Workers ["Horizontal Worker Cluster"]+ W1["Worker Instance 1"]+ W2["Worker Instance 2"]+ W3["Worker Instance N"]+ end + subgraph Buffers ["STM Decoupled Sinks"]+ B1["TimedOverflowBuffer (Logs)"]+ B2["TimedOverflowBuffer (Heartbeats)"]+ end++ P1 -->|INSERT INTO pgqueuer| Q+ P2 -->|Dispatch Due Jobs| Q+ P3 -->|insertJobTree| Q++ Q -.->|Notify Mutation| T+ T -.->|Instant Wakeup| Workers++ Workers -->|Batch Claim| Q+ Workers -->|Push Logs| B1+ Workers -->|Push Keepalives| B2++ B1 -->|Bulk Flush| L+ B2 -->|HOT Update| Q+```++---++## Key Features++- **Lock-Free Concurrency**: Leverages `FOR UPDATE SKIP LOCKED` and partial indexes to eliminate row lock contention across horizontal worker pools.+- **Dual Backend Architecture (`MonadPGQueuer`)**:+ - `SimpleDb`: Reference driver built on `postgresql-simple` for lightweight setups.+ - `HasqlDb`: High-performance binary driver using server-side prepared statements and `hasql-pool`.+- **Instant Event Dispatch**: Emits PostgreSQL `LISTEN` / `NOTIFY` signals when jobs arrive, waking workers immediately without wasteful high-frequency polling.+- **STM Timed Overflow Buffering**: Worker threads push status transitions and heartbeats to bounded STM queues (`TimedOverflowBuffer`), flushed in bulk to eliminate WAL write amplification.+- **Resilient Backoff & Jitter**: Configurable mathematical backoff strategies (`Exponential`, `Linear`, `Constant`) with anti-thundering-herd jitter (`FullJitter`, `EqualJitter`, `NoJitter`).+- **DAG Workflow Trees**: Build complex job dependency pipelines (`JobTree`, `<~~`). Parent jobs remain held in PostgreSQL until all child tasks finish successfully.+- **Distributed Cron Scheduling**: Native 5-field cron recurring jobs (`CronExpression`) stored and coordinated directly in PostgreSQL.+- **Distributed Tracing (OpenTelemetry)**: Built-in W3C trace context injection and span extraction in job headers (`-f otel`).++---+ ## Installation -Add `pgqueuer-hs` to your `package.yaml` or `project.cabal` dependencies:+Add `pgqueuer-hs` to your `package.yaml`: ```yaml dependencies:- - pgqueuer-hs+ - pgqueuer-hs >= 0.1.0.0 - postgresql-simple- - uuid- - time- - text - aeson+ - text+ - time+ - uuid+``` -## Quick start+Or in your `.cabal` file: -Install schema if not installed.+```cabal+build-depends:+ base >= 4.7 && < 5+ , pgqueuer-hs >= 0.1.0.0+``` +---++## Quick Start (15 Lines)+ ```haskell {-# LANGUAGE OverloadedStrings #-} +import Data.Aeson (encode) import Data.UUID.V4 (nextRandom) import PGQueuer-import Data.Either (isLeft)-import Data.UUID.V4 (nextRandom) main :: IO () main = do- let conStr = "postgresql://queue_user:queue_pass@localhost:5432/queue_db"+ let connStr = "postgresql://queue_user:queue_pass@localhost:5432/queue_db" queueMgrId <- nextRandom- withQueueManager conStr defaultDBSettings queueMgrId $ \qm -> do- -- setup schema- eInstalled <- verifyStructure qm- when (isLeft eInstalled) (installSchema qm) - -- Enqueue a job- let ep = Entrypoint "hello"- let params = [EntrypointExecutionParameter ep 0]- qm1 <- registerEntrypoint qm ep (\_ -> pure ())- _ <- enqueue qm1 ep Nothing 0 Nothing Nothing Nothing+ withQueueManager connStr defaultDBSettings queueMgrId $ \qm -> do+ -- 1. Setup schema automatically+ setupSchema qm - -- Dequeue jobs- pickedJobs <- dequeue qm1 20 params Nothing 3- mapM_ (\job -> jobStatus job) pickedJobs+ -- 2. Register entrypoint handler+ let ep = Entrypoint "SendWelcomeEmail"+ qm1 <- registerEntrypoint qm ep $ \job -> do+ putStrLn $ "Processing job #" ++ show (let JobId jid = jobId job in jid)++ -- 3. Enqueue a job+ _ <- enqueue qm1 ep (Just $ encode ("user@example.com" :: String)) 0 Nothing Nothing Nothing++ -- 4. Start worker loop (blocks and processes jobs)+ putStrLn "Worker listening for incoming jobs..."+ let execParams = [EntrypointExecutionParameter ep 5 3 (Exponential 2 60) FullJitter]+ workerLoop qm1 defaultBufferConfig execParams ``` -## Core Concepts-### Architecture+--- -PGQueuer creates a self-contained ecosystem within your PostgreSQL database:- 1. pgqueuer table: The primary ledger for active jobs (status: queued, picked).- 2. pgqueuer_log table: An unlogged table used for fast, high-volume event logging of job state transitions.- 3. pgqueuer_statistics table: Aggregates queue throughput and metrics.- 4. pgqueuer_schedules table: Manages cron-like recurring jobs and future executions.+## Backend Comparison - Database Triggers: Automatically emit pub/sub notifications via fn_pgqueuer_changed when queue states mutate.+`pgqueuer-hs` provides a unified `MonadPGQueuer` typeclass that abstracts low-level database operations: -### Status Lifecycle+| Feature | `SimpleDb` (postgresql-simple) | `HasqlDb` (hasql) |+|---|---|---|+| **Protocol** | Text/Parametrized | Compiled Binary Protocol |+| **Connection Pooling** | Single Connection or external pool | Native `hasql-pool` (built-in) |+| **Query Planning** | Client-side query preparation | Server-side prepared statements |+| **Best For** | Simple CLI scripts, prototypes, testing | High-throughput production microservices | -- Jobs transition through various states defined by JobStatus:-- Queued - Waiting for a worker.-- Picked - Claimed by a worker (protected by a heartbeat timeout).-- Successful - Completed without errors.-- Failed / Exception - Encountered an error (eligible for retry).-- Canceled / Deleted - Terminated or scrubbed.+### Running with Hasql Connection Pool -> [!IMPORTANT] -> Codebase is currently highly unstable.+```haskell+import Database.PostgreSQL.Simple (connectPostgreSQL)+import PGQueuer.Backend.Hasql+import PGQueuer.Core.Monad+import PGQueuer.Schema (install)+import PGQueuer.Settings (defaultDBSettings)+import PGQueuer.Types -## Notes+main :: IO ()+main = do+ let connStr = "postgresql://queue_user:queue_pass@localhost:5432/queue_db"+ env <- mkHasqlDbEnv connStr defaultDBSettings -- Postgresql-simple is currently being used as the primary database driver. In the future, adapter drivers will be implemented.-- Scheduling is not supported right now.+ -- Execute transactional job operations+ runHasqlDb env $ withTransaction $ do+ _ <- enqueue (Entrypoint "ImageResize") Nothing 0 Nothing Nothing Nothing Nothing Nothing Queued+ pure () + releaseHasqlDbEnv env+```++---++## Core Capabilities++### 1. Resilient Retries with Jitter++Prevent cascading failures and thundering herd stampedes by applying backoff and jitter algorithms:++```haskell+let params =+ [ EntrypointExecutionParameter+ { paramEntrypoint = Entrypoint "ExternalPaymentAPI"+ , paramConcurrencyLimit = 5 -- At most 5 concurrent jobs+ , paramMaxAttempts = 5 -- Retry up to 5 times+ , paramBackoffStrategy = Exponential 2 60 -- Base 2s, Cap 60s+ , paramJitter = EqualJitter -- Half deterministic, half random+ }+ ]+```++### 2. DAG Workflows & Dependency Trees++Define workflows where parent tasks wait for child tasks to complete:++```haskell+-- Define child task nodes+let childA = JobNode (Entrypoint "ExtractData") (Just "chunk-1") 0 Nothing Nothing Nothing Nothing <~~ []+ childB = JobNode (Entrypoint "ExtractData") (Just "chunk-2") 0 Nothing Nothing Nothing Nothing <~~ []++-- Parent MasterReport task depends on childA and childB+let workflow = JobNode (Entrypoint "MasterReport") Nothing 0 Nothing Nothing Nothing Nothing <~~ [childA, childB]++-- Atomically inserts tree: children are Queued, parent is Held until children complete+insertJobTree workflow+```++### 3. Distributed Cron Scheduling++Coordinate periodic jobs across your entire cluster without external daemons:++```haskell+-- Register a schedule running every 15 minutes+registerSchedule qm (CronExpression "*/15 * * * *") (Entrypoint "SyncCatalog")+```++---++## Examples++Fully working examples are located in the [`example`](example/) directory:++- [**01-hello-mailer**](example/app/01-hello-mailer.hs): Basic queue management, JSON payload handling, worker loop.+- [**02-resilient-scraper**](example/app/02-resilient-scraper.hs): Flaky API handling with `JobRetryableException`, exponential backoff, equal jitter, and admin retry watchdog.+- [**03-map-reduce-etl**](example/app/03-map-reduce-etl.hs): Hierarchical DAG workflows (`JobTree`) with 500 child tasks and parent state aggregation.+- [**04-chaos-ecommerce**](example/app/04-chaos-ecommerce.hs): High-throughput stress test with 5,000+ jobs/sec and a live queue status dashboard.+- [**05-hasql-worker**](example/app/05-hasql-worker.hs): Zero-allocation binary protocol backend with connection pooling and `FOR UPDATE SKIP LOCKED`.+- [**06-cron-pipeline**](example/app/06-cron-pipeline.hs): Distributed cron schedule management and periodic worker dispatch.++To run the examples:++```bash+# 1. Start local PostgreSQL+make db-up++# 2. Run any example+cd example+stack run hello-mailer+stack run hasql-worker+stack run cron-pipeline+```++---++## Development & Makefile++```bash+make help # List all available targets+make db-up # Start local PostgreSQL container (Podman or Docker)+make test # Run test suite against PostgreSQL+make bench # Compile and execute benchmarks+make lint # Run HLint static analysis+make format # Format all Haskell files with Fourmolu+make format-check # Verify formatting compliance (CI check)+make check # Run cabal check for Hackage packaging+make docs # Build Haddock documentation+make clean # Clean build artifacts+make db-down # Stop and remove local database container+```++---+ ## License -This project is licensed under the MIT License - see the LICENSE file for details.+This project is licensed under the [MIT License](LICENSE) - see the LICENSE file for details. +---+ ## See Also -- [Python pgqueuer](https://github.com/janbjorge/pgqueuer)-- [PostgreSQL Documentation](https://www.postgresql.org/docs/)-- [postgresql-simple](http://hackage.haskell.org/package/postgresql-simple)+- [Python pgqueuer](https://github.com/janbjorge/pgqueuer) - The original Python implementation.+- [PostgreSQL Documentation](https://www.postgresql.org/docs/) - `FOR UPDATE SKIP LOCKED` and `LISTEN/NOTIFY`.+- [hasql](https://hackage.haskell.org/package/hasql) - High-performance PostgreSQL driver.+- [postgresql-simple](https://hackage.haskell.org/package/postgresql-simple) - Mid-level client library.
+ bench/Main.hs view
@@ -0,0 +1,376 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++{- |+Module : Main+Description : Telemetry benchmarking harness for PGQueuer hasql backend.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Benchmarks the hasql engine against specific workloads, automatically+capturing WAL write-amplification, HOT update ratios, and dead-tuple+accumulation from a local PostgreSQL instance.+-}+module Main (main) where++import Control.Monad (forM_, replicateM_, unless, void)+import Data.ByteString (ByteString)+import Data.IORef+import Data.Int (Int64)+import qualified Data.Text as T+import Data.Time.Clock (diffUTCTime, getCurrentTime)+import Data.UUID.V4 (nextRandom)+import qualified Database.PostgreSQL.Simple as PG+import qualified Hasql.Pool as Pool+import qualified Hasql.Session as Session+import PGQueuer.Backend.Hasql+import PGQueuer.Backend.Hasql.Statements (tableStatsStmt, walLsnStmt)+import PGQueuer.Core.Monad+import PGQueuer.Schema (install, uninstall)+import PGQueuer.Settings (defaultDBSettings)+import PGQueuer.Types+import PGQueuer.Worker.Buffer+import System.IO (hFlush, stdout)++-- ============================================================================+-- Telemetry snapshot+-- ============================================================================++-- | Snapshot of database telemetry metrics.+data TelemetrySnapshot = TelemetrySnapshot+ { tsWalLsn :: Int64+ -- ^ WAL position in bytes+ , tsQueueUpdates :: Int64+ -- ^ n_tup_upd for pgqueuer table+ , tsQueueHotUpdates :: Int64+ -- ^ n_tup_hot_upd for pgqueuer table+ , tsQueueDeadTuples :: Int64+ -- ^ n_dead_tup for pgqueuer table+ , tsLogUpdates :: Int64+ -- ^ n_tup_upd for pgqueuer_log table+ , tsLogHotUpdates :: Int64+ -- ^ n_tup_hot_upd for pgqueuer_log table+ , tsLogDeadTuples :: Int64+ -- ^ n_dead_tup for pgqueuer_log table+ }+ deriving (Show)++-- | Connection string for benchmarks.+benchConnStr :: ByteString+benchConnStr = "postgresql://queue_user:queue_pass@localhost:5432/queue_db"++-- | Capture a telemetry snapshot from the database.+captureSnapshot :: HasqlDbEnv -> IO TelemetrySnapshot+captureSnapshot dbEnv = do+ walLsn <- runPoolSession' dbEnv $ Session.statement () walLsnStmt+ (qUpd, qHot, qDead) <- runPoolSession' dbEnv $ Session.statement "pgqueuer" tableStatsStmt+ (lUpd, lHot, lDead) <- runPoolSession' dbEnv $ Session.statement "pgqueuer_log" tableStatsStmt+ return+ TelemetrySnapshot+ { tsWalLsn = walLsn+ , tsQueueUpdates = qUpd+ , tsQueueHotUpdates = qHot+ , tsQueueDeadTuples = qDead+ , tsLogUpdates = lUpd+ , tsLogHotUpdates = lHot+ , tsLogDeadTuples = lDead+ }++-- | Run a session, throwing on error.+runPoolSession' :: HasqlDbEnv -> Session.Session a -> IO a+runPoolSession' dbEnv session = do+ result <- Pool.use (hdbPool dbEnv) session+ case result of+ Left err -> fail $ "Benchmark session error: " <> show err+ Right val -> return val++-- ============================================================================+-- Benchmark workload profiles+-- ============================================================================++-- | Run the ungrouped single-mode workload: batch_size=1, 1000 jobs.+benchUngroupedSingle :: HasqlDbEnv -> IO (IO ())+benchUngroupedSingle dbEnv = do+ let ep = Entrypoint "bench_single"+ params = [EntrypointExecutionParameter ep 0 5 (Exponential 5 60) FullJitter]+ jobCount = 1000 :: Int++ -- Enqueue all jobs+ forM_ [1 .. jobCount] $ \_ ->+ runHasqlDb dbEnv $+ enqueue ep Nothing 0 Nothing Nothing Nothing Nothing Nothing Queued++ -- Dequeue one at a time+ qmId <- nextRandom+ dequeued <- newIORef (0 :: Int)+ let loop = do+ jobs <- runHasqlDb dbEnv $ dequeue 1 params qmId Nothing 30+ unless (null jobs) $ do+ -- Simulate heartbeats to prove HOT updates+ replicateM_ 2+ $ runHasqlDb dbEnv+ $ updateHeartbeat [jobId j | j <- jobs]++ -- Log as successful+ runHasqlDb dbEnv $+ logJobs [(jobId j, Successful, Nothing) | j <- jobs]+ modifyIORef' dequeued (+ length jobs)+ loop+ return loop++-- | Run the ungrouped batched-mode workload: batch_size=10, 1000 jobs.+benchUngroupedBatched :: HasqlDbEnv -> IO (IO ())+benchUngroupedBatched dbEnv = do+ let ep = Entrypoint "bench_batch"+ params = [EntrypointExecutionParameter ep 0 5 (Exponential 5 60) FullJitter]+ jobCount = 1000 :: Int++ -- Enqueue all jobs+ forM_ [1 .. jobCount] $ \_ ->+ runHasqlDb dbEnv $+ enqueue ep Nothing 0 Nothing Nothing Nothing Nothing Nothing Queued++ -- Dequeue in batches of 10+ qmId <- nextRandom+ let loop = do+ jobs <- runHasqlDb dbEnv $ dequeue 10 params qmId Nothing 30+ unless (null jobs) $ do+ -- Simulate heartbeat+ replicateM_ 2+ $ runHasqlDb dbEnv+ $ updateHeartbeat [jobId j | j <- jobs]++ runHasqlDb dbEnv $+ logJobs [(jobId j, Successful, Nothing) | j <- jobs]+ loop+ return loop++-- | Run the high-cardinality grouped workload: 2500 distinct groups.+benchHighCardinalityGrouped :: HasqlDbEnv -> IO (IO ())+benchHighCardinalityGrouped dbEnv = do+ let jobCount = 2500 :: Int+ batchSize = 10++ -- Enqueue jobs across distinct entrypoints+ forM_ [1 .. jobCount] $ \(i :: Int) -> do+ let ep = Entrypoint (T.pack $ "group_" <> show i)+ void+ $ runHasqlDb dbEnv+ $ enqueue ep Nothing 0 Nothing Nothing Nothing Nothing Nothing Queued++ -- Build params for all groups+ let allParams =+ [ EntrypointExecutionParameter+ (Entrypoint (T.pack $ "group_" <> show i))+ 0+ 5+ (Exponential 5 60)+ FullJitter+ | i <- [1 .. jobCount]+ ]++ -- Dequeue in batches+ qmId <- nextRandom+ let loop = do+ jobs <- runHasqlDb dbEnv $ dequeue batchSize allParams qmId Nothing 30+ unless (null jobs) $ do+ -- Simulate heartbeat+ replicateM_ 2+ $ runHasqlDb dbEnv+ $ updateHeartbeat [jobId j | j <- jobs]++ runHasqlDb dbEnv $+ logJobs [(jobId j, Successful, Nothing) | j <- jobs]+ loop+ return loop++{- | Run the buffered batched-mode workload: batch_size=10, 1000 jobs.+Uses STM buffers for both job status logging and heartbeats.+-}+benchBufferedBatched :: HasqlDbEnv -> IO (IO ())+benchBufferedBatched dbEnv = do+ let ep = Entrypoint "bench_buffered"+ params = [EntrypointExecutionParameter ep 0 5 (Exponential 5 60) FullJitter]+ jobCount = 1000 :: Int++ -- Enqueue all jobs+ forM_ [1 .. jobCount] $ \_ ->+ runHasqlDb dbEnv $+ enqueue ep Nothing 0 Nothing Nothing Nothing Nothing Nothing Queued++ -- Build the dequeue + buffered-ACK loop+ qmId <- nextRandom+ let loop = do+ let logSink items = runHasqlDb dbEnv $ logJobs items+ hbSink ids = runHasqlDb dbEnv $ updateHeartbeat ids+ withBuffer defaultBufferConfig logSink $ \logBuf ->+ withBuffer defaultBufferConfig hbSink $ \hbBuf -> do+ let innerLoop = do+ jobs <- runHasqlDb dbEnv $ dequeue 10 params qmId Nothing 30+ unless (null jobs) $ do+ -- Buffer heartbeats+ mapM_ (add hbBuf . jobId) jobs+ mapM_ (add hbBuf . jobId) jobs+ -- Buffer ACKs+ mapM_ (\j -> add logBuf (jobId j, Successful, Nothing)) jobs+ innerLoop+ innerLoop+ return loop++-- ============================================================================+-- Telemetry reporting+-- ============================================================================++-- | Print telemetry report for a workload.+printTelemetryReport :: String -> Int -> TelemetrySnapshot -> TelemetrySnapshot -> Double -> IO ()+printTelemetryReport name jobCount pre post elapsedSecs = do+ let walDelta = tsWalLsn post - tsWalLsn pre+ walPerJob = if jobCount > 0 then walDelta `div` fromIntegral jobCount else 0+ queueUpdDelta = tsQueueUpdates post - tsQueueUpdates pre+ queueHotDelta = tsQueueHotUpdates post - tsQueueHotUpdates pre+ hotPct :: Double+ hotPct =+ if queueUpdDelta > 0+ then fromIntegral queueHotDelta / fromIntegral queueUpdDelta * 100.0+ else 0.0+ updPerJob :: Double+ updPerJob =+ if jobCount > 0+ then fromIntegral queueUpdDelta / fromIntegral jobCount+ else 0.0+ deadDelta = tsQueueDeadTuples post - tsQueueDeadTuples pre+ throughput :: Double+ throughput =+ if elapsedSecs > 0+ then fromIntegral jobCount / elapsedSecs+ else 0.0++ putStrLn $ " " <> name+ putStrLn $ " " <> show (round throughput :: Int) <> " jobs/sec"+ putStrLn $+ " write-amp: "+ <> show walPerJob+ <> " B WAL/job | queue HOT "+ <> showPct hotPct+ <> " ("+ <> showFrac updPerJob+ <> " upd/job)"+ putStrLn $+ " autovacuum: queue "+ <> show deadDelta+ <> " dead ("+ <> show deadDelta+ <> "/"+ <> show jobCount+ <> " jobs)"+ hFlush stdout++showPct :: Double -> String+showPct d = show (round d :: Int) <> "%"++showFrac :: Double -> String+showFrac d =+ let s = show d+ in take 4 s++-- ============================================================================+-- Main+-- ============================================================================++main :: IO ()+main = do+ putStrLn "============================================"+ putStrLn "PGQueuer Telemetry Benchmark (hasql backend)"+ putStrLn "============================================"+ putStrLn ""++ -- Set up schema via postgresql-simple+ schemaConn <- PG.connectPostgreSQL benchConnStr+ let settings = defaultDBSettings++ -- Analyze tables to update pg_stat counters+ let resetSchema = do+ uninstall schemaConn settings+ install schemaConn settings+ void $ PG.execute_ schemaConn "ANALYZE pgqueuer"+ void $ PG.execute_ schemaConn "ANALYZE pgqueuer_log"++ -- Create hasql pool+ dbEnv <- mkHasqlDbEnv benchConnStr settings++ putStrLn "Worker Throughput (hasql) - 4 pool connections"+ putStrLn ""++ let quietBenchDb = do+ void $ PG.execute_ schemaConn "ALTER TABLE pgqueuer SET (autovacuum_enabled = false);"+ void $ PG.execute_ schemaConn "VACUUM ANALYZE pgqueuer;"+ void $ PG.execute_ schemaConn "CHECKPOINT;"++ -- Profile 1: Ungrouped Single+ do+ resetSchema+ runBench <- benchUngroupedSingle dbEnv+ quietBenchDb+ preSnap <- captureSnapshot dbEnv+ startTime <- getCurrentTime+ runBench+ endTime <- getCurrentTime+ postSnap <- captureSnapshot dbEnv+ let elapsed = realToFrac (diffUTCTime endTime startTime) :: Double+ printTelemetryReport "ungrouped single (batch_size=1)" 1000 preSnap postSnap elapsed++ putStrLn ""++ -- Profile 2: Ungrouped Batched+ do+ resetSchema+ runBench <- benchUngroupedBatched dbEnv+ quietBenchDb+ preSnap <- captureSnapshot dbEnv+ startTime <- getCurrentTime+ runBench+ endTime <- getCurrentTime+ postSnap <- captureSnapshot dbEnv+ let elapsed = realToFrac (diffUTCTime endTime startTime) :: Double+ printTelemetryReport "ungrouped batched (batch_size=10)" 1000 preSnap postSnap elapsed++ putStrLn ""++ -- Profile 3: High-Cardinality Grouped+ do+ resetSchema+ runBench <- benchHighCardinalityGrouped dbEnv+ quietBenchDb+ preSnap <- captureSnapshot dbEnv+ startTime <- getCurrentTime+ runBench+ endTime <- getCurrentTime+ postSnap <- captureSnapshot dbEnv+ let elapsed = realToFrac (diffUTCTime endTime startTime) :: Double+ printTelemetryReport "high-cardinality grouped (2.5k groups)" 2500 preSnap postSnap elapsed++ putStrLn ""++ -- Profile 4: Buffered Batched+ do+ resetSchema+ runBench <- benchBufferedBatched dbEnv+ quietBenchDb+ preSnap <- captureSnapshot dbEnv+ startTime <- getCurrentTime+ runBench+ endTime <- getCurrentTime+ postSnap <- captureSnapshot dbEnv+ let elapsed = realToFrac (diffUTCTime endTime startTime) :: Double+ printTelemetryReport "buffered batched (batch_size=10, STM)" 1000 preSnap postSnap elapsed++ putStrLn ""+ putStrLn "============================================"+ putStrLn "Benchmark complete."+ putStrLn "============================================"++ -- Cleanup+ releaseHasqlDbEnv dbEnv+ PG.close schemaConn
pgqueuer-hs.cabal view
@@ -1,14 +1,30 @@-cabal-version: 1.12+cabal-version: 1.18 --- This file has been generated from package.yaml by hpack version 0.38.1.+-- This file has been generated from package.yaml by hpack version 0.39.6. -- -- see: https://github.com/sol/hpack name: pgqueuer-hs-version: 0.0.1.0-synopsis: PostgreSQL powered Job queue-description: Please see the README on GitHub at <https://github.com/tusharad/pgqueuer-hs#readme>-category: Database+version: 0.1.0.0+synopsis: High-performance PostgreSQL background job queue with cron and workflows+description: A high-throughput, type-safe PostgreSQL-backed job queue for Haskell applications.+ Inspired by pgqueuer in Python, pgqueuer-hs leverages PostgreSQL's LISTEN / NOTIFY+ and `FOR UPDATE SKIP LOCKED` for reliable, non-contending, at-least-once distributed job processing.+ .+ Key features:+ * Zero-polling real-time dispatch via PostgreSQL LISTEN / NOTIFY+ * Non-contending job claims using `FOR UPDATE SKIP LOCKED`+ * Dual backend support: `SimpleDb` (postgresql-simple) and `HasqlDb` (binary protocol via Hasql)+ * Declarative Workflow DAG orchestration (`JobTree` and `<~~` operator)+ * Native recurring cron job scheduling+ * Pluggable retry backoff policies (constant, linear, exponential) with full and equal jitter+ * Write batching and rate limiting via `TimedOverflowBuffer` to protect PostgreSQL WAL+ * Full end-to-end distributed tracing support+ .+ For getting started and runnable examples, please see the README on GitHub at+ <https://github.com/tusharad/pgqueuer-hs#readme>.+category: Database, Concurrency, Distributed Computing+stability: experimental homepage: https://github.com/tusharad/pgqueuer-hs#readme bug-reports: https://github.com/tusharad/pgqueuer-hs/issues author: Tushar Adhatrao@@ -17,22 +33,40 @@ license: MIT license-file: LICENSE build-type: Simple-extra-source-files:+tested-with:+ GHC == 9.8.4, GHC == 9.10.3+extra-doc-files: README.md CHANGELOG.md+ LICENSE+ CONTRIBUTING.md source-repository head type: git location: https://github.com/tusharad/pgqueuer-hs +flag otel+ description: Enable OpenTelemetry tracing integration+ manual: True+ default: False+ library exposed-modules: PGQueuer+ PGQueuer.Backend.Hasql+ PGQueuer.Backend.Hasql.Statements+ PGQueuer.Backend.Simple+ PGQueuer.Core.Monad PGQueuer.Listener PGQueuer.Query PGQueuer.Schema PGQueuer.Settings+ PGQueuer.Tracing PGQueuer.Types+ PGQueuer.Worker.Backoff+ PGQueuer.Worker.Buffer+ PGQueuer.Worker.Cron+ PGQueuer.Workflow other-modules: Paths_pgqueuer_hs hs-source-dirs:@@ -40,34 +74,118 @@ ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wredundant-constraints -Wno-partial-fields build-depends: aeson >=2.0 && <3+ , async >=2.2 && <3 , base >=4.7 && <5 , bytestring >=0.10.4.0 && <0.13 , containers >=0.6 && <0.8+ , contravariant >=1.5 && <2+ , cron >=0.7 && <1+ , hasql >=1.6 && <1.10+ , hasql-pool >=1.2 && <1.4+ , mtl >=2.2 && <3 , postgresql-simple >=0.7 && <0.9+ , random ==1.2.*+ , stm >=2.5 && <3 , text >=1.2 && <3 , time >=1.9 && <2+ , unliftio ==0.2.*+ , unordered-containers ==0.2.* , uuid >=1.3 && <2+ , vector >=0.12 && <1 default-language: Haskell2010+ if flag(otel)+ cpp-options: -DOTEL+ build-depends:+ case-insensitive+ , hs-opentelemetry-api+ , hs-opentelemetry-propagator-w3c+ , http-types test-suite pgqueuer-hs-test type: exitcode-stdio-1.0 main-is: Spec.hs other-modules:+ Tests.BackoffSpec+ Tests.BufferSpec+ Tests.CoreSpec+ Tests.CronSpec+ Tests.HasqlSpec Tests.PGQueuer+ Tests.SimpleSpec+ Tests.TestContainer+ Tests.TypesSpec+ Tests.WorkflowSpec Paths_pgqueuer_hs hs-source-dirs: test ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wredundant-constraints -Wno-partial-fields -threaded -rtsopts -with-rtsopts=-N build-depends: aeson >=2.0 && <3+ , async >=2.2 && <3 , base >=4.7 && <5 , bytestring >=0.10.4.0 && <0.13 , containers >=0.6 && <0.8+ , contravariant >=1.5 && <2+ , cron >=0.7 && <1+ , hasql >=1.6 && <1.10+ , hasql-pool >=1.2 && <1.4+ , mtl >=2.2 && <3 , pgqueuer-hs , postgresql-simple >=0.7 && <0.9+ , random ==1.2.*+ , stm >=2.5 && <3 , tasty >=1.4 && <2 , tasty-hunit >=0.10 && <1+ , testcontainers ==0.5.* , text >=1.2 && <3 , time >=1.9 && <2+ , unliftio ==0.2.*+ , unordered-containers ==0.2.* , uuid >=1.3 && <2+ , vector >=0.12 && <1 default-language: Haskell2010+ if flag(otel)+ cpp-options: -DOTEL+ build-depends:+ case-insensitive+ , hs-opentelemetry-api+ , hs-opentelemetry-propagator-w3c+ , http-types++benchmark pgqueuer-hs-bench+ type: exitcode-stdio-1.0+ main-is: Main.hs+ other-modules:+ Paths_pgqueuer_hs+ hs-source-dirs:+ bench+ ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wredundant-constraints -Wno-partial-fields -threaded -rtsopts -with-rtsopts=-N+ build-depends:+ aeson >=2.0 && <3+ , async >=2.2 && <3+ , base >=4.7 && <5+ , bytestring >=0.10.4.0 && <0.13+ , containers >=0.6 && <0.8+ , contravariant >=1.5 && <2+ , cron >=0.7 && <1+ , hasql >=1.6 && <1.10+ , hasql-pool >=1.2 && <1.4+ , mtl >=2.2 && <3+ , pgqueuer-hs+ , postgresql-simple >=0.7 && <0.9+ , random ==1.2.*+ , stm >=2.5 && <3+ , text >=1.2 && <3+ , time >=1.9 && <2+ , unliftio ==0.2.*+ , unordered-containers ==0.2.*+ , uuid >=1.3 && <2+ , vector >=0.12 && <1+ default-language: Haskell2010+ if flag(otel)+ cpp-options: -DOTEL+ build-depends:+ case-insensitive+ , hs-opentelemetry-api+ , hs-opentelemetry-propagator-w3c+ , http-types
src/PGQueuer.hs view
@@ -1,3 +1,7 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+ {- | Module : PGQueuer Description : Main interface for the PGQueuer job queue ecosystem.@@ -10,60 +14,87 @@ It re-exports essential types and settings required to configure, manage, and interact with the database-backed queue. -}-module PGQueuer (- -- * Queue Manager- QueueManager (..),- createQueueManager,- withQueueManager,+module PGQueuer+ ( -- * Queue Manager+ QueueManager (..)+ , createQueueManager+ , withQueueManager -- * Entrypoint Management- registerEntrypoint,+ , EntrypointHandler+ , registerEntrypoint+ , registerSchedule -- * Job Operations- workerLoop,- enqueue,- enqueueMultiple,- dequeue,- markJobAsCancelled,- requeueJobs,- retryJob,- updateHeartbeat,- logJobs,+ , workerLoop+ , enqueue+ , enqueueMultiple+ , insertJobTree+ , JobTree (..)+ , JobNode (..)+ , (<~~)+ , dequeue+ , markJobAsCancelled+ , requeueJobs+ , retryJobs+ , updateHeartbeat+ , logJobs -- * Queue Statistics and Management- getQueueSize,- clearQueue,- listFailedJobs,- listJobStatusById,+ , getQueueSize+ , clearQueue+ , listFailedJobs+ , listJobStatusById -- * Schema management- verifyStructure,- installSchema,- uninstallSchema,+ , setupSchema+ , verifyStructure+ , installSchema+ , uninstallSchema -- * Re-exported modules- module PGQueuer.Types,- module PGQueuer.Settings,+ , module PGQueuer.Types+ , module PGQueuer.Settings+ , module PGQueuer.Worker.Buffer ) where import Control.Concurrent (threadDelay)-import Control.Exception (bracket)++import Control.Concurrent.Async (withAsync) import Control.Monad (forever)-import Data.Aeson (Value)+import Data.Aeson (Value (String))+#ifdef OTEL+import Data.Aeson (Value (Object))+import qualified Data.Aeson.KeyMap as KM+#endif import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as BL+import Data.Int (Int32) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Text (Text)-import Data.Time (NominalDiffTime)+import qualified Data.Text as T+import Data.Time (NominalDiffTime, UTCTime)+import Data.Time.Clock (addUTCTime, getCurrentTime) import Data.UUID (UUID) import Database.PostgreSQL.Simple (Connection, close, connectPostgreSQL)+import UnliftIO.Exception (SomeException, bracket, catch, fromException) +import PGQueuer.Backend.Simple (SimpleDbEnv (..), runSimpleDb) import qualified PGQueuer.Query as Q import PGQueuer.Schema (install, uninstall, verifyStructure_) import PGQueuer.Settings import PGQueuer.Types+import PGQueuer.Worker.Backoff+import PGQueuer.Worker.Buffer+import PGQueuer.Worker.Cron +#ifdef OTEL+import PGQueuer.Tracing (injectOtelContext, withJobSpan)+#endif +import PGQueuer.Workflow (JobNode (..), JobTree (..), (<~~))+import qualified PGQueuer.Workflow as Workflow+ -- | Core state context for managing Queue. data QueueManager = QueueManager { qmConnection :: Connection@@ -112,26 +143,160 @@ { qmEntrypoints = Map.insert ep handler (qmEntrypoints qm) } --- | Continuously dequeue jobs and dispatch them to registered handlers.-workerLoop :: QueueManager -> [EntrypointExecutionParameter] -> IO ()-workerLoop qm params = forever $ do+-- | Register a cron schedule for a specific entrypoint+registerSchedule ::+ -- | QueueManager instance+ QueueManager ->+ -- | Cron expression (e.g. "*/5 * * * *")+ CronExpression ->+ -- | Entrypoint to invoke+ Entrypoint ->+ IO ()+registerSchedule qm expr ep = do+ Q.insertSchedule (qmConnection qm) (qmSettings qm) expr ep++{- | Continuously dequeue jobs and dispatch them to registered handlers.++Uses STM-backed 'JobStatusLogBuffer' and 'HeartbeatBuffer' to decouple+worker threads from database round-trips. Instead of calling 'logJobs'+and 'updateHeartbeat' synchronously for each batch, this loop pushes+results into STM buffers. Dedicated background flusher threads drain+the buffers and issue bulk database writes when either the buffer+overflows or a timer interval expires.++Both buffers are cleanly drained on exit via 'withBuffer' brackets,+ensuring no data loss during graceful shutdown.+-}+workerLoop :: QueueManager -> BufferConfig -> [EntrypointExecutionParameter] -> IO ()+workerLoop qm bufConfig params = do+ let conn = qmConnection qm+ settings = qmSettings qm+ logSink = Q.logJobs conn settings+ hbSink = Q.updateHeartbeat conn settings+ retrySink = Q.retryJobs conn settings+ -- Build a map of execution parameters for quick lookup+ paramMap = Map.fromList [(paramEntrypoint p, p) | p <- params]+ withBuffer bufConfig logSink $ \logBuf ->+ withBuffer bufConfig hbSink $ \hbBuf ->+ withBuffer bufConfig retrySink $ \retryBuf ->+ withAsync (runCronScheduler conn settings) $ \_cronAsync ->+ forever $ do jobs <- dequeue qm defaultBatchSize params Nothing defaultHeartbeatTimeout if null jobs then threadDelay 1000000- else mapM_ (dispatchJob qm) jobs+ else do+ -- Buffer heartbeats for all picked jobs+ mapM_ (add hbBuf . jobId) jobs+ -- Dispatch and buffer ACKs or Retries+ mapM_ (dispatchJob qm logBuf retryBuf paramMap) jobs -dispatchJob :: QueueManager -> Job -> IO ()-dispatchJob qm job =+#ifdef OTEL+wrapJobHandler :: Job -> (Job -> IO ()) -> IO ()+wrapJobHandler job handler = withJobSpan (jobEntrypoint job) (jobId job) (jobHeaders job) (handler job)+#else+wrapJobHandler :: Job -> (Job -> IO ()) -> IO ()+wrapJobHandler job handler = handler job+#endif++-- | Dispatch a job to its handler and buffer the result.+dispatchJob ::+ QueueManager ->+ JobStatusLogBuffer ->+ RetryBuffer ->+ Map Entrypoint EntrypointExecutionParameter ->+ Job ->+ IO ()+dispatchJob qm logBuf retryBuf paramMap job = case Map.lookup entrypointName (qmEntrypoints qm) of Nothing -> fail $ "No handler registered for entrypoint: " ++ show entrypointName- Just handler -> handler job+ Just handler -> do+ (wrapJobHandler job handler >> add logBuf (jobId job, Successful, Nothing))+ `catch` \e -> handleJobException e where Entrypoint entrypointName = jobEntrypoint job+ epParam = Map.lookup (jobEntrypoint job) paramMap + handleJobException :: SomeException -> IO ()+ handleJobException e = do+ -- Check if it's a permanent exception+ case fromException e of+ Just (JobPermanentException msg) ->+ add logBuf (jobId job, Failed, Just $ String msg)+ Nothing -> do+ -- It's either a JobRetryableException or SomeException.+ let msg = case fromException e of+ Just (JobRetryableException m) -> m+ Nothing -> T.pack $ show e++ -- Route to retry or DLQ+ case epParam of+ Nothing ->+ -- No param means no retry config, default to failed+ add logBuf (jobId job, Failed, Just $ String msg)+ Just param -> do+ let currentAttempts = jobAttempts job+ maxAttempts = paramMaxAttempts param+ if currentAttempts + 1 >= maxAttempts+ then add logBuf (jobId job, Failed, Just $ String msg)+ else do+ let strategy = paramBackoffStrategy param+ jitter = paramJitter param+ baseDelay = calculateBackoff strategy (currentAttempts + 1)++ jitteredDelay <- applyJitter jitter baseDelay+ now <- getCurrentTime+ let newExecuteAfter = addUTCTime jitteredDelay now+ newAttempts = fromIntegral (currentAttempts + 1) :: Int32++ add retryBuf (jobId job, newExecuteAfter, newAttempts)+ -- ============================================================================ -- Queue operations (wrappers around Query module) -- ============================================================================ +#ifdef OTEL+injectOtelIntoHeaders :: Maybe Value -> IO (Maybe Value)+injectOtelIntoHeaders headers = do+ mOtelHeaders <- injectOtelContext+ return $ case (headers, mOtelHeaders) of+ (Nothing, Nothing) -> Nothing+ (Just h, Nothing) -> Just h+ (Nothing, Just oh) -> Just (Object (KM.singleton "otel" oh))+ (Just (Object hMap), Just oh) -> Just (Object (KM.insert "otel" oh hMap))+ (Just other, Just _) -> Just other++injectOtelIntoHeadersList :: [Maybe Value] -> IO [Maybe Value]+injectOtelIntoHeadersList headersList = do+ mOtelHeaders <- injectOtelContext+ let injectOtel headers = case (headers, mOtelHeaders) of+ (Nothing, Nothing) -> Nothing+ (Just h, Nothing) -> Just h+ (Nothing, Just oh) -> Just (Object (KM.singleton "otel" oh))+ (Just (Object hMap), Just oh) -> Just (Object (KM.insert "otel" oh hMap))+ (Just other, Just _) -> Just other+ return $ map injectOtel headersList++injectOtelIntoTree :: JobTree -> IO JobTree+injectOtelIntoTree tree = do+ mOtelHeaders <- injectOtelContext+ let injectOtel headers = case (headers, mOtelHeaders) of+ (Nothing, Nothing) -> Nothing+ (Just h, Nothing) -> Just h+ (Nothing, Just oh) -> Just (Object (KM.singleton "otel" oh))+ (Just (Object hMap), Just oh) -> Just (Object (KM.insert "otel" oh hMap))+ (Just other, Just _) -> Just other+ return $ Workflow.mapJobTreeHeaders injectOtel tree+#else+injectOtelIntoHeaders :: Maybe Value -> IO (Maybe Value)+injectOtelIntoHeaders = return++injectOtelIntoHeadersList :: [Maybe Value] -> IO [Maybe Value]+injectOtelIntoHeadersList = return++injectOtelIntoTree :: JobTree -> IO JobTree+injectOtelIntoTree = return+#endif+ -- | Enqueue a single job enqueue :: -- | QueueManager instance@@ -149,10 +314,20 @@ -- | Optional headers for the job Maybe Value -> IO [JobId]-enqueue qm =+enqueue qm entrypoint payload priority executeAfter dedupeKey headers = do+ finalHeaders <- injectOtelIntoHeaders headers Q.enqueueSingle (qmConnection qm) (qmSettings qm)+ entrypoint+ payload+ priority+ executeAfter+ dedupeKey+ finalHeaders+ Nothing+ Nothing+ Queued -- | Enqueue multiple jobs enqueueMultiple ::@@ -171,11 +346,27 @@ -- | List of optional headers for the jobs [Maybe Value] -> IO [JobId]-enqueueMultiple qm =+enqueueMultiple qm entrypoints payloads priorities executeAfters dedupeKeys headersList = do+ finalHeadersList <- injectOtelIntoHeadersList headersList Q.enqueueMultiple (qmConnection qm) (qmSettings qm)+ entrypoints+ payloads+ priorities+ executeAfters+ dedupeKeys+ finalHeadersList+ (replicate (length entrypoints) Nothing)+ (replicate (length entrypoints) Nothing)+ (replicate (length entrypoints) Queued) +-- | Insert a JobTree using the QueueManager+insertJobTree :: QueueManager -> JobTree -> IO ()+insertJobTree qm tree = do+ finalTree <- injectOtelIntoTree tree+ runSimpleDb (SimpleDbEnv (qmConnection qm) (qmSettings qm)) (Workflow.insertJobTree finalTree)+ -- | Dequeue jobs dequeue :: -- | QueueManager instance@@ -240,13 +431,21 @@ requeueJobs :: QueueManager -> [JobId] -> IO () requeueJobs qm = Q.requeueJobs (qmConnection qm) (qmSettings qm) --- | Retry a job-retryJob :: QueueManager -> Job -> NominalDiffTime -> Maybe Value -> IO ()-retryJob qm = Q.retryJob (qmConnection qm) (qmSettings qm)+-- | Retry jobs in bulk+retryJobs :: QueueManager -> [(JobId, UTCTime, Int32)] -> IO ()+retryJobs qm = Q.retryJobs (qmConnection qm) (qmSettings qm) -- ============================================================================ -- Schema management -- ============================================================================++-- | Idempotent function to verify if schema exists, and if not, install it.+setupSchema :: QueueManager -> IO ()+setupSchema qm = do+ result <- verifyStructure qm+ case result of+ Left _ -> installSchema qm+ Right () -> return () -- | Verify schema structure verifyStructure :: QueueManager -> IO (Either String ())
+ src/PGQueuer/Backend/Hasql.hs view
@@ -0,0 +1,245 @@+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++{- |+Module : PGQueuer.Backend.Hasql+Description : High-performance backend using hasql binary protocol.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Provides 't:HasqlDb', a concrete monad transformer that implements+'MonadPGQueuer' using @hasql@'s binary protocol for zero-allocation+data transfers. All SQL operations are statically compiled as+@Hasql.Statement.Statement@ objects and executed through a+@hasql-pool@ connection pool.++This is the high-performance driver. It uses server-side prepared+statements (@True@) for all queries, enabling PostgreSQL to skip+the query planning phase in the inner worker loops.+-}+module PGQueuer.Backend.Hasql+ ( HasqlDb (..)+ , HasqlDbEnv (..)+ , runHasqlDb+ , mkHasqlDbEnv+ , releaseHasqlDbEnv+ ) where++import Control.Exception (SomeException, catch, throwIO)+import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Reader (MonadReader, ReaderT (..))+import qualified Data.Aeson as Aeson+import Data.ByteString (ByteString)+import qualified Data.ByteString.Lazy as BL+import Data.Int (Int32, Int64)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Time (NominalDiffTime)+import Data.UUID ()+import qualified Data.Vector as V+import qualified Hasql.Connection.Setting as HCS+import qualified Hasql.Connection.Setting.Connection as HCSC+import qualified Hasql.Pool as Pool+import qualified Hasql.Pool.Config as PoolConfig+import Hasql.Session (Session)+import qualified Hasql.Session as Session+import PGQueuer.Backend.Hasql.Statements+import PGQueuer.Core.Monad (MonadPGQueuer (..))+import PGQueuer.Settings (DBSettings)+import PGQueuer.Types++-- | Environment carrying the connection pool and database settings.+data HasqlDbEnv = HasqlDbEnv+ { hdbPool :: Pool.Pool+ -- ^ Connection pool+ , hdbSettings :: DBSettings+ -- ^ Table/schema naming settings+ }++{- | Create a 't:HasqlDbEnv' with a connection pool.++The pool is created with 4 connections and a 10-second acquisition+timeout, which is appropriate for both testing and benchmarking.+-}+mkHasqlDbEnv :: ByteString -> DBSettings -> IO HasqlDbEnv+mkHasqlDbEnv connStr dbSettings = do+ let poolCfg =+ PoolConfig.settings+ [ PoolConfig.size 4+ , PoolConfig.acquisitionTimeout 10+ , PoolConfig.staticConnectionSettings+ [HCS.connection (HCSC.string (TE.decodeUtf8 connStr))]+ ]+ pool <- Pool.acquire poolCfg+ return+ HasqlDbEnv+ { hdbPool = pool+ , hdbSettings = dbSettings+ }++-- | Release all connections in the pool.+releaseHasqlDbEnv :: HasqlDbEnv -> IO ()+releaseHasqlDbEnv = Pool.release . hdbPool++{- | A concrete monad transformer wrapping @ReaderT HasqlDbEnv IO@.++This is the high-performance 'MonadPGQueuer' implementation backed by+@hasql@'s binary protocol.+-}+newtype HasqlDb a = HasqlDb+ { unHasqlDb :: ReaderT HasqlDbEnv IO a+ }+ deriving newtype (Functor, Applicative, Monad, MonadIO, MonadReader HasqlDbEnv)++-- | Run a 't:HasqlDb' computation with the given environment.+runHasqlDb :: HasqlDbEnv -> HasqlDb a -> IO a+runHasqlDb env (HasqlDb action) = runReaderT action env++-- | Run a session against the pool, throwing on error.+runPoolSession :: HasqlDbEnv -> Session a -> IO a+runPoolSession env session = do+ result <- Pool.use (hdbPool env) session+ case result of+ Left err -> throwIO (userError $ "HasqlDb session error: " <> show err)+ Right val -> return val++instance MonadPGQueuer HasqlDb where+ enqueue ep payload priority executeAfter dedupeKey headers parentId parentState status = do+ env <- HasqlDb (ReaderT return)+ let settings = hdbSettings env+ liftIO $ do+ let priorities = V.singleton (fromIntegral priority :: Int32)+ entrypoints = V.singleton (let Entrypoint e = ep in e)+ payloads = V.singleton (BL.toStrict <$> payload)+ intervals = V.singleton (fmap formatInterval executeAfter)+ dedupeKeys = V.singleton dedupeKey+ headersBs = V.singleton (BL.toStrict . Aeson.encode <$> headers)+ parentIds = V.singleton ((\(JobId i) -> fromIntegral i :: Int32) <$> parentId)+ parentStates = V.singleton (BL.toStrict . Aeson.encode <$> parentState)+ statuses = V.singleton (jobStatusToText status)+ result <-+ runPoolSession env $+ Session.statement+ ( priorities+ , entrypoints+ , payloads+ , intervals+ , dedupeKeys+ , headersBs+ , parentIds+ , parentStates+ , statuses+ )+ (enqueueStmt settings)+ return $ map (JobId . fromIntegral) (V.toList result)++ dequeue batchSize params queueMgrId globalLimit heartbeatTimeoutSecs = do+ env <- HasqlDb (ReaderT return)+ let settings = hdbSettings env+ entrypoints = V.fromList $ map (\p -> let Entrypoint e = paramEntrypoint p in e) params+ concurrencyLimits = V.fromList $ map (fromIntegral . paramConcurrencyLimit) params+ batchSize' = fromIntegral batchSize :: Int32+ globalLimit' = fromIntegral <$> globalLimit :: Maybe Int64+ liftIO $ do+ result <-+ runPoolSession env $+ Session.statement+ (batchSize', queueMgrId, globalLimit', entrypoints, concurrencyLimits)+ (dequeueStmt settings heartbeatTimeoutSecs)+ return $ V.toList result++ logJobs jobStatuses = do+ env <- HasqlDb (ReaderT return)+ let settings = hdbSettings env+ jobIds = V.fromList $ map (\(JobId i, _, _) -> fromIntegral i :: Int32) jobStatuses+ statuses = V.fromList $ map (\(_, s, _) -> jobStatusToText s) jobStatuses+ tracebacks = V.fromList $ map (\(_, _, tb) -> BL.toStrict . Aeson.encode <$> tb) jobStatuses+ liftIO+ $ runPoolSession env+ $ Session.statement (jobIds, statuses, tracebacks) (logJobsStmt settings)++ updateHeartbeat jobIds = do+ env <- HasqlDb (ReaderT return)+ let settings = hdbSettings env+ ids = V.fromList $ map (\(JobId i) -> fromIntegral i :: Int32) jobIds+ liftIO $ runPoolSession env $ Session.statement ids (updateHeartbeatStmt settings)++ retryJobs updates = do+ env <- HasqlDb (ReaderT return)+ let settings = hdbSettings env+ executeAfters = V.fromList [ea | (_, ea, _) <- updates]+ attempts = V.fromList [a | (_, _, a) <- updates]+ ids = V.fromList [fromIntegral i | (JobId i, _, _) <- updates]+ liftIO+ $ runPoolSession env+ $ Session.statement+ (executeAfters, attempts, ids)+ (retryJobsStmt settings)++ mergedChildResults (JobId jid) = do+ env <- HasqlDb (ReaderT return)+ let settings = hdbSettings env+ liftIO $ do+ results <-+ runPoolSession env $ Session.statement (fromIntegral jid) (mergedChildResultsStmt settings)+ return (V.toList results)++ withTransaction action = do+ env <- HasqlDb (ReaderT return)+ liftIO $ do+ -- Manually manage BEGIN/COMMIT/ROLLBACK via raw SQL sessions+ let doBegin = runPoolSession env $ Session.sql "BEGIN"+ doCommit = runPoolSession env $ Session.sql "COMMIT"+ doRollback = runPoolSession env $ Session.sql "ROLLBACK"+ doBegin+ ( do+ result <- runHasqlDb env action+ doCommit+ return result+ )+ `catch` ( \(e :: SomeException) -> do+ _ <- doRollback `catch` (\(_ :: SomeException) -> return ())+ throwIO e+ )++ insertSchedule (CronExpression expr) (Entrypoint ep) = do+ env <- HasqlDb (ReaderT return)+ liftIO $ runPoolSession env $ Session.statement (expr, ep) insertScheduleStmt++ fetchSchedules = do+ env <- HasqlDb (ReaderT return)+ rows <- liftIO $ runPoolSession env $ Session.statement () fetchSchedulesStmt+ return $ V.toList $ V.map mapScheduleRow rows+ where+ mapScheduleRow (i, expr, ep, hb, cr, upd, nr, lr, st) =+ Schedule+ { scheduleId = ScheduleId (fromIntegral i)+ , scheduleExpression = CronExpression expr+ , scheduleEntrypoint = Entrypoint ep+ , scheduleHeartbeat = hb+ , scheduleCreated = cr+ , scheduleUpdated = upd+ , scheduleNextRun = nr+ , scheduleLastRun = lr+ , scheduleStatus = fromMaybe Queued (textToJobStatus st)+ }++ setScheduleQueued (ScheduleId sid) nextRun = do+ env <- HasqlDb (ReaderT return)+ liftIO $ runPoolSession env $ Session.statement (nextRun, fromIntegral sid) setScheduleQueuedStmt++ getEarliestNextRun = do+ env <- HasqlDb (ReaderT return)+ liftIO $ runPoolSession env $ Session.statement () getEarliestNextRunStmt++-- | Format a NominalDiffTime as a PostgreSQL interval string.+formatInterval :: NominalDiffTime -> Text+formatInterval dt =+ let secs = realToFrac dt :: Double+ in T.pack (show secs) <> " seconds"
+ src/PGQueuer/Backend/Hasql/Statements.hs view
@@ -0,0 +1,595 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module : PGQueuer.Backend.Hasql.Statements+Description : Statically compiled Hasql statements for queue operations.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Defines all SQL operations as @Hasql.Statement.Statement@ objects with+binary encoders and decoders. Every statement is marked as prepared+(@True@) to force PostgreSQL to skip query planning in hot paths.++The @dequeue@ statement is especially critical: it uses+@FOR UPDATE SKIP LOCKED@ and MUST be prepared to avoid repeated+planning inside the inner worker loop.+-}+module PGQueuer.Backend.Hasql.Statements+ ( enqueueStmt+ , dequeueStmt+ , logJobsStmt+ , updateHeartbeatStmt+ , retryJobsStmt+ , walLsnStmt+ , tableStatsStmt+ , insertScheduleStmt+ , fetchSchedulesStmt+ , setScheduleQueuedStmt+ , getEarliestNextRunStmt+ , mergedChildResultsStmt+ ) where++import qualified Data.Aeson as Aeson+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as BL+import Data.Functor.Contravariant ((>$<))+import Data.Int (Int32, Int64)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Time (UTCTime)+import Data.UUID (UUID)+import Data.Vector (Vector)+import qualified Hasql.Decoders as D+import qualified Hasql.Encoders as E+import Hasql.Statement (Statement (..))++import PGQueuer.Settings (DBSettings, queueStatusType, queueTable, queueTableLog)+import PGQueuer.Types++-- ============================================================================+-- Decoders for domain types+-- ============================================================================++{- | Decode a 'JobStatus' from a text column.+Uses 'D.custom' which has signature @(Bool -> ByteString -> Either Text a)@.+The Bool indicates text vs binary format; ByteString is the raw non-null value.+-}+jobStatusDecoder :: D.Value JobStatus+jobStatusDecoder = D.custom $ \_isBinary bs ->+ let t = TE.decodeUtf8 bs+ in case textToJobStatus_ t of+ Just s -> Right s+ Nothing -> Left ("Unknown job status: " <> t)++textToJobStatus_ :: Text -> Maybe JobStatus+textToJobStatus_ "queued" = Just Queued+textToJobStatus_ "picked" = Just Picked+textToJobStatus_ "successful" = Just Successful+textToJobStatus_ "failed" = Just Failed+textToJobStatus_ "exception" = Just Exception+textToJobStatus_ "canceled" = Just Canceled+textToJobStatus_ "deleted" = Just Deleted+textToJobStatus_ "held" = Just Held+textToJobStatus_ _ = Nothing++-- | Decode a JSONB value into Aeson.Value+jsonbDecoder :: D.Value Aeson.Value+jsonbDecoder = D.custom $ \isBinary bs ->+ let bs' = case BS.uncons bs of+ Just (1, rest) | isBinary -> rest+ _ -> bs+ in case Aeson.decodeStrict bs' of+ Just v -> Right v+ Nothing -> Left "Invalid JSONB"++-- | Decode a 't:Job' from a row.+jobRow :: D.Row Job+jobRow =+ (Job . JobId . fromIntegral <$> D.column (D.nonNullable D.int4)) -- id+ <*> (fromIntegral <$> D.column (D.nonNullable D.int4)) -- priority+ <*> D.column (D.nonNullable D.timestamptz) -- created+ <*> D.column (D.nonNullable D.timestamptz) -- updated+ <*> D.column (D.nonNullable D.timestamptz) -- heartbeat+ <*> D.column (D.nonNullable D.timestamptz) -- execute_after+ <*> D.column (D.nonNullable jobStatusDecoder) -- status+ <*> (Entrypoint <$> D.column (D.nonNullable D.text)) -- entrypoint+ <*> (fmap BL.fromStrict <$> D.column (D.nullable D.bytea)) -- payload+ <*> (fromIntegral <$> D.column (D.nonNullable D.int4)) -- attempts+ <*> D.column (D.nullable D.uuid) -- queue_manager_id+ <*> D.column (D.nullable D.jsonb) -- headers+ <*> (fmap (JobId . fromIntegral) <$> D.column (D.nullable D.int4)) -- parent_id+ <*> D.column (D.nullable D.jsonb) -- parent_state++-- ============================================================================+-- Enqueue Statement+-- ============================================================================++{- | Enqueue multiple jobs in a single round-trip.++Parameters: (priorities, entrypoints, payloads, intervals_text, dedupe_keys, headers_json)++Uses raw SQL with @UNNEST@ arrays to batch-insert jobs.+-}+enqueueStmt ::+ DBSettings ->+ Statement+ ( Vector Int32+ , Vector Text+ , Vector (Maybe ByteString)+ , Vector (Maybe Text)+ , Vector (Maybe Text)+ , Vector (Maybe ByteString)+ , Vector (Maybe Int32)+ , Vector (Maybe ByteString)+ , Vector Text+ )+ (Vector Int32)+enqueueStmt settings =+ Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "WITH inserted AS ("+ , " INSERT INTO " <> queueTable settings+ , " (priority, entrypoint, payload, execute_after, dedupe_key, headers, parent_id, parent_state, status)"+ , " SELECT"+ , " p, e, pay, COALESCE(NOW() + ea::interval, NOW()), d, h, pid, pstate, s::pgqueuer_status"+ , " FROM UNNEST("+ , " $1::int[],"+ , " $2::text[],"+ , " $3::bytea[],"+ , " $4::text[],"+ , " $5::text[],"+ , " $6::jsonb[],"+ , " $7::int[],"+ , " $8::jsonb[],"+ , " $9::text[]"+ , " ) AS t(p, e, pay, ea, d, h, pid, pstate, s)"+ , " RETURNING id, entrypoint, status, priority"+ , ")"+ , "INSERT INTO " <> queueTableLog settings+ , "(job_id, status, entrypoint, priority)"+ , "SELECT id, status, entrypoint, priority"+ , "FROM inserted"+ , "RETURNING job_id::int AS id"+ ]+ encoder =+ ( (\(a, _, _, _, _, _, _, _, _) -> a)+ >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int4)))+ )+ <> ( (\(_, b, _, _, _, _, _, _, _) -> b)+ >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.text)))+ )+ <> ( (\(_, _, c, _, _, _, _, _, _) -> c)+ >$< E.param (E.nonNullable (E.foldableArray (E.nullable E.bytea)))+ )+ <> ( (\(_, _, _, d, _, _, _, _, _) -> d)+ >$< E.param (E.nonNullable (E.foldableArray (E.nullable E.text)))+ )+ <> ( (\(_, _, _, _, e, _, _, _, _) -> e)+ >$< E.param (E.nonNullable (E.foldableArray (E.nullable E.text)))+ )+ <> ( (\(_, _, _, _, _, f, _, _, _) -> f)+ >$< E.param (E.nonNullable (E.foldableArray (E.nullable E.jsonbBytes)))+ )+ <> ( (\(_, _, _, _, _, _, g, _, _) -> g)+ >$< E.param (E.nonNullable (E.foldableArray (E.nullable E.int4)))+ )+ <> ( (\(_, _, _, _, _, _, _, h, _) -> h)+ >$< E.param (E.nonNullable (E.foldableArray (E.nullable E.jsonbBytes)))+ )+ <> ( (\(_, _, _, _, _, _, _, _, i) -> i)+ >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.text)))+ )+ decoder = D.rowVector (D.column (D.nonNullable D.int4))++-- ============================================================================+-- Dequeue Statement+-- ============================================================================++{- | Dequeue jobs using @FOR UPDATE SKIP LOCKED@.++This statement is marked as prepared (@True@) to force PostgreSQL to+cache the query plan. This is critical for CPU efficiency in the inner+worker loop.++Parameters: (batch_size, queue_manager_id, global_limit, entrypoints, concurrency_limits, heartbeat_timeout_secs)+-}+dequeueStmt ::+ DBSettings -> Int -> Statement (Int32, UUID, Maybe Int64, Vector Text, Vector Int64) (Vector Job)+dequeueStmt settings heartbeatTimeoutSecs =+ Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "WITH"+ , "runtime AS ("+ , " SELECT"+ , " $1::int AS batch_size,"+ , " $2::uuid AS queue_manager_id,"+ , " $3::bigint AS global_limit"+ , "),"+ , "params AS ("+ , " SELECT"+ , " UNNEST($4::text[]) AS entrypoint,"+ , " UNNEST($5::bigint[]) AS concurrency_limit"+ , "),"+ , "picked AS ("+ , " SELECT entrypoint, COUNT(*) AS total"+ , " FROM " <> queueTable settings <> " q"+ , " WHERE q.status = 'picked'"+ , " AND EXISTS (SELECT 1 FROM params p WHERE p.entrypoint = q.entrypoint)"+ , " GROUP BY q.entrypoint"+ , "),"+ , "worker_load AS ("+ , " SELECT COUNT(*) AS total"+ , " FROM " <> queueTable settings <> " q"+ , " WHERE q.queue_manager_id = (SELECT queue_manager_id FROM runtime)"+ , " AND EXISTS (SELECT 1 FROM params p WHERE p.entrypoint = q.entrypoint)"+ , "),"+ , "available AS ("+ , " SELECT p.entrypoint"+ , " FROM params p"+ , " LEFT JOIN picked pk ON pk.entrypoint = p.entrypoint"+ , " WHERE p.concurrency_limit <= 0"+ , " OR COALESCE(pk.total, 0) < p.concurrency_limit"+ , "),"+ , "next_queued_src AS ("+ , " SELECT q.id, q.priority"+ , " FROM available a"+ , " CROSS JOIN LATERAL ("+ , " SELECT q2.id, q2.priority"+ , " FROM " <> queueTable settings <> " q2"+ , " WHERE q2.entrypoint = a.entrypoint"+ , " AND q2.status = 'queued'"+ , " AND q2.execute_after < NOW()"+ , " ORDER BY q2.priority DESC, q2.id ASC"+ , " LIMIT (SELECT batch_size FROM runtime)"+ , " FOR UPDATE SKIP LOCKED"+ , " ) q"+ , " WHERE ((SELECT global_limit FROM runtime) IS NULL"+ , " OR (SELECT total FROM worker_load) < (SELECT global_limit FROM runtime))"+ , " ORDER BY q.priority DESC, q.id ASC"+ , " LIMIT (SELECT batch_size FROM runtime)"+ , "),"+ , "next_queued AS ("+ , " SELECT id FROM next_queued_src"+ , "),"+ , "next_stale AS ("+ , " SELECT q.id"+ , " FROM " <> queueTable settings <> " q"+ , " JOIN params p ON p.entrypoint = q.entrypoint"+ , " WHERE q.status = 'picked'"+ , " AND q.heartbeat < NOW() - INTERVAL '" <> T.pack (show heartbeatTimeoutSecs) <> " seconds'"+ , " AND q.execute_after < NOW()"+ , " AND ((SELECT global_limit FROM runtime) IS NULL"+ , " OR (SELECT total FROM worker_load) < (SELECT global_limit FROM runtime))"+ , " ORDER BY q.priority DESC, q.id ASC"+ , " FOR UPDATE SKIP LOCKED"+ , " LIMIT (SELECT batch_size FROM runtime)"+ , "),"+ , "eligible AS ("+ , " SELECT id FROM ("+ , " SELECT id, 0 AS src FROM next_queued"+ , " UNION ALL"+ , " SELECT id, 1 AS src FROM next_stale"+ , " ) combined"+ , " ORDER BY src, id"+ , " LIMIT (SELECT batch_size FROM runtime)"+ , "),"+ , "claimed AS ("+ , " UPDATE " <> queueTable settings+ , " SET status = 'picked',"+ , " updated = NOW(),"+ , " heartbeat = NOW(),"+ , " queue_manager_id = (SELECT queue_manager_id FROM runtime)"+ , " WHERE id IN (SELECT id FROM eligible)"+ , " RETURNING *"+ , "),"+ , "log_pick AS ("+ , " INSERT INTO " <> queueTableLog settings <> " (job_id, status, entrypoint, priority)"+ , " SELECT id, status, entrypoint, priority FROM claimed"+ , ")"+ , "SELECT id, priority, created, updated, heartbeat, execute_after, status::text AS status, entrypoint, payload, attempts, queue_manager_id, headers, parent_id, parent_state"+ , "FROM claimed"+ , "ORDER BY priority DESC, id ASC"+ ]+ encoder =+ ((\(a, _, _, _, _) -> a) >$< E.param (E.nonNullable E.int4))+ <> ((\(_, b, _, _, _) -> b) >$< E.param (E.nonNullable E.uuid))+ <> ((\(_, _, c, _, _) -> c) >$< E.param (E.nullable E.int8))+ <> ((\(_, _, _, d, _) -> d) >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.text))))+ <> ((\(_, _, _, _, e) -> e) >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int8))))+ decoder = D.rowVector jobRow++-- | Get earliest next_run.+getEarliestNextRunStmt :: Statement () (Maybe UTCTime)+getEarliestNextRunStmt = Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "SELECT MIN(next_run)"+ , "FROM pgqueuer_schedules"+ , "WHERE status = 'queued'"+ ]+ encoder = E.noParams+ decoder = D.singleRow (D.column (D.nullable D.timestamptz))++-- ============================================================================+-- LogJobs Statement+-- ============================================================================++{- | Log job status transitions.++Parameters: (job_ids, statuses, tracebacks)+-}+logJobsStmt :: DBSettings -> Statement (Vector Int32, Vector Text, Vector (Maybe ByteString)) ()+logJobsStmt settings =+ Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "WITH job_status AS ("+ , " SELECT"+ , " UNNEST($1::integer[]) AS id,"+ , " UNNEST($2::" <> queueStatusType settings <> "[]) AS status,"+ , " UNNEST($3::jsonb[]) AS traceback"+ , "), deleted AS ("+ , " DELETE FROM " <> queueTable settings+ , " WHERE id = ANY(SELECT js.id FROM job_status js WHERE js.status != 'failed')"+ , " RETURNING id, entrypoint, priority, parent_id"+ , "), held AS ("+ , " UPDATE " <> queueTable settings+ , " SET status = 'failed', updated = NOW(), queue_manager_id = NULL"+ , " WHERE id = ANY(SELECT js.id FROM job_status js WHERE js.status = 'failed')"+ , " RETURNING id, entrypoint, priority, parent_id"+ , "), all_resolved AS ("+ , " SELECT id, entrypoint, priority, parent_id FROM deleted"+ , " UNION ALL"+ , " SELECT id, entrypoint, priority, parent_id FROM held"+ , "), merged AS ("+ , " SELECT"+ , " job_status.id AS id,"+ , " job_status.status AS status,"+ , " job_status.traceback AS traceback,"+ , " all_resolved.entrypoint AS entrypoint,"+ , " all_resolved.priority AS priority,"+ , " all_resolved.parent_id AS parent_id"+ , " FROM job_status"+ , " INNER JOIN all_resolved"+ , " ON all_resolved.id = job_status.id"+ , "), log_insert AS ("+ , " INSERT INTO " <> queueTableLog settings <> " ("+ , " job_id,"+ , " status,"+ , " entrypoint,"+ , " priority,"+ , " traceback,"+ , " parent_id"+ , " )"+ , " SELECT id, status, entrypoint, priority, traceback, parent_id FROM merged"+ , " RETURNING parent_id"+ , "), rollup_parents AS ("+ , " SELECT DISTINCT parent_id FROM log_insert WHERE parent_id IS NOT NULL"+ , "), ready_parents AS ("+ , " SELECT rp.parent_id"+ , " FROM rollup_parents rp"+ , " WHERE NOT EXISTS ("+ , " SELECT 1 FROM " <> queueTable settings <> " q WHERE q.parent_id = rp.parent_id"+ , " AND q.id NOT IN (SELECT id FROM deleted)"+ , " )"+ , ")"+ , "UPDATE " <> queueTable settings+ , "SET status = 'queued', updated = NOW()"+ , "WHERE id IN (SELECT parent_id FROM ready_parents) AND status = 'held'"+ ]+ encoder =+ ((\(a, _, _) -> a) >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int4))))+ <> ((\(_, b, _) -> b) >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.text))))+ <> ((\(_, _, c) -> c) >$< E.param (E.nonNullable (E.foldableArray (E.nullable E.jsonbBytes))))+ decoder = D.noResult++-- ============================================================================+-- MergedChildResults Statement+-- ============================================================================++{- | Query completed children results for a parent job.+Returns a list of 'Aeson.Value' tracebacks from pgqueuer_log.+-}+mergedChildResultsStmt :: DBSettings -> Statement Int32 (Vector Aeson.Value)+mergedChildResultsStmt settings =+ Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "SELECT traceback"+ , "FROM " <> queueTableLog settings+ , "WHERE parent_id = $1"+ , " AND traceback IS NOT NULL"+ ]+ encoder = E.param (E.nonNullable E.int4)+ decoder = D.rowVector (D.column (D.nonNullable jsonbDecoder))++-- ============================================================================+-- UpdateHeartbeat Statement+-- ============================================================================++{- | Refresh heartbeat timestamps for active jobs.++Parameters: job_ids as int array+-}+updateHeartbeatStmt :: DBSettings -> Statement (Vector Int32) ()+updateHeartbeatStmt settings =+ Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "UPDATE " <> queueTable settings+ , "SET heartbeat = NOW()"+ , "WHERE id = ANY($1::integer[]) AND status = 'picked'"+ ]+ encoder = E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int4)))+ decoder = D.noResult++-- ============================================================================+-- RetryJobs Statement+-- ============================================================================++{- | Retry failed jobs after a specified delay.++Parameters: (execute_afters, attempts, job_ids)+-}+retryJobsStmt :: DBSettings -> Statement (Vector UTCTime, Vector Int32, Vector Int32) ()+retryJobsStmt settings =+ Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "WITH updates AS ("+ , " SELECT"+ , " UNNEST($1::timestamptz[]) AS execute_after,"+ , " UNNEST($2::integer[]) AS attempts,"+ , " UNNEST($3::integer[]) AS id"+ , ")"+ , "UPDATE " <> queueTable settings <> " q"+ , "SET status = 'queued',"+ , " execute_after = u.execute_after,"+ , " attempts = u.attempts,"+ , " queue_manager_id = NULL,"+ , " updated = NOW()"+ , "FROM updates u"+ , "WHERE q.id = u.id"+ ]+ encoder =+ ((\(a, _, _) -> a) >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.timestamptz))))+ <> ((\(_, b, _) -> b) >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int4))))+ <> ((\(_, _, c) -> c) >$< E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int4))))+ decoder = D.noResult++-- ============================================================================+-- Telemetry Statements (for benchmarking)+-- ============================================================================++{- | Query current WAL LSN position as a bigint (bytes).++Returns the WAL position for computing write-amplification.+-}+walLsnStmt :: Statement () Int64+walLsnStmt =+ Statement sql encoder decoder True+ where+ sql = "SELECT pg_current_wal_lsn() - '0/0'::pg_lsn"+ encoder = E.noParams+ decoder = D.singleRow (D.column (D.nonNullable D.int8))++{- | Query pg_stat_user_tables metrics for a given table.++Returns: (n_tup_upd, n_tup_hot_upd, n_dead_tup)+-}+tableStatsStmt :: Statement Text (Int64, Int64, Int64)+tableStatsStmt =+ Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "SELECT"+ , " COALESCE(n_tup_upd, 0)::bigint,"+ , " COALESCE(n_tup_hot_upd, 0)::bigint,"+ , " COALESCE(n_dead_tup, 0)::bigint"+ , "FROM pg_stat_user_tables"+ , "WHERE relname = $1::text"+ ]+ encoder = E.param (E.nonNullable E.text)+ decoder =+ D.singleRow $+ (,,)+ <$> D.column (D.nonNullable D.int8)+ <*> D.column (D.nonNullable D.int8)+ <*> D.column (D.nonNullable D.int8)++-- ============================================================================+-- Schedule Statements+-- ============================================================================++-- | Insert a new cron schedule.+insertScheduleStmt :: Statement (Text, Text) ()+insertScheduleStmt = Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "INSERT INTO pgqueuer_schedules (expression, entrypoint)"+ , "VALUES ($1, $2)"+ , "ON CONFLICT (expression, entrypoint) DO NOTHING"+ ]+ encoder =+ (fst >$< E.param (E.nonNullable E.text))+ <> (snd >$< E.param (E.nonNullable E.text))+ decoder = D.noResult++-- | Fetch due schedules.+fetchSchedulesStmt ::+ Statement () (Vector (Int32, Text, Text, UTCTime, UTCTime, UTCTime, UTCTime, Maybe UTCTime, Text))+fetchSchedulesStmt = Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "UPDATE pgqueuer_schedules"+ , "SET status = 'picked',"+ , " updated = NOW(),"+ , " heartbeat = NOW()"+ , "WHERE id IN ("+ , " SELECT id"+ , " FROM pgqueuer_schedules"+ , " WHERE status = 'queued'"+ , " AND next_run <= NOW()"+ , " ORDER BY id ASC"+ , " FOR UPDATE SKIP LOCKED"+ , ")"+ , "RETURNING id, expression, entrypoint, heartbeat, created, updated, next_run, last_run, status::text"+ ]+ encoder = E.noParams+ decoder =+ D.rowVector $+ (,,,,,,,,)+ <$> D.column (D.nonNullable D.int4)+ <*> D.column (D.nonNullable D.text)+ <*> D.column (D.nonNullable D.text)+ <*> D.column (D.nonNullable D.timestamptz)+ <*> D.column (D.nonNullable D.timestamptz)+ <*> D.column (D.nonNullable D.timestamptz)+ <*> D.column (D.nonNullable D.timestamptz)+ <*> D.column (D.nullable D.timestamptz)+ <*> D.column (D.nonNullable D.text)++-- | Reset schedule to queued and update next run.+setScheduleQueuedStmt :: Statement (UTCTime, Int32) ()+setScheduleQueuedStmt = Statement sql encoder decoder True+ where+ sql =+ TE.encodeUtf8 $+ T.unlines+ [ "UPDATE pgqueuer_schedules"+ , "SET status = 'queued',"+ , " updated = NOW(),"+ , " last_run = NOW(),"+ , " next_run = $1"+ , "WHERE id = $2"+ ]+ encoder =+ (fst >$< E.param (E.nonNullable E.timestamptz))+ <> (snd >$< E.param (E.nonNullable E.int4))+ decoder = D.noResult
+ src/PGQueuer/Backend/Simple.hs view
@@ -0,0 +1,159 @@+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Module : PGQueuer.Backend.Simple+Description : Reference backend using postgresql-simple.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Provides 't:SimpleDb', a concrete monad transformer that implements+'MonadPGQueuer' by delegating to the existing "PGQueuer.Query" functions+through a 'Control.Monad.Reader.ReaderT' over a single 'Connection'.++This is the baseline reference driver. It uses @FOR UPDATE SKIP LOCKED@+for lock-free dequeue and wraps transactions via @postgresql-simple@'s+'PG.withTransaction'.+-}+module PGQueuer.Backend.Simple+ ( SimpleDb (..)+ , SimpleDbEnv (..)+ , runSimpleDb+ , mkSimpleDbEnv+ )+where++import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Reader (MonadReader, ReaderT (..), asks)+import Data.Aeson (Value)+import Data.Int (Int32)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Database.PostgreSQL.Simple (Connection, Only (..), query)+import qualified Database.PostgreSQL.Simple as PG+import Database.PostgreSQL.Simple.Types (Query (..))+import PGQueuer.Core.Monad (MonadPGQueuer (..))+import qualified PGQueuer.Query as Q+import PGQueuer.Settings (DBSettings, defaultDBSettings, queueTableLog)+import PGQueuer.Types (JobId (..))++{- | Environment carrying the connection handle and database settings+required by the 't:SimpleDb' monad.+-}+data SimpleDbEnv = SimpleDbEnv+ { sdbConnection :: Connection+ -- ^ Database connection handle+ , sdbSettings :: DBSettings+ -- ^ Table/schema naming settings+ }++-- | Convenience constructor using 'defaultDBSettings'.+mkSimpleDbEnv :: Connection -> SimpleDbEnv+mkSimpleDbEnv conn =+ SimpleDbEnv+ { sdbConnection = conn+ , sdbSettings = defaultDBSettings+ }++{- | A concrete monad transformer wrapping @ReaderT SimpleDbEnv IO@.++This is the reference 'MonadPGQueuer' implementation backed by+@postgresql-simple@.+-}+newtype SimpleDb a = SimpleDb+ { unSimpleDb :: ReaderT SimpleDbEnv IO a+ }+ deriving newtype (Functor, Applicative, Monad, MonadIO, MonadReader SimpleDbEnv)++-- | Run a 't:SimpleDb' computation with the given environment.+runSimpleDb :: SimpleDbEnv -> SimpleDb a -> IO a+runSimpleDb env (SimpleDb action) = runReaderT action env++instance MonadPGQueuer SimpleDb where+ enqueue ep payload priority executeAfter dedupeKey headers parentId parentState status = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $+ Q.enqueueSingle+ conn+ settings+ ep+ payload+ priority+ executeAfter+ dedupeKey+ headers+ parentId+ parentState+ status++ dequeue batchSize params queueMgrId globalLimit heartbeatTimeoutSecs = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $+ Q.dequeue+ conn+ settings+ batchSize+ params+ queueMgrId+ globalLimit+ heartbeatTimeoutSecs++ logJobs jobStatuses = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $ Q.logJobs conn settings jobStatuses++ updateHeartbeat jobIds = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $ Q.updateHeartbeat conn settings jobIds++ retryJobs updates = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $ Q.retryJobs conn settings updates++ mergedChildResults (JobId jid) = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $ do+ let q =+ T.unlines+ [ "SELECT traceback"+ , "FROM " <> queueTableLog settings+ , "WHERE parent_id = ?"+ , " AND traceback IS NOT NULL"+ ]+ results <-+ query conn (Query $ TE.encodeUtf8 q) (Only (fromIntegral jid :: Int32)) :: IO [Only Value]+ return (map fromOnly results)++ withTransaction action = do+ env <- SimpleDb (ReaderT return)+ let conn = sdbConnection env+ liftIO $ PG.withTransaction conn (runSimpleDb env action)++ insertSchedule expr ep = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $ Q.insertSchedule conn settings expr ep++ fetchSchedules = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $ Q.fetchSchedules conn settings++ setScheduleQueued sid nextRun = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $ Q.setScheduleQueued conn settings sid nextRun++ getEarliestNextRun = do+ conn <- asks sdbConnection+ settings <- asks sdbSettings+ liftIO $ Q.getEarliestNextRun conn settings
+ src/PGQueuer/Core/Monad.hs view
@@ -0,0 +1,110 @@+{- |+Module : PGQueuer.Core.Monad+Description : Abstract typeclass for database queue operations.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Defines the 'MonadPGQueuer' typeclass which serves as the contract+for any database engine backend. This abstraction enables swapping+out low-level database clients without modifying the concurrency+or worker loop infrastructure.+-}+module PGQueuer.Core.Monad+ ( MonadPGQueuer (..)+ )+where++import Data.Aeson (Value)+import qualified Data.ByteString.Lazy as BL+import Data.Int (Int32)+import Data.Text (Text)+import Data.Time (NominalDiffTime, UTCTime)+import Data.UUID (UUID)+import PGQueuer.Types++{- | Abstract interface for database-backed queue operations.++Any backend that implements this typeclass provides the full+lifecycle management for jobs: enqueueing, dequeueing with+lock-free concurrency via @FOR UPDATE SKIP LOCKED@, status+logging, heartbeat maintenance, retry logic, and transactional+boundaries.+-}+class (Monad m) => MonadPGQueuer m where+ {- | Enqueue a single job with optional payload, priority, delay,+ deduplication key, and headers. Returns the assigned 't:JobId's.+ -}+ enqueue ::+ Entrypoint ->+ Maybe BL.ByteString ->+ Int ->+ Maybe NominalDiffTime ->+ Maybe Text ->+ Maybe Value ->+ Maybe JobId ->+ Maybe Value ->+ JobStatus ->+ m [JobId]++ {- | Dequeue a batch of jobs matching the given entrypoint parameters.+ Uses @FOR UPDATE SKIP LOCKED@ internally to avoid contention.+ -}+ dequeue ::+ -- | Batch size+ Int ->+ -- | Per-entrypoint execution parameters+ [EntrypointExecutionParameter] ->+ -- | Queue manager identifier+ UUID ->+ -- | Global concurrency limit+ Maybe Int ->+ -- | Heartbeat timeout in seconds+ Int ->+ m [Job]++ {- | Atomically update job statuses and append entries to the+ audit log table.+ -}+ logJobs :: [(JobId, JobStatus, Maybe Value)] -> m ()++ {- | Refresh heartbeat timestamps for the given active jobs.+ Only updates the @heartbeat@ column (HOT-friendly).+ -}+ updateHeartbeat :: [JobId] -> m ()++ {- | Retry failed jobs in bulk.+ Provides a list of (JobId, newExecuteAfter, newAttempts).+ -}+ retryJobs :: [(JobId, UTCTime, Int32)] -> m ()++ {- | Query completed children results for a parent job.+ Returns a list of 'Data.Aeson.Value' payloads or tracebacks.+ -}+ mergedChildResults :: JobId -> m [Value]++ {- | Execute an action within a database transaction boundary.+ Provides @BEGIN@, @COMMIT@ on success, and @ROLLBACK@ on exception.+ -}+ withTransaction :: m a -> m a++ {- | Insert a cron schedule if it does not already exist.+ Matches the Python implementation's @insert_schedule@ with ON CONFLICT DO NOTHING.+ -}+ insertSchedule :: CronExpression -> Entrypoint -> m ()++ {- | Fetch due schedules safely using @FOR UPDATE SKIP LOCKED@.+ Atomically transitions them to 'Picked' status and returns the 't:Schedule' records.+ -}+ fetchSchedules :: m [Schedule]++ {- | Reset a schedule's status back to 'Queued' after its job has been dispatched.+ Sets last_run = NOW() and updates next_run to the provided 'UTCTime'.+ -}+ setScheduleQueued :: ScheduleId -> UTCTime -> m ()++ {- | Get the earliest next_run among queued schedules.+ Used by the cron scheduler to determine how long to sleep.+ -}+ getEarliestNextRun :: m (Maybe UTCTime)
src/PGQueuer/Listener.hs view
@@ -1,13 +1,24 @@ {-# LANGUAGE OverloadedStrings #-} -module PGQueuer.Listener (- listen,- unlisten,- unlistenAll,- getNextNotification,- notifyJobCancellation,- notifyHealthCheck,- parseEventPayload,+{- |+Module : PGQueuer.Listener+Description : PostgreSQL LISTEN/NOTIFY event listener and event publisher.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Provides functions for subscribing to PostgreSQL asynchronous notifications+(@LISTEN@ / @UNLISTEN@) and publishing cancellation or health check signals.+-}+module PGQueuer.Listener+ ( listen+ , unlisten+ , unlistenAll+ , getNextNotification+ , notifyJobCancellation+ , notifyHealthCheck+ , parseEventPayload ) where import Control.Monad (void)
src/PGQueuer/Query.hs view
@@ -1,26 +1,43 @@ {-# LANGUAGE OverloadedStrings #-} -module PGQueuer.Query (- enqueueSingle,- enqueueMultiple,- dequeue,- logJobs,- queueSize,- queuedWork,- retryJob,- requeueJobs,- markJobAsCancelled,- updateHeartbeat,- jobStatusById,- clearQueue,- listFailedJobs,+{- |+Module : PGQueuer.Query+Description : Raw SQL statements and database execution using postgresql-simple.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++This module encapsulates all raw SQL queries used by the postgresql-simple+driver for queueing, dequeueing, state logging, heartbeats, and statistics.+-}+module PGQueuer.Query+ ( enqueueSingle+ , enqueueMultiple+ , dequeue+ , logJobs+ , queueSize+ , queuedWork+ , retryJobs+ , requeueJobs+ , markJobAsCancelled+ , updateHeartbeat+ , jobStatusById+ , clearQueue+ , listFailedJobs+ , insertSchedule+ , fetchSchedules+ , setScheduleQueued+ , getEarliestNextRun ) where import Data.Aeson (Value) import qualified Data.ByteString.Lazy as BL+import Data.Int (Int32)+import Data.Maybe (fromMaybe) import Data.Text (Text) import qualified Data.Text.Encoding as TE-import Data.Time (NominalDiffTime, addUTCTime)+import Data.Time (NominalDiffTime, UTCTime) import Data.UUID (UUID) import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.Types (PGArray (..), Query (..))@@ -42,20 +59,23 @@ Maybe NominalDiffTime -> Maybe Text -> Maybe Value ->+ Maybe JobId ->+ Maybe Value ->+ JobStatus -> IO [JobId]-enqueueSingle conn settings entrypoint payload priority executeAfter dedupeKey headers = do+enqueueSingle conn settings entrypoint payload priority executeAfter dedupeKey headers parentId parentState status = enqueueMultiple conn settings [entrypoint]- (maybeToList payload)+ [payload] [priority]- (maybeToList executeAfter)- (maybeToList dedupeKey)- (maybeToList headers)- where- maybeToList Nothing = []- maybeToList (Just x) = [Just x]+ [executeAfter]+ [dedupeKey]+ [headers]+ [parentId]+ [parentState]+ [status] -- | Enqueue multiple jobs enqueueMultiple ::@@ -67,28 +87,34 @@ [Maybe NominalDiffTime] -> [Maybe Text] -> [Maybe Value] ->+ [Maybe JobId] ->+ [Maybe Value] ->+ [JobStatus] -> IO [JobId]-enqueueMultiple conn settings entrypoints payloads priorities executeAfters dedupeKeys headersList = do+enqueueMultiple conn settings entrypoints payloads priorities executeAfters dedupeKeys headersList parentIds parentStates statuses = do let q = T.unlines [ "WITH inserted AS (" , " INSERT INTO " <> queueTable settings- , " (priority, entrypoint, payload, execute_after, dedupe_key, headers, status)"+ , " (priority, entrypoint, payload, execute_after, dedupe_key, headers, parent_id, parent_state, status)" , " SELECT"- , " p, e, pay, COALESCE(NOW() + ea, NOW()), d, h, 'queued'"+ , " p, e, pay, COALESCE(NOW() + ea, NOW()), d, h, pid, pstate, s::pgqueuer_status" , " FROM UNNEST(" , " ?::int[]," , " ?::text[]," , " ?::bytea[]," , " ?::interval[]," , " ?::text[],"- , " ?::jsonb[]"- , " ) AS t(p, e, pay, ea, d, h)"+ , " ?::jsonb[],"+ , " ?::int[],"+ , " ?::jsonb[],"+ , " ?::text[]"+ , " ) AS t(p, e, pay, ea, d, h, pid, pstate, s)" , " RETURNING id, entrypoint, status, priority" , ")" , "INSERT INTO " <> queueTableLog settings , "(job_id, status, entrypoint, priority)"- , "SELECT id, 'queued', entrypoint, priority"+ , "SELECT id, status, entrypoint, priority" , "FROM inserted" , "RETURNING job_id AS id" ]@@ -103,6 +129,9 @@ , PGArray executeAfters , PGArray dedupeKeys , PGArray headersList+ , PGArray (map (fmap (\(JobId i) -> i)) parentIds)+ , PGArray parentStates+ , PGArray (map jobStatusToText statuses) ) :: IO [Only JobId] @@ -139,7 +168,7 @@ , "picked AS (" , " SELECT entrypoint, COUNT(*) AS total" , " FROM " <> queueTable settings <> " q"- , " WHERE q.queue_manager_id IS NOT NULL"+ , " WHERE q.status = 'picked'" , " AND EXISTS (SELECT 1 FROM params p WHERE p.entrypoint = q.entrypoint)" , " GROUP BY q.entrypoint" , "),"@@ -212,7 +241,7 @@ , " INSERT INTO " <> queueTableLog settings <> " (job_id, status, entrypoint, priority)" , " SELECT id, status, entrypoint, priority FROM claimed" , ")"- , "SELECT id, priority, created, updated, heartbeat, execute_after, status::text AS status, entrypoint, payload, attempts, queue_manager_id, headers"+ , "SELECT id, priority, created, updated, heartbeat, execute_after, status::text AS status, entrypoint, payload, attempts, queue_manager_id, headers, parent_id, parent_state" , "FROM claimed" , "ORDER BY priority DESC, id ASC" ]@@ -247,35 +276,51 @@ , "), deleted AS (" , " DELETE FROM " <> queueTable settings , " WHERE id = ANY(SELECT js.id FROM job_status js WHERE js.status != 'failed')"- , " RETURNING id, entrypoint, priority"+ , " RETURNING id, entrypoint, priority, parent_id" , "), held AS (" , " UPDATE " <> queueTable settings , " SET status = 'failed', updated = NOW(), queue_manager_id = NULL" , " WHERE id = ANY(SELECT js.id FROM job_status js WHERE js.status = 'failed')"- , " RETURNING id, entrypoint, priority"+ , " RETURNING id, entrypoint, priority, parent_id" , "), all_resolved AS ("- , " SELECT id, entrypoint, priority FROM deleted"+ , " SELECT id, entrypoint, priority, parent_id FROM deleted" , " UNION ALL"- , " SELECT id, entrypoint, priority FROM held"+ , " SELECT id, entrypoint, priority, parent_id FROM held" , "), merged AS (" , " SELECT" , " job_status.id AS id," , " job_status.status AS status," , " job_status.traceback AS traceback," , " all_resolved.entrypoint AS entrypoint,"- , " all_resolved.priority AS priority"+ , " all_resolved.priority AS priority,"+ , " all_resolved.parent_id AS parent_id" , " FROM job_status" , " INNER JOIN all_resolved" , " ON all_resolved.id = job_status.id"- , ")"+ , "), log_insert AS (" , " INSERT INTO " <> queueTableLog settings <> " (" , " job_id," , " status," , " entrypoint," , " priority,"- , " traceback"+ , " traceback,"+ , " parent_id" , " )"- , "SELECT id, status, entrypoint, priority, traceback FROM merged"+ , " SELECT id, status, entrypoint, priority, traceback, parent_id FROM merged"+ , " RETURNING parent_id"+ , "), rollup_parents AS ("+ , " SELECT DISTINCT parent_id FROM log_insert WHERE parent_id IS NOT NULL"+ , "), ready_parents AS ("+ , " SELECT rp.parent_id"+ , " FROM rollup_parents rp"+ , " WHERE NOT EXISTS ("+ , " SELECT 1 FROM " <> queueTable settings <> " q WHERE q.parent_id = rp.parent_id"+ , " AND q.id NOT IN (SELECT id FROM deleted)"+ , " )"+ , ")"+ , "UPDATE " <> queueTable settings+ , "SET status = 'queued', updated = NOW()"+ , "WHERE id IN (SELECT parent_id FROM ready_parents) AND status = 'held'" ] _ <- execute conn (textToQuery q) (PGArray jobIds, PGArray statuses, PGArray tracebacks) return ()@@ -312,28 +357,34 @@ [Only count] -> return count _ -> return 0 --- | Retry a failed job-retryJob ::+-- | Retry failed jobs in bulk+retryJobs :: Connection -> DBSettings ->- Job ->- NominalDiffTime -> -- delay- Maybe Value -> -- traceback+ [(JobId, UTCTime, Int32)] -> -- (job_id, newExecuteAfter, newAttempts) IO ()-retryJob conn settings job delay _traceback = do- let newExecuteAfter = addUTCTime delay (jobExecuteAfter job)- newAttempts = jobAttempts job + 1+retryJobs conn settings updates = do+ let executeAfters = map (\(_, ea, _) -> ea) updates+ attempts = map (\(_, _, a) -> a) updates+ jobIds = map (\(JobId i, _, _) -> i) updates q = T.unlines- [ "UPDATE " <> queueTable settings+ [ "WITH updates AS ("+ , " SELECT"+ , " UNNEST(?::timestamptz[]) AS execute_after,"+ , " UNNEST(?::integer[]) AS attempts,"+ , " UNNEST(?::integer[]) AS id"+ , ")"+ , "UPDATE " <> queueTable settings <> " q" , "SET status = 'queued',"- , " execute_after = ?,"- , " attempts = ?,"+ , " execute_after = u.execute_after,"+ , " attempts = u.attempts," , " queue_manager_id = NULL," , " updated = NOW()"- , "WHERE id = ?"+ , "FROM updates u"+ , "WHERE q.id = u.id" ]- _ <- execute conn (textToQuery q) (newExecuteAfter, newAttempts, jobId job)+ _ <- execute conn (textToQuery q) (PGArray executeAfters, PGArray attempts, PGArray jobIds) return () -- | Requeue multiple jobs@@ -408,10 +459,86 @@ listFailedJobs conn settings limit = do let q = T.unlines- [ "SELECT id, priority, created, updated, heartbeat, execute_after, status::text AS status, entrypoint, payload, attempts, queue_manager_id, headers"+ [ "SELECT id, priority, created, updated, heartbeat, execute_after, status::text AS status, entrypoint, payload, attempts, queue_manager_id, headers, parent_id, parent_state" , "FROM " <> queueTable settings , "WHERE status = 'failed'" , "ORDER BY updated DESC" , "LIMIT " <> T.pack (show limit) ] query_ conn (textToQuery q)++-- | Insert a schedule+insertSchedule :: Connection -> DBSettings -> CronExpression -> Entrypoint -> IO ()+insertSchedule conn _ (CronExpression expr) (Entrypoint ep) = do+ let q =+ T.unlines+ [ "INSERT INTO pgqueuer_schedules (expression, entrypoint)"+ , "VALUES (?, ?)"+ , "ON CONFLICT (expression, entrypoint) DO NOTHING"+ ]+ _ <- execute conn (textToQuery q) (expr, ep)+ return ()++-- | Fetch schedules that are due+fetchSchedules :: Connection -> DBSettings -> IO [Schedule]+fetchSchedules conn _ = do+ let q =+ T.unlines+ [ "UPDATE pgqueuer_schedules"+ , "SET status = 'picked',"+ , " updated = NOW(),"+ , " heartbeat = NOW()"+ , "WHERE id IN ("+ , " SELECT id"+ , " FROM pgqueuer_schedules"+ , " WHERE status = 'queued'"+ , " AND next_run <= NOW()"+ , " ORDER BY id ASC"+ , " FOR UPDATE SKIP LOCKED"+ , ")"+ , "RETURNING id, expression, entrypoint, heartbeat, created, updated, next_run, last_run, status::text"+ ]+ rows <- query_ conn (textToQuery q)+ return $ map mapScheduleRow rows+ where+ mapScheduleRow (i, expr, ep, hb, cr, upd, nr, lr, st) =+ Schedule+ { scheduleId = ScheduleId i+ , scheduleExpression = CronExpression expr+ , scheduleEntrypoint = Entrypoint ep+ , scheduleHeartbeat = hb+ , scheduleCreated = cr+ , scheduleUpdated = upd+ , scheduleNextRun = nr+ , scheduleLastRun = lr+ , scheduleStatus = fromMaybe Queued (textToJobStatus st)+ }++-- | Set schedule back to queued and update next run+setScheduleQueued :: Connection -> DBSettings -> ScheduleId -> UTCTime -> IO ()+setScheduleQueued conn _ (ScheduleId sid) nextRun = do+ let q =+ T.unlines+ [ "UPDATE pgqueuer_schedules"+ , "SET status = 'queued',"+ , " updated = NOW(),"+ , " last_run = NOW(),"+ , " next_run = ?"+ , "WHERE id = ?"+ ]+ _ <- execute conn (textToQuery q) (nextRun, sid)+ return ()++-- | Get earliest next_run+getEarliestNextRun :: Connection -> DBSettings -> IO (Maybe UTCTime)+getEarliestNextRun conn _ = do+ let q =+ T.unlines+ [ "SELECT MIN(next_run)"+ , "FROM pgqueuer_schedules"+ , "WHERE status = 'queued'"+ ]+ rows <- query_ conn (textToQuery q) :: IO [Only (Maybe UTCTime)]+ case rows of+ [Only mbTime] -> return mbTime+ _ -> return Nothing
src/PGQueuer/Schema.hs view
@@ -1,9 +1,20 @@ {-# LANGUAGE OverloadedStrings #-} -module PGQueuer.Schema (- install,- uninstall,- verifyStructure_,+{- |+Module : PGQueuer.Schema+Description : Database DDL schemas, migration installation, and teardown.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Provides functions for installing and uninstalling the PGQueuer tables,+indexes, triggers, and enumeration types in PostgreSQL.+-}+module PGQueuer.Schema+ ( install+ , uninstall+ , verifyStructure_ ) where import Data.String (fromString)@@ -16,7 +27,10 @@ -- | Install the schema in the database install :: Connection -> DBSettings -> IO () install conn _settings = do- _ <- execute_ conn "CREATE TYPE pgqueuer_status AS ENUM ('queued', 'picked', 'successful', 'exception', 'canceled', 'deleted', 'failed');"+ _ <-+ execute_+ conn+ "CREATE TYPE pgqueuer_status AS ENUM ('queued', 'picked', 'successful', 'exception', 'canceled', 'deleted', 'failed', 'held');" _ <- execute_ conn $ textToQuery queueTableSQL _ <- execute_ conn $ textToQuery queueLogTableSQL _ <- execute_ conn $ textToQuery statisticsTableSQL@@ -28,7 +42,9 @@ -- | Uninstall the schema from the database uninstall :: Connection -> DBSettings -> IO () uninstall conn _settings = do- _ <- execute_ conn "DROP TRIGGER IF EXISTS tg_pgqueuer_changed ON pgqueuer;"+ _ <- execute_ conn "DROP TRIGGER IF EXISTS tg_pgqueuer_changed_insert_delete ON pgqueuer;"+ _ <- execute_ conn "DROP TRIGGER IF EXISTS tg_pgqueuer_changed_update ON pgqueuer;"+ _ <- execute_ conn "DROP TRIGGER IF EXISTS tg_pgqueuer_changed_truncate ON pgqueuer;" _ <- execute_ conn "DROP TABLE IF EXISTS pgqueuer;" _ <- execute_ conn "DROP TABLE IF EXISTS pgqueuer_log;" _ <- execute_ conn "DROP TABLE IF EXISTS pgqueuer_statistics;"@@ -40,7 +56,11 @@ -- | Verify the schema is properly installed verifyStructure_ :: Connection -> DBSettings -> IO (Either String ()) verifyStructure_ conn _settings = do- result <- PG.query_ conn "SELECT EXISTS (SELECT FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'pgqueuer');" :: IO [Only Bool]+ result <-+ PG.query_+ conn+ "SELECT EXISTS (SELECT FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'pgqueuer');" ::+ IO [Only Bool] case result of [Only True] -> return $ Right () _ -> return $ Left "Queue table is missing. Please run 'pgqueuer install' to set up the schema."@@ -64,10 +84,14 @@ , " dedupe_key TEXT," , " payload BYTEA," , " headers JSONB,"- , " attempts INT NOT NULL DEFAULT 0"+ , " attempts INT NOT NULL DEFAULT 0,"+ , " parent_id INTEGER REFERENCES pgqueuer(id) ON DELETE SET NULL,"+ , " parent_state JSONB" , ");" , "CREATE INDEX IF NOT EXISTS pgqueuer_priority_id_idx ON pgqueuer (priority ASC, id DESC)" , " INCLUDE (id) WHERE status = 'queued';"+ , "CREATE INDEX IF NOT EXISTS pgqueuer_parent_id_idx ON pgqueuer (parent_id)"+ , " WHERE parent_id IS NOT NULL;" , "CREATE INDEX IF NOT EXISTS pgqueuer_updated_id_idx ON pgqueuer (updated ASC, id DESC)" , " INCLUDE (id) WHERE status = 'picked';" , "CREATE INDEX IF NOT EXISTS pgqueuer_manager_id_idx ON pgqueuer (queue_manager_id)"@@ -78,6 +102,12 @@ , " WHERE status = 'queued';" , "CREATE UNIQUE INDEX IF NOT EXISTS pgqueuer_unique_dedupe_key ON pgqueuer (dedupe_key)" , " WHERE ((status IN ('queued', 'picked') AND dedupe_key IS NOT NULL));"+ , "ALTER TABLE pgqueuer SET (fillfactor = 70);"+ , "ALTER TABLE pgqueuer SET ("+ , " autovacuum_vacuum_scale_factor = 0.01,"+ , " autovacuum_vacuum_threshold = 1000,"+ , " autovacuum_analyze_scale_factor = 0.02"+ , ");" ] queueLogTableSQL :: T.Text@@ -91,7 +121,8 @@ , " priority INT NOT NULL," , " entrypoint TEXT NOT NULL," , " traceback JSONB DEFAULT NULL,"- , " aggregated BOOLEAN DEFAULT FALSE"+ , " aggregated BOOLEAN DEFAULT FALSE,"+ , " parent_id BIGINT" , ");" , "CREATE INDEX IF NOT EXISTS pgqueuer_log_not_aggregated ON pgqueuer_log (entrypoint, priority, status, created) WHERE not aggregated;" , "CREATE INDEX IF NOT EXISTS pgqueuer_log_created ON pgqueuer_log (created);"@@ -142,7 +173,7 @@ , "DECLARE" , " to_emit BOOLEAN := false;" , "BEGIN"- , " IF TG_OP = 'UPDATE' AND OLD IS DISTINCT FROM NEW THEN"+ , " IF TG_OP = 'UPDATE' THEN" , " to_emit := true;" , " ELSIF TG_OP = 'DELETE' THEN" , " to_emit := true;"@@ -179,9 +210,14 @@ triggerSQL :: T.Text triggerSQL = T.unlines- [ "CREATE TRIGGER tg_pgqueuer_changed"- , "AFTER INSERT OR UPDATE OR DELETE ON pgqueuer"+ [ "CREATE TRIGGER tg_pgqueuer_changed_insert_delete"+ , "AFTER INSERT OR DELETE ON pgqueuer" , "FOR EACH ROW EXECUTE FUNCTION fn_pgqueuer_changed();"+ , "CREATE TRIGGER tg_pgqueuer_changed_update"+ , "AFTER UPDATE ON pgqueuer"+ , "FOR EACH ROW"+ , "WHEN (OLD.status IS DISTINCT FROM NEW.status)"+ , "EXECUTE FUNCTION fn_pgqueuer_changed();" , "CREATE TRIGGER tg_pgqueuer_changed_truncate" , "AFTER TRUNCATE ON pgqueuer" , "FOR EACH STATEMENT EXECUTE FUNCTION fn_pgqueuer_changed();"
src/PGQueuer/Settings.hs view
@@ -1,25 +1,41 @@ {-# LANGUAGE OverloadedStrings #-} -module PGQueuer.Settings (- DBSettings (..),- defaultDBSettings,- queueTable,- queueTableLog,- statisticsTable,- schedulesTable,- queueStatusType,- function,- trigger,+{- |+Module : PGQueuer.Settings+Description : Configuration settings and table name resolvers for PGQueuer.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Provides 't:DBSettings' for configuring database table prefixes and+pub/sub channel names, along with helper functions resolving table names.+-}+module PGQueuer.Settings+ ( DBSettings (..)+ , defaultDBSettings+ , queueTable+ , queueTableLog+ , statisticsTable+ , schedulesTable+ , queueStatusType+ , function+ , trigger ) where import Data.Text (Text) import PGQueuer.Types (Channel, defaultChannel) +-- | Database schema configuration options. data DBSettings = DBSettings { dbPrefix :: Text+ -- ^ Optional prefix prepended to all table, function, and trigger names. , dbChannel :: Channel+ -- ^ PostgreSQL channel used for @LISTEN@ / @NOTIFY@ signals. }+ deriving (Show, Eq) +-- | Default settings with no prefix and standard channel @"ch_pgqueuer"@. defaultDBSettings :: DBSettings defaultDBSettings = DBSettings@@ -27,23 +43,30 @@ , dbChannel = defaultChannel } +-- | Resolved name of the primary active jobs table. queueTable :: DBSettings -> Text queueTable settings = dbPrefix settings <> "pgqueuer" +-- | Resolved name of the unlogged audit log table. queueTableLog :: DBSettings -> Text queueTableLog settings = dbPrefix settings <> "pgqueuer_log" +-- | Resolved name of the queue throughput statistics table. statisticsTable :: DBSettings -> Text statisticsTable settings = dbPrefix settings <> "pgqueuer_statistics" +-- | Resolved name of the recurring cron schedules table. schedulesTable :: DBSettings -> Text schedulesTable settings = dbPrefix settings <> "pgqueuer_schedules" +-- | Resolved name of the PostgreSQL status enum type. queueStatusType :: DBSettings -> Text queueStatusType settings = dbPrefix settings <> "pgqueuer_status" +-- | Resolved name of the database change trigger function. function :: DBSettings -> Text function settings = dbPrefix settings <> "fn_pgqueuer_changed" +-- | Resolved name of the database change trigger. trigger :: DBSettings -> Text trigger settings = dbPrefix settings <> "tg_pgqueuer_changed"
+ src/PGQueuer/Tracing.hs view
@@ -0,0 +1,92 @@+{-# LANGUAGE CPP #-}++{- |+Module : PGQueuer.Tracing+Description : OpenTelemetry distributed tracing and W3C trace context propagation.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Provides functions for injecting active OpenTelemetry contexts into job headers+at enqueue time and extracting them to create linked spans during execution.+Compiled conditionally with the @otel@ cabal flag.+-}+module PGQueuer.Tracing+ ( injectOtelContext+ , withJobSpan+ ) where++import Data.Aeson (Value (..))+import PGQueuer.Types (Entrypoint (..), JobId (..))++#ifdef OTEL+import qualified Data.Aeson.Key as K+import qualified Data.Aeson.KeyMap as KM+import qualified Data.CaseInsensitive as CI+import qualified Data.HashMap.Strict as HM+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified OpenTelemetry.Context as Context+import qualified OpenTelemetry.Context.ThreadLocal as ThreadLocal+import qualified OpenTelemetry.Propagator as Propagator+import qualified OpenTelemetry.Propagator.W3CTraceContext as W3C+import qualified OpenTelemetry.Trace.Core as Trace+import UnliftIO.Exception (catchAny, throwIO, bracket)+import Control.Monad (void)+#endif++-- | Serialize active OTel context to Aeson.Value+injectOtelContext :: IO (Maybe Value)+#ifdef OTEL+injectOtelContext = do+ mCtx <- ThreadLocal.lookupContext+ case mCtx of+ Nothing -> return Nothing+ Just ctx -> do+ let prop = W3C.w3cTraceContextPropagator+ headers <- Propagator.inject prop ctx []+ let obj = KM.fromList $ map (\(k, v) -> (K.fromText $ TE.decodeUtf8 $ CI.original k, String $ TE.decodeUtf8 v)) headers+ return $ Just (Object obj)+#else+injectOtelContext = return Nothing+#endif++-- | Wrap user execution in a new span, linking the parent context+withJobSpan :: Entrypoint -> JobId -> Maybe Value -> IO a -> IO a+#ifdef OTEL+withJobSpan (Entrypoint ep) (JobId jid) mHeaders action = do+ tp <- Trace.getGlobalTracerProvider+ let tracer = Trace.makeTracer tp "pgqueuer-hs" Trace.tracerOptions+ prop = W3C.w3cTraceContextPropagator+ headers = case mHeaders of+ Just (Object obj) ->+ [ (CI.mk $ TE.encodeUtf8 $ K.toText k, TE.encodeUtf8 s)+ | (k, String s) <- KM.toList obj+ ]+ _ -> []+ + let emptyCtx = Context.empty+ ctx <- Propagator.extract prop headers emptyCtx+ + let spanArgs = Trace.defaultSpanArguments + { Trace.attributes = HM.fromList + [ ("messaging.system", Trace.toAttribute ("pgqueuer" :: T.Text))+ , ("messaging.destination.name", Trace.toAttribute ep)+ , ("messaging.message.id", Trace.toAttribute (T.pack $ show jid))+ ]+ }+ + let restore prev = case prev of+ Nothing -> void ThreadLocal.detachContext+ Just c -> void (ThreadLocal.attachContext c)++ bracket (ThreadLocal.attachContext ctx) restore $ \_ -> do+ Trace.inSpan' tracer ("process " <> ep) spanArgs $ \otelSpan -> do+ action `catchAny` \e -> do+ Trace.setStatus otelSpan (Trace.Error (T.pack $ show e))+ Trace.recordException otelSpan HM.empty Nothing e+ throwIO e+#else+withJobSpan _ _ _ action = action+#endif
src/PGQueuer/Types.hs view
@@ -1,67 +1,125 @@+{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} -module PGQueuer.Types (- JobId (..),- ScheduleId (..),- Entrypoint (..),- Channel (..),- EntrypointExecutionParameter (..),- Job (..),- JobStatus (..),- QueueStatistics (..),- OnFailure (..),- onFailureToText,- textToOnFailure,- defaultHeartbeatTimeout,- defaultBatchSize,- jobStatusToText,- defaultChannel,+{- |+Module : PGQueuer.Types+Description : Core domain models, data types, and parameters for PGQueuer.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++This module defines all primary domain representations for PGQueuer: jobs,+schedules, statuses, failure strategies, jitter algorithms, retry backoffs,+and event payloads received from PostgreSQL @LISTEN@ / @NOTIFY@ channels.+-}+module PGQueuer.Types+ ( -- * Identifiers & Labels+ JobId (..)+ , ScheduleId (..)+ , Entrypoint (..)+ , CronExpression (..)+ , Channel (..)++ -- * Job Representation & Lifecycle+ , Job (..)+ , JobStatus (..)+ , jobStatusToText+ , textToJobStatus++ -- * Execution & Worker Configuration+ , EntrypointExecutionParameter (..)+ , BackoffStrategy (..)+ , Jitter (..)+ , OnFailure (..)+ , onFailureToText+ , textToOnFailure++ -- * Scheduling+ , Schedule (..)++ -- * Logging & Statistics+ , QueueStatistics (..)+ , LogEntry (..)+ , LogStatistics (..)+ , TracebackRecord (..)++ -- * Events & Notifications+ , Operation (..)+ , Event (..)++ -- * Exceptions+ , JobRetryableException (..)+ , JobPermanentException (..)++ -- * Defaults+ , defaultChannel+ , defaultBatchSize+ , defaultHeartbeatTimeout ) where -import Data.Aeson (Value)+import Data.Aeson (FromJSON, ToJSON, Value) import qualified Data.ByteString.Lazy as BL import Data.Maybe (fromMaybe) import Data.Text (Text)-import Data.Time (UTCTime)+import Data.Time (NominalDiffTime, UTCTime) import Data.UUID (UUID) import Database.PostgreSQL.Simple.FromField (FromField (..)) import Database.PostgreSQL.Simple.FromRow (FromRow (..), field) import Database.PostgreSQL.Simple.ToField (ToField (..)) import GHC.Generics (Generic)+import UnliftIO.Exception (Exception) +-- | Unique integer identifier for an enqueued job. newtype JobId = JobId Int deriving stock (Show, Eq, Ord, Generic)- deriving newtype (FromField, ToField)+ deriving newtype (FromField, ToField, FromJSON, ToJSON) +-- | Unique integer identifier for a recurring cron schedule. newtype ScheduleId = ScheduleId Int deriving stock (Show, Eq, Ord, Generic)- deriving newtype (FromField, ToField)+ deriving newtype (FromField, ToField, FromJSON, ToJSON) +-- | Named destination / routing key that associates a job with its handler. newtype Entrypoint = Entrypoint Text deriving stock (Show, Eq, Ord, Generic)- deriving newtype (FromField, ToField)+ deriving newtype (FromField, ToField, FromJSON, ToJSON) +-- | 5-field cron expression string (e.g. @"* * * * *"@ or @"0 0 * * *"@). newtype CronExpression = CronExpression Text deriving stock (Show, Eq, Ord, Generic)- deriving newtype (FromField, ToField)+ deriving newtype (FromField, ToField, FromJSON, ToJSON) +-- | PostgreSQL pub/sub channel name for @LISTEN@ / @NOTIFY@ signals. newtype Channel = Channel Text deriving stock (Show, Eq, Ord, Generic)- deriving newtype (FromField, ToField)+ deriving newtype (FromField, ToField, FromJSON, ToJSON) +-- | Lifecycle states of a job in the queue. data JobStatus- = Queued- | Picked- | Successful- | Failed- | Exception- | Canceled- | Deleted+ = -- | Job is waiting in the database to be claimed by an active worker.+ Queued+ | -- | Job has been claimed by a worker using @FOR UPDATE SKIP LOCKED@.+ Picked+ | -- | Job processing completed successfully.+ Successful+ | -- | Job failed and has exhausted its retry attempts.+ Failed+ | -- | Job execution resulted in an unhandled exception or crash.+ Exception+ | -- | Job was explicitly cancelled via 'PGQueuer.markJobAsCancelled'.+ Canceled+ | -- | Job was deleted or purged from the queue ledger.+ Deleted+ | -- | Job is held waiting for upstream dependency jobs (DAG workflow).+ Held deriving stock (Show, Eq, Ord, Generic, Bounded, Enum)+ deriving anyclass (FromJSON, ToJSON) +-- | Convert a 'JobStatus' to its lowercase PostgreSQL enum text representation. jobStatusToText :: JobStatus -> Text jobStatusToText Queued = "queued" jobStatusToText Picked = "picked"@@ -70,7 +128,9 @@ jobStatusToText Exception = "exception" jobStatusToText Canceled = "canceled" jobStatusToText Deleted = "deleted"+jobStatusToText Held = "held" +-- | Parse a 'JobStatus' from its PostgreSQL text enum representation. textToJobStatus :: Text -> Maybe JobStatus textToJobStatus "queued" = Just Queued textToJobStatus "picked" = Just Picked@@ -79,6 +139,7 @@ textToJobStatus "exception" = Just Exception textToJobStatus "canceled" = Just Canceled textToJobStatus "deleted" = Just Deleted+textToJobStatus "held" = Just Held textToJobStatus _ = Nothing instance FromField JobStatus where@@ -87,126 +148,268 @@ instance ToField JobStatus where toField = toField . jobStatusToText +-- | Database table change operations emitted by trigger functions. data Operation- = Insert- | Update- | Delete- | Truncate+ = -- | An INSERT statement occurred.+ Insert+ | -- | An UPDATE statement occurred.+ Update+ | -- | A DELETE statement occurred.+ Delete+ | -- | A TRUNCATE statement occurred.+ Truncate deriving stock (Show, Eq, Ord, Generic, Bounded, Enum)+ deriving anyclass (FromJSON, ToJSON) +-- | Asynchronous event notification payload broadcast over PostgreSQL pub/sub channels. data Event- = TableChangedEvent+ = -- | Trigger notification indicating queue table mutations.+ TableChangedEvent { eventChannel :: Channel+ -- ^ Channel the notification was broadcast over. , eventSentAt :: UTCTime+ -- ^ Timestamp when the notification was generated. , eventOperation :: Operation+ -- ^ Specific database DML operation performed. , eventTable :: Text+ -- ^ Target table name modified. }- | CancellationEvent+ | -- | Explicit cancellation signal for a list of job IDs.+ CancellationEvent { eventChannel :: Channel+ -- ^ Channel the cancellation was sent over. , eventSentAt :: UTCTime+ -- ^ Timestamp of cancellation dispatch. , eventIds :: [JobId]+ -- ^ Target job IDs marked for cancellation. }- | HealthCheckEvent+ | -- | Keepalive or heartbeat ping signal from an active manager.+ HealthCheckEvent { eventChannel :: Channel+ -- ^ Channel carrying the health check. , eventSentAt :: UTCTime+ -- ^ Ping timestamp. , eventId :: UUID+ -- ^ Originating queue manager UUID. } deriving stock (Show, Generic)+ deriving anyclass (FromJSON, ToJSON) +-- | Full database record representing an active or historical job. data Job = Job { jobId :: JobId+ -- ^ Unique primary key of the job. , jobPriority :: Int+ -- ^ Integer priority (lower numerical values dequeue first). , jobCreated :: UTCTime+ -- ^ Timestamp when the job was initially inserted. , jobUpdated :: UTCTime+ -- ^ Timestamp of the most recent state or field modification. , jobHeartbeat :: UTCTime+ -- ^ Worker keepalive timestamp (used to detect dead/stalled workers). , jobExecuteAfter :: UTCTime+ -- ^ Earliest time this job may be claimed for execution. , jobStatus :: JobStatus+ -- ^ Current lifecycle status of the job. , jobEntrypoint :: Entrypoint+ -- ^ Destination entrypoint that handles this job. , jobPayload :: Maybe BL.ByteString+ -- ^ Raw binary or serialized JSON payload. , jobAttempts :: Int+ -- ^ Number of execution attempts completed so far. , jobQueueManagerId :: Maybe UUID+ -- ^ UUID of the worker node currently holding this job. , jobHeaders :: Maybe Value+ -- ^ Optional metadata headers (e.g. OpenTelemetry trace contexts).+ , jobParentId :: Maybe JobId+ -- ^ Parent job ID for DAG workflow dependencies.+ , jobParentState :: Maybe Value+ -- ^ State passed to or collected by parent workflow nodes. } deriving stock (Show, Eq, Generic) +-- | Full database record representing a scheduled recurring cron job.+data Schedule = Schedule+ { scheduleId :: ScheduleId+ -- ^ Unique primary key of the recurring schedule.+ , scheduleExpression :: CronExpression+ -- ^ Cron expression defining recurring trigger intervals.+ , scheduleEntrypoint :: Entrypoint+ -- ^ Target entrypoint to dispatch jobs to when triggered.+ , scheduleHeartbeat :: UTCTime+ -- ^ Scheduler keepalive timestamp.+ , scheduleCreated :: UTCTime+ -- ^ Timestamp when this schedule was registered.+ , scheduleUpdated :: UTCTime+ -- ^ Timestamp of the latest update.+ , scheduleNextRun :: UTCTime+ -- ^ Target timestamp for the next job emission.+ , scheduleLastRun :: Maybe UTCTime+ -- ^ Timestamp when the last job was dispatched, if any.+ , scheduleStatus :: JobStatus+ -- ^ Current status of the schedule record.+ }+ deriving stock (Show, Eq, Generic)++-- | Entry logged to the unlogged @pgqueuer_log@ table for high-throughput audit tracking. data LogEntry = LogEntry { logCreated :: UTCTime+ -- ^ Creation timestamp of the log event. , logJobId :: JobId+ -- ^ Job ID associated with this log record. , logStatus :: JobStatus+ -- ^ Status recorded in this transition. , logPriority :: Int+ -- ^ Priority of the associated job. , logEntrypoint :: Entrypoint+ -- ^ Entrypoint of the associated job. , logTraceback :: Maybe Value+ -- ^ Stack trace or error payload captured on failure. , logAggregated :: Bool+ -- ^ Whether this entry has been folded into statistics.+ , logParentId :: Maybe JobId+ -- ^ Parent job ID if part of a workflow. } deriving stock (Show, Eq, Generic) +-- | Aggregated queue throughput and depth metrics. data QueueStatistics = QueueStatistics { statsCount :: Int+ -- ^ Number of jobs matching this grouping. , statsEntrypoint :: Entrypoint+ -- ^ Target entrypoint. , statsPriority :: Int+ -- ^ Priority level. , statsStatus :: JobStatus+ -- ^ Job lifecycle status. } deriving stock (Show, Eq, Generic)+ deriving anyclass (FromJSON, ToJSON) +-- | Aggregated historical log entry metrics. data LogStatistics = LogStatistics { logStatsCount :: Int+ -- ^ Aggregated count of events. , logStatsCreated :: UTCTime+ -- ^ Aggregation window bucket timestamp. , logStatsEntrypoint :: Entrypoint+ -- ^ Entrypoint category. , logStatsPriority :: Int+ -- ^ Priority level. , logStatsStatus :: JobStatus- }- deriving stock (Show, Eq, Generic)--data Schedule = Schedule- { scheduleId :: ScheduleId- , scheduleExpression :: CronExpression- , scheduleEntrypoint :: Entrypoint- , scheduleHeartbeat :: UTCTime- , scheduleCreated :: UTCTime- , scheduleUpdated :: UTCTime- , scheduleNextRun :: UTCTime- , scheduleLastRun :: Maybe UTCTime- , scheduleStatus :: JobStatus+ -- ^ Status recorded. } deriving stock (Show, Eq, Generic)+ deriving anyclass (FromJSON, ToJSON) +-- | Captured exception type, error message, and formatted callstack. data TracebackRecord = TracebackRecord { traceJobId :: JobId+ -- ^ Job ID that failed. , traceTimestamp :: UTCTime+ -- ^ Time exception occurred. , traceExceptionType :: Text+ -- ^ Stringified exception type / constructor. , traceExceptionMessage :: Text+ -- ^ Detailed exception message. , traceTraceback :: Text+ -- ^ Formatted call stack or traceback. } deriving stock (Show, Eq, Generic)+ deriving anyclass (FromJSON, ToJSON) +-- | Action to take when a job exceeds its maximum retry threshold. data OnFailure- = OnDelete- | OnHold+ = -- | Permanently remove the failed job from the queue ledger.+ OnDelete+ | -- | Retain the job in the dead-letter 'Held' state for manual triage.+ OnHold deriving stock (Show, Eq, Ord, Generic, Bounded, Enum)+ deriving anyclass (FromJSON, ToJSON) +-- | Convert an 'OnFailure' action to its text representation. onFailureToText :: OnFailure -> Text onFailureToText OnDelete = "delete" onFailureToText OnHold = "hold" +-- | Parse an 'OnFailure' action from its text representation. textToOnFailure :: Text -> Maybe OnFailure textToOnFailure "delete" = Just OnDelete textToOnFailure "hold" = Just OnHold textToOnFailure _ = Nothing +-- | Configuration parameters controlling execution limits and retry resilience per entrypoint. data EntrypointExecutionParameter = EntrypointExecutionParameter { paramEntrypoint :: Entrypoint+ -- ^ Target entrypoint to configure. , paramConcurrencyLimit :: Int+ -- ^ Maximum simultaneous active jobs for this entrypoint across workers (0 = unlimited).+ , paramMaxAttempts :: Int+ -- ^ Maximum allowed retry attempts before declaring failure.+ , paramBackoffStrategy :: BackoffStrategy+ -- ^ Mathematical formula calculating retry delays.+ , paramJitter :: Jitter+ -- ^ Random jitter formula applied to delay calculations. } deriving stock (Show, Eq, Generic)+ deriving anyclass (FromJSON, ToJSON) +-- | Strategy used for calculating backoff delays on job retries.+data BackoffStrategy+ = -- | Delay scales exponentially: @delay = min cap (base * 2^(attempts - 1))@.+ Exponential+ { backoffBase :: NominalDiffTime+ -- ^ Base retry delay.+ , backoffCap :: NominalDiffTime+ -- ^ Maximum delay cap.+ }+ | -- | Delay scales linearly: @delay = min cap (base * attempts)@.+ Linear+ { backoffBase :: NominalDiffTime+ -- ^ Base retry multiplier.+ , backoffCap :: NominalDiffTime+ -- ^ Maximum delay cap.+ }+ | -- | Constant delay regardless of attempt count.+ Constant+ { backoffDelay :: NominalDiffTime+ -- ^ Fixed retry delay.+ }+ deriving stock (Show, Eq, Generic)+ deriving anyclass (FromJSON, ToJSON)++-- | Randomization strategy applied to retry delays to prevent thundering herd problems.+data Jitter+ = -- | Apply no randomization; use exact calculated delay.+ NoJitter+ | -- | Uniform random delay between 0 and calculated delay: @[0, delay)@.+ FullJitter+ | -- | Half deterministic, half uniform random: @delay / 2 + random([0, delay / 2))@.+ EqualJitter+ deriving stock (Show, Eq, Generic)+ deriving anyclass (FromJSON, ToJSON)++-- | Exception indicating a transient, recoverable failure. Causes the job to be rescheduled with backoff.+newtype JobRetryableException = JobRetryableException Text+ deriving stock (Show, Eq)+ deriving anyclass (Exception)++-- | Exception indicating a fatal, non-recoverable failure. Immediately marks the job as permanently failed or held.+newtype JobPermanentException = JobPermanentException Text+ deriving stock (Show, Eq)+ deriving anyclass (Exception)++-- | Default PostgreSQL pub/sub channel name (@ch_pgqueuer@). defaultChannel :: Channel defaultChannel = Channel "ch_pgqueuer" +-- | Default batch size for fetching jobs (100). defaultBatchSize :: Int defaultBatchSize = 100 +-- | Default worker heartbeat timeout in seconds (300 seconds / 5 minutes). defaultHeartbeatTimeout :: Int-defaultHeartbeatTimeout = 300 -- 5 minutes in seconds+defaultHeartbeatTimeout = 300 instance FromRow Job where fromRow =@@ -223,6 +426,8 @@ <*> field -- jobAttempts <*> field -- jobQueueManagerId <*> field -- jobHeaders+ <*> field -- jobParentId+ <*> field -- jobParentState instance FromRow LogEntry where fromRow =@@ -234,6 +439,7 @@ <*> field -- logEntrypoint <*> field -- logTraceback <*> field -- logAggregated+ <*> field -- logParentId instance FromRow QueueStatistics where fromRow =
+ src/PGQueuer/Worker/Backoff.hs view
@@ -0,0 +1,54 @@+{- |+Module : PGQueuer.Worker.Backoff+Description : Retry backoff and jitter calculations.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++This module provides data types and functions to calculate backoff delays+and apply jitter for retrying failed jobs.+-}+module PGQueuer.Worker.Backoff+ ( BackoffStrategy (..)+ , Jitter (..)+ , calculateBackoff+ , applyJitter+ ) where++import Data.Time.Clock (NominalDiffTime)+import System.Random (randomRIO)++import PGQueuer.Types (BackoffStrategy (..), Jitter (..))++{- | Calculate the base backoff delay before applying jitter.+The attempt parameter should be the number of attempts already made (e.g., if failing on the first attempt, attempts=1).+-}+calculateBackoff :: BackoffStrategy -> Int -> NominalDiffTime+calculateBackoff (Constant delay) _ = delay+calculateBackoff (Linear base cap) attempts =+ let calculated = base * fromIntegral attempts+ in min cap calculated+calculateBackoff (Exponential base cap) attempts =+ -- For exponential, commonly delay = base * 2^(attempts - 1)+ let calculated = base * (2 ^ (attempts - 1))+ in min cap calculated++-- | Apply jitter to a calculated delay.+applyJitter :: Jitter -> NominalDiffTime -> IO NominalDiffTime+applyJitter NoJitter delay = return delay+applyJitter FullJitter delay = do+ let maxMs = round ((realToFrac delay :: Double) * 1000) :: Int+ if maxMs <= 0+ then return delay+ else do+ jitterMs <- randomRIO (0, maxMs)+ return $ realToFrac (fromIntegral jitterMs :: Double) / 1000+applyJitter EqualJitter delay = do+ let halfDelay = delay / 2+ maxMs = round ((realToFrac halfDelay :: Double) * 1000) :: Int+ if maxMs <= 0+ then return delay+ else do+ jitterMs <- randomRIO (0, maxMs)+ return $ halfDelay + (realToFrac (fromIntegral jitterMs :: Double) / 1000)
+ src/PGQueuer/Worker/Buffer.hs view
@@ -0,0 +1,315 @@+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE ScopedTypeVariables #-}++{- |+Module : PGQueuer.Worker.Buffer+Description : STM-backed timed overflow buffer for bulk database writes.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Provides a generic 't:TimedOverflowBuffer' that decouples worker threads+from database round-trips. Items are pushed into a bounded STM queue.+A dedicated flusher thread wakes when either:++ 1. The buffer reaches 'bcMaxSize' items (overflow trigger), or+ 2. A periodic timer of 'bcFlushInterval' microseconds expires and+ the queue is non-empty.++All items are then drained and flushed to the database in a single+bulk operation, dramatically reducing per-job WAL write amplification.++The 'withBuffer' bracket ensures the flusher thread is cleanly shut+down and all remaining items are drained on exit.+-}+module PGQueuer.Worker.Buffer+ ( -- * Configuration+ BufferConfig (..)+ , defaultBufferConfig++ -- * Core buffer type+ , TimedOverflowBuffer++ -- * Lifecycle+ , newBuffer+ , withBuffer++ -- * Operations+ , add+ , flushBuffer++ -- * Specialized sinks+ , JobStatusLogBuffer+ , mkJobStatusLogBuffer+ , HeartbeatBuffer+ , mkHeartbeatBuffer+ , RetryBuffer+ , mkRetryBuffer+ ) where++import Control.Concurrent.Async (async, uninterruptibleCancel)+import Control.Concurrent.STM+import Control.Exception (SomeException, bracket, catch)+import Control.Monad (unless, void, when)+import Data.Aeson (Value)+import Data.Int (Int32)+import Data.Time (UTCTime)+import PGQueuer.Types (JobId, JobStatus)++-- ============================================================================+-- Configuration+-- ============================================================================++-- | Configuration for a 't:TimedOverflowBuffer'.+data BufferConfig = BufferConfig+ { bcMaxSize :: !Int+ -- ^ Maximum number of items before an immediate flush is triggered.+ , bcFlushInterval :: !Int+ {- ^ Flush interval in microseconds. The flusher thread will wake+ at most this often even if the buffer hasn't overflowed.+ -}+ }+ deriving (Show, Eq)++-- | Default buffer configuration: 100 items max, 100ms flush interval.+defaultBufferConfig :: BufferConfig+defaultBufferConfig =+ BufferConfig+ { bcMaxSize = 100+ , bcFlushInterval = 100_000 -- 100ms in microseconds+ }++-- ============================================================================+-- Core buffer type+-- ============================================================================++{- | A generic STM-backed timed overflow buffer.++Items of type @a@ are enqueued by worker threads via 'add'. A dedicated+background flusher thread drains the queue and calls the flush action+when either the overflow threshold or the timer fires.+-}+data TimedOverflowBuffer a = TimedOverflowBuffer+ { bufQueue :: !(TBQueue a)+ -- ^ Bounded STM queue holding buffered items+ , bufCount :: !(TVar Int)+ -- ^ Current element count (O(1) reads, avoids O(n) lengthTBQueue)+ , bufOverflow :: !(TMVar ())+ -- ^ Overflow trigger: filled when count reaches maxSize+ , bufMaxSize :: !Int+ -- ^ Maximum buffer size before overflow+ , bufFlushInterval :: !Int+ -- ^ Flush interval in microseconds+ , bufFlushAction :: [a] -> IO ()+ -- ^ Callback to flush accumulated items to the database+ , bufShutdown :: !(TVar Bool)+ -- ^ Set to True to signal the flusher thread to exit+ }++-- ============================================================================+-- Construction+-- ============================================================================++{- | Create a new 't:TimedOverflowBuffer'. Does NOT start the flusher thread;+use 'withBuffer' for a fully managed lifecycle.+-}+newBuffer :: BufferConfig -> ([a] -> IO ()) -> IO (TimedOverflowBuffer a)+newBuffer config flushAction = do+ queue <- newTBQueueIO (fromIntegral $ bcMaxSize config)+ count <- newTVarIO 0+ overflow <- newEmptyTMVarIO+ shutdown <- newTVarIO False+ return+ TimedOverflowBuffer+ { bufQueue = queue+ , bufCount = count+ , bufOverflow = overflow+ , bufMaxSize = bcMaxSize config+ , bufFlushInterval = bcFlushInterval config+ , bufFlushAction = flushAction+ , bufShutdown = shutdown+ }++-- ============================================================================+-- Operations+-- ============================================================================++{- | Add an item to the buffer.++If adding this item causes the buffer count to reach 'bcMaxSize',+the overflow trigger is signalled, causing the flusher thread to+wake immediately and flush all items.++This function never blocks on a full queue — the TBQueue capacity+equals maxSize, and we flush at maxSize, so there's always room+unless the flusher is severely lagging. In that pathological case,+the STM retry on the full TBQueue provides natural backpressure.+-}+add :: TimedOverflowBuffer a -> a -> IO ()+add buf item = atomically $ do+ writeTBQueue (bufQueue buf) item+ n <- readTVar (bufCount buf)+ let n' = n + 1+ writeTVar (bufCount buf) n'+ when (n' >= bufMaxSize buf)+ $+ -- Signal overflow; tryPutTMVar is idempotent if already full+ void+ $ tryPutTMVar (bufOverflow buf) ()++{- | Drain all items from the buffer in a single STM transaction.++Returns an empty list if the queue is empty. Resets the count to 0+and clears the overflow trigger.+-}+drainAll :: TimedOverflowBuffer a -> STM [a]+drainAll buf = do+ items <- drainQueue (bufQueue buf)+ writeTVar (bufCount buf) 0+ -- Clear overflow trigger if it was set+ _ <- tryTakeTMVar (bufOverflow buf)+ return items++-- | Drain a TBQueue into a list (oldest first).+drainQueue :: TBQueue a -> STM [a]+drainQueue q = go []+ where+ go acc = do+ mItem <- tryReadTBQueue q+ case mItem of+ Nothing -> return (reverse acc)+ Just item -> go (item : acc)++{- | Flush the buffer: drain all items and call the flush action.+Does nothing if the buffer is empty.+-}+flushBuffer :: TimedOverflowBuffer a -> IO ()+flushBuffer buf = do+ items <- atomically (drainAll buf)+ unless (null items) $+ bufFlushAction buf items++-- ============================================================================+-- Periodic flusher+-- ============================================================================++{- | Background flusher loop.++Waits for either:+ 1. The overflow trigger (immediate flush), or+ 2. The timer to expire AND the queue to be non-empty.++On shutdown signal, performs one final drain and exits.+-}+periodicFlusher :: TimedOverflowBuffer a -> IO ()+periodicFlusher buf = loop+ where+ loop = do+ -- Create a fresh timer for this iteration+ timerVar <- registerDelay (bufFlushInterval buf)++ -- Wait for a wake-up condition+ shouldExit <- atomically $ do+ isShutdown <- readTVar (bufShutdown buf)+ if isShutdown+ then return True+ else do+ -- Try overflow trigger first+ let overflowWake = takeTMVar (bufOverflow buf) >> return False+ -- Or wait for timer + non-empty queue+ let timerWake = do+ expired <- readTVar timerVar+ check expired+ cnt <- readTVar (bufCount buf)+ check (cnt > 0)+ return False+ -- Or shutdown+ let shutdownWake = do+ s <- readTVar (bufShutdown buf)+ check s+ return True+ overflowWake `orElse` timerWake `orElse` shutdownWake++ -- Flush whatever we have+ flushBuffer buf+ `catch` (\(_ :: SomeException) -> return ())++ unless shouldExit loop++-- ============================================================================+-- Managed lifecycle+-- ============================================================================++{- | Run an action with a managed buffer.++Starts the periodic flusher in a background thread, runs the provided+action, and on exit:++ 1. Signals the flusher to shut down.+ 2. Cancels the flusher thread.+ 3. Performs a final drain to ensure no items are lost.++This provides clean graceful shutdown via 'bracket'.+-}+withBuffer ::+ BufferConfig ->+ ([a] -> IO ()) ->+ (TimedOverflowBuffer a -> IO b) ->+ IO b+withBuffer config flushAction action =+ bracket+ ( do+ buf <- newBuffer config flushAction+ flusherThread <- async (periodicFlusher buf)+ return (buf, flusherThread)+ )+ ( \(buf, flusherThread) -> do+ -- Signal shutdown+ atomically $ writeTVar (bufShutdown buf) True+ -- Cancel the flusher thread+ uninterruptibleCancel flusherThread+ -- Final drain — don't lose any buffered items+ flushBuffer buf+ )+ (\(buf, _) -> action buf)++-- ============================================================================+-- Specialized sinks+-- ============================================================================++{- | A buffer specialized for job status logging.+Buffers @(JobId, JobStatus, Maybe Value)@ tuples for bulk ACK.+-}+type JobStatusLogBuffer = TimedOverflowBuffer (JobId, JobStatus, Maybe Value)++{- | A buffer specialized for heartbeat updates.+Buffers @JobId@s for bulk heartbeat refresh.+-}+type HeartbeatBuffer = TimedOverflowBuffer JobId++-- | Create a 'JobStatusLogBuffer' with the given flush action.+mkJobStatusLogBuffer ::+ BufferConfig ->+ ([(JobId, JobStatus, Maybe Value)] -> IO ()) ->+ IO JobStatusLogBuffer+mkJobStatusLogBuffer = newBuffer++-- | Create a 'HeartbeatBuffer' with the given flush action.+mkHeartbeatBuffer ::+ BufferConfig ->+ ([JobId] -> IO ()) ->+ IO HeartbeatBuffer+mkHeartbeatBuffer = newBuffer++{- | A buffer specialized for job retries.+Buffers @(JobId, UTCTime, Int32)@ tuples for bulk retry update.+-}+type RetryBuffer = TimedOverflowBuffer (JobId, UTCTime, Int32)++-- | Create a 'RetryBuffer' with the given flush action.+mkRetryBuffer ::+ BufferConfig ->+ ([(JobId, UTCTime, Int32)] -> IO ()) ->+ IO RetryBuffer+mkRetryBuffer = newBuffer
+ src/PGQueuer/Worker/Cron.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE ScopedTypeVariables #-}++{- |+Module : PGQueuer.Worker.Cron+Description : SchedulerManager for distributed Cron Jobs.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++This module provides the logic for the distributed cron scheduler loop.+-}+module PGQueuer.Worker.Cron+ ( runCronScheduler+ , calculateNextRunTime+ ) where++import Control.Concurrent (threadDelay)+import Control.Exception (SomeException, catch)+import Control.Monad (forM_, forever)+import Data.Time (UTCTime, diffUTCTime, getCurrentTime)+import Database.PostgreSQL.Simple (Connection)+import System.Cron (nextMatch, parseCronSchedule)++import qualified PGQueuer.Query as Q+import PGQueuer.Settings (DBSettings)+import PGQueuer.Types++-- | Calculate the next run time for a given cron expression and reference time.+calculateNextRunTime :: CronExpression -> UTCTime -> Either String UTCTime+calculateNextRunTime (CronExpression exprText) refTime =+ case parseCronSchedule exprText of+ Left err -> Left err+ Right schedule ->+ case nextMatch schedule refTime of+ Just nextTime -> Right nextTime+ Nothing -> Left "No matching future run time found for cron schedule"++-- | Run the cron scheduler loop.+runCronScheduler :: Connection -> DBSettings -> IO ()+runCronScheduler conn settings = forever $ do+ -- 1. Fetch schedules that are due (status = 'queued' AND next_run <= NOW())+ -- This uses FOR UPDATE SKIP LOCKED to prevent other workers from picking them up.+ schedules <- Q.fetchSchedules conn settings `catch` (\(_ :: SomeException) -> return [])++ now <- getCurrentTime++ -- 2. For each picked schedule, dispatch a job to the queue and reset its state+ forM_ schedules $ \schedule -> do+ let ep = scheduleEntrypoint schedule+ sid = scheduleId schedule++ -- Enqueue the job for the cron task+ _ <-+ Q.enqueueMultiple+ conn+ settings+ [ep]+ [Nothing]+ [0]+ [Nothing]+ [Nothing]+ [Nothing]+ [Nothing]+ [Nothing]+ [Queued]+ `catch` (\(_ :: SomeException) -> return [])++ -- Calculate next run using the cron expression+ let nextRun = case calculateNextRunTime (scheduleExpression schedule) now of+ Right nextTime -> nextTime+ Left _ -> now++ -- Reset schedule state back to queued+ Q.setScheduleQueued conn settings sid nextRun+ `catch` (\(_ :: SomeException) -> return ())++ -- 3. Calculate sleep time+ -- Get the earliest next_run across all queued schedules+ mbEarliest <- Q.getEarliestNextRun conn settings `catch` (\(_ :: SomeException) -> return Nothing)+ sleepTime <-+ getCurrentTime >>= \newNow ->+ case mbEarliest of+ Just earliest -> do+ let diff = diffUTCTime earliest newNow+ if diff <= 0+ then return 1 -- Immediate retry if something is due+ else return (min (ceiling diff * 1000000) 60000000) -- Sleep up to 60s+ Nothing -> return 60000000 -- Default to 60s if no schedules exist+ threadDelay sleepTime
+ src/PGQueuer/Workflow.hs view
@@ -0,0 +1,87 @@+{-# LANGUAGE DerivingStrategies #-}++{- |+Module : PGQueuer.Workflow+Description : Directed Acyclic Graph (DAG) workflows and dependency job trees.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental++Provides support for hierarchical, tree-structured job dependencies.+A parent job can be submitted along with a set of dependent child jobs;+the parent is atomically held until all children reach 'Successful' completion,+at which point the parent is automatically released into the active queue and+can access its children's aggregated results.+-}+module PGQueuer.Workflow+ ( JobNode (..)+ , JobTree (..)+ , (<~~)+ , insertJobTree+ )+where++import Control.Monad (foldM_)+import Data.Aeson (Value)+import qualified Data.ByteString.Lazy as BL+import Data.Maybe (listToMaybe)+import Data.Text (Text)+import Data.Time (NominalDiffTime)+import PGQueuer.Core.Monad (MonadPGQueuer (..))+import PGQueuer.Types (Entrypoint, JobId (..), JobStatus (..))++-- | A single node representing a job's parameters within a 't:JobTree'.+data JobNode = JobNode+ { jnEntrypoint :: Entrypoint+ -- ^ Target entrypoint to process this job.+ , jnPayload :: Maybe BL.ByteString+ -- ^ Optional binary or JSON payload.+ , jnPriority :: Int+ -- ^ Execution priority (lower values dequeue earlier).+ , jnExecuteAfter :: Maybe NominalDiffTime+ -- ^ Optional execution delay.+ , jnDedupeKey :: Maybe Text+ -- ^ Optional deduplication key.+ , jnHeaders :: Maybe Value+ -- ^ Optional metadata headers.+ , jnParentState :: Maybe Value+ -- ^ Initial state passed down from a parent job.+ }+ deriving stock (Show, Eq)++-- | A tree of jobs where the parent node waits for all child subtrees to complete.+data JobTree = JobTree JobNode [JobTree]+ deriving stock (Show, Eq)++-- | Infix operator to construct a 't:JobTree' from a parent node and list of child trees.+(<~~) :: JobNode -> [JobTree] -> JobTree+(<~~) = JobTree++infixr 5 <~~++{- | Insert a 't:JobTree' into the database queue.+If the tree has child jobs, the parent is inserted with 'Held' status and+will only transition to 'Queued' when all children have completed.+Entire tree insertion occurs within a single atomic database transaction.+-}+insertJobTree :: (MonadPGQueuer m) => JobTree -> m ()+insertJobTree tree = withTransaction $ go Nothing tree+ where+ go :: (MonadPGQueuer m) => Maybe JobId -> JobTree -> m ()+ go mParent (JobTree node children) = do+ let status = if null children then Queued else Held+ jobIds <-+ enqueue+ (jnEntrypoint node)+ (jnPayload node)+ (jnPriority node)+ (jnExecuteAfter node)+ (jnDedupeKey node)+ (jnHeaders node)+ mParent+ (jnParentState node)+ status+ case listToMaybe jobIds of+ Nothing -> pure ()+ Just parentId -> foldM_ (\_ child -> go (Just parentId) child) () children
test/Spec.hs view
@@ -1,4 +1,48 @@-import Tests.PGQueuer+{-# LANGUAGE OverloadedStrings #-} +module Main (main) where++import System.Environment (lookupEnv)+import Test.Tasty+import Test.Tasty.Runners (NumThreads (..))+import Tests.BackoffSpec (backoffTests)+import Tests.BufferSpec (bufferTests)+import Tests.CronSpec (cronTests)+import Tests.HasqlSpec (hasqlCoreTestsWith)+import Tests.PGQueuer (pgqueuerTestsWith)+import Tests.SimpleSpec (simpleCoreTestsWith)+import Tests.TestContainer (resolveConnStr, withPostgresTestContainer)+import Tests.TypesSpec (typesTests)+import Tests.WorkflowSpec (workflowTests)+ main :: IO ()-main = runTests+main = do+ useTC <- lookupEnv "USE_TESTCONTAINERS"+ let runTestContainers = case useTC of+ Just v | v `elem` ["1", "true", "TRUE", "yes", "YES"] -> True+ _ -> False++ let e2eGroup label getConnStr =+ testGroup+ label+ [ pgqueuerTestsWith getConnStr+ , testGroup+ "Core - Backend Parity"+ [ simpleCoreTestsWith getConnStr+ , hasqlCoreTestsWith getConnStr+ ]+ ]++ defaultMain+ $ localOption (NumThreads 1)+ $ testGroup+ "PGQueuer"+ [ typesTests+ , cronTests+ , bufferTests+ , workflowTests+ , backoffTests+ , if runTestContainers+ then withPostgresTestContainer (e2eGroup "End-to-End Tests (Testcontainers PostgreSQL 16)")+ else e2eGroup "End-to-End Tests" resolveConnStr+ ]
+ test/Tests/BackoffSpec.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE OverloadedStrings #-}++module Tests.BackoffSpec (backoffTests) where++import PGQueuer.Types+import PGQueuer.Worker.Backoff+import Test.Tasty+import Test.Tasty.HUnit++backoffTests :: TestTree+backoffTests =+ testGroup+ "Backoff & Jitter Tests"+ [ testGroup+ "calculateBackoff"+ [ testCase "Constant strategy returns the constant delay" $ do+ let strategy = Constant 10+ calculateBackoff strategy 1 @?= 10+ calculateBackoff strategy 5 @?= 10+ , testCase "Linear strategy calculates base * attempts and respects cap" $ do+ let strategy = Linear 5 20+ calculateBackoff strategy 1 @?= 5+ calculateBackoff strategy 3 @?= 15+ calculateBackoff strategy 5 @?= 20 -- Capped at 20 (5 * 5 = 25)+ , testCase "Exponential strategy calculates base * 2^(attempts-1) and respects cap" $ do+ let strategy = Exponential 2 30+ calculateBackoff strategy 1 @?= 2+ calculateBackoff strategy 3 @?= 8 -- 2 * 2^2+ calculateBackoff strategy 5 @?= 30 -- Capped at 30 (2 * 2^4 = 32)+ ]+ , testGroup+ "applyJitter"+ [ testCase "NoJitter returns the exact delay" $ do+ res <- applyJitter NoJitter 10+ res @?= 10+ , testCase "FullJitter returns a value between 0 and delay" $ do+ res <- applyJitter FullJitter 10+ assertBool "FullJitter should be >= 0" (res >= 0)+ assertBool "FullJitter should be <= 10" (res <= 10)+ , testCase "EqualJitter returns a value between delay/2 and delay" $ do+ res <- applyJitter EqualJitter 10+ assertBool "EqualJitter should be >= 5" (res >= 5)+ assertBool "EqualJitter should be <= 10" (res <= 10)+ ]+ ]
+ test/Tests/BufferSpec.hs view
@@ -0,0 +1,74 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module : Tests.BufferSpec+Description : Unit tests for TimedOverflowBuffer concurrency and flush policies.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental+-}+module Tests.BufferSpec (bufferTests) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (replicateConcurrently_)+import Control.Concurrent.MVar (modifyMVar_, newMVar, readMVar)+import PGQueuer.Worker.Buffer+import Test.Tasty+import Test.Tasty.HUnit++bufferTests :: TestTree+bufferTests =+ testGroup+ "TimedOverflowBuffer"+ [ testCase "Manual flush drains all elements" $ do+ flushed <- newMVar ([] :: [Int])+ let config = BufferConfig {bcMaxSize = 100, bcFlushInterval = 1000000}+ withBuffer config (\items -> modifyMVar_ flushed (\acc -> pure (acc ++ items))) $ \buf -> do+ add buf 1+ add buf 2+ add buf 3+ flushBuffer buf+ res <- readMVar flushed+ assertEqual "Flushed items" [1, 2, 3] res+ , testCase "Overflow threshold automatically triggers flush" $ do+ flushed <- newMVar ([] :: [Int])+ -- Max size 5, long timer interval+ let config = BufferConfig {bcMaxSize = 5, bcFlushInterval = 5000000}+ withBuffer config (\items -> modifyMVar_ flushed (\acc -> pure (acc ++ items))) $ \buf -> do+ mapM_ (add buf) [1 .. 5]+ -- Allow background flusher thread to wake from overflow signal+ threadDelay 100000+ res <- readMVar flushed+ assertEqual "Automatically flushed on overflow" [1 .. 5] res+ , testCase "Timer expiration automatically triggers flush" $ do+ flushed <- newMVar ([] :: [Int])+ -- 50ms flush interval+ let config = BufferConfig {bcMaxSize = 100, bcFlushInterval = 50000}+ withBuffer config (\items -> modifyMVar_ flushed (\acc -> pure (acc ++ items))) $ \buf -> do+ add buf 999+ -- Wait for timer to fire+ threadDelay 150000+ res <- readMVar flushed+ assertEqual "Automatically flushed on timer" [999] res+ , testCase "withBuffer drains remaining items on exit" $ do+ flushed <- newMVar ([] :: [Int])+ let config = BufferConfig {bcMaxSize = 100, bcFlushInterval = 10000000}+ withBuffer config (\items -> modifyMVar_ flushed (\acc -> pure (acc ++ items))) $ \buf -> do+ add buf 42+ add buf 43+ -- After exiting withBuffer, flusher thread drains buffer+ res <- readMVar flushed+ assertEqual "Clean shutdown drains remaining" [42, 43] res+ , testCase "Concurrent pushes preserve all items" $ do+ flushed <- newMVar ([] :: [Int])+ let totalItems = 200 :: Int+ config = BufferConfig {bcMaxSize = 50, bcFlushInterval = 50000}+ withBuffer config (\items -> modifyMVar_ flushed (\acc -> pure (acc ++ items))) $ \buf -> do+ replicateConcurrently_ 4 $ do+ mapM_ (add buf) [1 .. 50]+ threadDelay 200000+ flushBuffer buf+ res <- readMVar flushed+ assertEqual "All concurrent items received" totalItems (length res)+ ]
+ test/Tests/CoreSpec.hs view
@@ -0,0 +1,379 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE ScopedTypeVariables #-}++module Tests.CoreSpec+ ( coreTests+ , coreTestsWith+ , Runner (..)+ , connStr+ , withFreshSchema+ , withFreshSchemaWith+ , testEnqueueCapturesJobId+ , testConcurrentDequeueSkipLocked+ , testLogJobsTransitionsStatus+ , testWithTransactionRollback+ , testJobTreeRollup+ )+where++import Control.Concurrent.Async (async, wait)+import Control.Exception (SomeException, try)+import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.Aeson (Value (String))+import Data.ByteString (ByteString)+import Data.List (nub)+import Data.Maybe (listToMaybe)+import Data.UUID.V4 (nextRandom)+import Database.PostgreSQL.Simple (Connection)+import qualified Database.PostgreSQL.Simple as PG+import PGQueuer.Core.Monad+import PGQueuer.Schema (install, uninstall)+import PGQueuer.Settings (DBSettings, defaultDBSettings)+import PGQueuer.Types+import PGQueuer.Workflow (JobNode (..), insertJobTree, (<~~))+import Test.Tasty+import Test.Tasty.HUnit+import Tests.TestContainer (resolveConnStr)++-- | Connection string used for testing.+connStr :: ByteString+connStr = "postgresql://queue_user:queue_pass@localhost:5432/queue_db"++{- | A wrapper for a polymorphic backend runner.++Wrapping in a newtype avoids the need for ImpredicativeTypes when+passing runners inside tuples or data structures.+-}+newtype Runner = Runner+ { runWith :: forall a. (forall m. (MonadPGQueuer m, MonadIO m) => m a) -> IO a+ }++{- | Core integration tests parameterized over any 'MonadPGQueuer' backend.++Accepts:+ 1. A label string (e.g., "SimpleDb", "HasqlDb")+ 2. A function that creates a Runner + cleanup from a fresh schema connection+ 3. A function that creates two independent Runners for concurrent tests+-}+coreTests ::+ -- | Backend label+ String ->+ -- | (conn -> settings -> IO (runner, cleanup))+ (Connection -> DBSettings -> IO (Runner, IO ())) ->+ -- | (conn -> settings -> IO (runner1, runner2, cleanup))+ (Connection -> DBSettings -> IO (Runner, Runner, IO ())) ->+ TestTree+coreTests label mkRunner mkDualRunners =+ coreTestsWith resolveConnStr label (\_ c s -> mkRunner c s) (\_ c s -> mkDualRunners c s)++-- | Core integration tests parameterized with a dynamic connection string action.+coreTestsWith ::+ -- | Connection string resolver (e.g. from Testcontainers)+ IO ByteString ->+ -- | Backend label+ String ->+ -- | (connStr -> conn -> settings -> IO (runner, cleanup))+ (ByteString -> Connection -> DBSettings -> IO (Runner, IO ())) ->+ -- | (connStr -> conn -> settings -> IO (runner1, runner2, cleanup))+ (ByteString -> Connection -> DBSettings -> IO (Runner, Runner, IO ())) ->+ TestTree+coreTestsWith getConnStr label mkRunner mkDualRunners =+ testGroup+ (label <> " - Core Integration")+ [ testEnqueueCapturesJobIdWith getConnStr mkRunner+ , testConcurrentDequeueSkipLockedWith getConnStr mkRunner mkDualRunners+ , testLogJobsTransitionsStatusWith getConnStr mkRunner+ , testWithTransactionRollbackWith getConnStr mkRunner+ , testJobTreeRollupWith getConnStr mkRunner+ ]++-- | Set up a fresh schema and run an action with a dynamically resolved connection string.+withFreshSchemaWith :: IO ByteString -> (ByteString -> Connection -> DBSettings -> IO a) -> IO a+withFreshSchemaWith getConnStr action = do+ cStr <- getConnStr+ conn <- PG.connectPostgreSQL cStr+ let settings = defaultDBSettings+ uninstall conn settings+ install conn settings+ result <- action cStr conn settings+ PG.close conn+ return result++-- | Set up a fresh schema using the default connStr.+withFreshSchema :: (Connection -> DBSettings -> IO a) -> IO a+withFreshSchema action = withFreshSchemaWith resolveConnStr (\_ conn settings -> action conn settings)++{- | Test: Call enqueue with an entrypoint and payload+Expectation: Return value contains a valid JobId; row exists in 'pgqueuer' table+-}+testEnqueueCapturesJobId ::+ (Connection -> DBSettings -> IO (Runner, IO ())) ->+ TestTree+testEnqueueCapturesJobId mkRunner =+ testEnqueueCapturesJobIdWith resolveConnStr (\_ c s -> mkRunner c s)++testEnqueueCapturesJobIdWith ::+ IO ByteString ->+ (ByteString -> Connection -> DBSettings -> IO (Runner, IO ())) ->+ TestTree+testEnqueueCapturesJobIdWith getConnStr mkRunner =+ testCase "performs basic job enqueuing and captures a distinct JobId" $ do+ withFreshSchemaWith getConnStr $ \cStr conn settings -> do+ (runner, cleanup) <- mkRunner cStr conn settings++ jobIds <-+ runWith runner $+ enqueue (Entrypoint "test_basic") Nothing 0 Nothing Nothing Nothing Nothing Nothing Queued++ assertEqual "enqueue should return exactly one JobId" 1 (length jobIds)+ case jobIds of+ [JobId jid] -> assertBool "JobId should be positive" (jid > 0)+ _ -> assertFailure "Expected exactly one JobId"++ -- Verify the row exists by dequeuing it+ queueMgrId <- nextRandom+ let params = [EntrypointExecutionParameter (Entrypoint "test_basic") 0 5 (Exponential 5 60) FullJitter]+ jobs <-+ runWith runner $+ dequeue 10 params queueMgrId Nothing 300++ case (jobIds, jobs) of+ ([expectedId], [job]) -> do+ assertEqual "Dequeued job should have the same id" expectedId (jobId job)+ assertEqual "Dequeued job status should be Picked" Picked (jobStatus job)+ _ -> assertFailure "Expected exactly one job dequeued"++ cleanup++{- | Test: Enqueue 3 matching jobs. Simulate two concurrent workers dequeuing with batch size 1.+Expectation: Worker 1 and Worker 2 must receive completely distinct jobs.+No thread should block or wait on the other worker's lock.+-}+testConcurrentDequeueSkipLocked ::+ (Connection -> DBSettings -> IO (Runner, IO ())) ->+ (Connection -> DBSettings -> IO (Runner, Runner, IO ())) ->+ TestTree+testConcurrentDequeueSkipLocked mkRunner mkDualRunners =+ testConcurrentDequeueSkipLockedWith+ resolveConnStr+ (\_ c s -> mkRunner c s)+ (\_ c s -> mkDualRunners c s)++testConcurrentDequeueSkipLockedWith ::+ IO ByteString ->+ (ByteString -> Connection -> DBSettings -> IO (Runner, IO ())) ->+ (ByteString -> Connection -> DBSettings -> IO (Runner, Runner, IO ())) ->+ TestTree+testConcurrentDequeueSkipLockedWith getConnStr mkRunner mkDualRunners =+ testCase "executes non-contending dequeue using FOR UPDATE SKIP LOCKED" $ do+ withFreshSchemaWith getConnStr $ \cStr conn settings -> do+ -- Use a single runner for enqueueing+ (enqRunner, enqCleanup) <- mkRunner cStr conn settings++ -- Enqueue 3 jobs+ _ <- runWith enqRunner $ do+ _ <- enqueue (Entrypoint "concurrent_test") Nothing 1 Nothing Nothing Nothing Nothing Nothing Queued+ _ <- enqueue (Entrypoint "concurrent_test") Nothing 1 Nothing Nothing Nothing Nothing Nothing Queued+ enqueue (Entrypoint "concurrent_test") Nothing 1 Nothing Nothing Nothing Nothing Nothing Queued++ enqCleanup++ -- Create two independent runners for concurrent dequeue+ (runner1, runner2, dualCleanup) <- mkDualRunners cStr conn settings++ let params = [EntrypointExecutionParameter (Entrypoint "concurrent_test") 0 5 (Exponential 5 60) FullJitter]++ qmId1 <- nextRandom+ qmId2 <- nextRandom++ a1 <- async $ runWith runner1 (dequeue 1 params qmId1 Nothing 300)+ a2 <- async $ runWith runner2 (dequeue 1 params qmId2 Nothing 300)++ jobs1 <- wait a1+ jobs2 <- wait a2++ dualCleanup++ assertEqual "Worker 1 should get exactly 1 job" 1 (length jobs1)+ assertEqual "Worker 2 should get exactly 1 job" 1 (length jobs2)++ let allIds = map jobId jobs1 ++ map jobId jobs2+ assertEqual+ "Workers must receive completely distinct jobs"+ (length allIds)+ (length (nub allIds))++{- | Test: Execute logJobs to mark a job as Failed.+Expectation: Active job row status updates to 'failed' and an append-only log+record is created in the 'pgqueuer_log' table.+-}+testLogJobsTransitionsStatus ::+ (Connection -> DBSettings -> IO (Runner, IO ())) ->+ TestTree+testLogJobsTransitionsStatus mkRunner =+ testLogJobsTransitionsStatusWith resolveConnStr (\_ c s -> mkRunner c s)++testLogJobsTransitionsStatusWith ::+ IO ByteString ->+ (ByteString -> Connection -> DBSettings -> IO (Runner, IO ())) ->+ TestTree+testLogJobsTransitionsStatusWith getConnStr mkRunner =+ testCase "atomically transitions job status and records to the transaction log" $ do+ withFreshSchemaWith getConnStr $ \cStr conn settings -> do+ (runner, cleanup) <- mkRunner cStr conn settings++ -- Enqueue and pick a job+ queueMgrId <- nextRandom+ let ep = Entrypoint "log_test"+ let params = [EntrypointExecutionParameter ep 0 5 (Exponential 5 60) FullJitter]++ _ <- runWith runner $ enqueue ep Nothing 0 Nothing Nothing Nothing Nothing Nothing Queued+ jobs <- runWith runner $ dequeue 1 params queueMgrId Nothing 300+ assertEqual "Should dequeue 1 job" 1 (length jobs)++ case jobs of+ [theJob] -> do+ -- Mark as Failed via logJobs+ runWith runner $ logJobs [(jobId theJob, Failed, Nothing)]++ -- Verify: job status should be 'failed' (via postgresql-simple for verification)+ statusRows <-+ PG.query+ conn+ "SELECT status::text FROM pgqueuer WHERE id = ?"+ (PG.Only (jobId theJob)) ::+ IO [PG.Only String]+ case statusRows of+ [PG.Only statusText] ->+ assertEqual "Status should be 'failed'" "failed" statusText+ _ -> assertFailure "Expected exactly one status row"++ -- Verify: log entry exists+ logRows <-+ PG.query+ conn+ "SELECT status::text FROM pgqueuer_log WHERE job_id = ? AND status = 'failed'"+ (PG.Only (jobId theJob)) ::+ IO [PG.Only String]+ assertBool "Should have at least one 'failed' log entry" (not (null logRows))+ _ -> assertFailure "Expected exactly one dequeued job"++ cleanup++{- | Test: Open a withTransaction boundary. Enqueue a job, then intentionally+throw an exception.+Expectation: The outer boundary catches the exception. A subsequent check+verifies that the job was never inserted into the database.+-}+testWithTransactionRollback ::+ (Connection -> DBSettings -> IO (Runner, IO ())) ->+ TestTree+testWithTransactionRollback mkRunner =+ testWithTransactionRollbackWith resolveConnStr (\_ c s -> mkRunner c s)++testWithTransactionRollbackWith ::+ IO ByteString ->+ (ByteString -> Connection -> DBSettings -> IO (Runner, IO ())) ->+ TestTree+testWithTransactionRollbackWith getConnStr mkRunner =+ testCase "strictly rolls back state modifications when a transaction block fails" $ do+ withFreshSchemaWith getConnStr $ \cStr conn settings -> do+ (runner, cleanup) <- mkRunner cStr conn settings++ -- Count rows before+ [PG.Only (beforeCount :: Int)] <-+ PG.query_ conn "SELECT COUNT(*) FROM pgqueuer"++ -- Attempt a transaction that will fail+ result <- try $ runWith runner $ do+ withTransaction $ do+ _ <- enqueue (Entrypoint "rollback_test") Nothing 0 Nothing Nothing Nothing Nothing Nothing Queued+ -- Force an exception inside the transaction+ liftIO $ ioError (userError "intentional failure to trigger rollback")++ -- Verify the exception was caught+ case result of+ Left (_ :: SomeException) -> return ()+ Right _ -> assertFailure "Expected an exception but transaction succeeded"++ -- Verify: no new rows were inserted (transaction was rolled back)+ [PG.Only (afterCount :: Int)] <-+ PG.query_ conn "SELECT COUNT(*) FROM pgqueuer"+ assertEqual+ "Row count should be unchanged after rollback"+ beforeCount+ afterCount++ cleanup++{- | Test: Insert a JobTree and verify that parent is only dequeued after children complete.+Expectation: Children are dequeued first, parent remains 'held'.+Upon completion of all children, parent is dequeued.+-}+testJobTreeRollup ::+ (Connection -> DBSettings -> IO (Runner, IO ())) ->+ TestTree+testJobTreeRollup mkRunner =+ testJobTreeRollupWith resolveConnStr (\_ c s -> mkRunner c s)++testJobTreeRollupWith ::+ IO ByteString ->+ (ByteString -> Connection -> DBSettings -> IO (Runner, IO ())) ->+ TestTree+testJobTreeRollupWith getConnStr mkRunner =+ testCase "atomically rolls up child results and unholds parent" $ do+ withFreshSchemaWith getConnStr $ \cStr conn settings -> do+ (runner, cleanup) <- mkRunner cStr conn settings++ let parentNode = JobNode (Entrypoint "parent") Nothing 0 Nothing Nothing Nothing Nothing+ childNode1 = JobNode (Entrypoint "child") (Just "c1") 0 Nothing Nothing Nothing Nothing+ childNode2 = JobNode (Entrypoint "child") (Just "c2") 0 Nothing Nothing Nothing Nothing+ tree = parentNode <~~ [childNode1 <~~ [], childNode2 <~~ []]++ runWith runner $ insertJobTree tree++ queueMgrId <- nextRandom+ let params =+ [ EntrypointExecutionParameter (Entrypoint "child") 0 5 (Exponential 5 60) FullJitter+ , EntrypointExecutionParameter (Entrypoint "parent") 0 5 (Exponential 5 60) FullJitter+ ]++ -- First dequeue: should only get children+ jobs1 <- runWith runner $ dequeue 10 params queueMgrId Nothing 300+ assertEqual "Should dequeue 2 children" 2 (length jobs1)+ assertBool+ "All dequeued jobs should be 'child'"+ (all (\j -> jobEntrypoint j == Entrypoint "child") jobs1)++ -- Mark first child as success+ case listToMaybe jobs1 of+ Nothing -> pure ()+ Just c1 -> runWith runner $ logJobs [(jobId c1, Successful, Just (String "result1"))]++ -- Second dequeue: should get 0 jobs (parent is still held)+ jobs2 <- runWith runner $ dequeue 10 params queueMgrId Nothing 300+ assertEqual "Should dequeue 0 jobs because 1 child is still pending" 0 (length jobs2)++ -- Mark second child as success+ case drop 1 jobs1 of+ (c2 : _) -> runWith runner $ logJobs [(jobId c2, Successful, Just (String "result2"))]+ [] -> pure ()++ -- Third dequeue: should now get the parent job+ jobs3 <- runWith runner $ dequeue 10 params queueMgrId Nothing 300+ assertEqual "Should dequeue 1 parent job" 1 (length jobs3)+ case listToMaybe jobs3 of+ Nothing -> pure ()+ Just parentJob -> do+ assertEqual "Dequeued job should be 'parent'" (Entrypoint "parent") (jobEntrypoint parentJob)++ -- Fetch merged child results+ results <- runWith runner $ mergedChildResults (jobId parentJob)+ assertEqual "Should have 2 child results" 2 (length results)+ let resStrs = [s | String s <- results]+ assertBool+ "Results should contain both child outputs"+ ("result1" `elem` resStrs && "result2" `elem` resStrs)++ cleanup
+ test/Tests/CronSpec.hs view
@@ -0,0 +1,44 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module : Tests.CronSpec+Description : Unit tests for Cron scheduling calculations and expression validation.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental+-}+module Tests.CronSpec (cronTests) where++import Data.Either (isLeft, isRight)+import Data.Time (UTCTime (..), fromGregorian, secondsToDiffTime)+import PGQueuer.Types (CronExpression (..))+import PGQueuer.Worker.Cron (calculateNextRunTime)+import Test.Tasty+import Test.Tasty.HUnit++cronTests :: TestTree+cronTests =+ testGroup+ "Cron Scheduler"+ [ testCase "Valid every-minute expression '* * * * *' produces future time" $ do+ let refTime = UTCTime (fromGregorian 2026 1 1) (secondsToDiffTime 3600)+ res = calculateNextRunTime (CronExpression "* * * * *") refTime+ assertBool "Calculation succeeds" (isRight res)+ case res of+ Right nextTime -> assertBool "Next time is strictly after refTime" (nextTime > refTime)+ Left err -> assertFailure ("Unexpected error: " ++ err)+ , testCase "Valid daily midnight expression '0 0 * * *' produces midnight time" $ do+ let refTime = UTCTime (fromGregorian 2026 1 1) (secondsToDiffTime 3600)+ res = calculateNextRunTime (CronExpression "0 0 * * *") refTime+ assertBool "Calculation succeeds" (isRight res)+ case res of+ Right nextTime -> do+ assertBool "Next time is after refTime" (nextTime > refTime)+ assertEqual "Midnight seconds" (secondsToDiffTime 0) (utctDayTime nextTime)+ Left err -> assertFailure ("Unexpected error: " ++ err)+ , testCase "Invalid cron expression returns Left with error message" $ do+ let refTime = UTCTime (fromGregorian 2026 1 1) (secondsToDiffTime 3600)+ res = calculateNextRunTime (CronExpression "not-a-valid-cron-string") refTime+ assertBool "Returns Left on malformed cron" (isLeft res)+ ]
+ test/Tests/HasqlSpec.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE OverloadedStrings #-}++module Tests.HasqlSpec+ ( hasqlCoreTests+ , hasqlCoreTestsWith+ )+where++import Data.ByteString (ByteString)+import PGQueuer.Backend.Hasql+import Test.Tasty+import Tests.CoreSpec (Runner (..), coreTestsWith)+import Tests.TestContainer (resolveConnStr)++{- | Core integration tests running on the 'HasqlDb' backend.++Uses the same 5 tests as SimpleDb to prove 100% behavioral parity.+-}+hasqlCoreTests :: TestTree+hasqlCoreTests = hasqlCoreTestsWith resolveConnStr++hasqlCoreTestsWith :: IO ByteString -> TestTree+hasqlCoreTestsWith getConnStr = coreTestsWith getConnStr "HasqlDb" mkHasqlRunner mkDualHasqlRunners+ where+ mkHasqlRunner cStr _conn settings = do+ env <- mkHasqlDbEnv cStr settings+ let runner = Runner $ \action -> runHasqlDb env action+ let cleanup = releaseHasqlDbEnv env+ return (runner, cleanup)++ mkDualHasqlRunners cStr _conn settings = do+ env1 <- mkHasqlDbEnv cStr settings+ env2 <- mkHasqlDbEnv cStr settings+ let runner1 = Runner $ \action -> runHasqlDb env1 action+ let runner2 = Runner $ \action -> runHasqlDb env2 action+ let cleanup = do+ releaseHasqlDbEnv env1+ releaseHasqlDbEnv env2+ return (runner1, runner2, cleanup)
test/Tests/PGQueuer.hs view
@@ -2,36 +2,43 @@ {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} -module Tests.PGQueuer (runTests) where+module Tests.PGQueuer+ ( pgqueuerTests+ , pgqueuerTestsWith+ )+where import Test.Tasty import Test.Tasty.HUnit import Data.Aeson+import Data.ByteString (ByteString) import Data.Either (isLeft, isRight) import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe, isJust, listToMaybe) import Data.UUID.V4 (nextRandom) import GHC.Generics import PGQueuer+import Tests.TestContainer (resolveConnStr) -runTests :: IO ()-runTests =- defaultMain $- dependentTestGroup+pgqueuerTests :: TestTree+pgqueuerTests = pgqueuerTestsWith resolveConnStr++pgqueuerTestsWith :: IO ByteString -> TestTree+pgqueuerTestsWith getConnStr =+ testGroup "All tests"- AllFinish- [ schemaTests- , entrypointTests- , enqueueDequeueJobs- , enqueueDequeueMultipleJobs- , logAndListJobs- , roundTripJSONPayload+ [ schemaTests getConnStr+ , entrypointTests getConnStr+ , enqueueDequeueJobs getConnStr+ , enqueueDequeueMultipleJobs getConnStr+ , logAndListJobs getConnStr+ , roundTripJSONPayload getConnStr ] -withFreshQueue :: (QueueManager -> IO a) -> IO a-withFreshQueue action = do- let conStr = "postgresql://queue_user:queue_pass@localhost:5432/queue_db"+withFreshQueueWith :: IO ByteString -> (QueueManager -> IO a) -> IO a+withFreshQueueWith getConnStr action = do+ conStr <- getConnStr let dbSetting = defaultDBSettings queueMgrId <- nextRandom withQueueManager conStr dbSetting queueMgrId $ \qm -> do@@ -45,33 +52,32 @@ Nothing -> assertFailure message Just value -> assertion value -schemaTests :: TestTree-schemaTests = do- testGroup "Schema related tests" [checkInstallUninstallSchema]+schemaTests :: IO ByteString -> TestTree+schemaTests getConnStr = testGroup "Schema related tests" [checkInstallUninstallSchema getConnStr] -checkInstallUninstallSchema :: TestTree-checkInstallUninstallSchema = testCase "installed schema should should be deleted safely" $ do- withFreshQueue $ \qm -> do+checkInstallUninstallSchema :: IO ByteString -> TestTree+checkInstallUninstallSchema getConnStr = testCase "installed schema should should be deleted safely" $ do+ withFreshQueueWith getConnStr $ \qm -> do schemaInstalled <- verifyStructure qm assertBool "Schema is installed and verified" (isRight schemaInstalled) uninstallSchema qm schemaInstalled2 <- verifyStructure qm assertBool "Schema is removed and verified" (isLeft schemaInstalled2) -entrypointTests :: TestTree-entrypointTests = testCase "Adding an entrypoint in qm adds entrypoint" $ do- withFreshQueue $ \qm -> do+entrypointTests :: IO ByteString -> TestTree+entrypointTests getConnStr = testCase "Adding an entrypoint in qm adds entrypoint" $ do+ withFreshQueueWith getConnStr $ \qm -> do let ep = Entrypoint "hello" qm1 <- registerEntrypoint qm ep (\_ -> pure ()) let entrypoints = qmEntrypoints qm1 assertBool "qm should contain entrypoint hello" $ isJust (Map.lookup "hello" entrypoints) -enqueueDequeueJobs :: TestTree-enqueueDequeueJobs =+enqueueDequeueJobs :: IO ByteString -> TestTree+enqueueDequeueJobs getConnStr = testCase "Enqueue jobs should have entry in PGQ table" $ do- withFreshQueue $ \qm -> do+ withFreshQueueWith getConnStr $ \qm -> do let ep = Entrypoint "hello"- let params = [EntrypointExecutionParameter ep 0]+ let params = [EntrypointExecutionParameter ep 0 5 (Exponential 5 60) FullJitter] qm1 <- registerEntrypoint qm ep (\_ -> pure ()) _ <- enqueue qm1 ep Nothing 0 Nothing Nothing Nothing stats <- getQueueSize qm1@@ -85,12 +91,12 @@ expectOne "job status lookup failed" status $ \(_, jobStatus') -> assertEqual "job should be picked" Picked jobStatus' -enqueueDequeueMultipleJobs :: TestTree-enqueueDequeueMultipleJobs =+enqueueDequeueMultipleJobs :: IO ByteString -> TestTree+enqueueDequeueMultipleJobs getConnStr = testCase "Enqueue multiple jobs dequeue them" $ do- withFreshQueue $ \qm -> do+ withFreshQueueWith getConnStr $ \qm -> do let ep = Entrypoint "hello"- let params = [EntrypointExecutionParameter ep 0]+ let params = [EntrypointExecutionParameter ep 0 5 (Exponential 5 60) FullJitter] qm1 <- registerEntrypoint qm ep (\_ -> pure ()) _ <- enqueueMultiple@@ -112,12 +118,12 @@ expectOne "statistics are empty" stats1 $ \stat -> assertEqual "picked jobs should be tracked" Picked (statsStatus stat) -logAndListJobs :: TestTree-logAndListJobs =+logAndListJobs :: IO ByteString -> TestTree+logAndListJobs getConnStr = testCase "Update job status, retry, requeue and clear queue" $ do- withFreshQueue $ \qm -> do+ withFreshQueueWith getConnStr $ \qm -> do let ep = Entrypoint "hello"- let params = [EntrypointExecutionParameter ep 0]+ let params = [EntrypointExecutionParameter ep 0 5 (Exponential 5 60) FullJitter] qm1 <- registerEntrypoint qm ep (\_ -> pure ()) jobIds <- enqueueMultiple@@ -141,7 +147,9 @@ failedJobs <- listFailedJobs qm1 10 expectOne "Need exactly one failed job" failedJobs $ \failedJob -> do assertEqual "failed job id mismatch" (jobId job1) (jobId failedJob)- retryJob qm1 failedJob 0 Nothing+ retryJobs+ qm1+ [(jobId failedJob, jobExecuteAfter failedJob, fromIntegral (jobAttempts failedJob + 1))] retryStatus <- listJobStatusById qm1 [jobId job1] expectOne "retry status lookup failed" retryStatus $ \(_, status) ->@@ -168,12 +176,12 @@ } deriving (Show, Eq, Generic, FromJSON, ToJSON) -roundTripJSONPayload :: TestTree-roundTripJSONPayload = do- testCase "Enqueue jobs should have entry in PGQ table" $ do- withFreshQueue $ \qm -> do+roundTripJSONPayload :: IO ByteString -> TestTree+roundTripJSONPayload getConnStr = do+ testCase "Round trip JSON payload through enqueue and dequeue" $ do+ withFreshQueueWith getConnStr $ \qm -> do let ep = Entrypoint "hello"- let params = [EntrypointExecutionParameter ep 0]+ let params = [EntrypointExecutionParameter ep 0 5 (Exponential 5 60) FullJitter] qm1 <- registerEntrypoint qm ep (\_ -> pure ()) let payload = encode $ BasicType "Hello" 25 _ <- enqueue qm1 ep (Just payload) 0 Nothing Nothing Nothing
+ test/Tests/SimpleSpec.hs view
@@ -0,0 +1,41 @@+{-# LANGUAGE OverloadedStrings #-}++module Tests.SimpleSpec+ ( simpleCoreTests+ , simpleCoreTestsWith+ )+where++import Data.ByteString (ByteString)+import qualified Database.PostgreSQL.Simple as PG+import PGQueuer.Backend.Simple+import Test.Tasty+import Tests.CoreSpec (Runner (..), coreTestsWith)+import Tests.TestContainer (resolveConnStr)++{- | Core integration tests running on the 'SimpleDb' backend.++Uses the same 5 tests as HasqlDb to prove behavioral parity.+-}+simpleCoreTests :: TestTree+simpleCoreTests = simpleCoreTestsWith resolveConnStr++simpleCoreTestsWith :: IO ByteString -> TestTree+simpleCoreTestsWith getConnStr = coreTestsWith getConnStr "SimpleDb" mkSimpleRunner mkDualSimpleRunners+ where+ mkSimpleRunner _cStr conn settings = do+ let env = SimpleDbEnv conn settings+ let runner = Runner $ \action -> runSimpleDb env action+ return (runner, return ())++ mkDualSimpleRunners cStr _conn settings = do+ conn1 <- PG.connectPostgreSQL cStr+ conn2 <- PG.connectPostgreSQL cStr+ let env1 = SimpleDbEnv conn1 settings+ let env2 = SimpleDbEnv conn2 settings+ let runner1 = Runner $ \action -> runSimpleDb env1 action+ let runner2 = Runner $ \action -> runSimpleDb env2 action+ let cleanup = do+ PG.close conn1+ PG.close conn2+ return (runner1, runner2, cleanup)
+ test/Tests/TestContainer.hs view
@@ -0,0 +1,121 @@+{-# LANGUAGE OverloadedStrings #-}++module Tests.TestContainer+ ( postgresContainer+ , withPostgresTestContainer+ , getTestConnStr+ , resolveConnStr+ ) where++import Control.Concurrent (threadDelay)+import Control.Exception (SomeException, try)+import Data.ByteString (ByteString)+import qualified Data.ByteString.Char8 as BS8+import Data.Function ((&))+import qualified Data.Text.Lazy as TL+import Database.PostgreSQL.Simple (Connection, close, connectPostgreSQL)+import System.Environment (lookupEnv)+import Test.Tasty (TestTree)+import TestContainers+ ( Container+ , ContainerRequest+ , Pipe (Stderr)+ , containerPort+ , containerRequest+ , fromTag+ , run+ , setEnv+ , setExpose+ , setWaitingFor+ , waitForLogLine+ , waitUntilTimeout+ , withoutReaper+ )+import TestContainers.Tasty (withContainers)++{- | PostgreSQL 16 container definition.+PostgreSQL logs its operational messages (including startup readiness) to Stderr.+-}+postgresContainer :: ContainerRequest+postgresContainer =+ containerRequest (fromTag "postgres:16-alpine")+ & setExpose [5432]+ & setEnv+ [ ("POSTGRES_USER", "queue_user")+ , ("POSTGRES_PASSWORD", "queue_pass")+ , ("POSTGRES_DB", "queue_db")+ ]+ & withoutReaper+ & setWaitingFor+ ( waitUntilTimeout 60 $+ waitForLogLine Stderr (TL.isInfixOf "database system is ready to accept connections")+ )++{- | Resolve connection host for mapped container ports.+Honors @TESTCONTAINERS_HOST@ if explicitly set, defaulting to @"127.0.0.1"@.+-}+getTestHost :: IO String+getTestHost = do+ mHost <- lookupEnv "TESTCONTAINERS_HOST"+ pure $ case mHost of+ Just h | not (null h) -> h+ _ -> "127.0.0.1"++-- | Retry connecting until PostgreSQL is actually responsive.+ensurePostgresReady :: ByteString -> IO ()+ensurePostgresReady connStr = go (30 :: Int)+ where+ go 0 = pure ()+ go n = do+ result <- try (connectPostgreSQL connStr) :: IO (Either SomeException Connection)+ case result of+ Right conn -> close conn+ Left _ -> do+ threadDelay 200000+ go (n - 1)++{- | Resolve connection string dynamically:+1. Uses PG_CONN_STRING if set.+2. Uses DATABASE_URL if set.+3. Falls back to the given dynamic container.+-}+getTestConnStr :: Container -> IO ByteString+getTestConnStr container = do+ mEnv <- lookupEnv "PG_CONN_STRING"+ case mEnv of+ Just str | not (null str) -> pure (BS8.pack str)+ _ -> do+ mDbUrl <- lookupEnv "DATABASE_URL"+ case mDbUrl of+ Just str | not (null str) -> pure (BS8.pack str)+ _ -> do+ host <- getTestHost+ let port = containerPort container 5432+ pure $+ "postgresql://queue_user:queue_pass@"+ <> BS8.pack host+ <> ":"+ <> BS8.pack (show port)+ <> "/queue_db"++-- | Static fallback connection resolver for local environments.+resolveConnStr :: IO ByteString+resolveConnStr = do+ mEnv <- lookupEnv "PG_CONN_STRING"+ case mEnv of+ Just str | not (null str) -> pure (BS8.pack str)+ _ -> do+ mDbUrl <- lookupEnv "DATABASE_URL"+ case mDbUrl of+ Just str | not (null str) -> pure (BS8.pack str)+ _ -> pure "postgresql://queue_user:queue_pass@localhost:5432/queue_db"++-- | Run a Tasty test tree with a dynamically provisioned PostgreSQL container.+withPostgresTestContainer :: (IO ByteString -> TestTree) -> TestTree+withPostgresTestContainer testFactory =+ withContainers (run postgresContainer) $ \getContainer ->+ testFactory $ do+ container <- getContainer+ connStr <- getTestConnStr container+ ensurePostgresReady connStr+ pure connStr
+ test/Tests/TypesSpec.hs view
@@ -0,0 +1,111 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module : Tests.TypesSpec+Description : Unit tests for PGQueuer domain types, JSON instances, and conversions.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental+-}+module Tests.TypesSpec (typesTests) where++import Data.Aeson (decode, encode)+import PGQueuer.Types+import Test.Tasty+import Test.Tasty.HUnit++typesTests :: TestTree+typesTests =+ testGroup+ "Types & Serialization"+ [ jobStatusConversions+ , onFailureConversions+ , jsonRoundtrips+ , defaultsTests+ ]++jobStatusConversions :: TestTree+jobStatusConversions =+ testGroup+ "JobStatus Conversions"+ [ testCase "All JobStatus constructors roundtrip through textToJobStatus" $ do+ let allStatuses = [minBound .. maxBound] :: [JobStatus]+ mapM_+ (\st -> assertEqual (show st) (Just st) (textToJobStatus $ jobStatusToText st))+ allStatuses+ , testCase "Invalid status text returns Nothing" $ do+ assertEqual "invalid text" Nothing (textToJobStatus "unknown_status")+ assertEqual "empty text" Nothing (textToJobStatus "")+ ]++onFailureConversions :: TestTree+onFailureConversions =+ testGroup+ "OnFailure Conversions"+ [ testCase "All OnFailure constructors roundtrip through textToOnFailure" $ do+ let allFailures = [minBound .. maxBound] :: [OnFailure]+ mapM_+ (\f -> assertEqual (show f) (Just f) (textToOnFailure $ onFailureToText f))+ allFailures+ , testCase "Invalid failure text returns Nothing" $ do+ assertEqual "invalid text" Nothing (textToOnFailure "ignore")+ assertEqual "empty text" Nothing (textToOnFailure "")+ ]++jsonRoundtrips :: TestTree+jsonRoundtrips =+ testGroup+ "JSON Roundtrips"+ [ testCase "JobId JSON roundtrip" $ do+ let jid = JobId 42+ assertEqual "JobId" (Just jid) (decode $ encode jid)+ , testCase "ScheduleId JSON roundtrip" $ do+ let sid = ScheduleId 101+ assertEqual "ScheduleId" (Just sid) (decode $ encode sid)+ , testCase "Entrypoint JSON roundtrip" $ do+ let ep = Entrypoint "email_processor"+ assertEqual "Entrypoint" (Just ep) (decode $ encode ep)+ , testCase "CronExpression JSON roundtrip" $ do+ let expr = CronExpression "*/5 * * * *"+ assertEqual "CronExpression" (Just expr) (decode $ encode expr)+ , testCase "Channel JSON roundtrip" $ do+ let ch = Channel "my_custom_channel"+ assertEqual "Channel" (Just ch) (decode $ encode ch)+ , testCase "JobStatus JSON roundtrip for all constructors" $ do+ let allStatuses = [minBound .. maxBound] :: [JobStatus]+ mapM_+ (\st -> assertEqual (show st) (Just st) (decode $ encode st))+ allStatuses+ , testCase "OnFailure JSON roundtrip" $ do+ let allFailures = [minBound .. maxBound] :: [OnFailure]+ mapM_+ (\f -> assertEqual (show f) (Just f) (decode $ encode f))+ allFailures+ , testCase "BackoffStrategy JSON roundtrip" $ do+ let s1 = Exponential 2 60+ s2 = Linear 1 30+ s3 = Constant 5+ assertEqual "Exponential" (Just s1) (decode $ encode s1)+ assertEqual "Linear" (Just s2) (decode $ encode s2)+ assertEqual "Constant" (Just s3) (decode $ encode s3)+ , testCase "Jitter JSON roundtrip" $ do+ let j1 = NoJitter+ j2 = FullJitter+ j3 = EqualJitter+ assertEqual "NoJitter" (Just j1) (decode $ encode j1)+ assertEqual "FullJitter" (Just j2) (decode $ encode j2)+ assertEqual "EqualJitter" (Just j3) (decode $ encode j3)+ ]++defaultsTests :: TestTree+defaultsTests =+ testGroup+ "Default Parameters"+ [ testCase "defaultChannel is ch_pgqueuer" $ do+ assertEqual "defaultChannel" (Channel "ch_pgqueuer") defaultChannel+ , testCase "defaultBatchSize is 100" $ do+ assertEqual "defaultBatchSize" 100 defaultBatchSize+ , testCase "defaultHeartbeatTimeout is 300" $ do+ assertEqual "defaultHeartbeatTimeout" 300 defaultHeartbeatTimeout+ ]
+ test/Tests/WorkflowSpec.hs view
@@ -0,0 +1,48 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module : Tests.WorkflowSpec+Description : Unit tests for DAG Workflow and JobTree construction.+Copyright : (c) Tushar Adhatrao, 2026+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : experimental+-}+module Tests.WorkflowSpec (workflowTests) where++import PGQueuer.Types (Entrypoint (..))+import PGQueuer.Workflow+import Test.Tasty+import Test.Tasty.HUnit++workflowTests :: TestTree+workflowTests =+ testGroup+ "Workflow DAG Construction"+ [ testCase "Leaf JobTree construction" $ do+ let node = JobNode (Entrypoint "leaf") Nothing 0 Nothing Nothing Nothing Nothing+ tree = node <~~ []+ case tree of+ JobTree n children -> do+ assertEqual "Entrypoint" (Entrypoint "leaf") (jnEntrypoint n)+ assertEqual "Children" 0 (length children)+ , testCase "Hierarchical JobTree with multiple children" $ do+ let parent = JobNode (Entrypoint "parent") Nothing 0 Nothing Nothing Nothing Nothing+ child1 = JobNode (Entrypoint "child1") Nothing 0 Nothing Nothing Nothing Nothing <~~ []+ child2 = JobNode (Entrypoint "child2") Nothing 0 Nothing Nothing Nothing Nothing <~~ []+ tree = parent <~~ [child1, child2]+ case tree of+ JobTree p children -> do+ assertEqual "Parent entrypoint" (Entrypoint "parent") (jnEntrypoint p)+ assertEqual "Parent child count" 2 (length children)+ , testCase "Nested multi-level JobTree" $ do+ let root = JobNode (Entrypoint "root") Nothing 0 Nothing Nothing Nothing Nothing+ mid = JobNode (Entrypoint "mid") Nothing 0 Nothing Nothing Nothing Nothing+ leaf = JobNode (Entrypoint "leaf") Nothing 0 Nothing Nothing Nothing Nothing <~~ []+ tree = root <~~ [mid <~~ [leaf]]+ case tree of+ JobTree _ [JobTree m [JobTree l _]] -> do+ assertEqual "Mid entrypoint" (Entrypoint "mid") (jnEntrypoint m)+ assertEqual "Leaf entrypoint" (Entrypoint "leaf") (jnEntrypoint l)+ _ -> assertFailure "Unexpected tree structure"+ ]