Skip to content

Effect

Use MonqueEffect from @monque/core/effect. Its scoped Layer borrows db; close your MongoDB connection after the scheduler scope finishes. Core includes Effect 4 and needs no OpenTelemetry SDK.

Pass a setup callback as the third argument to MonqueEffect.layer to register Workers and start processing. Setup resources are available until scheduler disposal and Worker cleanup finish.

import { MonqueEffect } from "@monque/core/effect";
import { Context, Effect, Layer } from "effect";
import type { Db } from "mongodb";

class Mailer extends Context.Service<Mailer, { send: (to: string) => Effect.Effect<void> }>()(
  "app/Mailer",
) {}

export const mailLayer = (db: Db) =>
  MonqueEffect.layer(db, { pollInterval: 100 }, (monque) =>
    monque.effects.register<{ to: string }, never, Mailer>("mail", (job) =>
      Effect.gen(function* () {
        const mailer = yield* Mailer;
        yield* mailer.send(job.data.to);
      }),
    ),
  );

export const runMail = (db: Db, send: (to: string) => Effect.Effect<void>) =>
  Effect.gen(function* () {
    const scheduler = yield* MonqueEffect;
    yield* scheduler.now("mail", { to: "ada@example.com" });
    yield* Effect.never;
  }).pipe(Effect.provide(mailLayer(db).pipe(Layer.provide(Layer.succeed(Mailer, { send })))));

Run the returned Effect once at your application entry point. Interrupting it starts scoped cleanup. Registration captures the supplied application services; keep them alive until Monque is disposed. Provide resource Layers to the scheduler Layer, as above. Acquire per-attempt resources in the Worker handler.

For producers, MonqueEffect.layer(db, options) initializes without starting processing. You can register and start explicitly later. For a host needing Management or EventEmitter access, use Monque.scoped(db, options) and call native operations through monque.effects. See the complete host example.

The service exposes enqueue, enqueueMany, now, schedule, all public Job management and read methods, pause, resume, isPaused, getProcessingState, start, stop, isHealthy, and dispose. Controls without arguments are Effects (yield* scheduler.start); methods with arguments return Effects. Acquisition initializes the scheduler. stop permits a later start; dispose is terminal.

Expected operation failures use the MonqueError channel. Recover from validation and state errors with instanceof InvalidCronError, JobStateError, or another public error. Database failures use ConnectionError with the underlying error in cause.

Worker failures follow the configured retry policy. NonRetryableError skips retries.

stop waits up to shutdownTimeout for active work. A timeout emits job:error. dispose interrupts native Workers and waits for their finalizers. Promise Workers must settle before disposal completes. Uninterruptible work can delay shutdown. Cancellation cannot undo MongoDB writes or external effects.