broker

module
v0.0.0-...-644b821 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0

README

Introduction

CrossLink broker is a system to manage inter-library loans (ILL), specifically it:

  • accepts and handles ILL requests from external requesters (e.g Alma or ReShare) via the ISO18626 protocol
  • locates suppliers and their holdings from a Union Catalog using the Search/Retrieval via URL (SRU) protocol
  • resolves supplier information via the Directory API
  • checks item availability using the Z3.50 or the SRU protocol
  • negotiates loans with external suppliers (e.g Alma or ReShare) via ISO18626
  • allows internal requesters and suppliers to manage ILL requests using a convenient JSON API
  • provides ILS integration for internal requesters and suppliers via NCIP (NCIP 1.0 adapter)

Incoming ISO18626 transaction events include eventData.charset, for example "UTF-8 (declaration)". The value records the encoding used to decode the message and its source: BOM, Content-Type, declaration, or default, in precedence order. This field is omitted for messages processed internally without HTTP input.

Patron-request patron-request-message events include resultData.stateModelEvent when a supplier or requester message resolves to a state-model event, for example will-supply or received. The label is retained even when the event is rejected in the current state or subsequent processing fails. It is omitted when no label is resolved, including ordinary notifications and initial requests. The ISO message and confirmation remain in the same log record.

Successful local-supply invoke-action events carry an audit label in the same field: completed-local for fill-locally and requester supply-document, cancelled-local for cancel-local-supply, and unfilled-local for cannot-supply-locally. The broker does not relay local-supply messages back to the requester, so the action records the outcome itself. These labels are not state-model events and do not change state; the action's transition does.

These results are available through GET /patron_requests/{id}/events. Older records may lack the field.

Cancellation reasons in ISO18626 notes

Incoming requester Cancel messages and supplier CancelResponse messages (including rejections) can carry #CancellationReason: <reason># in their note. The reason is arbitrary nonblank text, for example InvalidUser or Duplicate Request, and cannot contain #. The prefix is case-sensitive. Surrounding whitespace in the value is trimmed.

The first nonblank reason is stored in the patron request's cancellationReason; all complete nonblank reason markers are removed from the working note. Other text, whitespace, and microformats remain intact for normal processing. The first # after CancellationReason: closes the reason, regardless of following text. For example, #CancellationReason: InvalidUser#Ref: 123# stores InvalidUser and leaves Ref: 123#. Adjacent microformats require separate closing and opening hashes, such as #CancellationReason: InvalidUser##ReShareLoanConditionRejectResponse#; hashes cannot be shared between markers or escaped inside a reason. Empty markers and prefixes without a closing hash remain ordinary note text. Existing notification-history cleanup of condition and item markers still applies.

Plain notes no longer populate cancellationReason. A message without a valid reason marker leaves the stored reason unchanged; a later valid reason replaces it. This does not change cancellation routing or state transitions.

The extracted reason is also recorded as a notification of kind cancellation_reason, with the reason in code and the remaining note text, if any, in note. Requesters keep a sent copy when their cancel-request action succeeds; the receiving side stores a received copy.

Notification codes

A notification's code is interpreted by its kind: the loan condition for condition, the reason for cancellation_reason and unfilled_reason, and absent for note. Libraries define their own codes, so code is free text owned by the sender (fromSymbol). When the sender's cached Directory entry lists the code under loanConditions, cancellationReasons or unfilledReasons, its description is copied into codeDescription when the notification is stored; otherwise codeDescription is absent. Behind an opaque broker, received notifications come from the broker's symbol, so the sender's vocabulary is not visible and they carry only code; sent copies are always described from the sender's own entry. Unfilled reasons come from ISO18626 reasonUnfilled, both on incoming supplier messages and on this broker's cannot-supply action. A message is stored as one notification; when it carries several coded values, a condition (or cost) takes precedence over an unfilled reason, which takes precedence over a cancellation reason.

Email and pull-slip templates render conditions through {{.LoanConditions}}; the note text of every other notification kind, including reason notifications, appears in {{.StaffNotes}}; notifications without note text are skipped. Reason codes are not staff notes: cancellation reasons render through {{.CancellationReason}}.

External vendor shims strip these markers from outgoing requester, supplier, and request-service notes before serialization, using a copy so internal messages retain their data. Local CrossLink delivery retains markers for extraction. Original received messages remain in the event audit trail.

The requester cancel-request action accepts an optional actionParams.note and forwards it unchanged in the internal requester Cancel message, addressed to the configured Broker symbol. Omitting the note sends an empty note. Callers may include a cancellation-reason microformat in the note; the action does not generate one automatically. When cancellation is successfully sent, the extracted reason is saved on the originating borrowing request along with its action result and state. A failed send or a note without a valid reason leaves the stored reason unchanged. A supplier response without a reason marker preserves that value, including when cancellation is accepted. Existing incoming extraction and external-shim cleanup apply on delivery.

API

The broker exposes a JSON API that addresses two use cases:

  1. The ILL Transactions API endpoints allow monitoring ILL transactions and events and managing transaction-related entities such as peers and located suppliers. ILL transactions handled through this API are usually created by external ILL clients (e.g Alma or ReShare) via the ISO18626 protocol. See the Broker API Specification for details.

  2. The Patron Request API is used to create and manage ILL borrowing and lending requests directly in the broker. The lifecycle of a Patron Request is governed by a state model—a specification of allowed states, actions, and transitions. See the State Model Schema and the embedded state model for returnable loans and non-returnable copies, whose conditional elements use appliesTo.serviceTypes. This API supports building multi-tenant management/staff UIs on top of the broker or tightly integrating the broker into existing solutions. Internally, the broker creates an ILL transaction to back the execution of a Patron Request so that the detailed monitoring is available through the ILL Transactions API. See the Broker API Specification for details, where relevant endpoints are tagged with patron-requests-api.

