← Wiki

Content Enricher in Mule: the order gains the customer's data before it is invoiced

  • 11 min read
On this page

Code

In the series’ order scenario, the order arrives with the customerId and nothing else about the customer. Billing and shipping need the name, the tier and the shipping address, which live in the CRM. Fetching what is missing from another system and adding it to the message is the Content Enricher. In Mule 4, an operation with a target variable does it: the HTTP Request calls the CRM and stores the response in a variable, the order stays in the payload, and a Transform joins the two.

The problem

The order arrives like this:

{ "orderId": "ORD-3801", "customerId": "CUS-100", "items": [ { "sku": "SKU-BOOK", "quantity": 2, "unitPrice": 30 } ] }

The system that created the order knows the customer by ID. The one that invoices and ships needs the customer in full. A call to the CRM solves it, but in Mule the response of an operation replaces the payload: after the GET to the CRM, the order is gone from the message, and what is left is the customer.

The pattern in the book

The book observes that it is common for the destination system to need more information than the originating system can provide; one of its examples is exactly this one, the system that sends the customer ID when the receiver needs the name and the address. The question is how to communicate with another system when the originator of the message does not have all the required data. The answer is a specialized transformer, the Content Enricher, which accesses an external source to augment a message with the missing information (Content Enricher).

The enricher uses data from the message itself, such as key fields, to fetch the rest and appends the result to the message. The original information may stay in the resulting message or become unnecessary, depending on what the destination application needs. The book lists three common sources for the new data: computation (the enricher computes what is missing, and then it is much like a Message Translator, since it needs no external source), the environment (the most common case is a timestamp taken from the operating system) and another system, the most common option: a database, a file, an LDAP directory, a system or a user who types the data in (Content Enricher). This page’s example is of the third kind.

The enricher is also the second half of the Claim Check: in the book, the component that retrieves the stored data by its key is a Content Enricher. And it is the opposite of the Content Filter, which removes from the message what the destination does not need.

The message comes out bigger than it went in

The diagram, redrawn from the official sketch (CC BY 4.0), answers: where does the data the message gains come from?

The Order, which carries only the customerId, enters the Content Enricher. The Content Enricher sends the customerId to the CRM and gets back name, tier and address. It then delivers the Order with the customer.

In Mule

Mule 3 had an enricher scope. In Mule 4, it was replaced by the target parameter: every operation that returns a value (<flow-ref>, <http:request>, <db:select> and others) has target and targetValue, which send the operation’s output to a variable (Migrating the Enricher to a Target Variable). target is the variable’s name; targetValue is what gets stored in it, and the default is the response payload (Enrich Data with Target Variables).

What makes this an enricher is the effect on the message flow. Normally, an operation hands the next component a message different from the one it received; with a target variable, it hands the next component the same message it received (Enrich Data with Target Variables). The order stays in the payload after the call to the CRM, the customer is in vars.vCustomer, and a Transform joins the two. The lookup is the HTTP Request; the book’s “append to the message” is the Transform.

Each operation has a single target. When the enricher needs to store several parts of the response in separate variables, the migration documentation uses one target and then a Set Variable for each part (Migrating the Enricher to a Target Variable).

The enrichment flow

The diagram answers: what happens to the order on each CRM response?

The POST /eip/orders/enrich endpoint passes to the decision orderId, customerId and items?. If not, it answers 400 without calling the CRM. If yes, an HTTP Request to the CRM stores the response in target vCustomer. On 200, the Transform joins order and customer and the endpoint answers 200 with the enriched order. On HTTP:NOT_FOUND, it answers 400: unknown customer. On SERVICE_UNAVAILABLE, CONNECTIVITY or TIMEOUT, it answers 503: enrichment FAILED.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule maps the Content Enricher to Target Variables, the same mechanism this page uses.

The example

The POST /eip/orders/enrich endpoint receives the order and calls the CRM, simulated in the same application (content-enricher-crm.xml), which answers { customer: { id, name, tier, shippingAddress }, meta: { source, fetchedAt } }:

<http:request doc:name="Look Up Customer In CRM" config-ref="eip-self-http-request-config" method="GET" path="/eip/services/customers/{customerId}" target="vCustomer" targetValue="#[payload.customer]">
	<http:uri-params><![CDATA[#[{ customerId: payload.customerId }]]]></http:uri-params>
</http:request>
<ee:transform doc:name="Merge Customer Into Order">
	<ee:message>
		<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
payload ++ {
	customer: {
		name: vars.vCustomer.name,
		tier: vars.vCustomer.tier,
		shippingAddress: vars.vCustomer.shippingAddress
	}
}]]></ee:set-payload>
	</ee:message>
</ee:transform>

In the repository: src/main/mule/eip/content-enricher/content-enricher.xml

The targetValue picks the part of the response. #[payload.customer] stores only the customer; the CRM’s meta is left out. The uri-params still reads payload.customerId because, before the call, the payload is the order.

The Transform picks what goes into the order. payload ++ { customer: ... } keeps the order’s fields and adds the name, the tier and the address. The customer’s id, which the order already has as customerId, is not repeated.

The test ce-target-variable-holds-only-the-target-value checks both with a spy before the Transform, which sees the payload still holding the order’s fields, and a check of the variable afterwards:

<munit-tools:assert-that doc:name="Payload has only the order's fields" expression="#[keysOf(payload) map ($ as String)]" is="#[MunitTools::equalTo(['orderId', 'customerId', 'items'])]" />
<munit-tools:assert-that doc:name="Customer part only" expression="#[keysOf(vars.vCustomer) map ($ as String)]" is="#[MunitTools::equalTo(['id', 'name', 'tier', 'shippingAddress'])]" />

In the repository: src/test/munit/eip/content-enricher-test-suite.xml

When the CRM goes down

By default, the HTTP Request throws an error when the response has a status of 400 or higher, and the error triggers error handling (Configure HTTP Request Operation). The example handles two cases in a try around the call. A customer the CRM does not know (HTTP:NOT_FOUND) is the caller’s error: 400. A CRM that is unavailable, unreachable or too slow is another case:

<on-error-continue doc:name="On Error Continue (CRM unavailable)" type="HTTP:SERVICE_UNAVAILABLE, HTTP:CONNECTIVITY, HTTP:TIMEOUT" logException="false">
	<logger doc:name="WARN: Log enrichment failed" level="WARN" message="#['Order ' ++ payload.orderId ++ ' not enriched: ' ++ error.errorType.namespace ++ ':' ++ error.errorType.identifier ++ ', correlationId=' ++ correlationId]" />
	<set-variable doc:name="SET httpStatus" variableName="httpStatus" value="503" />
	<ee:transform doc:name="Build Enrichment Failed Response">
		<ee:message>
			<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
	orderId: payload.orderId,
	enrichment: "FAILED",
	// The error type only: the description names the requester's URL.
	reason: error.errorType.namespace ++ ":" ++ error.errorType.identifier
}]]></ee:set-payload>
		</ee:message>
	</ee:transform>
</on-error-continue>

The example answers 503 and does not pass the order along without the customer, because billing and shipping need the address. When the missing data is optional, the other choice is to carry on with the order marked to be enriched later.

Caveats

The target variable is not set when the operation fails. The documentation says: because the flow’s execution stops and does not finish successfully when an error occurs, target variables are not set (Enrich Data with Target Variables). Not being set is not the same as being empty: if the variable already had a value, it stays there. The test ce-crm-down-sets-no-target-variable-and-returns-503 puts 'VALUE BEFORE THE CALL' in vCustomer, makes the CRM answer 503 and checks that the old value is still in the variable and that the joining Transform did not run. That is why, in the example, the join sits inside the try, right after the call: when the CRM fails, it does not run, and the error handler ends the flow with 503. An on-error-continue hands the next component the result of the handling, as if the try had finished successfully (On Error Continue and On Error Propagate); a join placed after the try would also run when the CRM is down, with the failure response in the payload and vCustomer at its old value. The recommendation is to keep the join inside the try, next to the call.

Without target, the response replaces the whole message. In a 2020 Stack Overflow question, with Mule 4, the incoming request’s attributes disappeared after an HTTP Request. The answer points to the operation’s target and targetValue: with the target filled in, the operation does an enrichment and does not overwrite the message; empty, which is the default, the response’s payload and attributes take the place of the previous ones (Stack Overflow: attributes.headers getting lost after a http Request call in Mulesoft?). The documentation describes the same behavior: without a target variable, the operation hands the next component a message different from the one it received (Enrich Data with Target Variables).

With target, variables changed inside the operation go back to their previous value. When an operation with a target variable modifies other variables (a flow-ref to a flow that sets variables, for example), they go back to the value they had before the operation; only the target variable comes out of it (Enrich Data with Target Variables). An enricher built with flow-ref and target has to return everything that matters through the targetValue.

The CRM’s 404 is also an error. Because the HTTP Request fails from status 400 up (Configure HTTP Request Operation), the unknown customer does not reach the join with an empty payload: it becomes HTTP:NOT_FOUND and needs its own handling. The test ce-unknown-customer-returns-400 checks the 400 response with the customer ID.

When not to use it

When the missing data can be computed from the message itself, there is no external source to call: the book likens that case to the Message Translator, and a Transform is enough. When the destination can fetch the data on its own by ID, enriching along the way adds a call and a point of failure that the destination would already handle. And when the data is large and only the last step needs it, carrying it along the whole path is the problem the Claim Check solves: it fetches the data only at the end.

Running the example and the tests

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

The project needs Java 17, Maven 3.9+ and the Mule 4.9 runtime. MUnit runs on the Enterprise runtime, so Maven needs access to MuleSoft’s Enterprise repository (credentials in ~/.m2/settings.xml). The example runs with nothing external: the CRM is simulated and answers 503 for the customerId values that start with CUS-DOWN.

The content-enricher-test-suite.xml suite pins the behavior down, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
ce-order-is-enriched-with-the-customer Over HTTP, the endpoint answers 200 with the order’s fields and the name, tier and shipping address from the CRM
ce-target-variable-holds-only-the-target-value After the call, the payload is still the order, and vars.vCustomer has only the customer part of the response, without the meta
ce-crm-down-sets-no-target-variable-and-returns-503 With the CRM answering 503, vCustomer keeps its previous value, the join does not run and the endpoint answers 503 with enrichment: FAILED
ce-crm-unreachable-returns-503 An unreachable CRM (HTTP:CONNECTIVITY) gives the same 503
ce-crm-timeout-returns-503 A CRM that does not answer in time (HTTP:TIMEOUT) gives the same 503
ce-unknown-customer-returns-400 The CRM answers 404 for an unknown customer, and the order gets 400 with the customer ID (CUS-999)
ce-order-without-customer-returns-400 An order without customerId gets 400, and the CRM is not called

To call the endpoint, run the application in Anypoint Studio (port 8081) and use the Content Enricher entries in requests.http:

### EIP content enricher — the order gains the customer from the CRM
POST {{base}}/eip/orders/enrich
Content-Type: application/json

{ "orderId": "ORD-3801", "customerId": "CUS-100", "items": [ { "sku": "SKU-BOOK", "quantity": 2, "unitPrice": 30 } ] }

### The CRM is down for CUS-DOWN... customers: 503, enrichment FAILED
POST {{base}}/eip/orders/enrich
Content-Type: application/json

{ "orderId": "ORD-3802", "customerId": "CUS-DOWN-1", "items": [ { "sku": "SKU-BOOK", "quantity": 2, "unitPrice": 30 } ] }

In the repository: requests.http

The other patterns, with the Mule component that implements each one, are in the catalog of integration patterns in Mule; the reverse path, from component to patterns, is in the index by component.

Code for this page