← Wiki

File Transfer in Mule: one system writes the file, another consumes it

  • 11 min read
On this page

Code

The orders application has to hand billing the orders to charge, and the one thing the two can share is a directory. One writes a file, the other reads it later. The File Connector handles both ends in Mule 4. The work is in what happens between them: when the file is ready, what to do with a repeated name and where the file that failed goes.

The problem

The producer writes mulesoft-patterns-billing-EXP-7101.csv while the consumer is watching the directory. If the consumer reads it in the middle of the write, it imports half the orders. If a second export uses the same name before the first one is read, one may overwrite the other. If processing fails and the file is moved anyway, the orders are never billed and no later read picks them up.

The pattern in the book

File Transfer is one of the book’s four integration styles, along with Shared Database, Remote Procedure Invocation and Messaging. The setting is applications built independently, in different languages and platforms, and the question is how to integrate them so they exchange information. The solution is for each application to produce files with the information the others need to consume; integrators take care of transforming them into other formats, and the files are produced at regular intervals, according to the nature of the business (File Transfer).

The book singles out the choice of format as an important decision: one application’s output is rarely exactly what the other needs, and the format has to have tools that read, write and transform it.

The diagram answers what the two applications share. It redraws the book’s sketch (CC BY 4.0) in the order scenario:

The orders application exports a CSV file, and billing imports that file.

In Mule

The File Connector works with files and folders on a locally mounted file system. The On New or Updated File source polls a directory and generates one message per file found. To avoid reading the same file again, the documentation offers deleting it after processing (autoDelete), moving it to another directory (moveToDirectory) or using a watermark (watermarkMode), which picks files by creation or modification time (On New or Updated File).

A few parameters decide the behavior (connector reference):

Parameter What the reference says Default
applyPostActionWhenFailed Applies the delete or move to a file whose processing failed, too true
timeBetweenSizeCheck Compares the size twice, with this wait in between, before reading; with no value, it does not check blank in the reference
mode, on Write OVERWRITE, APPEND or CREATE_NEW OVERWRITE
overwrite, on Rename Overwrites a destination that already exists false
primaryNodeOnly In a cluster, runs the source on the primary node only blank in the reference

The diagram answers which names and directories the file goes through in the example:

POST /eip/billing/exports reaches the flow, which claims the exportId in an object store, writes the .tmp file in the inbox and renames it to the .csv name. The File listener reads the .csv. A valid file goes to processed with a unique name; an invalid one goes to error with a unique name; on a processing failure, the file stays in the inbox and is read again.

In the MuleSoft documentation

The page Enterprise Integration Patterns Using Mule maps File Transfer, in the integration styles group, to the File Connector. It is the component at both ends of the example.

The example

The producer never exposes a half-written file

Before writing, the flow validates the request: an order in which orderId, customerId, amount or currency is an object or a list is refused with 400.

The CSV is written under a temporary name, which the consumer’s filter (mulesoft-patterns-billing-*.csv) does not accept, and renamed once the content is complete:

<try doc:name="Try Publish Export File">
	<file:write doc:name="Write Temporary File" config-ref="eip-ft-file-config" path="#[vars.vTemporaryPath]" mode="CREATE_NEW" />
	<file:rename doc:name="Rename To Final Name" config-ref="eip-ft-file-config" path="#[vars.vTemporaryPath]" to="#[vars.vFileName]" overwrite="false" />
	<error-handler>
		<on-error-continue doc:name="On Error Continue (a file with this name is waiting)" type="FILE:FILE_ALREADY_EXISTS" logException="false">
			<set-variable doc:name="SET vNameTaken" variableName="vNameTaken" value="#[true]" />
			<flow-ref doc:name="Refer to sf-delete-temporary-export-file" name="sf-delete-temporary-export-file" />
		</on-error-continue>
		<on-error-propagate doc:name="On Error Propagate (publication failed, clean up)" type="ANY" logException="true">
			<flow-ref doc:name="Refer to sf-delete-temporary-export-file" name="sf-delete-temporary-export-file" />
			<os:remove doc:name="Release Export Id After Failure" key="#[vars.vExportId]" objectStore="eip-ft-export-claims-store" />
		</on-error-propagate>
	</error-handler>
</try>
<os:remove doc:name="Release Export Id" key="#[vars.vExportId]" objectStore="eip-ft-export-claims-store" />

In the repository: src/main/mule/eip/file-transfer/file-transfer.xml

The connector reference does not promise that the rename is atomic. What the tests show is that, at the moment of the rename, the inbox holds only the temporary file, complete, and that a file still under its temporary name is not read. When the producer is not yours and writes straight to the final name, what is left is timeBetweenSizeCheck, a heuristic: a producer that stops writing for longer than the interval looks finished.

overwrite="false" refuses a name that already exists at the destination, and the reference does not say that this refusal holds across simultaneous requests. That is why the producer first claims the exportId in an object store:

<try doc:name="Try Claim Export Id">
	<os:store doc:name="Claim Export Id" key="#[vars.vExportId]" objectStore="eip-ft-export-claims-store" failIfPresent="true">
		<os:value><![CDATA[#[output application/java --- { claimedAt: now() as String }]]]></os:value>
	</os:store>
	<error-handler>
		<on-error-continue doc:name="On Error Continue (this exportId is being written)" type="OS:KEY_ALREADY_EXISTS" logException="false">
			<set-variable doc:name="SET vAlreadyClaimed" variableName="vAlreadyClaimed" value="#[true]" />
		</on-error-continue>
	</error-handler>
</try>

With failIfPresent="true", the second claim fails, and the request gets 409; the claim is removed when publishing ends. Exports with other ids carry on in parallel. Limiting the flow with maxConcurrency="1" would have a different effect: with the flow at its limit, Mule applies back-pressure to the source, and the HTTP Listener may answer 503 (Execution Engine). The example’s claim lives in memory and does not cover another replica or anyone writing to the directory from outside.

The consumer decides where the file goes

<file:listener doc:name="On New Billing Export File" config-ref="eip-ft-file-config" directory="${eip.fileTransfer.inboxDirectory}" recursive="false" watermarkMode="DISABLED" primaryNodeOnly="true" applyPostActionWhenFailed="false" moveToDirectory="#[vars.vArchiveDirectory]" renameTo="#[vars.vArchiveName]" outputMimeType="text/plain">
	<scheduling-strategy>
		<fixed-frequency frequency="${eip.fileTransfer.pollFrequencyMillis}" timeUnit="MILLISECONDS" />
	</scheduling-strategy>
	<file:matcher filenamePattern="mulesoft-patterns-billing-*.csv" regularFiles="REQUIRE" directories="EXCLUDE" symLinks="EXCLUDE" />
</file:listener>

The matcher accepts only regular files: regularFiles="REQUIRE", directories="EXCLUDE" and symLinks="EXCLUDE", attributes whose default is INCLUDE (connector reference). A symbolic link or a directory with the expected name is not read (ft-symbolic-link-and-directory-with-a-matching-name-are-not-read). Hard links are not covered.

The flow sets the destination variables. Valid content goes to processed. A single row that fails validation rejects the whole file, which goes to error with the reasons recorded: it is the idea of the Invalid Message Channel applied to files. In both cases the name gets a UUID, so a name that arrives again does not overwrite the archived one.

Validation does not catch every malformed file. DataWeave’s CSV reader is lenient: according to the observation recorded in the flow’s comment, text after a closing quote is dropped with a warning, and the row may pass. A real contract needs a stricter check of the raw file. A failure of the check itself counts as a processing failure.

When processing fails for another reason, such as an unavailable store, the file should stay in the inbox. That takes applyPostActionWhenFailed="false" and a handler that propagates the error:

<error-handler>
	<on-error-propagate doc:name="On Error Propagate (processing failed, the file stays in the inbox)" type="ANY" logException="true">
		<logger doc:name="ERROR: Log file left in inbox" level="ERROR" message="#['Billing file ' ++ (vars.vFileName default 'unknown') ++ ' not processed, left in the inbox for the next poll: ' ++ error.errorType.namespace ++ ':' ++ error.errorType.identifier ++ ', correlationId=' ++ correlationId]" />
	</on-error-propagate>
</error-handler>

on-error-continue makes the handler’s owner finish as if it had succeeded (On Error), and this application’s default handler uses that scope. Without a handler of its own, the failure would count as success, and the false would not protect the file (this page’s inference from the documentation).

A file that always fails is read again forever, with one ERROR per attempt. A real integration limits the attempts, as Guaranteed Delivery does with its quarantine.

Reading again is safe for the example’s record: the key combines the name, the modification time and the SHA-256 of the content, and the same read rewrites the same record. Two deliveries identical in name, time and content become a single record, and both are archived. A new export with the same orders is recorded again; whether to charge twice is a job for an Idempotent Receiver.

The example uses no watermark (watermarkMode="DISABLED"), because a handled file leaves the inbox.

Caveats

  • A shared temporary directory is not private. The example defaults to the operating system’s temporary directory, where other users of the machine can inject or read files; the details are in app.yaml. Outside a demonstration, point the three directories to places only the application can access.
  • On CloudHub, the local disk is ephemeral. Files are deleted when the application restarts (CloudHub, CloudHub 2.0), and each worker or replica has its own disk. For that case, use SFTP, an object storage service or a shared server.
  • In a cluster, poll from one node only. With primaryNodeOnly="true", the source runs only on the primary node (HA Clusters). That page says to check the default in each connector, and the File reference leaves the field blank, so the example declares it. This does not coordinate separate applications or replicas that do not form a cluster.
  • An interrupted producer leaves the .tmp behind. When the write or the rename fails, the flow tries to delete it; if the application stops midway, it stays. The consumer does not read it, but someone has to clean it up.

When not to use it

When the sender needs the reply to carry on, a file does not work: that is a case for Request-Reply. When each order has to be handled as soon as it happens, with redelivery per message, a queue such as the Point-to-Point Channel handles the right unit; with a file, one bad row or one failure affects the whole batch. File Transfer makes sense when the other side only exchanges files or when the business already works in batches (this page’s recommendation).

Running the example and the tests

git clone https://github.com/brunosouzas/mulesoft-patterns-examples.git
cd mulesoft-patterns-examples
mvn clean test

MUnit runs on the Enterprise runtime, so Maven needs access to the MuleSoft Enterprise repository (credentials in ~/.m2/settings.xml). The tests use directories under target/, set in the pom.xml. The file-transfer-test-suite.xml suite records the behavior observed on Mule 4.9.17 with MUnit 3.7.1 and File Connector 1.5.7:

Test What it proves
ft-exported-file-is-imported-and-moved-to-processed The export is imported row by row and goes to processed
ft-half-written-file-is-not-read The incomplete .tmp is not read across several polls
ft-producer-renames-only-after-the-file-is-complete At the moment of the rename, there is only the temporary file, complete
ft-name-still-waiting-is-refused-and-not-overwritten A name still in the inbox gets 409 and is not overwritten
ft-repeated-name-after-consumption-keeps-both-files A name repeated after consumption leaves two archived files
ft-invalid-rows-send-the-whole-file-to-error One invalid row rejects the whole file
ft-wrong-header-empty-short-and-unreadable-files-go-to-error Wrong header, empty file, no rows, missing columns or unclosed quotes go to error
ft-failed-processing-leaves-the-file-in-the-inbox-and-reads-it-again A failure to record (OS:STORE_NOT_AVAILABLE simulated with a mock) keeps the file, which is read again
ft-failed-publish-is-answered-500-and-leaves-no-final-file A rename failure (FILE:ACCESS_DENIED simulated with a mock) gives 500, leaves no stray file and releases the id
ft-export-id-being-written-is-409-until-released A claimed id gets 409 until it is released
ft-concurrent-exports-run-together-and-one-id-wins-once Eight different ids are accepted; of eight requests with the same id, one is accepted
ft-symbolic-link-and-directory-with-a-matching-name-are-not-read A symbolic link and a directory with the expected name are neither read nor moved
ft-nested-order-field-is-400-and-writes-nothing An order field holding an object or a list gets 400, and nothing is written
ft-invalid-export-request-writes-nothing An exportId shaped like a path, or a request without orders, gets 400

The half-written file test checks the result:

<munit:validation>
	<munit-tools:assert-that doc:name="Half file untouched" expression="#[vars.vHalf]" is="#[MunitTools::equalTo({ inbox: ['mulesoft-patterns-billing-HALF.csv.0001.tmp'], processed: 0, error: 0, imports: 0, rejected: 0 })]" />
	<munit-tools:assert-that doc:name="All rows once complete" expression="#[vars.vImports map $.orderId]" is="#[MunitTools::equalTo(['ORD-FT-H1', 'ORD-FT-H2'])]" />
	<munit-tools:assert-that doc:name="Second row complete" expression="#[vars.vImports[1].customerId]" is="#[MunitTools::equalTo('C-2')]" />
	<munit-tools:assert-that doc:name="Nothing rejected" expression="#[sizeOf(vars.vRejected)]" is="#[MunitTools::equalTo(0)]" />
</munit:validation>

In the repository: src/test/munit/eip/file-transfer-test-suite.xml

To call the endpoints, run the application in Anypoint Studio (port 8081) with the File Transfer entries in requests.http:

### EIP file transfer — export a CSV file; the consumer reads it within about a second
POST {{base}}/eip/billing/exports
Content-Type: application/json

{ "exportId": "EXP-7101", "orders": [ { "orderId": "ORD-7101", "customerId": "C-1", "amount": 120.5, "currency": "BRL" }, { "orderId": "ORD-7102", "customerId": "C-2", "amount": 80, "currency": "EUR" } ] }

###
# A row without customerId and with a negative amount: the consumer rejects the whole file
POST {{base}}/eip/billing/exports
Content-Type: application/json

{ "exportId": "EXP-7102", "orders": [ { "orderId": "ORD-7103", "amount": -5, "currency": "BRL" } ] }

###
GET {{base}}/eip/billing/imports

###
GET {{base}}/eip/billing/rejected-files

In the repository: requests.http

The first export shows up in /eip/billing/imports; the second, with no customerId and a negative amount, in /eip/billing/rejected-files. The other patterns are in the catalog of integration patterns in Mule and, by component name, in the index by component.

Code for this page