← Wiki

Canonical Data Model in Mule: one canonical order between marketplace, partner, invoicing and inventory

  • 12 min read
On this page

Code

The order arrives by two paths, the marketplace as JSON and a partner as XML, and goes on to two systems, invoicing as JSON and inventory as CSV. Translating each source directly to each target ties everyone to everyone. With a canonical order in the middle, each system only knows its own format and the canonical one, and in Mule 4 each translation is a Transform that calls a DataWeave module.

The problem

In the series’ order scenario (order → payment → inventory → invoice), the same order has four shapes. The marketplace sends { id, buyer: { accountId }, shipping: { country }, lines: [...] }, with the currency on each line. The partner sends a <PurchaseOrder> with attributes. Invoicing expects an invoice request with lines and a total; inventory, a picking list in CSV. If each source has a translator for each target, a third source needs a new translator for every target that already exists, and a rule about orders (a required currency, say) is written in every translator.

The pattern in the book

The book starts from several applications designed to work together through messages, each with its own internal format, and asks how to minimize the dependencies between applications that use different data formats. The answer is to design a Canonical Data Model that is independent of any application, and to require that each application produce and consume messages in that common format. The canonical model adds a level of indirection between the applications’ formats: when a new application joins, only the translations between it and the canonical model need to be created, whatever the number of applications already taking part (Canonical Data Model).

The book also does the math. With few applications, the canonical model looks complicated, but the solution “quickly pays off” as the number of applications grows: two applications that exchange messages in both directions need 2 Message Translators translating directly and 4 with the canonical model. With three, it is 6 either way. With six, it is 30 without the canonical model and 12 with it (Canonical Data Model).

Each system translates only to the common model

The diagram, redrawn from the official sketch (CC BY 4.0), answers: how many translations does each system need to know?

Two sources, Marketplace in JSON and Partner in XML, feed the Canonical order. Two targets leave the Canonical order, Invoicing in JSON and Inventory in CSV. Each arrow is a translation.

Each arrow is a translation. No source points to a target.

In Mule

In Mule 4, each arrow in the diagram is a Transform, the component that converts input data into a new structure or format (Transform Message Component). The canonical model itself is not a component: it is a format the project decides on. In the example, it lives in DataWeave modules. The documentation explains that a module can define functions, variables, types and namespaces, that a module saved in src/main/resources is available to any DataWeave script in the application, and that the script uses the module after an import directive in the header (Create Custom Modules and Mappings). The canonical order is a DataWeave type, and each translator is a function in a module of its own:

  • CanonicalOrder.dwl: the canonical order type and the validation;
  • FromMarketplace.dwl and FromPartnerXml.dwl: source → canonical;
  • ToInvoicing.dwl and ToWarehouse.dwl: canonical → target.

In the repository: src/main/resources/dwl/canonical/

The canonical order flows

The diagram answers: what path does each source’s order take to the two target documents?

The POST /eip/canonical/orders/marketplace and POST /eip/canonical/orders/partner endpoints pass to the FromMarketplace and FromPartnerXml Transforms, and both go on to sf-deliver-canonical-order. There the canonical order is validated: if it is not valid, the answer is 400: APP:BAD_REQUEST; if it is, the ToInvoicing + ToWarehouse Transform produces the two target documents.

The same component also does two other patterns

The Transform also implements the Message Translator, which translates one format into another between two systems, and the Content Filter, which removes from the message the fields the target does not need. In the book these are three patterns; it was Mule, not the book, that put the three in one component. Each translator on this page is a Message Translator; the Canonical Data Model is the decision that all of them translate to and from the same order.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule does not list the Canonical Data Model. The closest line is the Message Translator’s, which it maps to the Message Transformer, the Transform: each arrow of the canonical model on this page. The model itself is a format the project decides on, not a component, so there is no component to map.

The example

The canonical order is a closed type:

type CanonicalItem = {| sku: String, quantity: Number, unitPrice: Number |}
type CanonicalOrder = {|
	orderId: String,
	source: String,
	customerId: String,
	country: String,
	currency: String,
	items: Array<CanonicalItem>
|}

In the repository: src/main/resources/dwl/canonical/CanonicalOrder.dwl

{| |} declares a closed object: it only accepts a value with no fields beyond those declared in the type (Type System). No field of the type accepts null, and there is one currency per order, not per line.

A source translator only knows its own format and the canonical one. The partner’s reads the XML attributes:

