Skip to main content

Share entities between Vox applications

Export a contract from the owning Vox application and generate an external entity type in each consuming application.

For the team workflow, see Keeping systems in step.

Export a contract​

An application with the Vox API exposes GET /api/contracts. Pass the stable name by which the consumer identifies the source, the namespace to generate in the consumer, and one or more entity types:

GET /api/contracts?source=pim&namespace=Shop.Cms.Entities&entity=Product&entity=Category

Referenced entity types and context types are included automatically. Save the response in the consuming project with a .vox.json suffix, for example Contracts/pim.vox.json.

The contract describes the serialized entity shape, nested objects, enums, relations, varying values and query fields. It does not contain the owner's actions, permissions, drafts, principals, CLR namespaces or the origins of its fields: whether the producer edits, imports or calculates a value is its own business, and changing that doesn't change the contract or its revision. Enum values travel as their names, eg "Orderable", so a consumer's generated enum has the producer's member names but not necessarily its numbers, eg when the producer declares Low = 1, High = 2.

A field set, eg a product's specifications, is described with its fields, its templates and which fields each template has and requires. The consumer's generated class is a sparse field set with an interface per template, named like the producer's, so it stores, reads and edits the values like the producer, and its admin offers the same templates. A new field or template changes the revision. Labels, units and groups of fields aren't in the contract, as for other properties.

Generate local external entities​

Include the downloaded contract as an AdditionalFiles item:

<ItemGroup>
<AdditionalFiles Include="Contracts\*.vox.json" />
</ItemGroup>

The source generator shipped with CommerceMind.Vox.Abstractions generates classes such as:

namespace Shop.Cms.Entities;

[VoxExternalSource("pim", "Product", "...")]
public partial class Product : IVoxSynchronizedExternalEntity
{
// Built-in, synchronization and contracted properties are generated.
}

AddVox() discovers the generated classes like handwritten entity classes. No reference to the PIM's entity assembly and no handwritten IProduct adapter are needed.

Add consumer-local calculated data​

Generated entity and object classes are partial. A consumer can add its own fields in its own code, on the entity or inside a generated object:

namespace Shop.Cms.Entities;

public partial class Product
{
[VoxCalculated(typeof(ProductPresentationCalculation))]
public virtual ProductPresentation Presentation { get; set; } = new();
}

public class ProductPresentation
{
public virtual string? PageTitle { get; set; }
}

Implement ProductPresentationCalculation as an IVoxCalculation<Product>, or mark local properties with [VoxOwned] to edit them in the consumer. The contracted properties are generated with [VoxSynchronized]: synchronization writes only those, so the consumer's own fields are kept, and only synchronization changes them.

Prefer a separate CMS-owned entity referencing Product when data is editorial rather than derived. This keeps the ownership boundary clear when complete snapshots arrive from the PIM.

Updating a contract​

Contract manifests contain a deterministic revision. Adding a producer property is compatible with an older consumer: the older generated class ignores the unknown JSON property until its contract is refreshed. Type changes can be incompatible and should be deployed by updating consumers before the producer starts sending the changed representation.

Refresh the checked-in manifest when the consumer needs new fields. Because the manifest is source-controlled, its generated API changes are visible and reviewable with the application change that uses them.

Each property of a manifest has two names, eg:

{ "name": "Name", "jsonName": "title", "type": { "kind": "builtIn", "name": "string", "isNullable": true } }

jsonName is the property's canonical name, which the snapshots, queries and paths use. name is only the CLR name to generate the member with, and the consumer gets:

[JsonPropertyName("title")]
[VoxSynchronized]
public virtual string? Name { get; set; }

The revision is computed from what the data means, not from how C# is generated: the CLR names of properties, their order and the names and namespaces of the classes of objects, field sets and enums, and the names of templates' interfaces, aren't part of it. So when the producer renames [JsonPropertyName("title")] Name to DisplayName, the refreshed manifest has "name": "DisplayName" but the same revision. A consumer generated before can keep its Name, a consumer generated after gets DisplayName, and both receive "title": "Rain jacket" into their own member, store and query it as title, without a resynchronization or a coordinated rollout. Refreshing a consumer's manifest only changes its C# API; its fields and stored values stay. A change of jsonName is a real rename, which renamedFrom records.

