Search by

adachsoft / workflow-definition-repository-json

Arkadiusz Adach

JSON file-based implementations of WorkflowDefinitionRepositoryInterface and WorkflowRunRepositoryInterface.

Package info

gitlab.com/a.adach/workflow-definition-repository-json

Issues

pkg:composer/adachsoft/workflow-definition-repository-json

Statistics

Installs: 52

Dependents: 0

Suggesters: 0

Stars: 0

v4.2.0 2026-11-23 20:54 UTC

This package is auto-updated.

Last update: 2026-11-23 19:54:47 UTC


README

A JSON file-based implementation of WorkflowDefinitionRepositoryInterface from adachsoft/workflow. Each workflow definition is stored in a separate JSON file.

Requirements

  • PHP 8.3 or later
  • adachsoft/workflow ^7.5

Installation

composer require adachsoft/workflow-definition-repository-json

Usage

<?php

declare(strict_types=1);

use AdachSoft\WorkflowDefinitionRepositoryJson\JsonFileWorkflowDefinitionRepository;
use AdachSoft\WorkflowDefinitionRepositoryJson\Mapper\WorkflowDefinitionJsonMapper;

$repository = new JsonFileWorkflowDefinitionRepository(
    __DIR__ . '/var/workflows',
    new WorkflowDefinitionJsonMapper(),
);

$definition = $repository->get('invoice');
$repository->save($definition);
$definitions = $repository->list();

get() returns a WorkflowDefinitionVo for the requested workflow ID and throws WorkflowNotFoundException when its JSON file does not exist. save() writes a workflow definition to <workflows-directory>/<workflow-id>.json, creating the directory when needed. list() returns workflow definitions keyed by ID in sorted order; it returns an empty array if the directory does not exist.

Workflow run repository

Workflow execution state can also be stored as one JSON file per run:

<?php

declare(strict_types=1);

use AdachSoft\WorkflowDefinitionRepositoryJson\JsonFileWorkflowRunRepository;
use AdachSoft\WorkflowDefinitionRepositoryJson\Mapper\WorkflowRunJsonMapper;

$runRepository = new JsonFileWorkflowRunRepository(
    __DIR__ . '/var/runs',
    new WorkflowRunJsonMapper(),
);

$run = $runRepository->get('run_6af54054929692.21062525');
$runRepository->save($run);

save() creates the runs directory when needed and atomically writes <runs-directory>/<run-id>.json by renaming a temporary file in that directory. Run IDs may contain only letters, digits, dots, underscores, and hyphens, and may not contain ... get() throws WorkflowNotFoundException when the run file does not exist. Invalid JSON and invalid run data raise a readable RuntimeException containing the file name. Payload and context values support scalars, null, and nested arrays; nested PayloadVo values are stored as arrays, while other objects are rejected with WorkflowException.

Run files use format version 2 and store the identifiers, current step, context, output, lifecycle, and latest step execution. The original workflow input is stored in context; there is no separate run input field. Dates are written as ISO 8601 strings with a timezone, and a suspended lifecycle stores its reason, optional deadline, allowed decisions, awaited run ID, and payload.

{
  "format": 2,
  "runId": "run_6af54054929692.21062525",
  "workflowId": "invoice",
  "parentRunId": null,
  "currentStep": "calculate_total",
  "context": {
    "customer": {
      "name": "Żaneta"
    },
    "locale": "pl-PL"
  },
  "output": {
    "total": 42
  },
  "lifecycle": {
    "status": "PAUSED",
    "mode": "DEBUG",
    "startedAt": "2025-01-01T10:00:00.000000+00:00",
    "updatedAt": "2025-01-01T10:01:00.000000+00:00",
    "error": null,
    "suspension": null
  },
  "lastStepExecution": {
    "stepName": "calculate_total",
    "input": {
      "subtotal": 40
    },
    "output": {
      "total": 42
    },
    "branch": "success"
  }
}