A rerequest creates a new borrowing request linked to its predecessor through prevReqId and nextReqId. With noop: true, the action only records the transition; the requester must create the replacement through POST /patron_requests and supply prevReqId to retain the link. Both flows send a New ISO18626 request carrying requestingAgencyPreviousRequestId. When the receiving supplier has the matching previous lending request for the same requester and tenant, it links the two supply requests atomically. A supplier without that predecessor accepts the request without links. Retries retain their Retry request type and use the same supplier-side linking.

The broker’s APIs use hyperlinks to connect JSON resources. If you use Chrome or another browser to explore the API, consider installing an extension like JSON Formatter Classic, which makes hyperlinked JSON easier to navigate.

Note on FOLIO integration: selected API endpoints are available under the base path /broker when the TENANT_TO_SYMBOL environment variable is set. This enables the broker to operate as a FOLIO/Okapi module with authentication/authorization and multi-tenancy support; see the ModuleDescriptor for details.

Archiving patron requests

Create a scheduled archive-borrowing-requests or archive-lending-requests batch action through POST /batch_actions (or /broker/batch_actions in Okapi). An owner symbol is required. batchQuery selects eligible patron-request states and may include other patron-request CQL filters. actionParams.interval is a positive Go duration measured from patron_request.updated_at; anonymize defaults to false. Borrowing actions are restricted to requester_symbol, and lending actions to supplier_symbol, matching the action's owner.

{
  "title": "Archive closed borrowing requests",
  "schedule": "FREQ=DAILY;BYHOUR=3",
  "actionName": "archive-borrowing-requests",
  "batchQuery": "terminal_state = true",
  "actionParams": {"interval": "720h", "anonymize": false}
}

The lending default uses the same schedule, CQL selector, and action parameters, with actionName: "archive-lending-requests" and title "Archive closed lending requests". Defaults are offered through the state-model API as starting points for tenant-owned scheduled actions.

Each run archives up to 100 matching requests. It scans pages of 100 candidates in creation-time/ID order, continuing past skipped and failed requests until the archive limit is reached or all matches have been examined. CQL sortBy does not change this scan order. Counts and up to 100 per-request failures are recorded in the batch-action event history. Both borrowing and lending runs report the total skipped count with three groups:

  • Active events or signals: events in NEW/PROCESSING or with pending signals on the request, or (for borrowing) its transaction and related lending requests.
  • Unfinished related requests: related nonterminal lending requests or Retry successors that still depend on the borrowing request's transaction. This count is always zero for lending archives.
  • Changed or busy requests: the selected request no longer matches its owner, side, state, timestamp, or age cutoff (including removal by another run), or a related request or item could not be locked immediately.

Each skipped request counts only in the group for its first blocking check, so the three counts sum to the skipped total. Skips remain eligible for later runs if they still match the selector and age cutoff. For example:

archived 0 borrowing requests; skipped 40 requests (active events or signals: 25; unfinished related requests: 10; changed or busy requests: 5); failed 0 requests

These counts describe the current run; earlier history is not recalculated. Pending signals are checked through event.last_signal, which consumers clear when claiming them. Borrowing checks exclude observer-only supplier-added and supplier-moved rota audit notices, whose signals remain set; these notices are still archived. Archiving does not track handlers through completion, so an old terminal request can be archived during the handoff from a claimed signal to follow-up work. The archive is in archived_resource, keyed by resource type and ID, with owner, timestamp, schema version, anonymization metadata, and one JSONB bundle. The bundle holds the selected request, its events, items, notifications, and notes.

Borrowing archival also waits for nonterminal lending requests with the same requester symbol and request ID, and for a nonterminal Retry successor while the transaction still belongs to its predecessor. Activity checks and event locks include related lending requests' patron-request-domain tasks, including tasks on terminal requests that use the synthetic transaction ID. New rerequests use independent transactions and do not defer predecessor archival. Contention on related request rows skips the candidate for a later run. Borrowing archives additionally include the associated ILL transaction, transaction events, and located suppliers. Lending archives store only the supplier PR's data and preserve the transaction, located suppliers, borrowing PR, and their events. Resource types are borrowing-patron-request and lending-patron-request. Each archive insertion and deletion of the corresponding live records is atomic. The request's internal_note and other notes are included in their owning rows. With anonymize: true, an explicit allowlist retains operational states, actions, outcomes, timestamps, institution symbols, service/request types, item LMS status, and notification amounts/currency. Personal fields, record identifiers inside the bundle, bibliographic/free-text fields, notes, embedded messages, error payloads, and custom data are omitted. Unknown keys and structured values in scalar fields are discarded, so numeric personal identifiers and personal JSON keys cannot survive through unstructured data. Archive owner/resource metadata remains for identification, and anonymization_method records operational-allowlist-v1. Import and restoration are not supported.

Archiving ILL transactions

Use archive-ill-transactions for transactions without a local borrowing PR. An owner symbol is required, and candidates are restricted to that exact requester_symbol. batchQuery uses ILL-transaction CQL, not patron-request fields. interval is measured from ill_transaction.timestamp; anonymize defaults to false and uses the same operational allowlist described above.

{
  "title": "Archive completed external borrowing transactions",
  "schedule": "FREQ=DAILY;BYHOUR=3",
  "actionName": "archive-ill-transactions",
  "batchQuery": "last_supplier_status==LoanCompleted or last_supplier_status==CopyCompleted or last_supplier_status==Unfilled",
  "actionParams": {"interval": "720h", "anonymize": false}
}

A default with these values is offered through the state-model API as a starting point for a scheduled action. Creating it still requires broker.consortium.all.

