@alxia/tenancy

中文文档
0.6.0发布于 2026/11/06MITTypeScriptES Module零依赖近 30 天下载 1908

Tenancy for an application on @softistx/mongo: one contract, two stores (a database per organisation next to a core database, or a single database), a request scope resolved from a header, provisioning and a loop over every tenant

原始使用文档
文档目录12 节
  1. In 30 seconds
  2. A request's scope
  3. A module's handles
  4. The header, id or slug
  5. Every tenant, for a job
  6. Provision, sync, migrate
  7. One database
  8. Test databases
  9. API
  10. Refusal codes
  11. Documentation
  12. License

@alxia/tenancy

Tenancy for an application on @softistx/mongo: one contract, TenantStore, and two strategies behind it. perOrganization keeps a core database (accounts, the organisation registry, cross-organisation data) and one database per organisation; single keeps one database and one fixed tenant. A request names its organisation in a header, and the scope it gets is that organisation's database, so a resolver never builds a database name and a query cannot reach another organisation's data.

bun add @alxia/tenancy @alxia/modules @softistx/mongo mongodb
bun add -d typescript

@softistx/mongo is private, on GitHub Packages. Map the scope in your project's bunfig.toml and export GITHUB_TOKEN, a token with read:packages:

[install.scopes]
"@softistx" = { url = "https://npm.pkg.github.com/", token = "$GITHUB_TOKEN" }

In 30 seconds

import { connectMongo, defineMongo, openMongo } from '@softistx/mongo';
import { perOrganization } from '@alxia/tenancy';

const { client } = await connectMongo(process.env.MONGO_URI!);

// The host's core database: the registry of organisations, accounts...
const core = await openMongo(
    defineMongo({ client, database: 'app_core', collections: coreCollections }),
);

export const tenancy = perOrganization({
    core,
    registry, // the port over your `organizations` collection, see the guide
    database: 'app_org_', // databases are named `app_org_<id>`
    configure: (database) =>
        defineMongo({ client, database, collections: tenantCollections }),
    membership: async (organizationId, accountId) =>
        (await roleOf(organizationId, accountId)) ?? null, // null: not a member
});

Already have a cache from createTenantDatabases (shared with jobs and tests)? Pass databases instead of database and configure: the store reuses it and never closes it, the host does.

import { createTenantDatabases, perOrganization } from '@alxia/tenancy';

const databases = createTenantDatabases({ database: 'app_org_', configure });

perOrganization({ core, registry, databases, membership });

A request's scope

const scope = await tenancy.scope(request, viewer); // viewer: { id } or null

scope.tenant; // the organisation record
scope.mongo; // ITS database, writes stamped with the viewer
scope.core; // the host's core database
scope.member; // what `membership` answered, a role for instance

It throws a TenancyError with a code, a status and params to map to your own errors: tenancy.errors.organization-required (400, header missing), tenancy.errors.unknown-organization (404, for an unknown, not-active or not-member organisation alike, so a caller learns nothing about which exist).

Resolve the scope once per request, only when something asks:

import { lazyScope } from '@alxia/tenancy';

const getScope = lazyScope(tenancy, request, viewer);
const { mongo } = await getScope(); // the same promise every time

A module's handles

@alxia/modules is a required peer. The modules option is optional: without it, forModule throws module "x" is not registered.

Give the store your registry and plugin code touches only the handles of its module, typed through Register; it never names a database:

import { resolveModules } from '@alxia/modules';

const modules = resolveModules(registered);
const tenancy = perOrganization({ /* … */ modules });

const scope = await tenancy.scope(request, viewer);
const { mongo, core } = tenancy.forModule(scope, 'notes');
mongo.db.notes; // the module's tenant collections and its `dependsOn` ones
core.db.accounts; // its `coreCollections`, on the core database

collections land in the tenant's database, coreCollections in the core one; on the single store both are the same database. forModule also takes { mongo, core: tenancy.core } for the tenant eachTenant hands you. It throws a ModuleWiringError for a module the registry lacks, or a collection your defineMongo wiring does not hold (wire it with collectionsOf(modules) and coreCollectionsOf(modules)). Provision, sync and migrate take the migrations from the registry (migrationsOf, coreMigrationsOf), before those of migrations and coreMigrations.

The header, id or slug

The header is x-organization-id by default and names the organisation by id or by slug, in any case. Change it with header:

perOrganization({ /* … */ header: 'x-tenant-id' });

The default is exported as DEFAULT_HEADER. Only an active organisation resolves. Outside a request, tenancy.resolve(ref) does the same lookup.

Every tenant, for a job

await tenancy.eachTenant(async (tenant, mongo) => {
    await mongo.db.outbox.deleteMany({ sentAt: { $lt: cutoff } });
}); // the active organisations, one after the other

await tenancy.eachTenant(visit, { withDeleted: true }); // every registered one

// keep going when a tenant fails (database unreachable, `fn` throws)
const results = await tenancy.eachTenant(visit, { onError: 'collect' });
const failed = results.filter((r) => !r.ok); // { tenant, ok: false, error }
// the others are { tenant, ok: true, value }

By default the first failure rejects and the later tenants are not visited.

Provision, sync, migrate

const tenant = await tenancy.provision({ slug: 'north', name: 'North' }, actorId);
// registered as `provisioning`, database synced and migrated, then `active`

// throws a TenancyError `tenancy.errors.slug-taken` (409) when the slug is taken

// a failed `provision` leaves the tenant `provisioning`: fix the cause, then
await tenancy.prepare(tenant.id);
await tenancy.activate(tenant.id, actorId); // `perOrganization`; active tenants are returned as is

await tenancy.sync(); // `db:sync`: the core, then every organisation
await tenancy.migrate({ kind: 'apply', dryRun: false }); // `db:migrate`
await tenancy.migrate({ kind: 'rollback', to: '2026-10-27-marker', dryRun: true });

One database

For a host that serves one organisation, the same contract with no header and no membership check:

import { single } from '@alxia/tenancy';

export const tenancy = single({
    mongo, // the one database
    tenant: { id: 'main', slug: 'main', name: 'Main' },
    migrations,
});

Code written against TenantStore runs on both stores unchanged.

Test databases

slotNaming names databases <prefix>_slot1, <prefix>_slot2… so a suite creates a bounded number of them, however many organisations it provisions:

import { slotNaming } from '@alxia/tenancy';

const database = slotNaming('app_test', 4);
perOrganization({ /* … */ database });
database.reset(); // between tests

API

ExportWhat it does
perOrganization(options), PerOrganizationOptions, PerOrganizationStorethe core database plus one database per organisation
single(options), SingleOptions, SingleStoreone database, one fixed tenant
TenantStorethe contract both answer: resolve, tenantOf, databaseOf, scope, forModule, eachTenant, provision, prepare, sync, migrate, close
lazyScope(store, request, viewer)a request's scope, resolved once, on first use
viewerMemberships(membership, viewer), ViewerMembershipsthe viewer's membership in any tenant, read once per request
slotNaming(prefix, slots), SlotNaming, DatabaseNaming<prefix>_slot<n> database names for tests, and the type of a database option (a prefix or a function from the tenant id)
createTenantDatabases(options), TenantDatabases, TenantDatabasesOptions, isTenantId, dbOfthe bounded cache of tenant Mongos, the check on ids that reach a database name, the driver's Db under a Mongo
ModuleScope, ModuleSourcewhat forModule returns (mongo, core) and takes: a scope, or { mongo, core: store.core } for the tenant eachTenant visits
TenancyError, TenancyErrorCode, UnknownMigrationError, ModuleWiringErrorthe refusals (tenancy.errors.*, see below) and the two boot errors, with the codes tenancy.unknown-migration and tenancy.module-wiring
organizationRequired(header), unknownOrganization(), slugTaken(slug)the TenancyErrors the stores throw, for a host's own store or spec to throw the same ones
DEFAULT_HEADER'x-organization-id', the header when header is not given
membershipOf(source)a Membership for a spec, from a plain function (sync or async) or a { [tenantId]: answer } map; undefined reads as not a member; with a map, every account is a member of a listed tenant; use a function to tell accounts apart
noMembersa Membership that admits nobody, for a spec or a locked-down host
Tenant, TenantStatus, TenantRegistry, TenantResult, EachTenant, Membership, TenantScope, Viewer, Resolution, EachTenantOptions, MigrationLists, MigrateMode, MigrationOutcomethe types (Viewer is { id }; @alxia/access has its own of the same shape)

Refusal codes

A request that cannot be served gets a TenancyError whose code is tenancy.errors.organization-required (400), tenancy.errors.unknown-organization (404) or tenancy.errors.slug-taken (409). These codes keep their tenancy.errors. namespace on purpose: they are the keys an existing host's i18n catalogue already translates, and they match the x-organization-id header and the perOrganization name the host already speaks. Renaming them would break every translation for no gain. The boot errors (tenancy.module-wiring, tenancy.unknown-migration) are a different kind: a developer's, never shown to a user, so they use the kernel's boot shape (tenancy.<reason> and a message).

Peers: @alxia/modules, @softistx/mongo, mongodb, typescript.

Documentation

  • Guide: the registry port, a request's scope, jobs, provisioning, migrations, the single store, testing.
  • Troubleshooting: an error message, and what to do about it.
  • Roadmap: what is coming, and what is not planned.

License

MIT

版本与发布记录

@alxia/tenancy 共发布 11 个版本,首次发布于 2026/11/01;过去 12 个月发布了 11 个版本。

版本发布日期距今
0.6.0latest2026/11/062 天前
0.5.02026/11/017 天前
0.4.02026/11/017 天前
0.3.02026/11/017 天前
0.2.12026/11/017 天前
0.2.02026/11/017 天前

关于 @alxia/tenancy 的常见问题

@alxia/tenancy 是什么?

Tenancy for an application on @softistx/mongo: one contract, two stores (a database per organisation next to a core database, or a single database), a request scope resolved from a header, provisioning and a loop over every tenant

如何安装 @alxia/tenancy?

在项目目录运行 npm install @alxia/tenancy,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:mongodb(^7.7.0)、typescript(^6.0.3 || ^7.0.0)、@alxia/modules(^0.4.0)、@softistx/mongo(^0.27.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@alxia/tenancy 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@alxia/tenancy 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@alxia/tenancy 可以商用吗?

@alxia/tenancy 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@alxia/tenancy 的下载量有多少?

根据 npm 官方下载统计,@alxia/tenancy 在 2026/10/06 – 2026/11/04 这 30 天内被下载 1,908 次,日均约 64 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@alxia/tenancy 还在维护吗?

最新版本 0.6.0 发布于 2026/11/06(2 天前);至今共发布 11 个版本,其中过去 12 个月发布了 11 个;首次发布于 2026/11/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。