-
Notifications
You must be signed in to change notification settings - Fork 4
feat(multi-tenant): Phase 2 - Turso Platform API integration and schema initialization #1171
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
82a7dbb
feat(multi-tenant): implement minimal prototype with UUID-based archi…
Claude 45dc94b
feat(multi-tenant): complete Phase 2 - Turso Platform API integration…
Claude 2ee82c4
chore: update pnpm-lock.yaml to fix frozen lockfile error
Claude a48e68e
fix: resolve service-tenant build errors and update lockfile
Claude 9dbe1be
chore: successful build and test pass for all packages
Claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,232 @@ | ||
| # @objectstack/service-tenant | ||
|
|
||
| Multi-tenant context management and routing service for ObjectStack. | ||
|
|
||
| ## Overview | ||
|
|
||
| This service provides comprehensive multi-tenant infrastructure for ObjectStack deployments, including: | ||
|
|
||
| - Tenant identification and context resolution | ||
| - Turso Platform API integration for automated database provisioning | ||
| - Tenant database schema initialization | ||
| - Global control plane management | ||
| - Package installation per tenant | ||
|
|
||
| ## Features | ||
|
|
||
| ### Phase 1 (Complete) | ||
| - **Multiple Identification Sources**: Subdomain, custom domain, HTTP headers, JWT claims, session | ||
| - **UUID-Based Tenant Naming**: Immutable tenant identifiers (not organization slugs) | ||
| - **Tenant Context Caching**: Performance optimization for frequently accessed tenants | ||
| - **Flexible Configuration**: Priority-based identification source ordering | ||
|
|
||
| ### Phase 2 (Complete) | ||
| - **Turso Platform API Integration**: Automated database creation via Turso Platform API | ||
| - **Tenant-Specific Auth Tokens**: Secure, database-specific authentication | ||
| - **Global Control Plane**: System objects for tenant registry and package installations | ||
| - **Schema Initialization**: Automated tenant database schema setup | ||
| - **Package Management**: Per-tenant package installation and schema migration | ||
|
|
||
| ## Installation | ||
|
|
||
| ```bash | ||
| pnpm add @objectstack/service-tenant | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| ### Basic Setup (Tenant Routing) | ||
|
|
||
| ```typescript | ||
| import { createTenantPlugin } from '@objectstack/service-tenant'; | ||
| import { ObjectKernel } from '@objectstack/core'; | ||
|
|
||
| const kernel = new ObjectKernel(); | ||
|
|
||
| // Create tenant plugin with routing configuration | ||
| const tenantPlugin = createTenantPlugin({ | ||
| routing: { | ||
| enabled: true, | ||
| identificationSources: ['header', 'custom_domain', 'jwt_claim'], | ||
| tenantHeaderName: 'X-Tenant-ID', | ||
| customDomainMapping: { | ||
| 'app.acme.com': '550e8400-e29b-41d4-a716-446655440000', | ||
| }, | ||
| }, | ||
| registerSystemObjects: true, // Register control plane objects | ||
| }); | ||
|
|
||
| await kernel.use(tenantPlugin); | ||
| await kernel.bootstrap(); | ||
| ``` | ||
|
|
||
| ### Tenant Provisioning | ||
|
|
||
| ```typescript | ||
| import { | ||
| TenantProvisioningService, | ||
| TursoPlatformClient, | ||
| } from '@objectstack/service-tenant'; | ||
|
|
||
| // Production mode: with Turso Platform API | ||
| const provisioningService = new TenantProvisioningService({ | ||
| turso: { | ||
| apiToken: process.env.TURSO_API_TOKEN!, | ||
| organization: 'my-org', | ||
| }, | ||
| controlPlaneDriver: globalDriver, // Global control plane driver | ||
| defaultRegion: 'us-east-1', | ||
| databaseGroup: 'production-tenants', | ||
| }); | ||
|
|
||
| // Provision a new tenant | ||
| const result = await provisioningService.provisionTenant({ | ||
| organizationId: 'org-123', | ||
| plan: 'pro', | ||
| region: 'us-west-2', | ||
| storageLimitMb: 5120, | ||
| }); | ||
|
|
||
| console.log('Tenant provisioned:', result.tenant); | ||
| // { | ||
| // id: '550e8400-e29b-41d4-a716-446655440000', | ||
| // databaseUrl: 'libsql://550e8400-e29b-41d4-a716-446655440000.turso.io', | ||
| // authToken: '<encrypted-token>', | ||
| // status: 'active', | ||
| // ... | ||
| // } | ||
| ``` | ||
|
|
||
| ### Development Mode (No Turso API) | ||
|
|
||
| ```typescript | ||
| // Development/Mock mode: no Turso Platform API required | ||
| const devService = new TenantProvisioningService({ | ||
| defaultRegion: 'us-east-1', | ||
| }); | ||
|
|
||
| const result = await devService.provisionTenant({ | ||
| organizationId: 'org-123', | ||
| plan: 'free', | ||
| }); | ||
|
|
||
| // Returns mock tenant with warnings | ||
| console.log(result.warnings); | ||
| // ['Running in mock mode - Turso Platform API credentials not configured'] | ||
| ``` | ||
|
|
||
| ### Schema Initialization | ||
|
|
||
| ```typescript | ||
| import { TenantSchemaInitializer } from '@objectstack/service-tenant'; | ||
|
|
||
| const initializer = new TenantSchemaInitializer(); | ||
|
|
||
| // Initialize tenant database with base schema | ||
| await initializer.initializeTenantSchema( | ||
| tenant.databaseUrl, | ||
| tenant.authToken, | ||
| baseObjects, // Optional: base objects to create | ||
| ); | ||
|
|
||
| // Install package schema | ||
| await initializer.installPackageSchema( | ||
| tenant.databaseUrl, | ||
| tenant.authToken, | ||
| packageObjects, | ||
| ); | ||
| ``` | ||
|
|
||
| ### Resolving Tenant Context | ||
|
|
||
| ```typescript | ||
| import { TenantContextService } from '@objectstack/service-tenant'; | ||
|
|
||
| const service = kernel.getService<TenantContextService>('tenant'); | ||
|
|
||
| const context = await service.resolveTenantContext({ | ||
| hostname: 'app.acme.com', | ||
| headers: { | ||
| 'X-Tenant-ID': '550e8400-e29b-41d4-a716-446655440000', | ||
| }, | ||
| jwt: { | ||
| organizationId: 'org-123', | ||
| }, | ||
| }); | ||
|
|
||
| console.log(context); | ||
| // { | ||
| // tenantId: '550e8400-e29b-41d4-a716-446655440000', | ||
| // organizationId: 'org-123', | ||
| // databaseUrl: 'libsql://550e8400-e29b-41d4-a716-446655440000.turso.io', | ||
| // plan: 'pro' | ||
| // } | ||
| ``` | ||
|
|
||
| ## Architecture | ||
|
|
||
| ### Tenant Identification Flow | ||
|
|
||
| ``` | ||
| Request → TenantContextService → Identification Sources (in order) | ||
| ↓ | ||
| 1. Subdomain | ||
| 2. Custom Domain | ||
| 3. HTTP Header | ||
| 4. JWT Claim | ||
| 5. Session | ||
| 6. Default Tenant | ||
| ↓ | ||
| Tenant Context | ||
| ``` | ||
|
|
||
| ### UUID-Based Naming | ||
|
|
||
| Tenant databases use UUID naming instead of organization slugs: | ||
|
|
||
| - **Why**: Organization slugs can be modified, UUIDs are immutable | ||
| - **Format**: `{uuid}.turso.io` (e.g., `550e8400-e29b-41d4-a716-446655440000.turso.io`) | ||
| - **Benefit**: Stable database URLs regardless of organization name changes | ||
|
|
||
| ## Configuration | ||
|
|
||
| ### TenantRoutingConfig | ||
|
|
||
| ```typescript | ||
| interface TenantRoutingConfig { | ||
| // Enable multi-tenant mode | ||
| enabled: boolean; | ||
|
|
||
| // Identification strategy (in order of precedence) | ||
| identificationSources: TenantIdentificationSource[]; | ||
|
|
||
| // Default tenant ID (for single-tenant or fallback) | ||
| defaultTenantId?: string; | ||
|
|
||
| // Subdomain pattern for tenant extraction | ||
| subdomainPattern?: string; | ||
|
|
||
| // Custom domain to tenant ID mapping | ||
| customDomainMapping?: Record<string, string>; | ||
|
|
||
| // Header name for tenant ID | ||
| tenantHeaderName: string; // Default: 'X-Tenant-ID' | ||
|
|
||
| // JWT claim name for organization ID | ||
| jwtOrganizationClaim: string; // Default: 'organizationId' | ||
| } | ||
| ``` | ||
|
|
||
| ## Testing | ||
|
|
||
| ```bash | ||
| # Run tests | ||
| pnpm test | ||
|
|
||
| # Run tests in watch mode | ||
| pnpm test:watch | ||
| ``` | ||
|
|
||
| ## License | ||
|
|
||
| Apache-2.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| { | ||
| "name": "@objectstack/service-tenant", | ||
| "version": "0.1.0", | ||
| "description": "ObjectStack Multi-Tenant Service - Tenant context management and routing", | ||
| "type": "module", | ||
| "main": "./dist/index.js", | ||
| "types": "./dist/index.d.ts", | ||
| "exports": { | ||
| ".": { | ||
| "types": "./dist/index.d.ts", | ||
| "import": "./dist/index.js" | ||
| } | ||
| }, | ||
| "files": [ | ||
| "dist", | ||
| "README.md" | ||
| ], | ||
| "scripts": { | ||
| "build": "tsup", | ||
| "dev": "tsup --watch", | ||
| "test": "vitest run", | ||
| "test:watch": "vitest", | ||
| "typecheck": "tsc --noEmit" | ||
| }, | ||
| "dependencies": { | ||
| "@objectstack/spec": "workspace:^", | ||
| "@objectstack/core": "workspace:^" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/node": "^22.10.5", | ||
| "tsup": "^8.3.5", | ||
| "typescript": "^5.7.3", | ||
| "vitest": "^2.1.8" | ||
| }, | ||
| "publishConfig": { | ||
| "access": "public" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "https://github.com/objectstack-ai/framework.git", | ||
| "directory": "packages/services/service-tenant" | ||
| }, | ||
| "keywords": [ | ||
| "objectstack", | ||
| "multi-tenant", | ||
| "saas", | ||
| "tenant-routing" | ||
| ], | ||
| "author": "ObjectStack Team", | ||
| "license": "Apache-2.0" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. | ||
|
|
||
| export * from './tenant-context'; | ||
| export * from './tenant-plugin'; | ||
| export * from './tenant-provisioning'; | ||
| export * from './turso-platform-client'; | ||
| export * from './tenant-schema-initializer'; | ||
| export * from './objects'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. | ||
|
|
||
| export * from './sys-tenant-database.object'; | ||
| export * from './sys-package-installation.object'; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This package pins significantly older toolchain versions (
vitest@^2,typescript@^5,@types/node@^22) than the rest ofpackages/services/*(which usevitest@^4,typescript@^6,@types/node@^25). This introduces duplicate transitive deps in the lockfile (e.g. extra vite/esbuild trees) and increases maintenance burden. Align devDependencies and build scripts with the existing service package conventions (seeservice-storage/service-package).