Skip to main content

Vox Serve

Vox Serve is a set of libraries for serving customer traffic, eg product pages, product cards, CMS pages and settings, from documents that Vox publishes to a projection store. A serve host reads the store and resolves each document in the visitor's market, language and customer group. It never evaluates projections and never reads Vox's entity stores for them, so the shop scales with its own hosts and store, not with Vox's database.

This page calls the rest of Vox, which stores entities and runs authoring, imports, calculations and publications, Vox core.

For the team workflow, see Serve customer traffic.

How it fits together​

Take a product card. An editor changes the Swedish name of product p1. Vox core recalculates what depends on it and runs the card's publication, which writes the card's changed documents to the projection store, eg Redis. The next request for the card on a serve host, eg GET /serve/Product/p1/projection/card?lang=sv on the Swedish shop's host, selects the market and language the way the application decides, reads the documents from Redis and returns the new name. Nothing in between caches the old one.

Vox Serve has two halves, since publications run in Vox core's processing hosts and serving runs anywhere:

PackageRuns inDoesDepends on
CommerceMind.Vox.Serve.PublishingEvery host that uses Vox corePublishes the served projections, the context manifest and the projection catalog to the storeVox core, CommerceMind.Vox.Serve
CommerceMind.Vox.ServeThe serve hostThe store abstractions, an in-memory store for tests, the reader that resolves and assembles documents, the endpoints, request selection and metricsCommerceMind.Vox.Contexts, CommerceMind.Vox.Abstractions, ASP.NET Core
CommerceMind.Vox.Serve.RedisBothThe Redis projection storeCommerceMind.Vox.Serve, StackExchange.Redis
CommerceMind.Vox.Serve.EntityFrameworkBothThe SQL projection storeCommerceMind.Vox.Serve, Entity Framework Core

The reading half doesn't reference Vox core or CommerceMind.Vox.Processing, and only the SQL store references Entity Framework Core; a test in Vox checks that it stays so. A serve host can use it alone, or beside Vox core in process for the data that must be authoritative, eg gift card balances. See serve hosts for the compositions and what each costs.

A projection store is fed by one Vox application. Two applications that share a Redis keep their stores apart with KeyPrefix, and two applications on the SQL store use two databases, see The projection store.

Vox Serve reads documents by key. It doesn't resolve URLs: route delivery, /content/{path}, stays in Vox core, see Routing and redirects. Listings and search come from a search engine that a publication feeds, see Also to a search engine.

Serve a projection​

A projection is served when its output type implements the marker interface IVoxServedProjection, in CommerceMind.Vox.Abstractions.EntityProjections. It still needs [VoxEntityProjectionPublication], which says which contexts its documents are published for:

public record ProductCard(string Id, string? Name, decimal? Price, string? Currency,
VoxProjectionRef<BrandCard>? Brand) : IVoxServedProjection;

public record BrandCard(string Id, string Name, string? Path) : IVoxServedProjection;

[VoxEntityProjection("card", "1", IsDefaultForReferences = true)]
[VoxEntityProjectionPublication(PerCombination = [typeof(Market)], KeyedCells = [typeof(Language), typeof(CustomerGroup)])]
public class ProductCardProjection : IVoxEntityProjectionFactory<Product, ProductCard> { ... }

The application doesn't register a sink for a served projection. AddServePublishing, see Register the backend, registers Vox Serve's sink for every published projection with a marked output, so no list of served projections is kept in Program.cs. For an entity family, mark the shared output, eg public abstract record BlockView(string Id) : IVoxServedProjection;, and every kind's output is served with it.

The backend checks the served projections when it starts and refuses to start, with a message that names the projection, when:

  • A served output has no publication. Add [VoxEntityProjectionPublication] to its factory.
  • A typed reference points at a projection that isn't served. A VoxProjectionRef<CategoryCard> in a served projection needs CategoryCard to implement the marker too. Otherwise every page in the store would reference a card that never reaches it.
  • A served projection includes drafts or releases. Remove IncludeDrafts and IncludeReleases: the store only holds published content, and a preview reads its drafts from Vox core, see Preview through Vox Serve.
  • A served output has a [VoxSensitive] value, on a property, on a nested object's property, or a class marked sensitive that it holds. Publications don't redact, so the value would be served to everyone. Remove it, or publish a separate projection that isn't served to a sink of the application's own, behind its own authorization.
  • A projection is served but AddServePublishing isn't called. The message names AddServePublishing.
  • AddServePublishing is called without a store. Register one, eg AddRedisProjectionStore.

Two kinds of references can't be checked at startup, since they don't name their target's output type: an entity embedded in rich text, and an untyped VoxProjectionRef<object>, which context.Reference(reference) returns for a relation with a projection hint, eg to the blocks of an entity family. If one points to a projection that isn't served, it stays a reference in the response and gets a diagnostic when it's read, eg The projection 'page' of Product isn't served.

Versions. A reference doesn't carry the version of its target: Vox Serve looks a document up by entity type, ID and projection. While a new version of a card is published incrementally, the store holds cards of both versions, as any sink does. Request a full build when every document needs the new version, see Incremental and full builds.

Choose the context shape​

The publication's context types decide what a source's documents are, see Publishing per context, and Vox Serve resolves both shapes:

  • Per combination: a document per combination of members where the source is read, eg the card of p1 in Sweden and the one in Norway, and none without a market. A request must select a member of each context type published per combination, eg a fallback market for a visitor the shop can't place; otherwise it finds no document and answers not found, and a reference resolved in its selection finds none either.
  • Keyed cells: one document whose values differ per key, eg the name in Swedish and the price for members, where a cell holds only what differs.

For example, a shop can publish its product pages and cards per market, with language and customer group as keyed cells. A market changes most of a product, its price, currency and assortment, so a document per market is natural. A language changes only the texts, and a customer group only a price, so they're cells of the market's document rather than documents of their own. A card in five markets, three languages and two customer groups is then five documents, not thirty. CMS pages, blocks and brands, which are the same in every market, are one document each with the language as keyed cells. Categories are per market with the language as keyed cells.

Use per combination for the context types that change most of a document, and keyed cells for those that change a few values. Vox Serve reads every document of a source when it serves one, so a card per market, language and channel in 10 markets, 5 languages and 3 channels is 150 documents read to serve one: the combinations multiply both the publication's work and each read.

Also to a search engine​

A served projection can go to sinks of the application's own as well, eg the product card to Typesense or Algolia for listings and search. Register the sink for the output type as for any publication:

[VoxPublicationSink("typesense-products", DisplayName = "Typesense product search")]
public class TypesenseProductCardSink : IVoxEntityProjectionPublicationSink<ProductCard> { ... }

Each source is evaluated once and written to both, and each sink moves at its own pace, so an outage of the search engine doesn't hold back the projection store, see Several sinks.

Register the backend​

The backend, which runs Vox's processing, publishes to the store. Call AddServePublishing on the Vox registration, and register a store:

using CommerceMind.Vox.Serve.Publishing.Extensions;
using CommerceMind.Vox.Serve.Redis.Extensions;

var vox = builder.AddVox(options => { /* model */ })
.AddSqlServerStorage()
.AddProcessing()
.AddServePublishing();
builder.Services.AddRedisProjectionStore(options =>
options.ConnectionString = builder.Configuration.GetConnectionString("serve-redis"));

For local development or a smaller site, register the SQL store instead, see The projection store:

using CommerceMind.Vox.Serve.EntityFramework.Extensions;

builder.Services.AddEntityFrameworkProjectionStore(options => options.ConfigureDbContext = (_, dbContext) =>
dbContext.UseSqlServer(builder.Configuration.GetConnectionString("serve")));

AddServePublishing registers:

  • The serve sink, VoxServeProjectionSink<T> with the key vox-serve, for each served output type, beside any sinks of the application's own.
  • The manifest sink, which publishes the context manifest to the store whenever its revision changes, eg when a market is added, so a serve host selects contexts the way Vox core does.
  • The catalog writer, a hosted service that writes the context manifest and the projection catalog to the store when a processing host starts, and tries again every 30 seconds while it fails, eg while Redis is down. First it requests the full builds of served publications that the serve sink has never published, by the publications' state, not the store's content, see below. It does nothing on a host that only produces Vox work.

Every host of an application that uses Vox core needs the sinks of every publication in its model, also a host that doesn't process publications, since building Vox checks them. So a serve host that uses Vox core in process calls AddServePublishing and registers a store too, and keeps every other registration that adds publications or sinks, eg routing and image routing, see A serve host with Vox core. Without AddServePublishing, its start fails with a message that names it. Only the backend's processing hosts publish documents and the manifest and write the catalog. A serve host never writes to the store, so it can read a read-only replica.

What fills the store. A new application fills its store with the publications' first builds. When AddServePublishing is added to an application that already publishes, or a projection becomes served in a later release, the catalog writer requests a full build of the vox-serve sink of each served publication that the sink has never published, since a new sink otherwise only receives the later changes. The application's own sinks aren't rebuilt. Like any full build, it holds the publication's other sinks until it completes, see Incremental and full builds, and a full build into a filled store keeps serving, see Freshness, releases and rebuilds.

Vox doesn't fill a store that lost its data, or one an application is pointed at after its publications published to another: its publications have already published everything. Run Redis with persistence. After losing a store's data, re-run the full Nexus jobs of the served publications (vox_pub_{publication}_full) and restart a processing host of the backend, which writes the context manifest and the catalog again.

Register a serve host​

A serve host registers the reading half and maps the endpoints:

using CommerceMind.Vox.AspNetCore.Extensions;
using CommerceMind.Vox.Serve.Extensions;
using CommerceMind.Vox.Serve.Redis.Extensions;

builder.Services.AddRedisProjectionStore(options =>
options.ConnectionString = builder.Configuration.GetConnectionString("serve-redis"));
builder.Services.AddVoxServe();
// The application chooses the market, language and customer group of a request, see Context selection
builder.Services.AddScoped<IVoxServeRequestContexts, ShopRequestContexts>();

var app = builder.Build();
app.MapVox(); // the reads at /serve, after authentication where the host registers it, eg to choose contexts from claims
app.Run();

AddVoxServe takes VoxServeOptions:

OptionDefault
PathPrefix/serveWhere MapVox() maps the reads
MaxDepth8The most levels of references a read assembles. A request's referenceDepth can only lower it
MaxProjections100The most documents in an assembled read, the root included
MaxOutputBytes1,000,000The most bytes of values in an assembled read
ModelRefreshInterval5 sHow long the host keeps the manifest and catalog it read, see Caching
AllowContextParameter(...)NoneThe context types a request may select with the context parameter, see Context selection
ReadDraftsFromVoxApi(uri)NonePreviews read drafts and releases from the Vox API of another application, see Preview through Vox Serve
DraftReadTimeout10 sHow long a preview waits for that Vox API before it answers 503

The limits are the same as Vox core's. To add authorization, rate limiting or output caching to the endpoints, a host maps them itself with app.MapVoxServe() instead of MapVox(): it returns the endpoints' route group. A host that maps them itself adds app.UseVoxServePreview() before them when it previews.

A serve host without Vox core finds its request stages, if any, in its own assembly, see Where Vox Serve finds a stage. They're matched with the served projections by the full names of their output types, so such a serve host references the output records from a project of their own that references only CommerceMind.Vox.Abstractions, rather than the backend's project.

A serve host with Vox core​

A serve host that also reads and writes authoritative entities in process, eg gift card balances and payments, uses Vox core with the same model as the backend, see serve hosts for what that costs. It doesn't migrate the database: the backend does, or vox migrate in the deployment pipeline. It sets RequireAppliedModel, so RunVoxAsync checks at startup that the model in code has been applied and loads it, which every entity read and write needs, and fails the start otherwise. It has no Vox API and no processing, and it keeps the import queues, since it produces work:

var vox = builder.AddVox(options => { /* the same model as the backend */ })
.AddSqlServerStorage(storage => storage.ConfigureEntityFramework = entityFramework =>
// Check that the backend applied the model in code, and load it, instead of migrating
entityFramework.RequireAppliedModel = true)
// Every host registers the sinks of the model's publications, also one that doesn't process them
.AddServePublishing();
builder.Services.AddRedisProjectionStore(options => options.ConnectionString = serveRedisConnection);
// Previews read drafts and releases from the backend's Vox API with the site's API key and grant
builder.Services.AddVoxServe(options => options.ReadDraftsFromVoxApi(new Uri("https://backend.internal/vox")));
// A cross-machine broker, to wake the backend's processing
builder.Services.AddNexus().AddDatabasePollingInstanceEvents();

var app = builder.Build();
// The reads at /serve, and the answers to refused previews, also in the application's own endpoints
app.MapVox();
app.MapGiftCards(); // the application's own endpoints, which check the caller themselves
// Verifies and loads the applied model; it doesn't migrate
await app.RunVoxAsync(args);

A serve host that also registers routing or images, since the sinks of its publications need them, maps its pipeline itself, app.UseVoxServePreview() and app.MapVoxServe(), since MapVox() would also serve their endpoints, see composing a host yourself.

It logs at startup that it only produces Vox work. Its own endpoints read and write authoritative entities in process, eg with IVoxEntityUpdater for a gift card payment. Without the Vox API, nothing checks permissions for them, so each endpoint checks the caller itself, see Security. It deploys with the backend's release, with the same deployment id as the backend's hosts of that release, see deployments. A serve host with Vox core has no Vox API of its own, so its previews read drafts from the backend too, see Preview through Vox Serve.

Read documents​

The endpoints at /serve read by key:

GET /serve/{entityType}/{entityId}/projection
GET /serve/{entityType}/{entityId}/projection/{projection}
GET /serve/{entityType}/projection
GET /serve/{entityType}/projection/{projection}

The first is the entity type's root default projection, and the second a projection by name. The last two are the same for a singleton, eg the shop's settings. The entity type is its name, eg Product, not the route name of the Vox API, products, since a serve host has no Vox API.

They take referenceDepth, the levels of references to assemble, 8 by default and 0 for the document alone. The request's contexts are selected as the application decides, see Context selection, eg here from the Swedish shop's host name and its lang parameter:

GET https://shop.example.se/serve/Product/p1/projection/card?lang=sv
{
"entityType": "Product",
"entityId": "p1",
"projection": "card",
"version": "1",
"key": "vox://entity/Product/p1?projection=card",
"scope": "published",
"selection": { "Market": ["se"], "Language": ["sv"] },
"value": {
"id": "p1",
"name": "Regnjacka",
"price": 999,
"currency": "SEK",
"brand": { "$projection": "vox://entity/Brand/b1?projection=card" }
},
"projections": {
"vox://entity/Brand/b1?projection=card": {
"entityType": "Brand",
"entityId": "b1",
"projection": "card",
"version": "1",
"value": { "id": "b1", "name": "Nordkyst", "path": "/sv/varumarken/nordkyst" }
}
}
}

The response has the same shape as Vox core's direct content delivery: entityType, kind for an entity of a family, entityId, projection, version, key, scope, selection, value, projections by key, aliases for rich-text references without a projection, and diagnostics for references that couldn't be read. So the TypeScript client's getProjectionGraph, resolveProjectionRef and inlineProjectionRefs read it unchanged, and a reference, { "$projection": key }, is the key of its projection in projections. There are two differences:

  • Rich text is always the JSON document form, Vox core's default, see Rich text as JSON. There's no richTextFormat parameter, so HTML isn't available.
  • Only published content. scope is always published, and scope=draft or a release is refused with 400.

A document that isn't served, or doesn't exist in the selection, eg a product that isn't sold in Denmark, answers 404. Before a processing host of the backend has written the catalog and the context manifest to the store, every read answers 503.

Served product cards and pages, category, brand and CMS pages have been compared with Vox core's responses, in several markets, languages and customer groups: their values, referenced projections, aliases and diagnostics were equal.

Context selection​

A serve host is publicly reachable, so the application decides which contexts a request selects and from what. A visitor mustn't be able to select another customer group's negotiated prices by adding ?context=CustomerGroup:b2b to a URL. The selector, IVoxServeRequestSelector, selects in this order, with the context manifest in the store:

  1. The context parameter, only for the context types the application allows. Nothing is allowed by default, and a request with the parameter is refused with 400.
  2. The members the application chooses in code, with its IVoxServeRequestContexts. They replace the parameter's members of the same context type.
  3. Criteria, for the context types neither selects, then the fallbacks of the selected members. Criteria read the host, path, query, headers, cookies, the claims of HttpContext.User as attributes, and the visitor cookie vox-visitor for buckets, see Criteria. They suit experiments and segments, whose members carry their own expressions.

With neither an IVoxServeRequestContexts nor allowed context types, only criteria select.

Choose members in code. A shop that has its market in its host name, its language in its own ?lang= parameter and the customer group in the shopper's login implements IVoxServeRequestContexts:

public class ShopRequestContexts : IVoxServeRequestContexts
{
public ValueTask<VoxServeRequestMembers> GetMembersAsync(HttpContext http, CancellationToken cancellationToken)
{
var members = new Dictionary<string, IReadOnlyList<string>>
{
["Market"] = [http.Request.Host.Host.EndsWith(".no") ? "no" : "se"],
["Language"] = [http.Request.Query["lang"].FirstOrDefault() ?? "sv"],
};
// From the shopper's login, never from the URL
if (http.User.FindFirst("customer_group") is { } group)
{
members["CustomerGroup"] = [group.Value];
}
return ValueTask.FromResult(new VoxServeRequestMembers(members)
{
Caching = VoxServeCaching.Shared("Host", "Authorization"),
});
}
}

builder.Services.AddScoped<IVoxServeRequestContexts, ShopRequestContexts>();

A caller can then only influence what this code reads. Members are keyed by a context type's name or query name, and a concurrent context type, eg experiments, can have several. A context type that isn't in the manifest, or several members of one that isn't concurrent, is a bug in the application, not the caller's: the selector throws InvalidOperationException and the endpoint answers 500. It's resolved from the request's services, so it can be scoped.

Allow the context parameter when the serve host isn't publicly reachable, eg when only a backend-for-frontend server calls it and knows the shopper's market, language and customer group from its own state, or for context types any visitor may choose:

builder.Services.AddVoxServe(options => options.AllowContextParameter("Market", "Language", "CustomerGroup"));
GET /serve/Product/p1/projection/card?context=Market:se,Language:sv,CustomerGroup:member

A name is a context type's name or query name. A context type that isn't allowed is refused with 400, and the message names those that are. Eg a storefront whose Next.js server calls /serve, while visitors don't, works this way.

Cache headers. The response gets Vary on the headers and cookies the criteria read, and Cache-Control: max-age until a criterion of the time, eg a campaign window, can change the selection, as in Vox core. Vox Serve can't see what the application's code reads, so VoxServeRequestMembers.Caching says it:

  • VoxServeCaching.Private, the default, gives the response Cache-Control: private, so no shared cache, eg a CDN, keeps it. It's safe when the members come from a session or anything else the application doesn't name.
  • VoxServeCaching.Shared(params string[] vary) says the members depend only on the URL and the named headers, which are added to Vary, eg Shared() for the path and query, Shared("Host") for the host name or Shared("Cookie") for a market picker's cookie.

Members of the context parameter are in the URL and need nothing. An application that puts HTTP caching in front then caches per variation correctly.

Before the backend has written the context manifest to the store, a request that selects members answers 503.

Batch reads in application endpoints​

An application's own endpoints read many documents at a time, eg the cards of a listing whose IDs came from a search engine, or the SKU facts of a cart. IVoxServeReader.ReadAsync reads them by key in one read of the store, without assembling their references:

app.MapGet("/shop/listing", async (string ids, HttpContext http, IVoxServeRequestSelector selector,
IVoxServeReader reader, CancellationToken cancellationToken) =>
{
var selection = await selector.SelectAsync(http, cancellationToken);
var cards = await reader.ReadAsync(
ids.Split(',').Select(id => new VoxServeDocumentRequest("Product", id, "card")).ToList(),
selection, cancellationToken);
// A card that isn't served, or doesn't exist in the selection, is null
return Results.Ok(cards.Where(card => card != null).Select(card => card!.Value));
});

Each result, a VoxServedValue, has the entity type and ID, the projection, its version, the Kind of a family's entity and the Value as JSON. A VoxServeDocumentRequest with a null projection reads the root default, and its Contexts reads the document in more members on top of the selection, eg {Market=no}. Before the catalog is in the store, every result is null.

ReadGraphAsync is the assembled read that the endpoints use.

SelectAsync throws ArgumentException for a request whose selection isn't valid, which answers 400, and VoxServeUnavailableException before the store has a context manifest, which answers 503.

The reader, the selector and IVoxServeModelReader, which reads the manifest and the catalog, are interfaces with VoxServeReader, VoxServeRequestSelector and VoxServeModelReader as their defaults. An application can register its own before or instead of them, eg to decorate the reader, and test its endpoints with a fake reader.

Request stages​

Some of what a touchpoint shows doesn't exist until a visitor asks for it: the products a recommendation engine picks for this visitor, the live stock of the nearest store, or a B2B shopper's negotiated price from the ERP. A projection can't build them, since it's built in the background when something it reads changes, and Vox doesn't know when the engine's answer changes. A request stage is application code in the serve host that adds them when a document is served.

Split the work in two:

  • The projection holds everything that can be worked out ahead and tracked, eg a block's heading in each language, the category to recommend from and the number of products.
  • The request stage adds only what the request can know, eg the products themselves.

For example, a CMS products block lets an editor choose "recommended" products. Its output carries what the engine needs, and its Products are published empty for a recommended block:

public record ProductsBlockView(string Id, string Name, string? Heading, string? Introduction, ProductBlockLayout Layout,
bool ShowPrice, bool ShowRating, bool ShowAddToCart, IReadOnlyList<VoxProjectionRef<ProductCard>> Products,
ProductRecommendation? Recommendation = null) : BlockView(Id, Name);

public record ProductRecommendation(string? CategoryId, int Count);

The serve host has a stage for the output type, which fills the products with references to their cards. Writing the class is enough: Vox Serve finds it when the host starts, like the application's projections, so nothing is registered in Program.cs. Only the services the stage takes are, eg the engine:

public class ProductRecommendationsStage(IRecommendationEngine engine) : IVoxServeRequestStage<ProductsBlockView>
{
public async Task<IReadOnlyList<ProductsBlockView>> ApplyAsync(IReadOnlyList<ProductsBlockView> blocks,
VoxServeRequestStageContext context, CancellationToken cancellationToken)
{
var recommended = blocks.Where(block => block.Recommendation != null).ToList();
if (recommended.Count == 0)
{
return blocks;
}

var visitor = context.HttpContext?.Request.Cookies[VoxServeRequestSelector.VisitorCookie];
// One call for every recommended block of this level of the page
var answers = await engine.RecommendAsync(recommended.Select(block => block.Recommendation!).ToList(), visitor,
context.Selection, cancellationToken);
return blocks.Select(block => block.Recommendation == null
? block
: block with { Products = answers[recommended.IndexOf(block)].Select(id => context.Reference<ProductCard>(id)).ToList() })
.ToList();
}
}

builder.Services.AddScoped<IRecommendationEngine, RecommendationEngine>();

For a request of the home page, the serve host reads the page, then its blocks in one batched read. Two are products blocks, so the stage runs once for both: the curated one comes back unchanged and the recommended one with four references to product cards. The next level reads those four cards in the same batched read as the curated block's cards, each in the visitor's market, language and customer group. The response has the usual graph shape, and the touchpoint renders both blocks the same way.

Because the stage adds references rather than copying values, the cards' prices are the served ones, and a price change still republishes only the product's card. A recommended product that isn't served in the visitor's market stays a reference with a "wasn't found" diagnostic, as any missing target does, so the block shows three products instead of four.

When to use a stage. Use one only for what depends on the request or changes without Vox knowing. Anything Vox tracks belongs in the projection: a stage runs on every request, and its calls cost every page view. A stage doesn't read Vox core's entity stores either: build what it needs into the projection, or read it from the projection store, eg a recommendation stage reads the category's served page.

How a stage runs:

  • Once per level, with every document of its output type. The reader resolves all documents of a level first, then calls each stage once with its documents, eg once for the 48 product cards of a category page with a live-stock stage. The stages of a level run concurrently, so a stage that shares a scoped service with another must allow that. The root is a level of its own.
  • On the resolved document, in the request's selection, eg with the Swedish heading, as an instance of its output type. It returns a value for each, in the same order.
  • Before references are collected and sizes counted. References a stage adds are assembled like the projection's own, within the request's referenceDepth and the limits on documents and output size.
  • In every read. ReadGraphAsync, which the /serve endpoints use, and ReadAsync both run stages. ReadAsync doesn't assemble, so the references a stage adds stay references.
  • Without changing the stored document. The stage's value is part of this response only.

Which documents. A stage applies to the documents whose output type is its type: a projection's output, or, for an entity family, the output of the document's kind, eg ProductsBlockView for the kind products of the block projection, never the family's shared BlockView. The serve host finds the output types in the projection catalog by their full names, so it must reference the output records. A serve host without Vox core references a project that holds the output records and references only CommerceMind.Vox.Abstractions.

What the stage gets. VoxServeRequestStageContext has the request's Selection and its HttpContext, eg to read the visitor's cookie or claims, which is null when an application reads documents outside a request, eg in a background job. AddVoxServe registers IHttpContextAccessor, so a stage gets the request in the /serve endpoints and in an application's own endpoints alike. Reference<T>(entityId) creates a reference to the served projection whose output is T, with its entity type and name from the catalog, as context.Reference<T> does in a factory. When several served projections have the output, it throws and names them, and Reference<T>(entityType, entityId, projection) chooses one. A read creates one instance of each stage it runs, from the request's services, or from a scope of its own outside a request. It reuses the instance for every level of the read, so a stage can keep its engine's answers in a field across the levels of a page, and disposes it at the end of the read when it's disposable. An application endpoint that calls ReadAsync twice in one request gets two instances. When the application registers the stage class itself, eg as scoped to share one instance between the reads of a request, the read takes that one instead and leaves its disposal to the services.

Only the properties a stage changes are written back. The backend writes served documents with Vox core's serializer, whose options partly depend on the model, eg for dictionaries keyed by entity references, which a serve host without Vox core can't reproduce. So the reader reads a document into the stage's type with VoxServedJson.Options, web defaults with enums by name, references as { "$projection": key } and rich text as its JSON document, compares what it gave the stage with what it got back, and replaces only the top-level properties that differ. Every other property keeps its stored form exactly. Write properties of plain kinds: references, lists, numbers, strings and enums.

Options. A stage that needs other options than the defaults declares them on its class with [VoxServeRequestStage]:

[VoxServeRequestStage(SharedCaching = true, Vary = ["Accept-Language"], TimeoutMilliseconds = 500)]
public class TrendingProductsStage(ITrendingProducts trending) : IVoxServeRequestStage<ProductsBlockView>
PropertyDefault
SharedCachingfalseWhether a shared cache may keep a response the stage ran for, see Caching below
VaryNoneThe request headers a shared stage's result depends on, which are added to the response's Vary
TimeoutMilliseconds2000How long the stage may take before its documents are served as they were stored

Caching. A stage that reads the request makes the response depend on it, which Vox Serve can't see. A stage is private by default, so a personalised result is never kept in a shared cache. A stage whose result depends only on the URL and the named headers sets SharedCaching = true and lists the headers in Vary, eg no headers for trending products per category. Vary without SharedCaching is refused, since a private response varies on nothing.

When a stage runs during a request, the response gets its caching: private wins, and otherwise its headers are added to Vary. Only responses whose documents the stage ran on are affected, so a page without a products block keeps its shared caching. Vox Serve keeps no stage results: the stage or its client caches what it wants to.

When a stage fails, the page still renders:

  • An exception, or the stage's timeout (2 seconds by default), leaves its documents as they were stored, eg the block without products. Each gets a diagnostic in the assembled response, eg { "ref": "vox://entity/ContentBlock/b12?projection=block", "reason": "The request stage ProductRecommendationsStage failed." }. The failure is logged as a warning and counted as vox.serve.request_stage.failures, see Metrics.
  • A document that can't be read as the stage's type, eg because the output type changed in a release that isn't fully published yet, is served as stored with a diagnostic too, and the stage runs on the others.
  • A stage that breaks its contract, by returning another number of values or a null, or changing a value's Id, is a bug in the application's code. The read throws VoxServeRequestStageContractException, and the endpoint answers 500.

A stage whose output type the catalog doesn't have, eg after a projection was removed, is logged as a warning once per catalog revision and never runs.

Request stages run only in Vox Serve. Vox core's direct delivery and route delivery return the stored shape, eg a recommended block without products.

Where Vox Serve finds a stage​

A class that implements IVoxServeRequestStage<T> is a request stage of T on every serve host that has the class where Vox Serve looks. Every serve host looks in the application's own assembly, the one IHostEnvironment.ApplicationName names, so a stage next to Program.cs is always found. A serve host with Vox core also looks where Vox core finds the rest of the application's code: the libraries of VoxOptions.EntityAssemblies and the classes of VoxOptions.Types. Abstract and open generic classes are skipped, and a class that implements the interface for two output types is two stages.

So when a model lives in a library, eg Shop.Model added with options.EntityAssemblies.Add(typeof(Product).Assembly), a stage next to its projections is found on a serve host with Vox core without being listed again. A serve host without Vox core doesn't scan libraries: to use a stage from a shared library, it declares a one-line subclass in its own project, which passes on the services the stage takes:

public class LiveStockStage(IStockClient stock) : Shop.Stages.LiveStockStage(stock);

The subclass inherits the base class's [VoxServeRequestStage] options. Don't add such a subclass to a host that also scans the library, eg a host with Vox core that has it in EntityAssemblies: it would find two stages of the same output type.

Mistakes fail the start. When a web host with Vox Serve starts, it finds its stages and refuses, in one message that names every class:

  • a stage of an abstract output type, eg IVoxServeRequestStage<BlockView> instead of the output of a kind, eg ProductsBlockView;
  • two stages of the same output type, eg "LiveStockStage and StockBadgeStage are both request stages of ProductCardView": an application that needs two steps does both in one stage;
  • invalid options: a timeout that isn't positive, or Vary headers without SharedCaching.

A host without a web pipeline, eg a worker that only calls IVoxServeReader.ReadAsync, gets the error on its first read instead.

References between documents​

A served document never contains another projection's value. A CMS page references its blocks, and a products block references four product cards, each a projection reference or an entity embedded in rich text, and each a document of its own in the store, see References to other projections. Vox Serve assembles them when the page is read, not when it's published:

  1. It reads the root document and resolves it in the request's selection.
  2. It collects the root's references and reads all of them in one batched read of the store, eg the page's 6 blocks. Then it reads what they reference in the next, eg their 30 product cards. Each document is resolved in the selection, and a reference narrowed to contexts, eg context=Market:no in its key, in the selection with those members.
  3. It stops at the requested depth, when a level references nothing new, or at a limit. Each document is read once however often it's referenced, so cycles stay finite.

A reference whose target isn't there stays a reference and gets a diagnostic, eg The referenced Product 'p9' wasn't found. A rich-text reference without a projection resolves to the entity type's reference default from the catalog, and aliases maps its key to the projection's key.

That keeps republishing cheap. A reference depends only on whether its target exists, so when a campaign recalculates 50,000 prices, Vox republishes those products' cards and nothing else, not every page, block and listing that shows one of them.

What assembly costs.

  • A batched read per level. A page three levels deep takes four reads of the store, a few milliseconds with Redis. A deeper page, or a store with slow lookups, costs more; the depth and count limits bound it. An endpoint that never needs deep pages, eg a mega menu, can read with a lower referenceDepth, or read the root alone with referenceDepth=0 and fetch the documents it needs by key as it shows them.
  • Caching an assembled response. An assembled page changes whenever any document in it changes. A CDN can purge it precisely only if the response is tagged with every document it read, eg a surrogate key per document key, so a purge of one product card reaches every cached page that shows it. A response of the root alone has one key.
  • Mixed versions. Documents reach the store one at a time, so an assembled page can briefly combine a new page with an old block, see Freshness, releases and rebuilds.

Embedding a level​

Sometimes a page should carry a level inside its own document, eg its blocks' headings and images, when blocks are never shared and one read matters more than reuse. The page's factory then builds that representation itself: it reads the block entities through its context and maps the fields it needs into its own types.

public record LandingPage(string Title, IReadOnlyList<LandingSection> Sections) : IVoxServedProjection;
public record LandingSection(string? Heading, string? Text);

public async Task<LandingPage?> ProjectAsync(Landing landing, IVoxEntityProjectionContext context,
CancellationToken cancellationToken)
{
var sections = new List<LandingSection>();
foreach (var reference in landing.Sections)
{
// Read through the context, so changing a section republishes the page
if (await context.GetAsync<Section>(reference.Id, cancellationToken) is { } section)
{
sections.Add(new LandingSection(section.Heading, section.Text));
}
}
return new LandingPage(landing.Title, sections);
}

A factory can't include another projection's output, eg the value of the ProductCard factory: Vox Serve has no embedding mode. What an embedding factory reads is a dependency of the page, so the page is republished whenever anything it embeds changes. For a few hundred CMS pages with their own sections that's fine. For listings of products whose prices change often it isn't: a price change would republish every listing that embeds the product. Reference the product card instead.

Rich text as JSON​

Served documents hold rich text in its JSON document form, as Vox stores it, and the response has it the same way:

{
"version": 1,
"type": "document",
"children": [
{ "type": "paragraph", "children": [{ "type": "text", "text": "Our favourite rain jacket:" }] },
{
"type": "entity-reference",
"ref": "vox://entity/Product/p1",
"entityType": "Product",
"entityId": "p1",
"key": "vox://entity/Product/p1?projection=card"
}
]
}

A touchpoint renders the document its own way, eg an embedded product as its card component. An embedded entity is a node of the document, which the assembler resolves like any other reference, with the entity type's reference default when it names no projection. Its key is the key of the projection it resolves to in projections, as in Vox core's responses, eg vox://entity/Product/p1?projection=card when card is the reference default. It's added when the document is read, from the catalog, so it follows the reference default the store was last published with. A touchpoint that moves from Vox core to Vox Serve reads rich text the same way, see Rich text and entity references.

The projection store​

The store abstractions are in CommerceMind.Vox.Serve:

  • IVoxProjectionStore reads. ReadSourcesAsync reads the documents of many sources at once, eg the cards of a listing, by projection key and source ID, eg Product/card and p1, and an implementation should read them in one round trip. ReadManifestAsync and ReadCatalogAsync read the context manifest and the catalog.
  • IVoxProjectionStoreWriter writes. ApplyAsync applies upserts and deletes of documents, each visible once it's applied, and WriteManifestAsync and WriteCatalogAsync write the manifest and the catalog. Replaying a write must change nothing.

Each published document is a VoxServedDocument: its ID, eg p1?Market=no, its key, whether the source exists there, its kind, its version, the manifest revision it was built with, its value as JSON and its keyed cells. All the documents of a source and projection are kept as one record, so a read gets them together and resolves the selection's document from them.

Vox ships three stores:

  • Redis, AddRedisProjectionStore, in CommerceMind.Vox.Serve.Redis, for high traffic. Each source and projection is a hash, eg vox:serve:doc:Product/card:p1, with a field per document ID, eg p1 and p1?Market=no, so a write sets or deletes fields without reading first. The manifest is at vox:serve:manifest and the catalog at vox:serve:catalog. Reads of many sources are pipelined in one round trip. Options: ConnectionString, or ConnectionFactory to share a connection, Database, and KeyPrefix, vox:serve by default.

  • SQL, AddEntityFrameworkProjectionStore, in CommerceMind.Vox.Serve.EntityFramework, for local development and smaller sites that don't expect a lot of load, on SQLite, SQL Server or PostgreSQL. Each document is a row of VoxServeDocuments, keyed by projection, source ID and document ID, and the manifest and the catalog are rows of VoxServeStoreValues. Every read is by key: a level of a page is one statement that seeks the primary key once per source, also when it covers several publications, so the store scales further than its purpose needs. The tables are created on first use, also in a database that has other tables, eg Vox's own. Two applications use two databases. Option: ConfigureDbContext, which picks the provider and connection:

    using CommerceMind.Vox.Serve.EntityFramework.Extensions;

    builder.Services.AddEntityFrameworkProjectionStore(options => options.ConfigureDbContext = (_, dbContext) =>
    dbContext.UseSqlServer(builder.Configuration.GetConnectionString("serve")));

    Keys are case-sensitive, as in Redis: a read returns the documents whose keys match exactly. On a database whose collation ignores case, eg SQL Server's default, two keys that differ only in case, eg sources p1 and P1, can't both be stored, and writing the second fails that publication's serve sink until the first is gone; use a case-sensitive collation for the store's database if your IDs can differ only in case. On SQL Server a document's projection key, source ID and document ID must stay under 450 characters together, the limit of a clustered key. Several processes can share a SQLite file, eg a backend and a serve host on one machine. A file the store creates is in WAL mode, as Entity Framework Core creates SQLite databases, so reads go on during a write; an existing file keeps its journal mode.

  • In memory, AddInMemoryVoxProjectionStore, for tests. Each process has its own, and it's empty after a restart.

An application implements both interfaces for any other store and registers them in place of these.

A store that loses its data. Vox keeps what the serve sink published, not whether the store still has it, and doesn't fill a store again, see What fills the store. A Redis without persistence that restarts has no documents, manifest or catalog, and its reads answer 503. Run Redis with persistence, and after losing the store's data, re-run the full Nexus jobs of the served publications and restart a processing host of the backend.

The projection catalog​

A serve host without Vox core needs part of the model to read documents. The catalog, VoxProjectionCatalog, has each served projection's key, entity type, name and version, its properties that reference other projections, the context types its publication publishes per combination and as keyed cells, its factories with the kinds of a family they project, the full names of its output type and of each factory's output, which request stages are matched by, and whether it's the entity type's root default or reference default. The defaults are the effective ones, with Vox's fallbacks, eg an entity type's only projection is both, see Defaults and explicit selection.

The catalog comes from the model in code, so the catalog writer writes it when a processing host of the backend starts, and tries again every 30 seconds while the write fails. A host that only produces Vox work, eg a serve host that uses Vox core in process, never writes it. During a rolling deployment, processing hosts of the old and the new release can start at the same time, and the catalog is the one written last by a starting processing host, until every processing host of the new release has started. A new region starts from the store alone.

Freshness, releases and rebuilds​

Every request reads the store. Vox Serve keeps no documents in memory, so two reads after a republish return the new document. The store is as fresh as the publication behind it: a saved price reaches it once the calculations and the publication have run, as fast as Vox runs them.

No guarantee that a release arrives together. A content release is published atomically in Vox core, but its documents reach the store as each publication processes them, as close together as Vox can, with no further guarantee. When a release goes live at 08:00, a read can briefly assemble the new campaign page with an old block, or a new product card next to an old one.

A full build keeps serving. The serve sink applies each page of documents to the store as it receives it. A full build doesn't empty the store: each document is replaced when the build reaches it, the old ones are served until then, and once the build completes, Vox deletes what the build no longer produced, see Failures and replay. Replaying a page writes the same documents again.

Timelines are served as they are. A projection that publishes a timeline, eg "999 kr from Friday", is served with the timeline, and the touchpoint picks the value by time.

Caching​

Vox Serve caches no documents. It keeps the context manifest and the catalog in memory for ModelRefreshInterval, 5 seconds by default, since every request needs them and they change rarely: a new market can take that much longer to be selectable on a serve host.

An application that wants HTTP caching, a CDN or an in-memory cache adds it on top, eg with output caching on the route group that MapVoxServe returns, and owns its staleness. The responses' Vary and Cache-Control headers say what a cached response varies on, and what assembly costs says what an assembled response depends on. A request stage makes the responses it runs for private, unless it says what its result varies on.

Preview through Vox Serve​

A touchpoint that reads its published pages from Vox Serve reads its previews from Vox Serve too, with the same requests. In a preview, its server adds the editor's grant and its own API key, as a site that reads Vox core does for every request:

const grant = readVoxPreview(request);
const page = await fetch(`${VOX_SERVE_URL}/serve/ContentPage/home/projection`, {
headers: grant ? { Authorization: `ApiKey ${apiKey}`, ...voxPreviewHeaders(grant) } : {},
});

A published read needs no API key. An application without Vox Serve previews through Vox core's direct and route delivery, see Preview your site. A touchpoint can mix them, but use one path per touchpoint: request stages only run in Vox Serve, so a touchpoint that uses them previews through Vox Serve to see their results.

Every read of the request is a preview. The reader sees the Vox-Preview header of the current request, so the /serve endpoints' reads, an application's own endpoints that call ReadAsync, and the reads that request stages make, eg a recommendation engine that reads a category's page, all read the draft or release. A read outside a request is never a preview.

Vox core reads the drafts. In a preview the reader reads each level of the graph from Vox core instead of the projection store, with the members the serve host selected as usual, the grant and the caller's Authorization. Vox core authenticates the caller, checks the grant, adds its scope and restricted members, and evaluates the documents. The request stages then run on the draft documents, and the assembly continues as for published reads. The response has the usual shape, with the scope and selection that Vox core read in, eg draft and a staff-only experiment variant of the grant.

Register a draft reader on every serve host that previews:

// Vox core runs in another application, the backend: the serve host passes the request's API key and grant on to
// its Vox API's batch read, POST /vox/api/entity-projections/read. It has no API key of its own.
builder.Services.AddVoxServe(options => options.ReadDraftsFromVoxApi(new Uri("https://backend.internal/vox")));

// Vox core runs in the same application, eg one application for a small site: the drafts are read in process, from
// CommerceMind.Vox.Serve.Api
builder.AddVox(options => { /* model */ }).AddApi().AddServeDrafts();

ReadDraftsFromVoxApi waits DraftReadTimeout, 10 seconds by default, for the backend.

What goes wrong is answered as Vox core answers it. /serve answers a refused preview with its status, and so do an application's own endpoints that read Vox Serve, through the middleware that MapVox() adds on a host with a draft reader, or app.UseVoxServePreview() on a host that maps its pipeline itself:

SituationAnswer
The grant expired or isn't valid401 with WWW-Authenticate: VoxPreview error="expired" or "invalid", so the web SDK's isVoxPreviewExpired and the admin's renewal work
Vox core doesn't accept the API key, or its client may not preview, eg without vox:Preview:DraftsVox core's 401 or 403 with its message
A grant without an Authorization header403: a grant alone authenticates nothing, so a grant that leaks reads nothing at a public serve host
A serve host without a draft reader400, with how to register one
Vox core doesn't answer within the timeout, or fails503

The scope parameter stays refused: a preview is only selected by a grant.

A preview response is Cache-Control: private, no-store, whatever the selection or stages say.

What a preview costs. Each level of a graph is one call to Vox core, which evaluates the level's documents together in batches per projection, so a page three levels deep is four calls. A level of more than 200 documents is read in several calls. That's fine for editors' traffic, and customers' published reads never reach Vox core.

Security​

The projection store holds what the served projections output, nothing else, and Vox Serve's endpoints serve what they read, to anyone who reaches them. Vox doesn't add a permission model to the store. So:

  • The application decides what a caller can select. A context type that isn't selected by the application's code, criteria or an allowed context parameter can't be chosen by a caller, see Context selection. Allowing the parameter lets anyone who reaches the endpoints choose those context types.
  • A served projection contains only what the application may serve to everyone who can reach the endpoints. A [VoxSensitive] value fails startup, see Serve a projection, but nothing is inferred: a purchase price copied into an unmarked property is served.
  • Restricted content is the application's to structure and protect, eg a staff view with purchase prices or per-customer documents. Publish it as a projection that isn't served to a store of the application's own, and put an endpoint in front that checks the caller. Or map the endpoints with app.MapVoxServe() and add authorization to the route group it returns, where every served document needs the same check.
  • Authoritative writes check the caller themselves. A serve host that writes through Vox core in process, eg a gift card payment, has no Vox API to check permissions. Its endpoint decides who may do what, eg it finds a gift card by its number, which a shopper proves they hold, not by its ID, and only in the card's market.

Metrics​

A serve host that also uses Vox core should read catalog data from the store, and only authoritative data, eg a gift card balance, from the entity stores. Vox Serve makes the difference visible on a host with Vox core, without a call: it records how many entities each request read from Vox core's entity stores, as the histogram vox.serve.request.entity_store_reads of the meter CommerceMind.Vox.Serve, tagged with the request's http.route, and as the tag vox.entity_store.reads of the request's activity. Vox core also counts every entity read from its stores as vox.reads.entity_store.entities of the meter CommerceMind.Vox.Reads.

On a typical serve host, a served page request reads 0 entities and a gift card request 1. A route whose reads aren't 0, but should be, reads catalog data from the entity stores. Watch them with dotnet-counters or an OpenTelemetry exporter:

dotnet-counters monitor -n MyShop.Serve --counters CommerceMind.Vox.Serve,CommerceMind.Vox.Reads

The same meter counts the failures of request stages as vox.serve.request_stage.failures, tagged with the output type the stage runs on as vox.serve.output_type: each time a stage threw, timed out or couldn't read a document, and documents were served as they were stored.