lastStepExecution.branch is null when the recorded step suspended. Files from the 3.x format (without format) remain readable: the old input is merged into context, unfinished debug runs become paused debug runs, and missing timestamps use the file modification time. get() throws a RuntimeException with the file path for unreadable or invalid run files; find() silently skips those files.

The repository implements exists() and find() in addition to save() and get():

use AdachSoft\Workflow\Run\WorkflowRunQueryDto;
use AdachSoft\Workflow\Run\WorkflowRunStatusEnum;

$exists = $runRepository->exists('run_6af54054929692.21062525');
$suspendedRuns = $runRepository->find(new WorkflowRunQueryDto(
    statuses: [WorkflowRunStatusEnum::SUSPENDED],
));

Query results are ordered by lifecycle.updatedAt descending and then by run ID ascending, with limit and offset applied afterward. deadlineBefore includes suspended runs whose deadline is equal to the supplied time. An empty payload is restored as an empty PayloadVo.

Step execution history

JsonFileStepExecutionHistory implements StepExecutionRecorderInterface and StepExecutionHistoryQueryInterface. It appends each step record to <history-directory>/<run-id>.steps.jsonl under a file lock and creates the directory when needed. Run IDs use the same safe file-name rules as JsonFileWorkflowRunRepository.

use AdachSoft\WorkflowDefinitionRepositoryJson\JsonFileStepExecutionHistory;

$stepHistory = new JsonFileStepExecutionHistory(
    __DIR__ . '/var/workflow-runs',
    maxRecordsPerRun: 500,
    maxPayloadBytes: 65536,
);

$runId = 'run_6af54054929692.21062525';
$nextSequence = $stepHistory->nextSequence($runId);
// Use $nextSequence when constructing the StepExecutionRecordDto to record.
$stepHistory->record($record);
$records = $stepHistory->findByRunId($runId);

nextSequence() returns the next one-based sequence under a lock, and record() rejects records that do not use that sequence. findByRunId() returns records in sequence order, skips corrupt lines, and returns an empty collection when the run file does not exist. The default limit is 500 records per run; records beyond the limit are silently ignored. Input and output payloads are limited independently to 65,536 encoded JSON bytes by default. An oversized payload is replaced with {"_truncated": true, "_original_bytes": N}, where N is the original encoded payload size in bytes. Record timestamps are stored as ISO 8601 values with microseconds.

JSON format

A workflow file contains a steps object keyed by step name. It may also contain input_schema and output_schema objects:

{
  "name": "Invoice workflow",
  "description": "Processes invoices and records the final status.",
  "input_schema": {
    "customer_id": {
      "type": "string",
      "required": true,
      "description": "Customer identifier"
    }
  },
  "output_schema": {
    "status": {
      "type": "string",
      "required": true,
      "description": "Batch status"
    },
    "images": {
      "type": "array",
      "required": true,
      "description": "Saved images"
    }
  },
  "steps": {
    "finish": {
      "type": "finish",
      "config": {
        "output": {
          "status": "done",
          "images": []
        }
      }
    }
  }
}

The optional top-level name and description fields must be strings; they are mapped to WorkflowDefinitionVo and written back when non-null. Definitions without these fields remain readable and are saved without them. The mapper converts workflow steps and nested JSON objects to workflow payload values, and maps schema declarations to workflow schema value objects. If input_schema is omitted, it is treated as empty; saving a workflow writes the input_schema field. If output_schema is omitted, no workflow output contract is declared and saving omits the key. An explicit empty output schema is serialized as [], declares an empty output contract, and is preserved on save and load; it is distinct from an omitted schema. Output schema fields use the same format as input schema fields. Invalid schema field definitions are rejected by the schema contract in adachsoft/workflow. Malformed JSON or an invalid top-level workflow structure raises RuntimeException.

Tests

Run the PHPUnit suite with:

vendor/bin/phpunit tests