Each run archives up to 100 transactions, scanning pages of 100 in stable ID order regardless of CQL sortBy. Changed or locked transactions, transactions with local borrowing PRs, nonterminal related requests, active events, pending consumer signals, or pending availability attempts are skipped. Observer-only supplier-added and supplier-moved rota audit signals do not block archival. Claiming a signal clears it; consumer handlers are not tracked through completion. Related requests are matched by requester symbol and current/previous requester request ID. The caller selects the statuses to retain through CQL; age alone does not prove that a transaction is finished.

Each atomic archive stores a version-1 ill-transaction bundle in archived_resource containing illTransaction, illTransactionEvents, and locatedSuppliers, then removes their live records. Lending PRs and their PR-domain events remain live; their transaction references are detached. Counts and bounded failure details are recorded in batch-action history.

Creating, updating, enabling, disabling, deleting, or manually running this action requires broker.consortium.all in addition to the normal batch-action operation permission. The Tenant abstraction resolves this capability from trusted Okapi permissions; trusted master access retains its existing behavior. Owner scoping still applies. Reading actions and their history uses existing read permissions. Import is available only through trusted master access and accepts this action with the same configuration validation.

POST /batch_actions/{id}/run (or /broker/batch_actions/{id}/run) queues one manual run and returns 202. It preserves the saved schedule and enabled state, so a disabled action can be run once without enabling it. Okapi callers need broker.batch_actions.item.run.post. Scheduled and manual batch runs can overlap, including while earlier batch events or background actions remain unfinished. Archive operations use database locking and atomic checks for each resource.

The legacy archive binary, POST /archive_ill_transactions, call_archive.sh, and their database function have been removed. Replace old jobs with scheduled batch actions. Historical rows in archived_ill_transactions are preserved; new archives use archived_resource. Stop legacy jobs and upgrade all broker replicas before enabling the new action: migration 078 removes the legacy function and adds request/transaction locking used by the new archiver. Import and restoration of transaction archives are not supported.

Compatibility with external peers

ISO18626 is designed as a peer-to-peer protocol and, as such, does not include any specific provisions (e.g., message types or statuses) for broker-based operations.

CrossLink Broker relies on regular ISO18626 exchanges to provide broker-specific functionality in a protocol-compliant manner:

  1. Automatically sends a requester-facing ISO18626 ExpectToSupply message each time a new supplier is selected.
  2. Forwards supplier Unfilled messages as Notification messages rather than StatusChange messages, to avoid terminating the borrowing request too early. Regular Unfilled status is communicated at the end of the transaction when the broker exhausts all suppliers ("end of rota").
  3. local supply feature: detects when the supplier is part of or the same institution as the requester and acts accordingly to the selected mode

To remain compatible with existing external ISO18626 peers, CrossLink Broker can operate in two modes:

  1. opaque -- in this mode, Broker's own symbol (set via the BROKER_SYMBOL env var) is used in the headers of outgoing messages, behaving as a regular ISO18626 peer. For external peer messages, the actual supplier is identified by prepending Supplier: {symbol} to the message note field. ExpectToSupply messages after a supplier change are sent as a Notification rather than a StatusChange. Supplier notifications from skipped suppliers are still forwarded, with the original supplier identified in the note. Upon detecting local supply, the supplier is skipped.

  2. transparent -- the requester and supplier symbols are used in the forwarded message headers, thus fully revealing both parties. When detecting local supply, messages are not forwarded but instead handled between the requester and the broker.

The broker mode can be configured for each peer individually by setting the BrokerMode field on the peer entity (via the /peers/:id endpoint). Unless explicitly set, the broker will configure the BrokerMode automatically based on the peer Vendor field as follows:

  • vendor Alma -> external peer in opaque mode
  • vendor ReShare -> external peer in transparent mode
  • vendor ILLiad -> external peer in opaque mode
  • vendor CrossLink -> internal peer, ILL requests are managed via the Patron Requests API, no outgoing ISO18626
  • vendor Unknown -> mode set via the fallback BROKER_MODE env var, opaque by default

Additionally, the broker includes a shim layer to modify the ISO18626 messages using vendor-specific logic. This is often needed as ISO18626 implementations tend to diverge from the standard and may include custom extensions.

Note that for all modes, the broker attaches Directory information about the supplier and the requester by

  • appending requestingAgencyInfo and supplierInfo fields to the outgoing lending request message
  • appending returnInfo field to the outgoing Loaned supplying agency message

Configuration

Configuration is provided via environment variables:

