Workflow data tools

Native Pascal, workflow preparation

Description

Use these native Pascal units to prepare JSON requests, manage memory-backed job resources, plan page batches and transfer bounded byte streams before executing a document operation

JSON ownership and editing

PDFlibWorkflowJSON owns children added to an object or array and frees them with the parent; after successful insertion, do not free the child separately

procedure TPLWorkflowJSON.SetMember(const MemberName: WideString; Value: TPLWorkflowJSON);
procedure TPLWorkflowJSON.Insert(Index: Integer; Value: TPLWorkflowJSON);
function TPLWorkflowJSON.Detach(Index: Integer): TPLWorkflowJSON;
function TPLWorkflowJSON.RemoveMember(const MemberName: WideString): Boolean;
function TPLWorkflowJSON.Remove(Index: Integer): Boolean;
function TPLWorkflowJSON.Clone: TPLWorkflowJSON;
function TPLWorkflowJSON.EqualsValue(Other: TPLWorkflowJSON): Boolean;

SetMember replaces or appends an object member; Insert inserts into an array at a zero-based index, including its end; Detach transfers a child to the caller, whilst the remove methods free it

Nil children, duplicate object names passed to Add, already-owned children and ownership cycles are rejected with an exception before ownership transfers; an invalid detach returns Nil and an invalid remove returns False

Clone copies every descendant independently and preserves the original number text; EqualsValue ignores object member order, respects array order and compares decimal numbers exactly, including equivalent spellings such as 1, 1.0 and 10e-1

Cloning, comparison, transformations and formatted serialisation enforce a maximum depth of 256, a 250,000-node work budget and a cumulative 32 Mi UTF-16 character work budget; formatted output is also limited to 32 Mi code units; construct values using the ownership methods and treat the public Kind and Text as the matching JSON scalar representation

JSON Pointer and transformations

function TPLWorkflowJSON.Pointer(const Path: WideString): TPLWorkflowJSON;
function PLApplyWorkflowJSONPatch(Source, Patch: TPLWorkflowJSON;
  out Value: TPLWorkflowJSON; out ErrorText: WideString): Boolean;
function PLMergeWorkflowJSON(Source, Patch: TPLWorkflowJSON): TPLWorkflowJSON;

JSON Pointer uses ~0 for a literal tilde and ~1 for a literal slash; an empty path selects the root; array indexes start at zero and may not have leading zeros; malformed or missing paths return Nil

For example, /a~1b/~0/0 selects the first array element under the object keys a/b and ~

JSON Patch accepts up to 10,000 operations named add, remove, replace, move, copy and test; array add accepts - to append; moving a value into its own descendant fails

The patch works on a private clone; a failed operation returns False with an operation number and leaves Value Nil and the original source untouched; success transfers the resulting tree to the caller, including Nil when removing the entire document

Merge Patch recursively merges objects, deletes members whose patch value is null, and replaces other values, including arrays; it returns a new caller-owned tree and never modifies either input; invalid or excessive work raises an exception

Controlled JSON parsing and values

function PLDefaultWorkflowJSONOptions: TPLWorkflowJSONOptions;
function PLParseWorkflowJSONEx(const Source: WideString;
  const Options: TPLWorkflowJSONOptions; out Value: TPLWorkflowJSON;
  out Error: TPLWorkflowJSONError): Boolean;
function TPLWorkflowJSON.TryInt64(out Value: Int64): Boolean;
function TPLWorkflowJSON.TryDouble(out Value: Double): Boolean;
function TPLWorkflowJSON.SerializeFormatted(Indent: Integer; SortNames: Boolean): WideString;

Start from the default options and adjust MaxLength, MaxDepth, MaxNodes and MaxContainerItems for the request budget; defaults are 32 Mi UTF-16 code units, depth 64, 250,000 nodes and 10,000 children per container; depth may not exceed 256

A failed parse leaves the output Nil and returns the one-based UTF-16 character Position, Line, Column, BudgetExceeded and MessageText; the original parse function retains these defaults and its string error interface

TryInt64 accepts only an exact integer number spelling within the signed 64-bit range; TryDouble accepts decimal and exponent spellings with a JSON decimal point independently of the system locale and rejects overflow and non-finite values; both return False and zero for invalid input

Use SerializeFormatted(2, True) for readable, repeatable request files; indentation is 0 to 16 spaces, newlines are LF, and optional key sorting compares UTF-16 names; this is stable formatting rather than a cryptographic JSON canonicalisation format; compact Serialize is unchanged

Ordered page plans

function PLCombinePageSelections(const Left, Right: array of Integer;
  Operation: TPDFPageSelectionOperation; MaxPages: Integer = 1000000): TPDFPageRangePages;
function PLAnalyzePageSelection(const Pages: array of Integer;
  MaxPages: Integer = 1000000): TPDFPageSelectionAnalysis;
function PLBatchPageSelection(const Pages: array of Integer; BatchSize: Integer;
  MaxPages: Integer = 1000000): TPDFPageSelectionBatches;

PDFlibPageRanges combines parsed selections using psoUnion, psoIntersection or psoDifference; every result is deduplicated in left selection order, and union appends new right-side pages in their original order

Analysis reports TotalCount, UniqueCount, DuplicateCount, MinPage, MaxPage and maximal contiguous Runs; a run carries the zero-based selection Offset, Count, endpoint pages and a Direction of 1, -1 or 0 for a singleton; empty min and max are zero

Batching returns zero-based selection offsets and counts without copying, sorting or deduplicating the pages; duplicates and reverse order remain available to the document operation; invalid page numbers, limits or batch sizes raise an exception before processing

Read slices and copying

constructor TPLWorkflowReadSlice.Create(Source: TStream; Offset, Count: Int64;
  PreserveSourcePosition: Boolean = True);
function PLCopyWorkflowStream(Source, Target: TStream; Count, MaxBytes: Int64;
  PreserveSourcePosition: Boolean = False;
  Checkpoint: TWorkflowCheckpoint = Nil): Int64;

PDFlibWorkflowStreams provides a non-owning read-only slice of a seekable stream; offsets are absolute in the source and relative in the slice; writes, resizing and seeks outside the slice fail; the source must remain alive and unchanged whilst the slice is used

Copying uses fixed 64 KiB chunks and returns the bytes written; Count=-1 copies through EOF, whilst a nonnegative count requires exactly that many bytes; MaxBytes is a hard output budget, including zero; a specified count above the budget fails before I/O

A checkpoint runs before reads and writes and may raise EWorkflowCancelled; excess output raises EWorkflowBudgetExceeded, early EOF raises EReadError, and failed writes raise EWriteError; the target may contain a partial result, so stage it before publishing

When copying through EOF, one extra byte may be read to distinguish an exhausted budget from EOF; with position preservation enabled, a seekable source is restored on success and on failure; source and target must differ and must not share mutable backing storage

Example and related APIs

Virtual file registry describes scoped resources, quotas, snapshots and revisions used with these tools; the complete console example is Demo/Lazarus/WorkflowTools/WorkflowTools.lpr

ProbeWorkflowRequest checks renderer and resource dependencies after preparing a request