Skip to main content

Import data from another system

Map each source payload to a Vox entity with a typed import handler.

For the team workflow, see Who owns each value.

Model the entity the way Vox should hold it, then write an import for each source payload that fills it. An import is an IVoxImport<TEntity> class that has the shape of the payload, and its typed handler maps that payload onto the entity. The entity never has to look like the payload: a source can send flat rows, nested documents or deltas, and the handler decides which entity values they become, also when it creates a new external entity from them. This works the same for an entity that another system owns (IVoxExternalEntity, whose properties are imported by default), for an entity Vox owns and for one that several systems contribute to; for the last two, mark the imported properties with [VoxImportOwned]. The imported values can be anywhere in the entity; there's no need for one object per import.

Only when the payload already has exactly the shape of an external entity can you skip the import class and handler and use a full-entity import.

An import is a durable command from an external source, not a direct database write. Vox keeps its original payload, puts it on the Nexus queue for its import type and applies it in a queue job. The handler runs against the latest entity in published content, so a retry does not overwrite a concurrent change made by another source, and no expected version is needed.

Each import type has a Nexus queue and queue job of its own, which operators watch, pause and retry in the Nexus admin. A job applies each batch of messages in the order it gets them, also several imports of the same entity. Nexus decides that order: with the default settings it's the order the imports arrived, but priorities, several workers or threads of a queue, and retrying a failed message after later ones were processed all change it. When a source needs strict ordering, keep its queue on those defaults or carry what the handler needs to ignore an older import, eg a change time, in the import. Different import types run in parallel, also when they import into the same entity type, eg a price import and a stock import of products. That's safe: an import writes only the fields its import type owns, merged into the latest stored entity, and applies only its permitted relation mutations. If another import changed the same fields in the meantime, the imports are applied again to the newest entities.

An import that fails for a reason that passes is deferred rather than failed, and Nexus processes it again later: one that still conflicts after five attempts, eg while two ERP feeds update the same prices at the same moment, after a few seconds; one that hits a timeout or a lost connection, eg of the database, after VoxProcessingOptions.TransientDeferral (30 seconds by default); and one that waits for storage that a model migration is building, once a minute. The same rule decides this for the change processing, assessments and model migration steps, and an application can teach it about the exceptions of its own services with an IVoxExceptionClassifier. Any other exception, eg of a bug in a handler or of invalid data, fails the import, also when it happens next to one that would be deferred.

The imports are applied as the system, so the entity's history shows the import type as the cause and the system as who made the change; who enqueued an import is checked against the import permission when it's enqueued, eg over HTTP.

Full-entity imports​

A full-entity import is a shortcut for the case where the payload is the external entity itself. It is available only when the complete entity is externally owned, its payload has the entity's own shape and a new import replaces the source-owned representation. Vox still manages versions, relation indexes, context memberships, calculations, search indexing and events around the imported data.

Use this when the external entity was modelled to match the payload, eg a product that is wholly mastered in a PIM and whose class follows the PIM's export. Don't bend an entity to a source's payload just to get this shortcut: when the payload differs from the entity you want, or the source sends deltas, write a custom import with a handler instead. If more than one source contributes to an entity, use custom imports as well, see Combine several sources into one external entity; allowing a full import would let one source erase the other's fields.

An external entity type with any custom import, including a relation-only import, has no full-entity import. Use custom imports for its ordinary fields as well.

Custom imports with a handler​

An import class has the shape of the payload and the entity has the shape that suits Vox, so the two usually differ. The handler is where one is mapped to the other. The entity names the imports that may change each imported field:

public class Product : IVoxEntity
{
// Other fields omitted.
[VoxImportOwned(typeof(ErpProductImport))]
public virtual decimal Cost { get; set; }

public virtual ProductTax Tax { get; set; } = new();
}

public class ProductTax
{
[VoxImportOwned(typeof(ErpProductImport))]
public virtual string? TaxCode { get; set; }

// Owned: an editor writes it.
public virtual string? TaxNote { get; set; }
}

public class ErpProductImport : IVoxImport<Product>
{
[VoxImportEntityId]
public required string Sku { get; set; }

public required decimal Cost { get; set; }
public required string TaxCode { get; set; }
}

public class ErpProductImportHandler : IVoxImportHandler<ErpProductImport, Product>
{
public Task<Product> ApplyAsync(
ErpProductImport import,
Product product,
IVoxEntityChanges<Product> changes,
CancellationToken cancellationToken)
{
product.Cost = import.Cost;
product.Tax.TaxCode = import.TaxCode;
return Task.FromResult(product);
}
}