Name Description Default value
HTTP_PORT Server port 8081
DB_TYPE Database type postgres
DB_USER Database user crosslink
DB_PASSWORD Database password crosslink
DB_HOST Database host localhost
DB_DATABASE Database name crosslink
DB_PORT Database port 25432
DB_SCHEMA Database schema to use crosslink_broker
DB_PROVISION Should app create DB role/schema (true/false) false
DB_MIGRATE Should app run DB migrations (true/false) true
DB_EXPLAIN_ANALYZE Whether to run EXPLAIN ANALYZE on patron false
requests limited by CQL
LOG_LEVEL Log level: ERROR , WARN , INFO , DEBUG INFO
ENABLE_JSON_LOG Should JSON log format be enabled false
BROKER_MODE Default broker mode if not configured for a peer: opaque
opaque or transparent
BROKER_SYMBOL Symbol for the broker when in the opaque mode ISIL:BROKER
REQ_AGENCY_INFO Should request/requestingAgencyInfo be populated true
from Directory Deprecated: use requester
illConfig.includeRequestingAgencyInfo .
SUPPLIER_INFO Should request/supplierInfo be populated from true
Directory Deprecated: use supplier
illConfig.includeSupplierInfo .
RETURN_INFO Should returnInfo be populated from Directory true
for supplier Loaned message Deprecated: use
supplier illConfig.includeReturnInfo .
VENDOR_NOTE Should note field be prepended with true
Vendor: {vendor} text Deprecated: use requester
illConfig.includeVendorNote .
OFFERED_COSTS Should deliveryCosts be transferred to false
offeredCosts for ReShare vendor requesters
Deprecated: use requester
illConfig.useOfferedCosts .
NOTE_FIELD_SEP Separator for fields (e.g. Vendor) prepended to ,
the note Deprecated: use recipient
illConfig.noteFieldSeparator .
CLIENT_DELAY Delay duration for outgoing ISO18626 messages 0ms
SHUTDOWN_DELAY Delay duration for graceful shutdown (in-flight 15s
connections)
MAX_MESSAGE_SIZE Max accepted ISO18626 message size 100KB
HOLDINGS_ADAPTER Comma-separated, ordered list of holdings lookup mock
methods: mock , sru and/or consortium (e.g.
consortium,sru ). Each is tried in order; the
next is used when one has no adapter for the
requester, cannot search with the request's
parameters, or returns no holdings. Other lookup
and adapter configuration errors stop the chain
once reached, unless an earlier source found a
record. Entries must be unique
HOLDINGS_SRU_URL Comma separated list of URLs when http://localhost:8081/sru
HOLDINGS_ADAPTER includes sru
HOLDINGS_ISXN_LOOKUP Whether to use ISBN/ISSN lookup for sru method false
HOLDINGS_FORMAT Parser for SRU holdings: reservoir , marc , reservoir
opac or MARC-21plus-1
CONSORTIUM_SYMBOL Consortium configuration peer, including lender scoring policy (empty value)
for consortium. At this time, it is used when
HOLDINGS_ADAPTER = consortium .
DIRECTORY_ADAPTER Directory lookup method: mock or api mock
DIRECTORY_API_URL Comma separated list of URLs when http://localhost:8086/directory/entries
DIRECTORY_ADAPTER is api
AVAILABILITY_ADAPTER Availability adapter: mock , zoom , zoom
metaproxy . see
Building with native extensions (CGO)
METAPROXY_URL Metaproxy URL when AVAILABILITY_ADAPTER = (empty value)
metaproxy
PEER_REFRESH_INTERVAL Peer refresh interval (via Directory lookup) 5m
MOCK_PEER_URL Mocked peer URLs value when DIRECTORY_ADAPTER is http://localhost:19083/iso18626
mock
MOCK_PICKUP_INSTITUTION_SYMBOL Institution symbol owning synthetic pickup ISIL:MOCK
locations in mock directory mode; use this as the
requester symbol for selected pickup locations
API_PAGE_SIZE Default value for the limit query parameter when 10
paging the API
TENANT_TO_SYMBOL Pattern to map tenant to requesterSymbol when (empty value)
accessing the API via Okapi, the {tenant} token
is replaced by the X-Okapi-Tenant header value.
If pattern is exactly directory the symbol will
be obtained by directory lookup.
SUPPLIER_PATRON_PATTERN Pattern used to create patron ID when receiving %v_user
Request on supplier side Deprecated: use supplier
illConfig.supplierPatronPattern .
LANGUAGE Language parameter used for ts_vector search in DB english
SCHEDULER_RETRY_DELAY Delay for failed tasks, pull-slip email runs 5m
waiting for prior work, and fallback polling
SMTP_HOST SMTP server host for sending emails, if not (empty value)
configured all email tasks will fail
SMTP_PORT SMTP server port 2525
SMTP_USERNAME Username for SMTP authentication (empty value)
SMTP_PASSWORD Password for SMTP authentication (empty value)
BATCH_PULLSLIP_MAX_COUNT Max count of Patron request to include in pullslip 100
batch
BATCH_ACTION_RUN_RETENTION Number of batch action events to retain. Set to 0 5
to disable retention cleanup.

Availability checks are enabled per supplier by the presence of catalogConfig.sru or catalogConfig.zoom in its Directory entry. Other catalog settings, such as metadataUpdateMode, do not enable availability checks. A successful lookup with no holdings skips the supplier and advances the rota. Adapter, lookup, and result-processing failures are recorded as errors but fail open: the selected supplier still receives the request. This prevents a transient catalog failure from being treated as confirmed unavailability.

Build

Generate sources and compile the broker with:

make

This builds broker, the main program for the ILL service.

You can also run included tests with:

make check

or run test for selected _test package

go test -v -coverpkg=./... -cover ./cmd/broker

Building with native extensions (CGO)

The zoom availability adapter requires the native libyaz library and CGO to be enabled during the build (the default).

Install libyaz using your OS package manager:

  • Debian/Ubuntu: sudo apt-get install libyaz-dev
  • RHEL/CentOS (requires EPEL): sudo yum install libyaz-devel
  • Fedora: sudo dnf install libyaz-devel
  • macOS: brew install yaz

To build without native extensions, disable CGO:

CGO_ENABLED=0 make

This will make zoom adapter unavailable and the metaproxy adapter should be used instead.

Run locally

You can run the broker program locally with:

make run

The application requires a Postgres DB and will use hard-coded default DB connection params unless configured, see DB_* env vars above.

If DB_PROVISION=true, default false, the configured database user must have privileges to create roles and schemas in the database (the CREATE privilege on the database and the ability to run CREATE SCHEMA). The DB_SCHEMA env must be non-empty when provisioning (default). If DB_PROVISION=false, schema and role provisioning must be done before startup.

If DB_MIGRATE=true, default, the app runs migrations on startup. Migrations will create and update all required tables and other objects in the schema. Empty DB_SCHEMA means default user schema is used (usually public).

You can execute provisioning- or migration-only via /broker db-up, after which the app will terminate.