A manifest also describes how the producer's model evolved, by contract names: renamedFrom lists the names an entity type and its properties had before a rename, and entityKinds and defaultKind describe a family. The generated classes declare the renames with [VoxRenamedFrom], so refreshing the manifest renames the consumer's own fields instead of replacing them, and the consumer's stored data is kept; see Model evolution. A conversion of the producer, eg a string that became a number, isn't executed by the consumer: declare a conversion, or clear the property, in a model migration of the consumer.

Vox doesn't pause deliveries because a producer's contract changed: the change may not affect the consumer, and other updates keep flowing. The contract-revision warning is informational. Plan a breaking change with the owners of both applications: update the consumer's model, deploy it, then start a full synchronization of the changed entity type, see below. Its snapshots are applied again even at versions the consumer already has, so values that its earlier contract ignored are filled, but never over newer state.

Synchronize changes​

Create a subscription in the owning application with:

  • Payload: Entity snapshot for Vox sync
  • Source name: the same stable name used to download the contract, for example pim
  • Entity types: the locally-owned types to synchronize, for example Product and Category
  • Transport: webhook, RabbitMQ or Redis

Snapshot subscriptions intentionally require explicit, locally-owned entity types and events of published changes. They don't allow field, relation or context filters, because skipping some changes would leave the consumer stale.

Each delivery contains the latest committed entity representation, not merely the version mentioned by the original change event. Retries therefore coalesce intermediate changes and converge on the producer's current state, and a subscription has at most one delivery of an entity waiting, see Delivery. Deletions are delivered as tombstones. Delivery is at least once. Each snapshot carries the stream it's delivered by, its subscription, and the revision of the entity, which the producer reads consistently with the snapshot. The consumer keeps what each stream delivered of each entity, also after a deletion, and ignores duplicate, older and late snapshots, so a deleted entity isn't brought back. Each snapshot is imported in one transaction: the entity, its cells and the stream's revision.

A raw subscription can choose context types for its context sidecar, eg ["Market"], whose cells the consumer imports as cells of the external entity, or a concurrent context type, eg the variants of experiments. includeDrafts and includeReleases opt in to the drafts and releases, with the cells of the chosen context types there, and entities that only exist there. See Synchronized contexts, which also covers what the consumer does with a cell of a context type it doesn't have. To work on the same campaign in both applications, each creates a release with the same id, see Content releases.

After creating the subscription, choose Sync now in the subscriptions screen, or call:

POST /vox/api/subscriptions/{subscriptionId}/sync

This requests a synchronization, which Vox's vox_subscription_sync background work runs a page at a time, on one processing host at a time, so it covers any number of entities. Synchronizations are operated in the Vox admin, not in the Nexus admin. One that stops, eg because its host did, runs again from the beginning as a new one, which may deliver entities again, and one requested while another runs stops that one and runs once it has. It delivers the current entities, unchanged ones too, through the same durable delivery path as ongoing changes, and up to those created when it started, which ongoing changes deliver. The answer is 202 Accepted with the operation; GET /vox/api/subscriptions/{subscriptionId}/sync reads how far the latest one has come. Its snapshots carry the generation of the operation, resync, a newer one for each, so a receiver applies them again even at a version it has, but never one older than what it has.

The links of reference properties are in the entity. A snapshot also has every link of the entity's index-backed relations that the subscription may see, in relations, and names those relations in relationCoverage:

"relationCoverage": ["relatedProducts"],
"relations": [
{ "relation": "relatedProducts", "address": "published", "revision": 12,
"links": [{ "entityType": "Product", "id": "p2" }], "suppressed": [] }
]

The consumer replaces the links of the covered relations of its external entity with those of the snapshot, and removes the ones it doesn't have, also all of them for a relation without links, which is always in the snapshot. A relation that isn't covered, eg one whose property the subscription may not see, keeps its links. A raw subscription also gets the links that the cells of its context types and its drafts and releases add (links) and hide (suppressed), at their addresses, eg published|Market=se, which replace the consumer's links there; a resolved one gets the links as they're read in its selection. The related entities needn't be synchronized, and the consumer derives the inverse links. The generated external entity has the relation with the same names, so its links can be read and expanded like local ones; regenerate it after updating the contract.

A relation with more links than a complete read gets (VoxReadBudgets.MaxRelationLinks) is delivered in parts: every part is the whole snapshot with some of the links and transfer (id, part, and parts in the last one). The consumer keeps the parts and imports the snapshot once it has every part, so a part that's lost never removes links; a retry delivers a new transfer. The parts wait about a day for each other, and they can't be imported if the consumer's model of the entity type changed in between. A webhook producer then delivers the snapshot again by itself, since the delivery fails. A queue, RabbitMQ or Redis, would deliver the same last part again in vain, so give the consumer the producer's API and an API key there of a principal that may manage subscriptions:

options.RequestSnapshotsFrom("pim", new Uri("https://pim.example/vox/"), pimApiKey);

The consumer then acknowledges the part, records that it needs the snapshot, and asks the producer for it with POST api/subscriptions/{id}/resend ({ "entityType": "Product", "entityIds": ["p1"] }, at most 100), which delivers the current snapshots again. A request that can't reach the producer is kept and sent again later, so the update isn't lost. The links of a large snapshot converge a page at a time, see Changes of links. While an entity's links are being replaced at the source, its snapshots wait until the replacement is done.

Webhooks​

The producer enables webhook subscriptions:

vox.AddWebhookSubscriptions();

Configure the subscription URL as the consumer's Vox endpoint and give it a secret:

https://cms.example/vox/api/entity-sync/pim

The consumer accepts that source and verifies the existing X-Vox-Signature HMAC:

.AddApi(options => options.ReceiveEntitySync("pim", configuration["PimSyncSecret"]!))

An unknown source returns 404, an invalid signature returns 401, and an incompatible snapshot returns 400 so it isn't mistaken for a transient delivery failure.

RabbitMQ​

Both applications configure the RabbitMQ subscription package. The producer creates an entity snapshot subscription whose exchange setting names an existing topic exchange. The consumer adds a durable queue and binding:

.AddRabbitMqSubscriptions(options =>
{
options.ConnectionString = configuration.GetConnectionString("rabbitmq");
options.ReceiveEntitySync(
source: "pim",
exchange: "vox.entity-sync",
queue: "cms.pim.entity-sync",
routingKey: "#");
})

The producer counts a snapshot as delivered once the broker confirms it, and tries it again otherwise. The receiver acknowledges a snapshot only after Vox stores it. Transient failures are requeued and tried again with a growing delay, so a message that keeps failing isn't retried every moment; RabbitMQ puts a requeued message back first, so the order of the queue doesn't change. Incompatible messages are rejected, allowing a configured RabbitMQ dead-letter exchange to capture them. Only the hosts of the active deployment receive, so a standby or retiring host leaves the messages in the queue, see deployments.

Redis​

The producer creates an entity snapshot subscription whose stream setting names the shared stream. The consumer joins its own consumer group:

.AddRedisSubscriptions(options =>
{
options.ConnectionString = configuration.GetConnectionString("redis");
options.ReceiveEntitySync(
source: "pim",
stream: "vox:pim:entity-sync",
consumerGroup: "cms");
})

Every CMS instance uses the same group, so each snapshot is applied once by one instance. Unacknowledged messages are claimed and retried after 30 seconds by default. Give each consuming application a different consumer group.

Contract revisions​

Snapshots include the deterministic revision of the exact entity set selected by the subscription. A different local revision is logged as a warning but doesn't reject the delivery: additive producer fields remain compatible because older consumers ignore unknown JSON properties. A genuinely incompatible body fails deserialization and is rejected or retried according to the transport.