%dw 2.0
import decimalOrNull, CanonicalOrderDraft from dwl::canonical::CanonicalOrder
// Source translator: the partner's XML purchase order -> the canonical order (not yet validated).
//   <PurchaseOrder number="..." currency="..."><Customer code="..."/><ShipTo country="..."/>
//     <Lines><Line sku="..." quantity="..." unitPrice="..."/>...</Lines></PurchaseOrder>
fun toCanonical(document: Any): CanonicalOrderDraft = do {
	var po = document.PurchaseOrder
	---
	{
		orderId: if (isEmpty(po.@number)) null else "ORD-" ++ po.@number,
		source: "PARTNER",
		customerId: if (isEmpty(po.Customer.@code)) null else "CUS-" ++ po.Customer.@code,
		country: upper(po.ShipTo.@country default ""),
		currency: if (isEmpty(po.@currency)) null else po.@currency,
		items: (po.Lines.*Line default []) map ((line) -> {
			sku: line.@sku,
			quantity: decimalOrNull(line.@quantity),
			unitPrice: decimalOrNull(line.@unitPrice)
		})
	}
}

In the repository: src/main/resources/dwl/canonical/FromPartnerXml.dwl

The translator returns a draft of the canonical order, with null where the source did not send the field or sent something unreadable, such as a quantity of two. It validates nothing. Both source flows call the same sub-flow, which validates the canonical order once and produces the target documents:

<sub-flow name="sf-deliver-canonical-order" doc:description="Validates the canonical order in the payload and translates it into each target's document; called by every source flow, which knows nothing of the targets.">
	<set-variable doc:name="SET vCanonicalProblems" variableName="vCanonicalProblems" value="#[dwl::canonical::CanonicalOrder::problems(payload)]" />
	<choice doc:name="Validate Canonical Order">
		<when expression="#[not isEmpty(vars.vCanonicalProblems)]">
			<raise-error doc:name="Raise BAD_REQUEST Error - Invalid canonical order" type="APP:BAD_REQUEST" description="#[vars.vCanonicalProblems joinBy '; ']" />
		</when>
	</choice>
	<logger doc:name="INFO: Log canonical order" level="INFO" message="#['Canonical order ' ++ payload.orderId ++ ' from ' ++ payload.source ++ ', correlationId=' ++ correlationId]" />
	<ee:transform doc:name="Translate Canonical Order To Targets">
		<ee:message>
			<ee:set-payload><![CDATA[%dw 2.0
import dwl::canonical::ToInvoicing
import dwl::canonical::ToWarehouse
output application/json
---
{
	canonicalOrder: payload,
	targets: {
		invoicing: ToInvoicing::fromCanonical(payload),
		warehouse: write(ToWarehouse::fromCanonical(payload), "application/csv")
	}
}]]></ee:set-payload>
		</ee:message>
	</ee:transform>
</sub-flow>

In the repository: src/main/mule/eip/canonical-data-model/canonical-data-model.xml

The currency rule, the customer rule and the items rule are written once, in problems(), and hold for any source. The target translators take the CanonicalOrder type as a parameter and do not know where the order came from:

%dw 2.0
import CanonicalOrder from dwl::canonical::CanonicalOrder
// Target translator: the canonical order -> the invoicing system's invoice request (JSON).
// Takes a CanonicalOrder (validated: no null fields), so an order of another shape fails at the call.
type InvoiceRequest = {| invoiceFor: String, customer: String, currency: String, lines: Array<{| sku: String, qty: Number, amount: Number |}>, total: Number |}
fun fromCanonical(order: CanonicalOrder): InvoiceRequest = {
	invoiceFor: order.orderId,
	customer: order.customerId,
	currency: order.currency,
	lines: order.items map ((item) -> { sku: item.sku, qty: item.quantity, amount: item.quantity * item.unitPrice }),
	total: sum(order.items map ($.quantity * $.unitPrice))
}

In the repository: src/main/resources/dwl/canonical/ToInvoicing.dwl

The book’s math assumes every application exchanges messages with every other. The example has separate sources and targets, and applied to it (this page’s application of the math, not the book’s), the count is a tie with two sources and two targets: 2 × 2 = 4 direct translators and 2 + 2 = 4 through the canonical model. The gain shows up with the next system. A third source needs a single translator, to the canonical order, and nothing else changes; translating directly, it would need one per target.

The suite proves that the same order, as JSON and as XML, produces the same items, the same total and the same inventory lines, and it calls the target translators directly, with no flow and no source. An order that is not canonical fails at the call:

<munit:test name="cdm-module-target-translator-rejects-an-order-that-is-not-canonical" description="Canonical data model (module test, no flow): the invoicing translator takes a CanonicalOrder, so an order without currency fails at the call instead of producing an invoice without one" expectedErrorType="MULE:EXPRESSION">
	<munit:execution>
		<set-variable doc:name="SET vInvoice" variableName="vInvoice" value="#[dwl::canonical::ToInvoicing::fromCanonical({orderId: 'ORD-C-2', source: 'ANY', customerId: 'CUS-1', country: 'PT', currency: null, items: [{sku: 'SKU-EBOOK', quantity: 3, unitPrice: 9}]})]" />
	</munit:execution>
</munit:test>

In the repository: src/test/munit/eip/canonical-data-model-test-suite.xml

Caveats

With few systems, the canonical model can cost more than it earns. The book itself warns that with two applications it needs twice the translators (Canonical Data Model). In a 2015 Stack Overflow question, tagged mule and from the Mule 3 era, someone asked whether it was worth putting a canonical model between a REST API and the SOAP services it orchestrated; the answer says it depends on the complexity of the environment and on the cost and likelihood of change, and that coupling to services that already expose a mature, versioned canonical model can be acceptable (Stack Overflow: Canonical data model).

The module does not see Mule’s attributes. In a 2020 community forum thread, already on DataWeave 2, a module function that read attributes.headers failed with Unable to resolve reference of attributes, and the same expression worked outside the module; the answer was to pass attributes as a parameter of the function (Trailblazer Community: Issue With DataWeave Custom Module). The documentation adds that a module cannot have an output directive, a body or the --- separator (Create Custom Modules and Mappings). In the example, every translator receives what it needs as a parameter (toCanonical(payload), fromCanonical(payload)), which is why the suite can call the target translators with no flow.

The canonical model only works among the applications that share it. The book asks that each application produce and consume messages in the common format (Canonical Data Model), and in a real system the applications are different Mule projects. In a 2023 Stack Overflow question, about Mule 4, someone wanted to use .dwl files from outside the project; the answer says that referencing DataWeave files outside the project directory does not seem possible by standard means, and points to DataWeave libraries published to Exchange or a Maven repository (Stack Overflow: Create dwl library for common dwl mapping in mule 4). In the example the modules live in the application itself, because everything runs in a single application.

The canonical model forces decisions the source does not make. The marketplace gives one currency per line; the canonical order has one. The translator joins the lines’ currencies, and an order in BRL and USD becomes "BRL,USD", which the validation rejects with 400 (the cdm-marketplace-order-in-two-currencies-returns-400 test). A partner order without a currency also gets 400 (cdm-partner-order-without-currency-returns-400): no currency is assumed.

When not to use it

With two systems that exchange messages only with each other, a direct Message Translator does the job, with half the translators. And when a target only needs part of the order, the canonical → target translation is a Content Filter, not a new model.

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 requires 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.

What each test in the suite proves, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
cdm-marketplace-order-becomes-canonical-and-both-targets The marketplace’s JSON order becomes the canonical order, an invoice request with a total of 72.5 and a CSV picking list
cdm-partner-xml-gives-the-same-target-documents The same order as the partner’s XML produces the same canonical items and the same target documents; only the identifiers and source change
cdm-module-target-translators-need-only-the-canonical-order The invoicing and inventory translators, called with no flow, need only the canonical order
cdm-module-target-translator-rejects-an-order-that-is-not-canonical An order without a currency fails at the invoicing translator’s call (MULE:EXPRESSION), instead of producing an invoice without a currency
cdm-partner-order-without-currency-returns-400 A partner order without a currency gets 400 with currency is required
cdm-marketplace-order-in-two-currencies-returns-400 A marketplace order with lines in two currencies gets 400
cdm-marketplace-order-without-buyer-returns-400 An order without a buyer gets 400, and the message names the canonical field (customerId is required)
cdm-partner-line-with-bad-quantity-returns-400 A quantity of two in the XML is caught by the same canonical validation, with 400
cdm-over-http-errors-answer-400-and-success-200 Over HTTP, both listeners return the status the error handling set: a marketplace order without a buyer and a partner order without a currency get 400 in JSON, and the valid order gets 200

To call the endpoints, run the application in Anypoint Studio (port 8081) and open requests.http in VS Code (REST Client) or IntelliJ. The two Canonical Data Model entries send the same order through the marketplace and through the partner:

### ...the same order as a partner XML purchase order gives the same target documents
POST {{base}}/eip/canonical/orders/partner
Content-Type: application/xml

<PurchaseOrder number="PO-77" currency="BRL"><Customer code="A-9"/><ShipTo country="BR"/><Lines><Line sku="SKU-BOOK" quantity="2" unitPrice="30.00"/><Line sku="SKU-MUG" quantity="1" unitPrice="12.50"/></Lines></PurchaseOrder>

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