Download the PHP package lekoala/kaly-tasks without Composer

On this page you can find all versions of the php package lekoala/kaly-tasks. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package kaly-tasks

Kaly Tasks

A durable SQL task queue for invocable PHP objects, with first-class Kaly integration.

It stores tasks in PostgreSQL, MySQL or SQLite and runs them in supervised worker processes: a durable task queue without a queue server. It implements the task dispatcher contracts of kaly-contracts, without depending on Kaly itself, so with Kaly it is one optional engine and application code does not change:

A task stays a plain invocable object, with its data in the constructor and its services in __invoke():

It is a specialized engine, not a messaging framework: no attributes, no handler registry, no events, no transports.

Scheduling

notBefore is an optional DateTimeImmutable lower bound. Without it, dispatch is immediate; a past date is immediately eligible. A future task cannot be reserved before its deadline, but polling and worker load may make it run later. stopWhenEmpty stops when nothing is due, even if future tasks remain queued.

The application expresses business dates with its injected PSR-20 clock. The stores keep SQL time for availability comparisons, leases, retries and retention; application and database clocks must be synchronized for relative business delays. Dates are normalized at the storage boundary: PostgreSQL stores timezone-aware instants and MySQL stores UTC DATETIME(6), both preserving microseconds. SQLite keeps integer epoch seconds and rounds fractional deadlines up to the next second, so precision never makes a task eligible early. No schema migration is needed.

For portable dates, use UTC years 1000 through 9999, the range of MySQL DATETIME(6). Dates outside this range are unsupported; use strict SQL mode so MySQL rejects out-of-range dates instead of coercing them to a zero date. PostgreSQL dates before the common era are also unsupported by this date codec.

Deduplication preserves the existing task, including its payload and deadline: a second dispatch with the same key neither advances nor postpones it. Retries use their normal SQL-clock delay after execution, independently of the original deadline. A scheduled insertion joins the application transaction as usual.

Kaly\Task\ScheduledTaskDispatcher comes from lekoala/kaly-contracts ^1.0. Kaly is optional; applications using it require Kaly 0.7 or later. Services that schedule work depend on this interface; services that only submit tasks can keep Kaly\Task\TaskDispatcher. Kaly's direct dispatcher offers the minimal contract, and its recording dispatcher supports scheduling with an injectable test clock.

Moving a scheduled reminder

Use a business version to supersede reminders without changing stored tasks:

Increment the business version for every relevant change: date, location, recipient and cancellation. The handler explicitly checks deletion and cancellation too: matching a version does not establish that an appointment is still active. An obsolete reminder still runs at its original deadline, consumes one execution slot and returns without sending.

The version check is not atomic with sending: if the appointment changes during an external call, an outdated reminder may still be sent. Decide whether that race is acceptable for notifications; business writes need suitable concurrency control. Use a stable provider idempotency key for the reminder operation to prevent repeated external effects on retries; it does not make the version check atomic with sending.

Deduplicating by appointmentId alone cannot move a reminder because it preserves the existing deadline. Versioned keys provide a recipe without a cancellation or rescheduling API.

Recurring tasks

There is no recurring scheduler: cron or Symfony Scheduler decides which occurrences are due and dispatches them. Deduplicating by the occurrence stores it once, even when several hosts dispatch it:

This prevents duplicate insertions, not missed or repeated occurrences:

For an effect that must happen once per period, such as billing, keep a business constraint (a unique row per period) and check it in the task.

Sequences

Submit a linear sequence without coupling each task to its successor:

DatabaseTaskDispatcher implements Kaly\Tasks\TaskSequenceDispatcher, a capability local to this package. Bind that interface to the same dispatcher instance when a service needs sequences; kaly-contracts remains unchanged. There is no builder or final dispatch() call: sequence() writes the first task and its continuation, subject to the application's transaction. It returns true for a new insertion and false when the first step's deduplication key is already stored. A true result inside an application transaction still needs that transaction to commit. A thrown error may leave the insertion outcome uncertain, just like dispatch().

Only the first step may have a deduplication key. A conflict skips the whole new submission, preserving the original continuation even if the new steps differ. That protection lasts until the first row is deleted or purged, even if later steps are still running. Use a distinct business execution ID when needed. sequence() rejects deduplicated task types in later positions before calling the store. SQL stores also reject keys on continuation steps passed directly to push().

Tasks keep their results in durable application state identified by their payloads. Task return values are ignored. Delivery is still at least once: the atomic queue transition does not include business writes or external API calls, so task effects must be idempotent. Branches, parallel steps, compensation and an onFailure callback are outside this API.

Use sequences for short chains that benefit from independent retries or reusable steps. Each transition rewrites the remaining list, so the cumulative continuation data written grows quadratically with the number of equally sized steps. The number of task insertions remains linear.

Custom stores and the continuation codec

Kaly\Tasks\Store\TaskChain is a public storage codec:

It stores a flat JSON list of objects containing name, queue and payload strings. Payload text is preserved verbatim. Encoding rejects invalid steps, keys and nested continuations with InvalidArgumentException; decoding malformed stored data throws UnexpectedValueException.

A custom TaskStore validates and encodes EncodedTask::$chain before insertion, then returns that raw JSON in ReservedTask::$chain without decoding at reservation. This lets the worker isolate malformed continuations using the normal failed-task path. Completion decodes it with the same codec and atomically transfers the remaining steps to the successor, clearing the completed row. Other settlement and recovery operations preserve the raw value unchanged. A custom backend may choose its own persistence representation, but must return this JSON format in the reservation.

Upgrading an existing queue for sequences

All three stores require the new column, including for ordinary dispatches and reservations. schema() creates new tables; it does not migrate existing ones. Add the nullable column through your application's migrations, adapting the table name as needed:

Existing rows have chain = NULL and remain ordinary tasks. Add the column first, replace all workers, then enable sequence submissions. An old worker can mark a step done without inserting its continuation. Keep sequence producers disabled during the worker rollout; do not roll back to old workers while any continuations remain. No new indexes or statuses are needed.

Guarantees

Deduplicating a task is not deduplicating its effects. If a worker calls an external API and crashes before settling the task, the call is repeated. Carry a stable operation key in the task and use it for the provider idempotency, or reconcile the external state before acting.

When a dispatch fails

Situation What is known Response
Validation rejection before SQL: unregistered task, unencodable payload, NUL in an identifier or an out-of-range value No insertion was attempted Correct the input and dispatch again
A definite SQL rejection, such as an invalid type or a NOT NULL constraint violation That insertion was rejected Correct the cause and dispatch again; respect the transaction's error state
Lost connection, ambiguous COMMIT or a failure after sending the statement The task may have been stored Do not infer that the task is absent; retry with the same deduplication key while it is retained, or reconcile the stored state

Retrying with the same deduplication key prevents duplicate stored tasks while that key is retained. It does not guarantee exactly-once external effects. purge() and deleteFailed() free retained keys. An application transaction must commit before the task becomes durable; commit failures may themselves have an uncertain outcome.

PDO, Doctrine and Cycle cannot reliably classify every failure, so there is no OutcomeUnknownException hierarchy. An arbitrary exception is not proof that nothing was written. See Where the queue lives: with a dedicated queue database, business commit and dispatch are separate writes.

Where the queue lives

The table can live in the application database or in a database of its own. The connection given to the dispatcher decides what dispatch() guarantees:

Dispatcher connection When dispatch() returns
The application connection, inside a transaction The task is written in that transaction: durable with the commit, gone with a rollback (transactional outbox)
A dedicated queue database The task is durable immediately, independently of the business transaction

With a dedicated database, the business commit and the dispatch are two separate writes. For reliable publication, write a transactional application outbox and publish it idempotently: a process can crash between the business commit and a direct dispatch. Tasks must also tolerate changed business data.

The worker always uses its own connection to the queue database.

Stores

All three stores give the same guarantees and pass the same test suite. Use the database the application already has: on the application connection, a dispatch joins the business transaction.

PostgresTaskStore SqliteTaskStore MysqlTaskStore
Hosts Any number of hosts One host Any number of hosts
Reservation One statement with SKIP LOCKED One UPDATE ... RETURNING Short transaction with SKIP LOCKED
Clock Database Host, in whole seconds Database, UTC microseconds
Requires PostgreSQL SQLite 3.38 through pdo_sqlite MySQL 8.0.16+ / Aurora MySQL v3, InnoDB

The SQLite store does not support ext-sqlite3 (Doctrine's sqlite3 driver): it runs a statement again when its rows are fetched, so a reservation would claim a second task. DoctrineConnection refuses that driver. See the PHP bugs:

SQLite serializes writes, not tasks: a worker holds no lock while its task runs, so several workers process tasks in parallel. Contention only shows with many concurrent writes or long application transactions. The store leaves the connection settings to you:

Connections

All SQL stores require Kaly\Tasks\Connection\TransactionalConnection, which extends the two statement operations of Connection with a transaction callback:

Library Connection
PDO new PdoConnection($pdo), or new PdoConnection(fn(): PDO => ...) for a lazy handle, which must return the handle running the transaction
Doctrine DBAL / ORM new DoctrineConnection($entityManager->getConnection())
Cycle new CycleConnection($databaseManager->database())

Statements run on the given connection, inside its current transaction. An EntityManager or a Cycle unit of work opened per operation does not matter: the transaction belongs to the shared connection.

TransactionalConnection is implemented by all three adapters. Its transaction() callback receives a connection pinned to the primary for the whole transaction, commits before returning and rolls back on failure. Existing transactions are refused for this callback: MySQL reservation must release its locks before executing the task, and a sequence completion must commit its transition before returning. Tasks must close their own transactions before returning to the worker. Dispatch and sequence submission still join an existing application transaction normally.

MySQL and Aurora

Requires MySQL 8.0.16+ with InnoDB, or Aurora MySQL v3. Use the writer endpoint for dispatch, reservation and maintenance. Reservations select with FOR UPDATE SKIP LOCKED, update the owner and lease, then commit before the worker invokes the task. The worker uses its own connection without an existing transaction. Database errors propagate and the supervisor restarts the worker; an uncertain commit is recovered through the lease, without running the task on the failed reservation.

MySQL polls queues individually through the pending index to avoid a filesort locking every ready task across several queues. Queue order is shuffled for each reservation; ordering by availability and ID is preserved within each queue. There is no global FIFO guarantee across queues. Use prioritizeQueues on the worker for a strict queue order.

Times are UTC DATETIME(6) values computed by the database, independently of the session time zone. Payloads use LONGTEXT to preserve their exact JSON text. Deduplication indexes a SHA-256 hash of the task name and key, compared bytewise, with the same retention as the other stores (subject to SHA-256 collision risk). Queue names and owner tokens are limited to 255 bytes. Use strict SQL mode to reject oversized values. MySQL table names are plain lowercase identifiers of at most 64 characters. Run schema() through migrations before dispatching; MySQL DDL implicitly commits.

When publishing a business change and a task atomically, share the same physical connection and transaction. Otherwise use a transactional application outbox: a dispatch after a business commit can be lost if the process crashes between the two writes.

Setup

Create the table from your migrations:

PostgresTaskStore takes a table name, optionally schema-qualified (queue.tasks). SqliteTaskStore takes a plain table name.

Register task types and bind the required contracts to the same dispatcher instance:

A persistable task has only public promoted constructor parameters, typed int, float, string, bool, array (of scalars, null and arrays) or a backed enum. Registration checks it. Payloads are JSON objects, including {} for tasks without constructor parameters; JSON lists such as [] are rejected. Float values must be finite, including inside nested arrays. Decoding checks enum backing types strictly and reports invalid payloads with UnexpectedValueException.

Stored payloads are a public contract in both directions while tasks are stored: see Deploying task changes.

dispatch() follows Kaly's void contract. To observe whether deduplication skipped an insertion, use $store->push($registry->encode($task)): it returns true for a new task and false for an existing key.

All stores reject NUL bytes (\0) in task names, queue names, deduplication keys and owner tokens with InvalidArgumentException before executing SQL. This prevents PostgreSQL text parameters from being silently truncated, changing routing or treating distinct tasks as duplicates. NUL characters in task data remain supported as JSON escapes, unless used as a deduplication key.

Worker

Kaly has no console: a worker is a small script of the application.

The third argument is the invoker: it calls each decoded task and provides the services of its __invoke(). With kaly-di, pass $injector->invoke(...). Any other container that can call a callable with its dependencies fits behind a closure; tasks without services only need static fn(object $task) => $task(). The invoker is required on purpose: a worker that silently called tasks without their services would turn a configuration mistake into failed tasks.

Run it under a supervisor (systemd, supervisord, a container restart policy). The worker is crash-only and recycles itself:

Without ext-pcntl (Windows), there is no hard timeout: the lease must cover the longest run.

Queue priority

By default the order of queues carries no meaning: each store keeps its own selection policy (oldest available task across queues on PostgreSQL and SQLite, queues in shuffled order on MySQL). This is not a fairness guarantee.

With prioritizeQueues, the order becomes a strict priority: the worker asks each queue in turn and takes the first reservable task.

The worker opens no container scope per task. Shared services must be re-entrant, and stateful resources (EntityManager, unit of work) are opened by the operation that uses them, as for a request. A task never receives an HTTP context: identity and authorization travel in its data and are checked again.

With PostgreSQL, leases and delays use the database clock, so workers on several hosts agree.

Low-latency PostgreSQL workers

An idle worker sleeps for sleepMs (1 s by default), so an isolated task can wait almost a second before it starts. To wake on commit instead, opt in to LISTEN/NOTIFY:

Add the trigger to your migrations, after schema():

notificationSchema() is idempotent and changes no table or index. It installs an AFTER INSERT OR UPDATE trigger and its function; dropNotificationSchema() removes both and restores plain polling. notificationsEnabled() reports whether the trigger is present and enabled. The waiter logs a warning at start when it is missing, then falls back to polling.

pg_notify() cannot run inside a prepared transaction. If you use two-phase commit (XA), installing the trigger makes PREPARE TRANSACTION fail for any transaction that inserts, releases, recovers or manually retries a task. Enqueue outside the prepared transaction, or leave the trigger uninstalled and poll. This affects existing producers as soon as the trigger exists, even if no worker uses a waiter.

The table stays the source of truth. A notification only makes the worker look again, and every wakeup ends in the usual reservation:

LISTEN does not work through a transaction-pooling PgBouncer connection: give the waiter a direct or session-pooled connection to the same database. The trigger itself costs no measurable insert time, and an idle worker sends about 0.7 statements per second with the default fallback instead of one reservation per sleepMs. See bench/README.md to reproduce the measurements on your own topology.

Failures and retries

A task that throws is retried with its type's backoff until maxAttempts, then fails. Two exceptions change that:

Wrapping execution

One optional wrapper runs around each task invocation, to set up and clean a log context, a trace span, an error tracker scope or a tenant:

TaskRun carries the stored id, the registered name, the queue, the attempt (from 1), maxAttempts and the decoded task. It does not expose the owner token.

Going to production

Retention

Purging is part of the setup, not optional maintenance. Without it the table grows and every deduplication key stays active forever. Choose a retention explicitly and schedule it:

Long tasks and timeouts

Order the limits with a margin at each step: external call timeouts, then the worker timeout, then the lease.

Deploying task changes

Stored payloads are a contract in both directions. New code reads payloads stored by the previous version, and during a rolling deploy previous workers read payloads from new producers. Decoding is strict: a payload with a key the worker does not know fails for good, without retry.

Unknown keys are rejected on purpose: silently dropping data would be worse than a visible failure. A task failed this way can be retried with retryFailed() once compatible workers run.

Maintenance

failed() returns rows with id, queue, name, payload, attempts, error, created_at and finished_at. Both dates are Unix timestamps in whole seconds. retryFailed() preserves the previous error until the task succeeds or another failure replaces it.

Done and failed tasks are kept until purged: their deduplication keys stay active for the retention period. Without the second argument, failed tasks are kept until you retry or delete them. Schedule the purge as part of the setup: see Retention.

Each call uses one aggregate SELECT on the writer. Its five values share the statement's view under the connection's isolation rules; they may be stale as soon as it returns, and separate calls do not share a snapshot. Availability comparisons use the database clock. earliestPendingAt is floored to whole UTC seconds, or null without pending tasks. When work is ready, this date is in the past or now and shows how long the oldest pending work has been waiting. stats(null) covers the whole table; an empty queue name or one containing NUL bytes is rejected.

Statistics use the existing status indexes without a schema change. The global minimum may scan pending entries across queues; the cost grows with pending work, even though completed tasks can be excluded. A queue filter allows an indexed lookup for its oldest pending availability. Measure against your active queue size before polling frequently. These statistics support application dashboards and supervision; they do not provide history, durations, per-type metrics or a console command.

Tests

Every suite runs against all three stores. The SQLite tests use temporary files and always run; set KALY_TASKS_PGSQL_DSN to another database, or empty to skip the PostgreSQL tests. KALY_TASKS_MYSQL_DSN defaults to mysql:host=127.0.0.1;port=53306;dbname=kaly_tasks;user=kaly;password=kaly;charset=utf8mb4; set it empty to skip MySQL. The MySQL test engine reads the user/password fields from this test DSN and passes them to PDO separately. MySQL tests include the store contract through PDO, Doctrine and Cycle, worker concurrency, signals, transaction rollback, locked rows and stale owners.

To run only the local SQLite tests:

The default DSNs expect Docker on ports 55432 (PostgreSQL) and 53306 (MySQL). If a database is configured but unreachable, the tests fail rather than silently skipping it.

The PostgreSQL suite also covers the opt-in LISTEN/NOTIFY support: trigger semantics, schema install and drop, deferred wakeups, draining, reconnect and SIGTERM interrupting an idle wait. php bench/run.php reproduces the latency and reservation measurements; see bench/README.md.


All versions of kaly-tasks with dependencies

PHP Build Version
Package Version
Requires php Version ^8.3
ext-pdo Version *
lekoala/kaly-contracts Version ^1.0
psr/log Version ^1.0 || ^2.0 || ^3.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package lekoala/kaly-tasks contains the following files

Loading the files please wait ...