NOTE: For production use it's recommended to disable DB_PROVISION and separately provision a runtime user (e.g. crosslink) with CONNECT to the target database and public privileges locked down and an owner role (e.g crosslink_broker) with full privileges on the dedicated schema granted to the user. See the example DB provisioning script. Optionally, with DB_MIGRATE off, migrations can be performed separately and the runtime user won't require any CREATE privileges.

To run locally in a container, there is a docker-compose.yml file prepared with both the app and the DB.

To start just the DB container with default connection params:

docker compose up -d postgres

To run db-up only (and exit):

docker compose --profile db-up run --rm db-up

Start the default stack (DB + broker; broker runs provision and migrations on startup):

docker compose up

Data import

For information about importing patron requests, batch actions, and templates, see the Import API documentation.

Supplier pull slips and shipment

When a supplier uses add-condition with a cost, the offered cost must be at least the lender's Directory illConfig.minimumCost. An omitted or null minimum imposes no limit; a configured zero still applies. The action fails before sending conditions if the cost is too low or the lender's settings cannot be resolved. Conditions without a cost do not require this check. Amounts are compared directly without currency conversion.

While requester conditions are pending, accept-condition agrees to the supplier's terms, reject-condition cancels with that supplier and allows the broker to try another, and cancel-request cancels through the broker to stop further sourcing. Both cancellation actions enter CANCEL_PENDING while awaiting the response; the current supplier can still refuse cancellation.

For Loan and CopyOrLoan requests, generating a pull-slip PDF queues the pullslip-printed action for the included eligible supplier requests. Accepted conditions return the supplier to WILL_SUPPLY. Printing moves WILL_SUPPLY to SEARCHING (picking and awaiting shipment). Reprinting in SEARCHING leaves the state unchanged. The ship action is available only in SEARCHING. Copy delivery remains available without this loan workflow.

The email-pullslips batch queues the same action after SMTP successfully accepts an email containing a PDF. Emails without PDFs and failed generation or sending do not advance requests. Actions run asynchronously and recheck the current state. If queuing fails after output, the operation reports an error; retrying may reproduce the PDF or email, while repeated pullslip-printed actions in SEARCHING are harmless. Existing saved batch queries are not rewritten; use WILL_SUPPLY for pull-slip queries and include SEARCHING in aging queries as needed.

Action results and automatic execution

Action outcomes (success, failure, and review) only select their configured transitions. An unbound outcome leaves the request in its current state. Each action declaration may specify continueOn: [PROBLEM, ERROR] to tolerate those non-success results; omitted or empty continueOn tolerates neither. SUCCESS always continues normally.

Result Bound outcome Unbound outcome
SUCCESS Apply the transition and continue normally Continue in the current state
PROBLEM / ERROR, listed in continueOn Apply the transition and continue normally Continue in the current state
PROBLEM / ERROR, not listed Persist the transition, then stop and propagate Stay in the current state, stop and propagate

Normal continuation runs the remaining automatic actions in the current state. A change of state runs the target state's entry actions and finishes the source state's chain; a self-transition does not restart entry actions. A non-tolerated result is persisted, along with any outcome transition, before propagation, and no further automatic actions run, including target-state entry actions. The source state's action declaration determines tolerance for both manual and automatic execution. Errors processing tasks, committing the request update, or propagating a child-chain failure are never tolerated by continueOn. An action's reported ERROR can be tolerated, including technical failures within that action.

Both manual and automatic actions receive the static params declared for the action in the current state. Parameters already carried by a task retain precedence. Static configuration is carried under staticActionParams in task custom data, separately from user input.

Attention starts with the resulting state's needsAttention setting, even when the action has no transition. Both ERROR and PROBLEM force attention to true. A subsequent successful action resets attention to its resulting state's setting; previous failures remain in event history. Outcome failure has no separate attention or execution rule.

Email notification preparation and delivery failures produce PROBLEM with outcome failure, including the cause in the event result and manual action response. The default notification actions use continueOn: [PROBLEM, ERROR] without failure self-transitions so fulfillment can continue. Requester patron validation tolerates only PROBLEM; supplier item reservation and will-supply tolerate both statuses, retaining the reservation failure transition to ITEM_PENDING. Existing custom models must declare continueOn wherever they intend to tolerate failures; binding an outcome no longer suppresses them. Email sending remains synchronous; successful sends and skipped recipients retain their existing behavior.

Action triggers

The state model supports three action triggers:

Trigger Runs on state entry Staff execution
manual (default) No Available through the normal staff action API
auto Yes Existing manual retry behavior after failure
background No Hidden and rejected by the staff action API, including after failure

Background jobs may invoke any action supported in the current state. The trigger does not bypass state checks or cause background actions to run on state entry. The default supplier overdue actions use trigger: background and run through the scheduled overdue batch. Existing saved batch selectors must include the desired loan states, including RENEWAL_REJECTED when applicable.

Loan renewal

Borrowers can invoke renew from RECEIVED, RENEWED, and OVERDUE for Loan and CopyOrLoan, including loans with a future due date or no due date. Both sides enter RENEWAL_PENDING. Acceptance moves both sides to RENEWED; rejection moves them to RENEWAL_REJECTED, preserving the due date and the supplier's current ISO18626 loan status (Loaned or Overdue).

RENEWAL_REJECTED is an active loan state with checkout/check-in, return, and recall available, but no renewal action. When the supplier marks the loan overdue, both sides move to OVERDUE and renewal becomes available again. The overdue batch includes rejected loans; after transition, OVERDUE is excluded from subsequent batches. This also applies to rejection of an already-overdue loan. Receipt notifications remain configured only on entry into RECEIVED.

Loan recall

Lenders can invoke recall from RECEIVED, RENEWED, OVERDUE, RENEWAL_PENDING, or RENEWAL_REJECTED for Loan and CopyOrLoan. Optional action parameters are note and dueDate (a date or RFC3339 timestamp). An omitted or null date preserves the current deadline, including an open-ended loan; a date without a time means the end of the supplier's calendar day. Blank or invalid dates are rejected. A recall date may be in the past, allowing an immediate return request for an already overdue loan.

The action sends ISO18626 StatusChange / Recalled and moves the lender to RECALLED only after successful sending. The borrower enters RECALLED with staff attention required. Its primary action is ship-return; check-in remains available, while checkout and renewal are unavailable. Recall supersedes pending renewal. Duplicate recall and late renewal/overdue messages preserve the recall status and deadline; recall after return shipment does not reopen the loan. The existing return and completion steps still apply. Recall during outbound shipment is not supported.

Manual supplier rota editing

Okapi must grant staff broker.located_suppliers.write to add or reorder suppliers. No broker environment setting is required. Tenants that enforce automatic ordering should withhold this permission. The broker independently checks requester ownership, and these mutations require the tenant-scoped /broker routes.

  • POST /broker/ill_transactions/{id}/located_suppliers/{supplierId}/move with {"offset":-3} moves the located supplier ID among new entries. Negative moves up, positive moves down, and destinations are clamped. Zero and already-reached boundaries return 200 without changes or an audit event. The response is the updated LocatedSuppliers list. Selected/skipped suppliers retain their status and ordinal; other new suppliers retain relative order.
  • POST /broker/ill_transactions/{id}/located_suppliers with {"supplierSymbol":"ISIL:EXAMPLE","localId":"record-123"} returns 201 with the created supplier. Both fields are required. It inserts a new supplier first among new entries, storing localId as localID. The exact requester symbol is instead appended as skipped in opaque mode, preserving existing ordinals; in transparent mode it is new and marked as a local supplier. Other symbols, including aliases on the requester peer, are non-local. Manual addition bypasses holdings discovery and ranking. Normal downstream checks, including closures and availability, still apply. It neither selects/sends immediately nor restarts a stalled workflow.

Requests may originate from patrons or staff, and remaining candidates may be edited while another supplier is selected. Completed transactions and terminal borrowing requests return 409; archived/missing transactions return 404. A recorded requester Cancel addressed to the broker also blocks edits with 409, even if the supplier refuses cancellation. Supplier-targeted cancellations do not block edits. A retry with a new requester request ID starts a fresh cancellation scope. A supplier absent from the specified transaction returns 404, a target no longer new returns 409, and an existing symbol in any rota status returns 409. Unknown/ambiguous symbols or suppliers without a usable HTTP(S) endpoint return 422; Directory transport failures return 500. Transactions belonging to another requester return 404.

Edits, ordinal updates, and supplier-added/supplier-moved audit notices commit atomically. Notices include the staff user and edit details and notify observers. Automatic selection and rota persistence share the same transaction lock. Rota edits also lock the linked borrowing request until commit, so it cannot become terminal between the edit's eligibility check and commit. Locks are acquired in patron-request then ILL-transaction order, matching imports. Manual additions during discovery retain their identifier and priority. An explicit retry that rebuilds the rota still retires the old rota using the existing retry behavior.

Clients should serialize mutations and refresh after conflicts. After an uncertain outcome (for example a lost response), refresh before offering another edit; do not automatically retry relative moves. This backend change adds no UI controls.

Lender load balancing

Lender scoring uses the consortium Directory entry's illConfig.loadBalancingPolicy. deficit prioritizes the largest lending shortfall: actualBorrows * (desiredLoans / desiredBorrows) - actualLoans. proportional (the default) prioritizes the smallest actual-to-desired ratio: (actualLoans / max(actualBorrows, 1)) / (desiredLoans / desiredBorrows). Each lender supplies its own lendToBorrowRatio (desired loans:borrows), defaulting to 1:1. An omitted or null policy, missing illConfig, or unset CONSORTIUM_SYMBOL uses proportional, regardless of requester settings. Locality, cost, network priority, and holdings preferences retain precedence over the score; last-resort lenders remain at the end. Rota diagnostics include the selected loadBalancingPolicy and raw scores.

Catalog prefill

GET /patron_requests/prefill retrieves metadata without creating or modifying a patron request. Supply at least one of identifier, isbn, or issn, and a requester symbol. On /broker/patron_requests/prefill, X-Okapi-Tenant resolves the requester; an optional symbol must belong to that tenant. The existing requester/consortium/global catalog selection applies, independently of metadataUpdateMode.

Optional serviceType=Loan|Copy|CopyOrLoan is passed to catalog lookup and echoed in serviceInfo.serviceType. Omit it to leave the service choice unset. No other service fields are inferred. ISBN/ISSN syntax accepts spaces and hyphens; checksums are not validated. Values are passed unchanged after trimming outer whitespace.

The response uses ISO 18626 JSON sections bibliographicInfo, publicationInfo, and serviceInfo, omitting empty sections. A returned record with no mapped fields yields {} (or just the supplied service type). The general query builder tries identifier, ISBN, then ISSN. Existing holdings-driven fallback and first-record metadata selection are retained; metadata does not require available holdings.

Responses are 400 for invalid input or requester context, 404 for no record, 502 for lookup failures, and 503 when no catalog is configured. Prefill has a 30-second deadline; SRU/metaproxy requests honor cancellation. Native ZOOM calls check cancellation between operations, with individual calls limited to at most 10 seconds (or a shorter configured timeout).

Publication extraction defaults to MARC 264 with second indicator 1, falling back to 260 ($a place, $b publisher, $c date). Dates retain the catalog's text. The three extraction specifications can be overridden in catalogConfig.metadataFormat.marc21 using placeOfPublication, publisher, and publicationDate; an explicit empty string disables a field. An asterisk in the first indicator in a five-character field selector matches any first indicator. Publication type uses conservative leader mappings: language monographs to Book, monographic components to Chapter, serial components to Article, manuscript text to Manuscript, notated music to MusicScore, maps to Map, nonmusical sound to SoundRecording, and musical sound to MusicRecording. Other types are omitted.

Holdings policy and request identifiers

Holdings policy runs after the supplier availability lookup when the supplier's resolved catalog configuration contains an SRU or Z39.50 (ZOOM) endpoint. Otherwise it runs after the central holdings lookup. A profile, parser, or metadata setting alone does not enable availability lookup. No additional policy-stage setting is needed; invalid configuration is reported as an error. OPAC parsing always returns all available circulation candidates before policy filtering and ranking, for both central and supplier lookups. Availability and other parser filters still apply. The deprecated allCirculations setting is accepted for compatibility but has no effect, including when explicitly set to false.

An eligible holding selected by a configured holdings policy supplies the located supplier's nullable ItemID. The central bibliographic LocalID remains unchanged. Reevaluation through a configured availability endpoint replaces or clears the selected item, including when lookup fails. Suppliers without eligible holdings are skipped. If availability lookup or holdings parsing fails, the error is recorded and deferred holdings policy is skipped. The workflow continues with unknown availability, sending the request to the supplier (or continuing local supply) without a selected item. Adapter creation failures use the same fallback; invalid configuration and database errors still stop processing. holdingsPolicyResolved persists readiness separately from ItemID: an eligible holding without an item ID still resolves the policy. Deferred-policy reevaluation first revokes readiness; a successful check or a committed lookup-failure bypass restores it. Unresolved selections cannot send a new supply request or run fill-locally, including requests already in LOCAL_SUPPLY. Legacy rows without readiness are accepted only when the supplier has no holdings policy; otherwise they require an availability check (or new supplier discovery for a central policy). Availability updates lock and re-read the selected supplier in short transactions, preserving concurrent protocol updates. If the selection or lookup identity changes during a check, its result is recorded as superseded and schedules no follow-up workflow tasks. Catalog lookup runs outside these transactions. Each availability attempt (including a retry of the same task) receives a fresh persisted token. Starting another attempt atomically supersedes older writes and results. Configured or invalid availability lookups revoke readiness; valid configurations without an availability endpoint preserve the discovery decision and selected item across overlapping checks and restarts. An unresolved central-policy selection still requires supplier discovery, including rows whose readiness was erased by an earlier broker version. Follow-up messages and rota selection carry the token and revalidate it before acting; successful reselection invalidates it. An exhausted rota retains the token for its requester notification. Tokens are transient coordination state, not imported/exported request data. Checks run without holding database locks during catalog or message I/O. Local fill also snapshots the selection and attempt under these locks, then revalidates both and policy readiness after pickup resolution, immediately before NCIP RequestItem. A message already dispatched cannot be recalled by a later reevaluation. During deployment, drain old broker workers before relying on token enforcement; older binaries do not perform these checks.

The check-availability transaction event includes availabilityLookup and holdingsPolicy diagnostics in resultData.customData. Lookup diagnostics record the supplier, bibliographic ID, configured protocol and sanitized target, actual query, lookup/parsing duration in milliseconds, available-holding count and outcome. Targets omit URL credentials, query parameters and fragments; ZOOM options and complete Directory configuration are never copied. Counts describe holdings returned by the parser after availability filters, not every inventory item. Outcomes distinguish no record, no available holdings and lookup/parsing failures. SRU and Z39.50 holdings-parser failures report holdings-failed, including when parsing occurs inside Lookup. Connection, search and retrieval errors retain lookup-failed. Policy diagnostics report whether policy was absent, previously applied at discovery, still pending, skipped after lookup failure, or evaluated here; they include eligibility/exclusion counts, effective location and shelving preferences, rejection reasons, the selected copy and its selection reason. Tied preferences retain the first returned eligible holding, matching selection behavior.

Candidate details are limited to 50 holdings, including the winner marked selected: true. If necessary, the winner replaces the last displayed candidate. Eligible and excluded counts describe all parsed candidates; candidatesTruncated is included only when holdings are omitted. Reasons are included only for exclusions. The winner is not repeated in a separate object. Diagnostic text fields are bounded to 2048 bytes plus a truncation marker. Policy status becomes applied only after a current result commits successfully; superseded attempts and commit failures retain evaluated status. availabilityLookup.resultApplied records whether the lookup decision or lookup-failure bypass committed. A committed bypass reports policy status skipped-lookup-failure and retains the lookup error. The normal event uses its existing availability token; a nested attempt token is included only when that token is absent from the result.

Both event types include a short operator summary in resultData.note, explaining the lookup outcome and policy decision. For example: "Found 2 available items. Holdings policy selected RS3-CL-000008-POPULAR at Popular Reading Collection: shelving preference 20, compared with Main Library's 10." Superseded and failed saves explicitly state that the evaluated decision was not applied.

The central locate-suppliers event uses the same lookup summary under resultData.customData.holdingsLookup, alongside its existing query, holdings and rotaInfo data. It records lookup/parsing time, returned-holding counts and failures, including on unsuccessful discovery. The discovery note says "Found N holdings" because these results may identify supplier holdings without identifying individual items or confirming current circulation availability. The existing availableHoldings field counts those parsed holdings. configurationSource distinguishes global adapters from Directory configuration. With several HOLDINGS_ADAPTER entries it reports the source whose result was used. A global adapter does not report the Directory endpoint as its target. Each rotaInfo.suppliers candidate includes its raw catalog itemId, holdingsPolicyStatus (not-configured, deferred, evaluated, or applied), and, for evaluated policies, holdingsPolicyEligible and any holdingsPolicyReason. Deferred candidates do not claim policy eligibility. Policy status becomes applied only after successful rota persistence; a failed save retains the evaluated decisions and reports holdingsLookup.resultApplied as false. These fields describe holdings policy separately from the existing overall candidate match, which also includes network, tier and other filters.

ISO18626 requests put LocalID in bibliographicInfo.supplierUniqueRecordId and a nonempty selected ItemID in supplierInfo.bibliographicRecordId.bibliographicRecordIdentifier. Internal CrossLink delivery uses the same fields. Transparent local fulfillment (fill-locally) passes the same persisted bibliographic and item identifiers to the LMS adapter. It requires a selected local supplier belonging to the borrowing request and preserves the original request's bibliographic identifier. Catalog parsing or availability lookup without a holdings policy does not select an item ID. The selected holding's call number, when available, is persisted with its item ID and sent in supplierInfo.callNumber. Both fields are cleared when a new availability lookup invalidates the previous selection.

bibRecordId is a read-only shared-index ID (VuFind UUID or Trove ANBD record ID), derived from illRequest: bibliographicInfo.supplierUniqueRecordId for borrowing, or the ReShare-coded bibliographicInfo.bibliographicRecordId for lending. The borrowing value follows creation, edits, metadata updates, and corrected retry requests automatically. Clients cannot set bibRecordId directly; create and update requests ignore that property, and import bundles do not accept it. Import the source identifiers in illRequest instead. Migration 082 removes the legacy bib_record_id database column and recreates patron_request_search_view without it. Before deploying this migration, deploy an intermediate release to every broker instance that removes the column from queries and models but does not include migration 082. Do not upgrade directly from a release that still references the column: Helm runs migrations before upgrading instances, so older instances would fail during the rollout. Rolling migration 082 back restores the nullable column and view, but cannot recover discarded legacy values. The source identifiers in illRequest are preserved.

The broker replaces supplierUniqueRecordId with the supplier's local ID in the requests it sends to suppliers, so it also sends the shared-index ID as a bibliographicRecordId with code ReShare. Other record codes are preserved; incoming requests with conflicting ReShare IDs are rejected.

Clients linking to the shared index should use bibRecordId with their configured VuFind/Trove URL and hide the link when it is absent. They must not fall back to supplierUniqueRecordId, which on a lending request is the supplier's local ID.

When supplier Request Item is disabled (including manual LMS workflows), a Loan automatically attaches the selected copy as a volume before proceeding to WILL_SUPPLY. The volume uses the selected item ID as its barcode, the request title, and the supplied call number; it has no LMS reservation. Existing volumes are preserved on retries so staff can add or replace copies. Without a selected copy, the workflow continues without an automatically attached volume. Location fields are not carried by this mapping. CopyOrLoan retains its deferred item attachment at shipping; Copy does not attach a loan volume.

For both NCIP versions, requestItemRequestScopeType controls identifier selection:

  • auto is the Generic default. A supplied item ID selects Item scope; otherwise supplierUniqueRecordId supplies the bibliographic ID with bibItemScopeName scope. The code default is Bibliographic Item; Sierra and FOLIO profiles override the name to Title. Libraries can override lmsConfig.bibItemScopeName. Item identifiers are not normalized; bibliographic identifiers are.
  • Title or Bibliographic Item uses the bibliographic identifier with requestItemBibIdCode and bibliographic normalization, even when a selected item ID is supplied. Both NCIP versions send the configured scope name unchanged.
  • Item uses the supplied item ID, falling back to supplierUniqueRecordId for compatibility with existing item-scoped integrations, without normalization.

Named vendor profiles retain their existing scopes. Explicit per-library scopes also override the Generic default. Unsupported scopes, empty required identifiers, and conflicting item IDs in supplierInfo are rejected before NCIP is sent. Explicit bibliographic scopes take precedence over supplied item IDs for incoming ISO18626 requests and local fulfillment. The LMS may select another copy of the requested title. A missing bibliographic ID still fails before NCIP is sent. Cancellation in auto uses the saved request ID and omits the optional NCIP scope; auto is never sent on the wire.

Compatibility: Generic configurations without a scope override now interpret supplierUniqueRecordId as a bibliographic ID. Integrations that put item IDs in that field must retain an explicit Item setting or move the item ID into supplierInfo.bibliographicRecordId. The scope is not inferred from ID contents.

Directories

Path Synopsis
cmd
broker command
Package events contains generated broker event database models and queries.
Package events contains generated broker event database models and queries.
Package ill_db contains generated ILL database models and queries.
Package ill_db contains generated ILL database models and queries.
import
api
db
Package importdb contains generated import database models and queries.
Package importdb contains generated import database models and queries.
oapi
Package importoapi contains generated import API bindings.
Package importoapi contains generated import API bindings.
Package ncipclientv1 exchanges native NCIP 1.0 messages over HTTP.
Package ncipclientv1 exchanges native NCIP 1.0 messages over HTTP.
Package oapi contains generated broker API bindings.
Package oapi contains generated broker API bindings.
patron_request
api
db
Package pr_db contains generated patron-request database models and queries.
Package pr_db contains generated patron-request database models and queries.
proapi
Package proapi contains generated patron-request API bindings.
Package proapi contains generated patron-request API bindings.
Package profiles resolves host integrations without modifying directory records.
Package profiles resolves host integrations without modifying directory records.
pullslip
api
db
Package ps_db contains generated pull-slip database models and queries.
Package ps_db contains generated pull-slip database models and queries.
oapi
Package psoapi contains generated pull-slip API bindings.
Package psoapi contains generated pull-slip API bindings.
scheduler
api
db
Package sched_db contains generated scheduler database models and queries.
Package sched_db contains generated scheduler database models and queries.
oapi
Package schedoapi contains generated scheduler API bindings.
Package schedoapi contains generated scheduler API bindings.
test

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL