Skip to content

Background tenancy ​

Work that runs outside a request has no session to read a tenant from. The framework gives it one of three contexts, never an inherited one. The tests that fix this are BackgroundTenancyPostgresTests and FailClosedProfilesPostgresTests (acceptance criteria CA-10 to CA-12 of ADR 0012).

Capture and restore ​

FlowWhere the tenant is capturedContext while it runs
JobThe scheduling envelope, written when the job is enqueuedThat tenant, or none when it was enqueued without one
Outbox consumer, tenant messageThe message's ownerThat tenant, with optional-tenant rows limited to it
Outbox consumer, platform messageThe message scopeThe platform frame: no tenant, global rows only
System serviceIts declared identityThe platform frame plus the identity

The executor of each flow begins the context through ITenantAmbient.Begin and disposes the handle when the flow ends, also when it throws. The execution that follows therefore starts from the context it would have had alone: an A job then a B job then a job with no tenant see A, B and nothing. The code that calls OutboxProcessor.ProcessOneAsync keeps its own context too.

No tenant means no rows ​

With no tenant in session a query on a tenant-required entity returns zero rows, and an optional-tenant entity returns only its global rows. This is the default of every host profile (web, worker, the templates) and is not an option. A routine that needs another tenant's data names it:

  • run the work as that tenant (a job is enqueued from a session of the tenant; a message names its owner), or
  • sweep explicitly with ITenantAmbient.BeginSystemScope(reason), which is audited and forbidden in request code.

An outbox envelope of scope Tenant with an empty tenant is refused when it is staged. The framework never infers a tenant from the data, from a header or from the process.

System services ​

A routine that serves no tenant, such as a catalog refresh, writes data the platform owns. It implements ISystemService, declares which entities it may write, and runs through ISystemServiceExecutor:

csharp
public sealed class ExchangeRateRefresh(CatalogDbContext db, IRateSource source) : ISystemService
{
    public static SystemServiceIdentity Identity { get; } =
        SystemServiceIdentity.Declare("exchange-rate-refresh", typeof(ExchangeRate));

    public async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        db.ExchangeRates.AddRange(await source.FetchAsync(cancellationToken));
        await db.SaveChangesAsync(cancellationToken);
    }
}

// composition
services.AddSystemService<ExchangeRateRefresh>();

// the hosted service or the scheduled job
await executor.RunAsync<ExchangeRateRefresh>(cancellationToken);

Declare refuses an empty or padded name, an empty or repeated list and any entity that implements IRequireTenant. An IOptionalTenant entity is accepted, and the write guard still refuses a row of it that carries a tenant. AddSystemService validates the identity at composition and refuses a second service with the same name, so an invalid declaration stops the host from starting.

The executor opens a DI scope, begins the platform frame with the identity, runs the service and restores the caller's context. The host never opens the frame itself. While it runs the write guard refuses any added, modified or deleted entity that is not in the declared list, whether or not it carries a tenant marker, with a message naming the service and the entity. The single exception is OutboxMessage, so a service can publish through the platform outbox.

Add a test that fails when a module declares an invalid identity:

csharp
SystemServiceCatalogInspector.FindViolations(typeof(ModuleMarker).Assembly).Should().BeEmpty();

The user who caused the work is data ​

A job envelope and an outbox message may carry the user that caused them (UserId, CausedBy). That is attribution: it is recorded and shown, and it is never an identity, a permission or an authentication. A job or a consumer must not authorize an act from it.

Host role: producer and executor ​

A deployment may split the process that enqueues work from the process that runs it. The host says which it is:

csharp
builder.Services.SetGrydHostRole(GrydHostRole.Producer); // All (default), Producer or Executor
RoleBackground loops and job serverEnqueue and schedule
All (no call)runyes
Executorrunyes
Producerneither created nor startedyes

A loop is registered with AddGrydBackgroundLoop<T>() (or the overload that takes a factory), never with AddHostedService. The decorator RoleGatedHostedService<T> builds and starts the loop only when the role is not Producer. For a library that registers its own hosted services, wrap the registration with GateHostedServicesAddedBy(services => ...); GrydJobs does so around AddHangfireServer, so a producer enqueues and schedules through Hangfire's client with no BackgroundJobServer. Calling SetGrydHostRole twice with different roles throws.

The loops that obey it: audit retention, the job dead-letter cleanup and lifecycle reconciliation, the notification processors and cleanup, the GeoIP updater and the outbox worker. A hosted service that runs once at startup (validators, the Redis warm-up, RecurringJobRegistrationService) is not a loop and is not gated; an architecture test (BackgroundLoopHelperArchitectureTests) lists them with the reason and fails for any other AddHostedService. The proofs are GrydHostRoleJobsTests (real Hangfire on PostgreSQL) and GrydHostRoleTests.

Listing active tenants ​

A module that acts on every tenant (a per-tenant job) asks IActiveTenantDirectory (Gryd.Application.Abstractions.Tenancy) which tenants exist. The port belongs to the core; GrydAuth implements it.

csharp
using var system = ambient.BeginSystemScope("list tenants for the nightly job");
Guid? after = null;
while (true)
{
    var page = await directory.ReadAsync(after, IActiveTenantDirectory.MaxLimit, cancellationToken);
    // ... use page ...
    if (page.Count < IActiveTenantDirectory.MaxLimit)
        break;
    after = page[^1].TenantId;
}
  • It lists active, non-deleted tenants of every type (ActiveTenant(TenantId, Type)), ascending by id, in keyset pages. limit must be from 1 to 500; anything else throws ArgumentOutOfRangeException.
  • It lists the platform, so it runs only inside ITenantAmbient.BeginSystemScope (audited, ADR 0011 D21). With any other ambient (empty, platform execution or a tenant) it throws InvalidOperationException before querying.
  • It reads committed data. A tenant created while paging may be missed until the next call, because ids are not ordered by creation.

Released under the MIT License.