tenancy

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 25 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

laravel-go-tenancy

CI Go Reference Release Go Docs

Multi-tenancy for Laravel Go. Identify a tenant from the request, initialize a request-scoped tenant context, and keep tenant data isolated (by default with a dedicated database and pooled connections per tenant).

Module: github.com/martinshaw/laravel-go-tenancy

Install

go get github.com/martinshaw/laravel-go-tenancy

List the package in bootstrap/app.go:

import (
    laravel "go.laravel.com"
    "go.laravel.com/db"
    "go.laravel.com/db/postgres"

    "github.com/martinshaw/laravel-go-tenancy"
)

Packages: []laravel.Package{
    tenancy.New(func(cfg *tenancy.Config) {
        cfg.Drivers = []db.Driver{postgres.Driver} // same as Options.Drivers
        cfg.CentralDomains = []string{"localhost", "example.com"}
        cfg.TenantMigrations = tenantMigrations.All
    }),
},

Run central migrations (tenants, domains tables are registered by the package):

laravel migrate

Quick start

  1. Create a tenant and domain (single-domain mode shown):
pkg := tenancy.From(ctx)
domain := "acme.example.com"
tenant := models.Tenant{ID: "acme", Domain: &domain}
if err := pkg.CreateTenant(ctx, &tenant); err != nil {
    return err
}
// On Laravel Herd (APP_ENV=local), *tenant.Domain will become "acme.example.com.test"
// when Herd is available so local redirects use the real hostname. See docs/herd.md.
  1. Register central and tenant routes. When both use the same method+path, scope central hosts with OnCentral (covers every CentralDomains entry):
pkg.OnCentral(route, func(route *routing.Router) {
    route.Get("/", central.Home)
})

route.Middleware(pkg.PreventCentral(), pkg.ByDomain()).Group(func(route *routing.Router) {
    route.Get("/", home.Show)
})

Or enable early identification and mark route modes:

tenancy.New(func(cfg *tenancy.Config) {
    cfg.Identification.EarlyIdentification = true
    // DefaultRouteMode is tenant (fail closed). Mark exceptions:
})
route.Middleware(pkg.CentralRoute()).Get("/", central.Home)
route.Middleware(pkg.UniversalRoute()).Get("/status", status.Show)
route.Get("/app", tenant.Home) // unmarked → tenant required

Use pkg.Universal() on a single route when you want identify-or-continue without enabling early identification globally.

  1. Inside a tenant request, queries use that tenant’s database pool. Use tenancy.Central(ctx) only when you intentionally need the central database.

Security and isolation

  • Fail-closed: unknown hosts, paths, or headers are denied (404 by default).
  • Multi-database (default): each tenant gets its own DB; pooled db.Open connections are keyed by tenant id and closed on delete.
  • Single-database (opt-in): tenancy.BelongsToTenant refuses to query without a tenant in context.
  • Cache / files / sessions / queues: bootstrappers namespace keys and paths by tenant id; path helpers reject .. escapes.
  • Central access: only via tenancy.Central(ctx) after the database bootstrapper has run.

Examples

Runnable Herd demos live under examples/ (domain, path, subdomain, domain-or-subdomain, request-data, origin). Each module has tests; CI runs them. Setup and usage: docs/examples.md.

Documentation

Canonical guides live in docs/. The pages/ site publishes them to GitHub Pages on each release: https://martinshaw.github.io/laravel-go-tenancy/

Requirements

  • Go 1.27+
  • Laravel Go (go.laravel.com)

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrAlreadyInitialized = errors.New("tenancy: tenancy is already initialized")

ErrAlreadyInitialized is returned when Initialize is called on a context that already carries a tenant.

View Source
var ErrNoTenant = errors.New("tenancy: no tenant in context")

ErrNoTenant is returned when tenant context is required but missing.

Functions

func BelongsToTenant

func BelongsToTenant[T any](ctx context.Context, column string) (*model.Builder[T], error)

BelongsToTenant returns a fail-closed scoped query for single-DB mode.

func Central

func Central(ctx context.Context) context.Context

Central returns a context bound to the central database when tenancy has preserved it; otherwise returns ctx unchanged.

func End

func End(ctx context.Context) context.Context

End leaves the tenant context, reverting bootstrappers in reverse order.

func Initialized

func Initialized(ctx context.Context) bool

Initialized reports whether ctx is in a tenant context.

func StoragePath

func StoragePath(ctx context.Context, key string) (string, error)

StoragePath joins a relative key under the tenant filesystem prefix.

func TenantCache

func TenantCache(ctx context.Context) *cache.Cache

TenantCache returns the tenant-scoped cache from context.

Types

type Bootstrapper

type Bootstrapper interface {
	Bootstrap(ctx context.Context, tenant Tenant) (context.Context, error)
	Revert(ctx context.Context) context.Context
}

Bootstrapper switches one application concern into (and out of) tenant context. Implementations must be safe for concurrent use across requests and must not store the current tenant in package-level mutable state.

type Config

type Config struct {
	// Drivers are the database drivers used to open tenant pools. Pass the same
	// drivers listed in the application's Options.Drivers.
	Drivers []db.Driver

	// CentralDomains are hostnames that belong to the central application
	// (never treated as tenant domains/subdomains).
	CentralDomains []string

	// Database controls multi-database tenancy.
	Database DatabaseConfig

	// Identification controls how tenants are resolved from HTTP requests.
	Identification IdentificationConfig

	// Bootstrappers run in order on Initialize and reverse on End.
	Bootstrappers []Bootstrapper

	// TenantMigrations are schema migrations applied to each tenant database.
	TenantMigrations []db.Migration

	// TenantSeed runs inside an initialized tenant context for tenants:seed.
	TenantSeed func(ctx context.Context) error

	// CreatePipeline runs after a tenant is created (multi-DB provisioning).
	CreatePipeline []Job

	// DeletePipeline runs before a tenant row is removed (multi-DB teardown).
	DeletePipeline []Job

	// MigrateConcurrency caps parallel tenant migrate/rollback workers.
	MigrateConcurrency int

	// SingleDatabase disables multi-database managers and the Database
	// bootstrapper expectation; apps use BelongsToTenant scoping instead.
	SingleDatabase bool

	// AutoProvision runs CreatePipeline when a tenant is created through the
	// package helpers (CreateTenant).
	AutoProvision bool

	// AutoTeardown runs DeletePipeline when a tenant is deleted through the
	// package helpers (DeleteTenant).
	AutoTeardown bool

	// Herd controls optional Laravel Herd site aliases for tenant domains in
	// the local environment. See docs/herd.md.
	Herd HerdConfig
}

Config holds package settings. Applications change it with New(...), or via TENANCY_* environment variables read in Register.

type DatabaseConfig

type DatabaseConfig struct {
	// TemplateURL builds tenant database URLs. Use {database} as the database
	// name placeholder. When empty, the application's DATABASE_URL is used as
	// a template (scheme/user/host) and only the path/database name changes.
	TemplateURL string

	// NamePrefix prefixes generated tenant database names.
	NamePrefix string

	// MaxConnectionsPerTenant limits each tenant pool (default 5).
	MaxConnectionsPerTenant int

	// IdleTimeout for unused pooled connections (default 5m).
	IdleTimeout time.Duration
}

DatabaseConfig configures tenant database URLs and pools.

type Domain

type Domain = models.Domain

Domain is the package's domain record type.

type HerdConfig

type HerdConfig struct {
	// Enabled turns automatic Herd domain rewrite and aliases on or off.
	// Default true; effective only when Herd is detected. Set
	// TENANCY_HERD_ALIASES=false to opt out.
	Enabled bool

	// Binary is the Herd CLI name or path (default "herd").
	// Override with TENANCY_HERD_BINARY.
	Binary string

	// TLD is appended to tenant hostnames when Herd aliases are active
	// (default "test"). Herd's `link` command appends the same TLD to the
	// alias name. Override with TENANCY_HERD_TLD.
	TLD string

	// Environments lists APP_ENV values where aliases run. Empty means only
	// "local". Comma-separated override: TENANCY_HERD_ENVIRONMENTS.
	Environments []string

	// Runner overrides CLI execution. Nil uses the real Herd binary.
	// Intended for tests.
	Runner herd.Runner
}

HerdConfig configures automatic Laravel Herd aliases for tenant domains.

When Enabled (default true) and Herd is detected in an allowed environment (default APP_ENV=local), CreateDomain / CreateTenant rewrite hostnames onto the Herd TLD (tenant.example.com → tenant.example.com.test), run `herd link`, and DeleteDomain / DeleteTenant run `herd unlink`. Opt out with TENANCY_HERD_ALIASES=false. Failures are soft: domain CRUD still succeeds.

type IdentificationConfig

type IdentificationConfig struct {
	// Header is the request header for request-data identification (default X-Tenant).
	Header string
	// QueryParameter is the query key (default tenant). Empty disables.
	QueryParameter string
	// Cookie is the cookie name (default tenant). Empty disables.
	Cookie string
	// PathParameter is the route parameter name for path identification (default tenant).
	PathParameter string
	// TenantColumn is the tenants-table column used for path/request lookup
	// (empty = id).
	TenantColumn string
	// ResolverCache enables caching of successful resolves.
	ResolverCache bool
	// ResolverCacheTTL is the cache lifetime (default 1h).
	ResolverCacheTTL time.Duration
	// SingleDomainTenants looks up domains on tenants.domain instead of domains.
	SingleDomainTenants bool

	// EarlyIdentification registers EarlyIdentify on the Web and API stacks so
	// tenancy can initialize before route handlers (and path params are
	// available). Opt-in; default false keeps fail-closed route middleware.
	EarlyIdentification bool
	// EarlyStrategy selects how EarlyIdentify / Universal resolve tenants
	// (default domain).
	EarlyStrategy identification.Strategy
	// DefaultRouteMode is used when a route has no CentralRoute / TenantRoute /
	// UniversalRoute marker (default tenant = fail closed).
	DefaultRouteMode identification.RouteMode
}

IdentificationConfig configures resolvers and middleware defaults.

type Job

type Job interface {
	Name() string
	Handle(ctx context.Context, tenant Tenant) error
}

Job is a step in a tenant lifecycle pipeline.

type JobFunc

type JobFunc struct {
	Label string
	Fn    func(ctx context.Context, tenant Tenant) error
}

JobFunc adapts a function into a Job.

func (JobFunc) Handle

func (j JobFunc) Handle(ctx context.Context, tenant Tenant) error

func (JobFunc) Name

func (j JobFunc) Name() string

type ListTenants

type ListTenants struct {
	Package *Package
}

ListTenants lists tenants in the central database.

func (*ListTenants) Description

func (*ListTenants) Description() string

func (*ListTenants) Name

func (*ListTenants) Name() string

func (*ListTenants) Run

func (c *ListTenants) Run(ctx context.Context, out *console.Console) error

type MigrateFreshTenants

type MigrateFreshTenants struct {
	Package *Package
	Tenants string
}

MigrateFreshTenants drops all tables on each tenant database and re-migrates.

func (*MigrateFreshTenants) Description

func (*MigrateFreshTenants) Description() string

func (*MigrateFreshTenants) Flags

func (c *MigrateFreshTenants) Flags(flags *flag.FlagSet)

func (*MigrateFreshTenants) Name

func (*MigrateFreshTenants) Name() string

func (*MigrateFreshTenants) Run

type MigrateTenants

type MigrateTenants struct {
	Package *Package
	Tenants string
}

MigrateTenants runs tenant migrations for all (or selected) tenants.

func (*MigrateTenants) Description

func (*MigrateTenants) Description() string

func (*MigrateTenants) Flags

func (c *MigrateTenants) Flags(flags *flag.FlagSet)

func (*MigrateTenants) Name

func (*MigrateTenants) Name() string

func (*MigrateTenants) Run

func (c *MigrateTenants) Run(ctx context.Context, out *console.Console) error

type Package

type Package struct {
	// contains filtered or unexported fields
}

Package is the Laravel Go multi-tenancy package.

func From

func From(ctx context.Context) *Package

From returns the Package installed on ctx's application.

func New

func New(configure ...func(*Config)) *Package

New returns the package. Each configure function changes settings after they are read from the environment.

func (*Package) ByDomain

ByDomain returns domain identification middleware wired to this package.

func (*Package) ByDomainOrSubdomain

ByDomainOrSubdomain returns combined domain/subdomain middleware.

func (*Package) ByOriginHeader

ByOriginHeader returns Origin-header identification middleware.

func (*Package) ByPath

ByPath returns path identification middleware.

func (*Package) ByRequestData

ByRequestData returns header/query/cookie identification middleware.

func (*Package) BySubdomain

BySubdomain returns subdomain identification middleware.

func (*Package) CentralRoute

func (p *Package) CentralRoute() identification.CentralRoute

CentralRoute marks a route (or group) as central under early identification.

func (*Package) Config

func (p *Package) Config() Config

Config returns the resolved configuration.

func (*Package) CreateDomain

func (p *Package) CreateDomain(ctx context.Context, tenantID, host string) (string, error)

CreateDomain attaches a domain to a tenant (multi-domain mode). When Herd aliases are active, host is rewritten onto the Herd TLD before insert (tenant.example.com → tenant.example.com.test) and a site alias is linked. The returned string is the stored hostname; use it for redirects.

func (*Package) CreateTenant

func (p *Package) CreateTenant(ctx context.Context, tenant *models.Tenant) error

CreateTenant creates a tenant row and runs the create pipeline when enabled. When tenant.Domain is set, it may be rewritten onto the Herd TLD in local Herd setups (tenant.example.com → tenant.example.com.test) so redirects that use tenant.Domain hit the real local hostname. See docs/herd.md.

func (*Package) DeleteDomain

func (p *Package) DeleteDomain(ctx context.Context, host string) error

DeleteDomain removes a hostname from the domains table and, when applicable, unlinks the matching Laravel Herd site alias. host may be the production name or the local Herd form (tenant.example.com or tenant.example.com.test).

func (*Package) DeleteTenant

func (p *Package) DeleteTenant(ctx context.Context, tenant models.Tenant) error

DeleteTenant runs teardown (if enabled), removes domain rows and Herd aliases for the tenant, then deletes the tenant row.

func (*Package) EarlyIdentify

func (p *Package) EarlyIdentify() identification.EarlyIdentify

EarlyIdentify returns early identification middleware wired to this package. Prefer enabling Identification.EarlyIdentification so Register installs it on the Web and API stacks automatically.

func (*Package) EnsureHerdAlias added in v0.1.1

func (p *Package) EnsureHerdAlias(ctx context.Context, host string) string

EnsureHerdAlias rewrites host onto the Herd TLD when aliases are active and runs `herd link`. Returns the local hostname (rewritten or unchanged). Soft-fails CLI errors the same way as CreateTenant / CreateDomain.

func (*Package) EnsureTenant

func (p *Package) EnsureTenant() identification.EnsureInitialized

EnsureTenant denies requests that reach a handler without an initialized tenant.

func (*Package) Finder

func (p *Package) Finder() identification.Finder

Finder returns an identification finder configured from package settings.

func (*Package) HerdActive

func (p *Package) HerdActive() bool

HerdActive reports whether Herd domain rewrite and aliases are in effect.

func (*Package) Initialize

func (p *Package) Initialize(ctx context.Context, tenant Tenant) (context.Context, error)

Initialize enters the tenant context by running configured bootstrappers.

func (*Package) LocalDomain

func (p *Package) LocalDomain(host string) string

LocalDomain returns the hostname to store and redirect to when Herd aliases are active. Otherwise returns host unchanged.

func (*Package) OnCentral added in v0.1.2

func (p *Package) OnCentral(route *routing.Router, register func(*routing.Router))

OnCentral registers routes on a Domain-scoped router for every host in CentralDomains. Use this when central and tenant share a method+path without early identification, instead of calling route.Domain for each host:

pkg.OnCentral(route, func(route *routing.Router) {
	route.Get("/", centralHome)
})

func (*Package) Pool

func (p *Package) Pool() *database.Pool

Pool returns the tenant database pool.

func (*Package) PreventCentral

PreventCentral returns middleware that blocks central hosts on tenant routes.

func (*Package) Provision

func (p *Package) Provision(ctx context.Context, tenant models.Tenant) error

Provision runs the create pipeline for an existing tenant.

func (*Package) Register

func (p *Package) Register(app *laravel.Registrar) error

Register installs the package in an application.

func (*Package) Run

func (p *Package) Run(ctx context.Context, tenant Tenant, fn func(ctx context.Context) error) (err error)

Run initializes tenancy for tenant, runs fn, then ends tenancy.

func (*Package) Teardown

func (p *Package) Teardown(ctx context.Context, tenant models.Tenant) error

Teardown runs the delete pipeline.

func (*Package) TenantRoute

func (p *Package) TenantRoute() identification.TenantRoute

TenantRoute marks a route (or group) as tenant-required under early identification.

func (*Package) Universal

func (p *Package) Universal() identification.Universal

Universal returns middleware that initializes tenancy when a tenant can be resolved and continues centrally otherwise. Use on specific routes without enabling EarlyIdentification.

func (*Package) UniversalRoute

func (p *Package) UniversalRoute() identification.UniversalRoute

UniversalRoute marks a route (or group) as universal under early identification.

type SeedTenants

type SeedTenants struct {
	Package *Package
	Tenants string
}

SeedTenants runs Config.TenantSeed inside each tenant context.

func (*SeedTenants) Description

func (*SeedTenants) Description() string

func (*SeedTenants) Flags

func (c *SeedTenants) Flags(flags *flag.FlagSet)

func (*SeedTenants) Name

func (*SeedTenants) Name() string

func (*SeedTenants) Run

func (c *SeedTenants) Run(ctx context.Context, out *console.Console) error

type Tenant

type Tenant = models.Tenant

Tenant is the package's tenant record type.

func MustTenant

func MustTenant(ctx context.Context) Tenant

MustTenant returns the current tenant or panics.

func TenantFrom

func TenantFrom(ctx context.Context) (Tenant, bool)

TenantFrom returns the current tenant and whether one is present.

Directories

Path Synopsis
Package herd manages optional Laravel Herd site aliases for tenant domains.
Package herd manages optional Laravel Herd site aliases for tenant domains.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL