Transaction Mapping and File Transfer in a REST Delegator
If every new integration requires a new Controller, DTO, and database-call deployment, the Runtime becomes a collection of business-specific code. A REST Delegator fixes repeated execution paths in code and moves destination selection, data selection, and field transformation into Transaction Metadata. A large class of integrations can then be added through Metadata deployment, provided that the expressive boundary and failure semantics of configuration remain explicit.
This article applies Designing Metadata and Contracts for an Integration Platform to concrete rest2db, file2db, sftp2sftp, and http2sftp executions. The responsibility boundaries follow the model in Why Split an Integration Platform Runtime into Listener, Mapper, and Adapter.
Fix the Entry Point with a Common Envelope
Section titled “Fix the Entry Point with a Common Envelope”When every request has a head and body, the Runtime can identify an Interface and return a result independently of payload shape.
{ "head": { "interfaceId": "if-order-import-001", "messageId": "msg-20240413-0001", "statusCode": "", "statusMessage": "" }, "body": { "data": { "orders": [ { "orderNo": "ORD-1042", "amount": 42000, "currency": "KRW" } ] } }}The head is for routing and Runtime results; body.data is the business Contract. A caller need not send empty status fields. If a field is meaningful only in a response, make it optional in the request schema and let the Runtime populate it. Authentication tokens, passwords, and destination endpoints belong in neither area.
A common envelope must not make the business Contract loose. Select a versioned input schema by interfaceId, then validate required fields, types, and array cardinality before mapping. messageId identifies a delivery attempt. A separate idempotency key that remains stable across redelivery must be explicit in the business Contract.
targetList Expresses an Execution Plan
Section titled “targetList Expresses an Execution Plan”A rest2db Transaction can describe one or more ordered targets in targetList.
transaction: id: tx-order-import-001 type: rest2db targetRef: order-database transactionMode: ALL_OR_NOTHING targetList: - targetName: order_upsert targetType: PROCEDURE targetParam: key: orders remap: true mapping: orderNo: order_id amount: total_amount currency: currency_code - targetName: order_import_audit targetType: TABLE targetParam: key: orders remap: falsetargetNameis a registered procedure or logical table name from an allow-list.targetTypeselects a Runtime-supported Adapter such asPROCEDUREorTABLE.targetParam.keylocates an input record or array underbody.data.remapdetermines whether field-name transformation applies.mappingexplicitly maps source fields to target parameters.
Concatenating targetName directly into a SQL identifier creates injection and privilege-escalation risks. Metadata validation should resolve a logical name to an approved statement ID, and values must always use bound parameters. targetRef is likewise an environment reference, not a literal connection string.
transactionMode states the atomicity of multiple targets. Two targets on one datasource can share a database transaction when declared ALL_OR_NOTHING. One local transaction cannot make operations across separate databases or a file transfer atomic. Such a flow needs an explicit INDEPENDENT or saga/compensation policy and a result for each target.
The rest2db Mapping Flow
Section titled “The rest2db Mapping Flow”Validate the complete mapping before invoking any target. Discovering a missing field in the second target after the first target has mutated data turns a validation error into a partial-application incident. At minimum, preflight checks should cover key existence, extracted-value shape, required target parameters, and source-to-target type compatibility.
Interpret Nested JSON key Paths Safely
Section titled “Interpret Nested JSON key Paths Safely”targetParam.key selects repeating records from a nested payload. Applying shipments.items to the following payload yields two target inputs.
{ "shipments": { "batchId": "BATCH-042", "items": [ { "sku": "SKU-100", "quantity": 2 }, { "sku": "SKU-200", "quantity": 1 } ] }}Keep the path language small. Support dot-separated object fields and limited array selection, but do not permit arbitrary scripts or expression execution. Return distinct validation codes for a missing path, a scalar where an object was expected, and an array beyond the allowed cardinality.
remap: false does not mean forwarding every field without validation. It skips name transformation only; the target Contract allow-list and type checks still apply. Fix the handling of unknown fields (ignore or reject) in the Transaction version and record it in Metrics.
A Fixed-Width File Is a Byte Contract
Section titled “A Fixed-Width File Is a Byte Contract”file2db reads the fixed-width file referenced by a file event and splits each record using the ordered lengths in fileMap.
fileContract: id: inventory-fixed-v2 encoding: UTF-8 recordTerminator: LF fields: - { name: warehouseCode, bytes: 6, trim: true } - { name: sku, bytes: 20, trim: true } - { name: quantity, bytes: 10, type: INTEGER } - { name: status, bytes: 1, enum: [A, H, D] }State whether lengths count characters or bytes. A non-ASCII UTF-8 character spans multiple bytes, so splitting with Java string indexes can corrupt field boundaries. Manage encoding, line endings, padding, sign, decimal scale, and null representation as one versioned Contract.
Schema drift corrupts fixed-width data more silently than JSON. If the sender inserts a two-character field in the middle, every later value shifts into the wrong column. Validate total record length, enums, numeric parsing, and trailer count before the target transaction. Move a failed file to a quarantine reference separate from its original path, and do not copy the complete record into application logs.
Treat File Events and Transfer as One Lifecycle
Section titled “Treat File Events and Transfer as One Lifecycle”For file2db, the Delegator streams records into the parser and database target. sftp2sftp connects a source SFTP download to a target SFTP upload, while http2sftp replaces only the source Adapter with an HTTP download. Their common lifecycle is discovery, stability verification, transfer-ID assignment, streaming, validation, and completion.
An inotify Event Is Not a File-Completion Signal
Section titled “An inotify Event Is Not a File-Completion Signal”An inotify create or modify event does not prove that the writer has closed the file. A large file can emit many modify events, and the same file can be rediscovered after the monitor restarts.
The safest protocol is for the producer to write a temporary name on the same filesystem, complete fsync and close, then atomically rename to the final name. The monitor processes only the move-to event. If that protocol is unavailable, check whether size and modification time remain stable for a configured interval and enforce a minimum age and maximum wait. This method is heuristic, not proof of completion.
Absorb duplicate events with a discovery key derived from (sourceRef, normalizedPath, size, checksum). A path-only key misses a new file that reuses a name, while an event-timestamp key processes the same file repeatedly. Persist processing, completed, and quarantined states in durable storage so the decision survives monitor restarts.
SFTP Failure Modes and Idempotency
Section titled “SFTP Failure Modes and Idempotency”A lost response during SFTP upload does not mean that no file was stored. A partial or even complete file may remain at the destination.
- Upload under a temporary name such as
.partial, not the final name. - Verify byte count and, when possible, checksum after transfer.
- Atomically rename within the same directory only after verification.
- Prevent duplicate completion with a unique constraint on
transferIdand final path. - Before retry, inspect temporary and final state and choose resume, delete-and-resend, or already-complete.
Do not assume that an HTTP source supports Range requests. Resume only when support and ETag behavior are known; otherwise restart into a new temporary file. Stream through a bounded buffer instead of loading the complete file into memory, and enforce maximum file size and download timeout.
Do not trust remote paths and file names directly from the request payload. Accept only relative paths under an allowed base directory, rejecting .., absolute paths, and control characters. Keep host-key verification enabled, and obtain credentials and private keys from a secret store through sourceRef and targetRef.
Limits of Metadata-Driven Mapping
Section titled “Limits of Metadata-Driven Mapping”Configuration works well for field renaming, nested-array selection, and simple type conversion. Attempting to express the following requirements turns it into a small programming language.
- Joining multiple source records or performing stateful aggregation
- Business validation that requires external lookup
- Order-dependent compensation and complex branching
- Validating relationships across records during large streaming operations
- New transport behavior such as encryption, signing, or a proprietary protocol
Promote such a requirement into a versioned Mapper or dedicated Adapter with unit and integration tests. Do not evade the boundary by enabling an expression engine or arbitrary scripts in Configuration.
Metadata needs code-level deployment quality. CI should validate schemas, resolve references, run sample-payload mappings, enforce the target allow-list, and check Contract compatibility. Record the immutable bundle version in Trace data. During Runtime reload, one request must use exactly one bundle version.
Signals to Observe in Production
Section titled “Signals to Observe in Production”Record at least the following as structured data.
| Area | Metrics and Trace fields |
|---|---|
| Request | interfaceId, messageId, metadataVersion, validation result |
| Mapping | extracted record count, rejected field count, Mapper version |
| Database | affected row count per target, duration, rollback status |
| File monitor | duplicate event count, stability wait, quarantine count |
| Transfer | transferId, byte count, checksum result, retry count, finalization status |
Do not log payloads, complete local paths, remote endpoints, usernames, or credentials. To support diagnosis without sensitive source data, use Contract version, field path, value type, a hash, or a safe sample.
Summary
Section titled “Summary”A REST Delegator identifies an Interface from a common envelope and uses targetList, key, remap, and mapping to select a database execution plan. Validating the complete mapping before side effects and declaring transaction mode across targets prevents a Metadata change from becoming a partial-application incident.
Treat a fixed-width file as a versioned Contract with encoding and byte lengths, and distinguish a file event from write completion. SFTP delivery needs temporary upload, checksum verification, atomic rename, and a durable transferId to control duplicates and partial files during retry. When a requirement exceeds the expressive boundary of configuration, an explicit Mapper or Adapter is safer than a more powerful configuration language.