Class TenantContext

java.lang.Object
com.tnsai.context.TenantContext

public final class TenantContext extends Object
Thread-local tenant scope for tenant-aware runtime components.

Agent entry points establish this scope from AgentBuilder.tenantId(...). Implementations of TenantAware can read the current tenant without changing their base SPI contract. Scopes are nested: closing an inner scope restores the previous tenant, and closing the outermost scope clears the thread-local value.


 try (var ignored = TenantContext.enter("acme")) {
     String tenantId = TenantContext.requireTenantId();
     // tenant-scoped work
 }
 
Since:
0.13.0 (TAN-3232)
  • Method Details

    • currentTenantId

      public static Optional<String> currentTenantId()
      Returns the tenant currently bound to this thread.
      Returns:
      the current tenant, or empty outside a tenant scope
    • requireTenantId

      public static String requireTenantId()
      Returns the tenant currently bound to this thread and fails closed when a tenant-aware component is invoked without an active scope.
      Returns:
      the current tenant id
      Throws:
      IllegalStateException - when no tenant scope is active
    • enter

      public static TenantContext.Scope enter(String tenantId)
      Binds a tenant for the lifetime of the returned scope.

      A null or blank tenant creates an explicitly unscoped region. Closing the scope always restores the previous value. Nested agent turns may intentionally inherit the tenant in their enclosing AgentContext; this method only applies the value it is given.

      Parameters:
      tenantId - tenant to bind, or null/blank for no tenant
      Returns:
      a scope that restores the previous tenant on close