[VoxImportEntityId] selects the target entity by its id. [VoxImportContext] can identify a context key when an import updates one contextual value. The handler may transform the source shape, preserve values omitted by a delta feed and use other services while deciding what to store. It receives a copy of the whole entity, but the import fails if it changes a field that the import may not write, eg TaxNote above.

Custom imports keep the values of all other fields and are retried against the latest entity when imported fields change concurrently. They can create an external entity that doesn't exist yet, but an entity owned by Vox must first be created through its create action; see Entities owned by Vox and external entities.

See Owned and mirrored data for how imports, actions and calculations share an entity.

Set only what the payload carries​

The handler never starts from an empty entity. Vox loads the latest published entity, gives the handler a copy and saves what comes back, so a field the handler doesn't assign keeps its stored value. An import that doesn't carry every field therefore doesn't clear the others. The handler decides what a missing value means, so one payload can mean "leave it", "clear it" or "use a default" for different fields:

public class ErpProductImport : IVoxImport<Product>
{
[VoxImportEntityId]
public required string Sku { get; set; }

// A delta feed: a property that is null was not part of this message.
public decimal? Cost { get; set; }
public string? TaxCode { get; set; }
public bool ClearDiscontinuedOn { get; set; }
public DateOnly? DiscontinuedOn { get; set; }
}

public class ErpProductImportHandler : IVoxImportHandler<ErpProductImport, Product>
{
public Task<Product> ApplyAsync(
ErpProductImport import,
Product product,
IVoxEntityChanges<Product> changes,
CancellationToken cancellationToken)
{
// Set a field only when the payload carries it.
if (import.Cost is not null) product.Cost = import.Cost.Value;
if (import.TaxCode is not null) product.Tax.TaxCode = import.TaxCode;

// Clearing is an explicit decision, never a side effect of leaving a value out.
if (import.ClearDiscontinuedOn) product.DiscontinuedOn = null;
else if (import.DiscontinuedOn is not null) product.DiscontinuedOn = import.DiscontinuedOn;

return Task.FromResult(product);
}
}

When the source sends the complete data every time, assign every field unconditionally and a missing value clears the field, as that source's data says.

If a concurrent import changed the same fields while the handler ran, Vox runs the handler again against the newest entity, so don't keep state outside the entity between runs. For index-backed relations, Replace treats what it's given as the complete set, which clears the links that aren't in it, while Link and Unlink change only the links named. See Relations.

Identify the entity by a unique field​

This is available for entities owned by Vox only, since an external entity can't have a unique constraint: an import of an external entity always identifies it by its id, see Combine several sources into one external entity.

A source often doesn't know Vox's ids, only its own identifier, eg the SKU of a variant whose Vox id is v-123. Name the entity's property in [VoxImportEntityId], and the import reaches the entity with that value:

public class Variant : IVoxEntity
{
// Other fields omitted.
[VoxUnique]
public virtual required string Sku { get; set; }

[VoxImportOwned(typeof(ErpCostImport))]
public virtual decimal Cost { get; set; }
}

public class ErpCostImport : IVoxImport<Variant>
{
[VoxImportEntityId(nameof(Variant.Sku))]
public required string Sku { get; set; }

public decimal Cost { get; set; }
}

The property must be unique on its own with [VoxUnique], not as part of a unique combination, and not vary on contexts, and the import's property must have its type. Vox checks this when it starts. The value is looked up when the import is applied, not when it's enqueued, by the unique index of published values and with the constraint's comparison, eg without case: abc reaches the variant with SKU ABC. Imports of a batch look up their values together, and imports by id don't look anything up. Use identifiers that sources don't change, since a value is matched against what's published.

An import whose value no entity has fails with VoxImportTargetNotFoundException, and Nexus retries it like any other failure; it never creates an entity. While a migration builds the storage of the unique constraint, Vox's own jobs enqueue the imports again for later rather than failing them. A job of the application, see Own the queue of an import, gets a VoxCapabilityPendingException as the outcome's error instead and decides itself, eg reports the message failed so Nexus retries it, or enqueues it again with a later ProcessAtUtc. The handler gets the entity with its Vox id, and must return it with that id.

Entities owned by Vox and external entities​

A handler works the same way for both kinds of entity: it edits a copy of the latest stored entity and keeps what it doesn't assign. They differ in which fields an import may write, in what happens when the entity doesn't exist and in how the entity is identified:

Entity owned by Vox (IVoxEntity)External entity (IVoxExternalEntity)
Fields an import may writeOnly those marked [VoxImportOwned] for it. The rest belong to editors and actions or are calculated.Every field by default, except those marked [VoxOwned] (a local field on the entity) or [VoxCalculated]. Restrict a field to certain imports with [VoxImportOwned(typeof(...))].
Assigning a field it may not writeThe import fails.The import fails.
The entity doesn't existThe import fails. Create the entity through its create action first.The import creates it, from a new entity with default values and version 0.
Identified byIts id, or a unique field.Its id.

So an import of an entity owned by Vox always updates some of its fields, and what the handler leaves out stays as editors and other sources left it. An import of an external entity carries a source's data for the entity, and can be the one that brings the entity into Vox.

Create the entity before importing into it​

An import never creates an entity owned by Vox, so a source that knows a product before editors do can't bring it into Vox by itself. Say Vox is a PIM, Product is owned by Vox and an ERP is the first to know the SKUs. Create the product from your own queue job, then apply the import. This uses an import that is also a Nexus IQueueMessage, see Own the queue of an import, so the job is yours and can do something before the imports are applied:

[Queue(Name = "erp_product")]
public class ErpProductImport : IVoxImport<Product>, IQueueMessage
{
[VoxImportEntityId]
public required string Sku { get; set; }

public required string Name { get; set; }
public required decimal Cost { get; set; }
}

public class ErpProductJob(
IVoxEntityStore<Product> products,
IVoxEntityUpdater updater,
IVoxImportProcessor imports) : IBatchQueueJob<ErpProductImport>
{
public async Task ProcessMessagesAsync(QueueMessageBatch<ErpProductImport> batch, CancellationToken cancellationToken)
{
// Create the products that don't exist yet, looking them all up at once.
var skus = batch.Messages.Select(message => message.Sku).Distinct().ToList();
var existing = (await products.GetManyAsync(skus, cancellationToken)).Select(product => product.Id).ToHashSet();
var failed = new Dictionary<string, Exception>();

foreach (var message in batch.Messages.DistinctBy(message => message.Sku).Where(message => !existing.Contains(message.Sku)))
{
try
{
await updater.CreateAsync(
new ProductActions.Create { Id = message.Sku, Name = message.Name },
cancellationToken);
}
catch (VoxVersionConflictException)
{
// Someone created it after the lookup, which is what was wanted.
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
failed[message.Sku] = exception;
}
}

// Apply the imports of the products that exist, and report the others as failed so Nexus retries them.
foreach (var message in batch.Messages.Where(message => failed.ContainsKey(message.Sku)))
{
batch.Failed(message, failed[message.Sku]);
}

var toApply = batch.Messages.Where(message => !failed.ContainsKey(message.Sku)).ToList();
foreach (var outcome in await imports.ApplyBatchAsync(toApply, cancellationToken))
{
if (outcome.Error == null) batch.Processed(outcome.Import);
else batch.Failed(outcome.Import, outcome.Error);
}
}
}

The create action carries the fields editors own (Name here), since an import can't write those once the product exists, so the job gives the new product a starting value and the import takes over the imported fields (Cost) from then on. Notes on the example:

  • The lookup is a bounded read of the SKUs in the batch, not of all products. CreateAsync throws VoxVersionConflictException when an entity with the id exists, so two jobs creating the same product at once is safe: the one that lost simply goes on to the import.
  • The import identifies the product by its id, so the id given to CreateAsync is the id of the import (Sku). An import that names a unique field can't be used for this, since it never creates anything and you would have to find the id first.
  • A create runs the product's create action: its validation, calculations and permissions apply, and it can be rejected like any other create. A rejected create fails the messages for that product, which Nexus retries, so a source's invalid product doesn't block the rest of the batch.
  • Creating is not part of the import's transaction. A crash after the products were created but before the batch was reported makes Nexus process the messages again, and the products then exist; this is the same replay every queue job must tolerate.
  • Authorization of the create is the same as for any use of IVoxEntityUpdater. A queue job has no signed-in user, so see Users and permissions for the principal that background work runs as.

If the ERP's data should never be mixed into a product that editors own, use an external entity for the ERP's data instead, or make Product external, as in the next section.

Combine several sources into one external entity​

Vox can hold an entity without owning it, and several systems can contribute to it. Say Vox holds products for unified reads, the PIM supplies their names and descriptions and the ERP supplies their costs. Give each source an import and a handler of its own, and name the import that writes each field:

public class Product : IVoxExternalEntity
{
// Other fields omitted.
[VoxImportOwned(typeof(PimProductImport))]
public virtual string Name { get; set; } = "";

[VoxImportOwned(typeof(ErpProductImport))]
public virtual decimal? Cost { get; set; }
}

public class PimProductImport : IVoxImport<Product>
{
[VoxImportEntityId]
public required string Sku { get; set; }

public required string Title { get; set; }
}

public class PimProductImportHandler : IVoxImportHandler<PimProductImport, Product>
{
public Task<Product> ApplyAsync(
PimProductImport import,
Product product,
IVoxEntityChanges<Product> changes,
CancellationToken cancellationToken)
{
product.Name = import.Title;
return Task.FromResult(product);
}
}

public class ErpProductImport : IVoxImport<Product>
{
[VoxImportEntityId]
public required string ArticleNumber { get; set; }

public required decimal PurchasePrice { get; set; }
}

public class ErpProductImportHandler : IVoxImportHandler<ErpProductImport, Product>
{
public Task<Product> ApplyAsync(
ErpProductImport import,
Product product,
IVoxEntityChanges<Product> changes,
CancellationToken cancellationToken)
{
product.Cost = import.PurchasePrice;
return Task.FromResult(product);
}
}

The two payloads share nothing but the product's identity, and neither has to look like Product. Each import is queued, retried and watched on its own, and the two run in parallel.

Either source can create the product. An import whose entity doesn't exist yet gets a new entity with default values, so it doesn't matter which system knows the product first. The import writes the fields it owns, and every other field keeps its default until its own source's import arrives. Here a product the PIM created has no Cost until the ERP import arrives, which is why Cost is nullable: readers can tell an unknown cost from a free product. Give a field a default that readers can interpret, or make it nullable, when its source may come second.

Both sources must use the same id. An external entity is identified by its id only, so Sku and ArticleNumber above must hold the same value, which becomes the product's id. The id is read from the payload when the import is enqueued, so if the systems use different identifiers, whatever sends the payload to Vox has to translate its own identifier to the shared one. The id is what the two imports must agree on, not their payloads. An import never creates an entity that it identifies by a unique field, and an external entity can't have one.

Two imports creating the same product at once is safe. Vox creates a new entity only if it doesn't exist. If the other import created it a moment earlier, the later one is applied again to the product as it is stored, now as an update of its own fields, and the handlers run again, so they must not keep state outside the entity. A write that keeps losing is retried a few times and then fails like any other import, and Nexus retries it.

An import writes only the fields it owns. An ERP handler that assigns Name fails the import, so the two sources can't overwrite each other by accident. If a field has no [VoxImportOwned] types, every import of the entity may write it, and the last one applied wins; name the owner whenever two sources send the same kind of value, or use a [VoxOwned] field for what an editor in Vox maintains next to the imported data.

Don't use a full-entity import for an entity that several sources fill: it replaces the complete source-owned representation, so it would erase what the other source brought. An external entity type with custom imports can't have one, see Full-entity imports.

Relations​

Embedded relations, such as a list of references, are imported by changing their field values. For an index-backed IVoxRelationReferences<T>, use the handler's IVoxEntityChanges<TEntity>.Relations collector instead.

Declare ownership with the same attributes as fields. Put [VoxImportOwned] directly on the relation, or inherit it from its containing object. The nearest declaration wins: [VoxOwned] can make one relation locally editable inside an imported object. Neighbouring fields do not decide who may change the relation.

An import can own only relations, with no ordinary fields. For example, add this property to Product:

[VoxImportOwned(typeof(ProductCategoriesImport))]
public virtual IVoxRelationReferences<Category> Categories { get; set; } = default!;

Its import and handler can contain just the product identity and the category identities:

public class ProductCategoriesImport : IVoxImport<Product>
{
[VoxImportEntityId]
public required string ProductId { get; set; }
public List<string> CategoryIds { get; set; } = [];
}

public class ProductCategoriesImportHandler : IVoxImportHandler<ProductCategoriesImport, Product>
{
public Task<Product> ApplyAsync(
ProductCategoriesImport import,
Product product,
IVoxEntityChanges<Product> changes,
CancellationToken cancellationToken)
{
changes.Relations.Replace(
p => p.Categories,
import.CategoryIds.Select(id => new VoxReference<Category>(id)));
return Task.FromResult(product);
}
}

Vox registers the import when it may write at least one field or index-backed relation. The handler cannot change other fields or relations. As with other partial imports, a locally owned product must already exist; an external entity can be created by the import.

Replace treats the supplied references as the complete set, so do not call it for each page of a partial feed. It does not load the old collection into the handler; storage computes the difference. Use Link and Unlink for delta feeds without first reading the existing links.

Entity values and relation mutations go through the same write pipeline. Small changes commit atomically; very large replacements converge through bounded background work, and reads can observe their progress. See Changing an index-backed relation for the replacement limits and concurrency behaviour.

When a source publishes links with data independently of either endpoint, eg an assortment, import them as entities of their own with references to both sides.

Own the queue of an import​

By default Vox stores an import in a Nexus queue of its own and applies it with its own job. An import that also implements Nexus's IQueueMessage is enqueued to the application's queue instead, as the import itself, so the application configures that queue like any other: its name, retries, priorities, workers, retention and idempotency. The application also writes the job that processes it; Vox has no job for that queue.

[Queue(Name = "erp_cost")]
public class ErpCostImport : IVoxImport<Variant>, IQueueMessage
{
[VoxImportEntityId(nameof(Variant.Sku))]
public required string Sku { get; set; }

public decimal Cost { get; set; }
}

The import needs exactly one concrete Nexus queue, a discovered one or a named one; a host that enqueues imports fails when it starts if it has none or several. IVoxEntityImporter, the HTTP endpoint and the application's own IEnqueuer all enqueue the import in its own shape, with Nexus's serialization, validation and message ids, rather than in an envelope that keeps the exact JSON that was posted. A message that Nexus's validation rejects is a 400 Bad Request over HTTP.

Register a Nexus queue job for that queue like any other job of the application, eg a discovered queue job of the message type, or one added with vox.ConfigureNexus(nexus => nexus.AddJobs(...)). A host that processes Vox work (AddProcessing()) fails when it starts if that queue has no job, so the messages don't wait unprocessed without anything saying why. The job applies the messages with IVoxImportProcessor, which uses the same import pipeline as Vox's jobs:

public class ErpCostJob(IVoxImportProcessor imports) : IBatchQueueJob<ErpCostImport>
{
public async Task ProcessMessagesAsync(QueueMessageBatch<ErpCostImport> batch, CancellationToken cancellationToken)
{
foreach (var outcome in await imports.ApplyBatchAsync(batch.Messages, cancellationToken))
{
if (outcome.Error == null) batch.Processed(outcome.Import);
else batch.Failed(outcome.Import, outcome.Error);
}
}
}

ApplyBatchAsync applies the imports of each entity type in the order given, one entity type after another, and returns an outcome per import in the order given, with the original exception of each one that failed, so one failure doesn't block the others. The entities of a batch are written together, so when storage refuses one of them, eg a value too long for the database, the imports of the other entities are applied again one entity at a time, running their handlers again, and only the imports of that entity fail. In a transaction of IVoxTransactionRunner, the imports of the entity type all fail instead, since the transaction may no longer be usable. ApplyAsync applies one import and throws its exception. The imports of a list may be of different import types, eg a list of object. Cancellation throws instead of failing imports: leave the batch unreported, and Nexus processes the messages again. A crash after the imports were saved but before the batch was reported also makes Nexus process them again, so handlers must tolerate replay, as with every queue.

The ordinary operations return nothing about the entities, so they cost no more than Vox's own jobs. When the caller needs to know what an import changed, ApplyWithEntityAsync and ApplyBatchWithEntitiesAsync also return the entity of each import as that import left it, with its version and calculated values. Each import of the same entity gets the entity of its own change. Called inside a transaction of IVoxTransactionRunner, the imports join it, and the entities describe changes that are only saved if that transaction commits.

Batches and completion​

One request can contain one import or an array, and the response is an empty 202 Accepted once the imports are queued. Nexus keeps the history of each message, and the entity shows the change once it's applied. Imports in the same batch are applied in order, while independent import types can be processed in parallel.

The request returns as soon as the imports are queued; there's no option to wait for them. What happens next is the same as for an edit in the admin UI. Say an ERP import changes a variant's cost from 100 to 120, and the variant's margin is calculated from its cost:

  1. The import is processed: its handler runs, and the save evaluates the margin against the new cost and publishes the cost and margin together. From then on, lists and other readers see 120 with its margin.
  2. Other entities whose calculations read the variant, eg its product's price range, are recalculated in the background.

The imports of a batch are evaluated together, so what their calculations read is read once for the batch. A calculation that fails fails the import of that entity, and of the other entities saved with it, while the rest of the batch is saved. See Calculations and Dependency and change tracking.

An integration that needs to act on the result subscribes to the entity's events instead of waiting or polling. One event is sent per published change, so subscriptions observe the same entity lifecycle whether the change began as an action or an import.

See Events and subscriptions, Calculations and Querying and search.