NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / SETUP SCRIPTS / PER-USER SHARDS

Per-user shards

Starts a small enterprise cluster on one machine in which each customer's login is pinned to one shard. The customer's whole database lives on that shard, and the gateway sends every statement of that login there, with no route keys and no hashing. Use it when customers are separate (one database each) and you want to spread them over machines, rather than split one large table across all of them (that is the sharded-cluster recipe). Customers are added through the gateway's configuration API, which creates the database and login role on the chosen shard and records the route.

This is a test cluster on one host, not a multi-host production deployment.

Before you start

  • The enterprise server and the enterprise gateway, 1.1.0 or later, under their own licence (LICENSE-POLYFORM-SB). The rasterizeddb-enterprise-<version>-<platform> release archive holds both, as rasterizeddb-enterprise and rasterizeddb-gateway-enterprise (see Installing the enterprise edition); a build from source names them rasterizeddb_core_enterprise and rasterizeddb_gateway_enterprise. Pass them with RDB_BIN and RDB_GATEWAY_BIN.
  • openssl, psql and, for add-customer.sh, curl 7.76 or newer.
  • Free ports: 5440-5442, 61180-61182 and 7400-7402 for the shards, 6432 for the gateway and 6480 for its configuration API.
  • A password in RASTERIZEDDB_PG_PASSWORD for the operator role rasterized on every shard.

How it fits together

  • Shards run the enterprise server with --role shard and an enterprise configuration file holding one line, pinned_roles_file <path>: the list of customer roles that shard hosts, one database role per line. A shard admits a pinned login only for a role on its list.
  • The gateway runs with user_routing = prefer (or require), which looks every login up in its route table first. A pinned login goes to its shard for the whole session; it may not change its routing (SET rdb.route_key is refused with 42501), and its statements never reach another shard. With prefer, a login that has no route is routed by key as in the sharded-cluster recipe; with require it is refused.
  • The configuration API (api_listen, with a bearer token read from api_token_file) keeps the routes in a small store under config_dir, so they survive a restart. POST /v1/customers makes the customer's database and role on its shard, adds the role to that shard's list and stores the route.

The gateway's configuration file the script writes:

text
listen = 127.0.0.1:6432
map = <work>/cluster.map
home_shard = 0
shard_trust = ca:<work>/tls/ca.pem
shard_cert = <work>/tls/gateway.pem
shard_key = <work>/tls/gateway.key
auth = scram
unrouted = fan_out
two_phase = on
user_routing = prefer
api_listen = 127.0.0.1:6480
api_token_file = <work>/api.token
config_dir = <work>/gateway_config

Settings

setup.sh / setup.ps1:

bash variablePowerShell parameterDefaultWhat it does
RDB_BIN-RdbBinrasterizeddb-enterpriseThe enterprise server.
RDB_GATEWAY_BIN-GatewayBinrasterizeddb-gateway-enterpriseThe enterprise gateway.
RDB_WORK-Work./per-user-clusterCertificates, map, configuration, data, logs, .pid files and api.token.
RDB_GATEWAY_PORT-GatewayPort6432Where clients connect.
RDB_API_PORT-ApiPort6480The configuration API, on 127.0.0.1 only.
RDB_USER_ROUTING-UserRoutingpreferprefer or require (refuse logins with no route).
RDB_PG_BASE, RDB_NATIVE_BASE, RDB_RSHARD_BASE-PgBase, -NativeBase, -RshardBase5440, 61180, 7400Shard n's ports are these plus n.

add-customer.sh / add-customer.ps1:

bash variablePowerShell parameterDefaultWhat it does
RDB_CUSTOMER-CustomerrequiredThe customer's database. Starts with a letter; letters, digits and _; at most 63.
RDB_CUSTOMER_ROLE-Role<customer>_appIts login role.
RDB_CUSTOMER_SHARD-ShardrequiredThe shard it lives on: 0, 1 or 2.
RDB_CUSTOMER_PASSWORD$env:RDB_CUSTOMER_PASSWORDrequiredThe login role's password. Sent in the request body, never on the command line.
RDB_API-Apihttp://127.0.0.1:6480The configuration API.
RDB_WORK-Work./per-user-clusterWhere api.token is.

Run it

sh
export RASTERIZEDDB_PG_PASSWORD='change-me'
RDB_BIN=./rasterizeddb-enterprise RDB_GATEWAY_BIN=./rasterizeddb-gateway-enterprise ./setup.sh
RDB_CUSTOMER=acme RDB_CUSTOMER_SHARD=1 RDB_CUSTOMER_PASSWORD='acme-secret-123' ./add-customer.sh
powershell
$env:RASTERIZEDDB_PG_PASSWORD = 'change-me'
.\setup.ps1 -RdbBin .\rasterizeddb-enterprise.exe -GatewayBin .\rasterizeddb-gateway-enterprise.exe
$env:RDB_CUSTOMER_PASSWORD = 'acme-secret-123'
.\add-customer.ps1 -Customer acme -Shard 1

add-customer prints the API's answer and the route table:

text
{"routes":[{"database":"acme","role":"acme_app","shard":1}]}

Check that it works

Log in as the customer through the gateway and make a table:

sh
PGPASSWORD='acme-secret-123' psql "postgresql://acme_app@127.0.0.1:6432/acme?sslmode=disable" \
  -c "CREATE TABLE notes (id INT PRIMARY KEY, body TEXT NOT NULL)" \
  -c "INSERT INTO notes (id, body) VALUES (1, 'hello')" \
  -c "SELECT body FROM notes WHERE id = 1"

The table is on shard 1 only. Ask the shards directly as the operator: shard 1 answers, and shards 0 and 2 have no database acme:

sh
for n in 0 1 2; do
  PGPASSWORD='change-me' psql "postgresql://rasterized@127.0.0.1:544$n/acme?sslmode=require" -Atc "SELECT count(*) FROM notes"
done

Manage routes

With the token from api.token in an Authorization: Bearer … header:

RequestWhat it does
GET /v1/routesEvery route.
PUT /v1/routes/{database}/{role} with {"shard": N}Pin a role to a shard, from its next login.
PUT /v1/routes/{database}/{role} with {"refuse": true}Keep a role out: its next login is refused.
DELETE /v1/routes/{database}/{role}Remove the route.
POST /v1/customers with {"database", "role", "password", "shard"}Make a customer, as add-customer does.

A route change applies at the role's next login; sessions already open keep their shard.

Stop or undo

sh
kill $(cat per-user-cluster/*.pid)
powershell
Get-Content .\per-user-cluster\*.pid | ForEach-Object { Stop-Process -Id $_ }

Delete the work directory to start again from nothing.

Limits

  • A pinned customer is never split: its database must fit on its shard.
  • Moving a customer's database to another shard is not built yet. Changing its route without moving the data would point it at a shard that does not have it.
  • The configuration API listens on 127.0.0.1 here and has no TLS of its own; keep it off networks you do not control.

The files

setup.sh · Linux and macOS (Bash)DOWNLOAD ↓
#!/usr/bin/env bash
# RasterizedDB Enterprise: per-user shards on one machine. Three enterprise
# shard servers and the enterprise gateway; each customer's login is pinned to
# one shard, where its whole database lives, and the gateway sends every one
# of its statements there. Customers are added through the gateway's
# configuration API with add-customer.sh.
# Needs release 1.1.0 or later.
#
# Everything runs in the background, with logs and process ids in RDB_WORK.
# Running it again starts whatever is not running. Stop with:
#   kill $(cat per-user-cluster/*.pid)
set -euo pipefail

RDB_BIN="${RDB_BIN:-rasterizeddb-enterprise}"
RDB_GATEWAY_BIN="${RDB_GATEWAY_BIN:-rasterizeddb-gateway-enterprise}"
RDB_WORK="${RDB_WORK:-./per-user-cluster}"
RDB_GATEWAY_PORT="${RDB_GATEWAY_PORT:-6432}"
RDB_API_PORT="${RDB_API_PORT:-6480}"          # the gateway's configuration API, on 127.0.0.1
RDB_USER_ROUTING="${RDB_USER_ROUTING:-prefer}"  # prefer: unmapped logins use key routing; require: they are refused
RDB_PG_BASE="${RDB_PG_BASE:-5440}"
RDB_NATIVE_BASE="${RDB_NATIVE_BASE:-61180}"
RDB_RSHARD_BASE="${RDB_RSHARD_BASE:-7400}"
SHARDS=(0 1 2)

die() { echo "error: $*" >&2; exit 1; }

command -v "$RDB_BIN" >/dev/null 2>&1 || die "'$RDB_BIN' not found; set RDB_BIN to the enterprise server"
command -v "$RDB_GATEWAY_BIN" >/dev/null 2>&1 || die "'$RDB_GATEWAY_BIN' not found; set RDB_GATEWAY_BIN to the enterprise gateway"
case "$("$RDB_BIN" --help)" in *--enterprise-config*) ;; *) die "$RDB_BIN is not the enterprise server" ;; esac
command -v openssl >/dev/null 2>&1 || die "openssl is needed for the certificates"
command -v psql >/dev/null 2>&1 || die "psql is needed"
: "${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD; every shard gets the operator role rasterized with it}"
export RASTERIZEDDB_PG_PASSWORD PGPASSWORD="$RASTERIZEDDB_PG_PASSWORD"

mkdir -p "$RDB_WORK/tls"
cd "$RDB_WORK"
work="$PWD"
RDB_BIN="$(command -v "$RDB_BIN")"; RDB_BIN="$(cd "$(dirname "$RDB_BIN")" && pwd)/$(basename "$RDB_BIN")"
RDB_GATEWAY_BIN="$(command -v "$RDB_GATEWAY_BIN")"; RDB_GATEWAY_BIN="$(cd "$(dirname "$RDB_GATEWAY_BIN")" && pwd)/$(basename "$RDB_GATEWAY_BIN")"

running() { [ -f "$1.pid" ] && kill -0 "$(cat "$1.pid")" 2>/dev/null; }
wait_for() { # wait_for <port> <sslmode> <what> <pidfile>
  for _ in $(seq 1 60); do
    psql "postgresql://rasterized@127.0.0.1:$1/postgres?sslmode=$2" -Atqc "SELECT 1" >/dev/null 2>&1 && return 0
    kill -0 "$(cat "$4")" 2>/dev/null || die "$3 exited; see $work/${4%.pid}.log"
    sleep 1
  done
  die "$3 did not answer on port $1 within 60 s; see $work/${4%.pid}.log"
}

# 1. Certificates: a CA, one for each shard and one for the gateway.
if [ ! -f tls/ca.pem ]; then
  (
    cd tls
    umask 077
    openssl req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=rdb-cluster-ca -keyout ca.key -out ca.pem
    printf 'subjectAltName=DNS:localhost,IP:127.0.0.1\nextendedKeyUsage=serverAuth,clientAuth\n' > ext.cnf
    for name in shard0 shard1 shard2 gateway; do
      openssl req -newkey rsa:2048 -nodes -subj "/CN=$name" -keyout "$name.key" -out "$name.csr"
      openssl x509 -req -in "$name.csr" -CA ca.pem -CAkey ca.key -CAcreateserial -days 365 -extfile ext.cnf -out "$name.pem"
    done
    rm -f ./*.csr
  )
fi

# 2. The shard map.
if [ ! -f cluster.map ]; then
  {
    echo "rasterizeddb shard map"
    echo "format 1"
    echo "cluster $(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
    echo "epoch 1"
    echo "route_v 1"
    for n in "${SHARDS[@]}"; do echo "shard $n 127.0.0.1:$((RDB_RSHARD_BASE + n))"; done
    echo "range 0x0 0"
    echo "range 0x555555555555 1"
    echo "range 0xaaaaaaaaaaaa 2"
  } > cluster.map
fi
cluster_id="$(sed -n 's/^cluster //p' cluster.map)"

# 3. Three enterprise shards. Each keeps the list of customer roles it hosts
# in pinned_roles_file, which the gateway's API adds to.
for n in "${SHARDS[@]}"; do
  [ -f "enterprise$n.conf" ] || echo "pinned_roles_file $work/shard$n.hosted_roles" > "enterprise$n.conf"
  if running "shard$n"; then echo "shard $n is running"; continue; fi
  mkdir -p "shard$n"
  nohup "$RDB_BIN" --enterprise-config "$work/enterprise$n.conf" --location "$work/shard$n" --protocol both \
    --pg-port $((RDB_PG_BASE + n)) --rdb-port $((RDB_NATIVE_BASE + n)) \
    --role shard --cluster-map "$work/cluster.map" --shard-id "$n" --cluster-id "$cluster_id" \
    --shard-listen "127.0.0.1:$((RDB_RSHARD_BASE + n))" \
    --shard-cert "$work/tls/shard$n.pem" --shard-key "$work/tls/shard$n.key" \
    --gateway-ca "$work/tls/ca.pem" --peer-ca "$work/tls/ca.pem" \
    --log-level info > "shard$n.log" 2>&1 &
  echo $! > "shard$n.pid"
  echo "started shard $n (pid $!)"
done
for n in "${SHARDS[@]}"; do wait_for $((RDB_PG_BASE + n)) require "shard $n" "shard$n.pid"; done

# 4. The enterprise gateway, with per-user routing and its configuration API.
if [ ! -f api.token ]; then
  (umask 077; od -An -N24 -tx1 /dev/urandom | tr -d ' \n' > api.token)
fi
cat > gateway.conf <<EOF
listen = 127.0.0.1:$RDB_GATEWAY_PORT
map = $work/cluster.map
home_shard = 0
shard_trust = ca:$work/tls/ca.pem
shard_cert = $work/tls/gateway.pem
shard_key = $work/tls/gateway.key
auth = scram
unrouted = fan_out
two_phase = on
user_routing = $RDB_USER_ROUTING
api_listen = 127.0.0.1:$RDB_API_PORT
api_token_file = $work/api.token
config_dir = $work/gateway_config
EOF
if running gateway; then
  echo "the gateway is running"
else
  nohup "$RDB_GATEWAY_BIN" --config "$work/gateway.conf" > gateway.log 2>&1 &
  echo $! > gateway.pid
  echo "started the gateway (pid $!)"
fi
wait_for "$RDB_GATEWAY_PORT" disable gateway gateway.pid

echo
echo "Up. Operator, through the gateway: psql \"postgresql://rasterized@127.0.0.1:$RDB_GATEWAY_PORT/postgres?sslmode=disable\""
echo "Configuration API: http://127.0.0.1:$RDB_API_PORT (bearer token in $work/api.token)"
echo "Add a customer:    RDB_CUSTOMER=acme RDB_CUSTOMER_SHARD=1 RDB_CUSTOMER_PASSWORD=… ./add-customer.sh"
echo "Stop with: kill \$(cat $work/*.pid)"
setup.ps1 · Windows (PowerShell)DOWNLOAD ↓
#Requires -Version 5.1
<#
.SYNOPSIS
  RasterizedDB Enterprise: per-user shards on one machine. Three enterprise
  shard servers and the enterprise gateway; each customer's login is pinned to
  one shard, where its whole database lives, and the gateway sends every one
  of its statements there. Customers are added through the gateway's
  configuration API with add-customer.ps1.
  Needs release 1.1.0 or later.
.DESCRIPTION
  Everything runs in the background, with logs and process ids in -Work.
  Running it again starts whatever is not running. Stop with:
    Get-Content .\per-user-cluster\*.pid | ForEach-Object { Stop-Process -Id $_ }
.EXAMPLE
  $env:RASTERIZEDDB_PG_PASSWORD = 'change-me'
  .\setup.ps1 -RdbBin .\rasterizeddb-enterprise.exe -GatewayBin .\rasterizeddb-gateway-enterprise.exe
#>
[CmdletBinding()]
param(
    [string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb-enterprise.exe' }),
    [string]$GatewayBin = $(if ($env:RDB_GATEWAY_BIN) { $env:RDB_GATEWAY_BIN } else { 'rasterizeddb-gateway-enterprise.exe' }),
    # Certificates, map, data, logs, the API token.
    [string]$Work = $(if ($env:RDB_WORK) { $env:RDB_WORK } else { '.\per-user-cluster' }),
    [int]$GatewayPort = $(if ($env:RDB_GATEWAY_PORT) { [int]$env:RDB_GATEWAY_PORT } else { 6432 }),
    # The gateway's configuration API, on 127.0.0.1.
    [int]$ApiPort = $(if ($env:RDB_API_PORT) { [int]$env:RDB_API_PORT } else { 6480 }),
    # prefer: unmapped logins use key routing; require: they are refused.
    [ValidateSet('prefer', 'require')]
    [string]$UserRouting = $(if ($env:RDB_USER_ROUTING) { $env:RDB_USER_ROUTING } else { 'prefer' }),
    # Shard n's ports are base + n.
    [int]$PgBase = $(if ($env:RDB_PG_BASE) { [int]$env:RDB_PG_BASE } else { 5440 }),
    [int]$NativeBase = $(if ($env:RDB_NATIVE_BASE) { [int]$env:RDB_NATIVE_BASE } else { 61180 }),
    [int]$RshardBase = $(if ($env:RDB_RSHARD_BASE) { [int]$env:RDB_RSHARD_BASE } else { 7400 })
)
$ErrorActionPreference = 'Stop'
$shards = 0, 1, 2

$server = Get-Command $RdbBin -ErrorAction SilentlyContinue
if (-not $server) { throw "'$RdbBin' not found; pass -RdbBin with the enterprise server." }
$gateway = Get-Command $GatewayBin -ErrorAction SilentlyContinue
if (-not $gateway) { throw "'$GatewayBin' not found; pass -GatewayBin with the enterprise gateway." }
if (-not ((& $server.Source --help) -match '--enterprise-config')) { throw "$RdbBin is not the enterprise server." }
$openssl = Get-Command openssl -ErrorAction SilentlyContinue
if (-not $openssl) { throw 'openssl is needed for the certificates (Git for Windows has one in C:\Program Files\Git\usr\bin).' }
if (-not (Get-Command psql -ErrorAction SilentlyContinue)) { throw 'psql is needed.' }
if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD; every shard gets the operator role rasterized with it.' }
$env:PGPASSWORD = $env:RASTERIZEDDB_PG_PASSWORD

New-Item -ItemType Directory -Force -Path (Join-Path $Work 'tls') | Out-Null
$Work = (Resolve-Path -LiteralPath $Work).Path
$tls = Join-Path $Work 'tls'

function Join-Args([string[]]$Items) {
    ($Items | ForEach-Object {
        if ($_ -notmatch '[\s"]') { $_ } else { '"' + ($_ -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"' }
    }) -join ' '
}
function Test-Running([string]$Name) {
    $pidFile = Join-Path $Work "$Name.pid"
    if (-not (Test-Path -LiteralPath $pidFile)) { return $false }
    return [bool](Get-Process -Id ([int](Get-Content -LiteralPath $pidFile)) -ErrorAction SilentlyContinue)
}
function Start-Background([string]$Name, [string]$Exe, [string[]]$Arguments) {
    $p = Start-Process -FilePath $Exe -ArgumentList (Join-Args $Arguments) -WindowStyle Hidden -PassThru `
        -RedirectStandardOutput (Join-Path $Work "$Name.out.log") -RedirectStandardError (Join-Path $Work "$Name.log")
    Set-Content -LiteralPath (Join-Path $Work "$Name.pid") -Value $p.Id
    Write-Host "started $Name (pid $($p.Id))"
}
function Wait-For([int]$Port, [string]$SslMode, [string]$Name) {
    for ($i = 0; $i -lt 60; $i++) {
        # Windows PowerShell turns a native program's stderr into errors when
        # it is redirected, so relax the preference around the probe.
        $saved = $ErrorActionPreference
        $ErrorActionPreference = 'Continue'
        & psql "postgresql://rasterized@127.0.0.1:$Port/postgres?sslmode=$SslMode" -Atqc 'SELECT 1' 2>$null | Out-Null
        $code = $LASTEXITCODE
        $ErrorActionPreference = $saved
        if ($code -eq 0) { return }
        if (-not (Test-Running $Name)) { throw "$Name exited; see $Work\$Name.log" }
        Start-Sleep -Seconds 1
    }
    throw "$Name did not answer on port $Port within 60 s; see $Work\$Name.log"
}

# 1. Certificates: a CA, one for each shard and one for the gateway.
if (-not (Test-Path -LiteralPath (Join-Path $tls 'ca.pem'))) {
    Push-Location $tls
    try {
        & $openssl.Source req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=rdb-cluster-ca -keyout ca.key -out ca.pem
        if ($LASTEXITCODE -ne 0) { throw 'openssl could not make the CA.' }
        Set-Content -LiteralPath ext.cnf -Value "subjectAltName=DNS:localhost,IP:127.0.0.1`nextendedKeyUsage=serverAuth,clientAuth`n" -Encoding ascii -NoNewline
        foreach ($name in 'shard0', 'shard1', 'shard2', 'gateway') {
            & $openssl.Source req -newkey rsa:2048 -nodes -subj "/CN=$name" -keyout "$name.key" -out "$name.csr"
            if ($LASTEXITCODE -ne 0) { throw "openssl could not make the key for $name." }
            & $openssl.Source x509 -req -in "$name.csr" -CA ca.pem -CAkey ca.key -CAcreateserial -days 365 -extfile ext.cnf -out "$name.pem"
            if ($LASTEXITCODE -ne 0) { throw "openssl could not sign the certificate for $name." }
            Remove-Item -LiteralPath "$name.csr"
        }
    }
    finally { Pop-Location }
}

# 2. The shard map: which shard owns which slice of the 2^48 key space.
$mapFile = Join-Path $Work 'cluster.map'
if (-not (Test-Path -LiteralPath $mapFile)) {
    $clusterId = -join ((1..32) | ForEach-Object { '{0:x}' -f (Get-Random -Maximum 16) })
    $lines = @('rasterizeddb shard map', 'format 1', "cluster $clusterId", 'epoch 1', 'route_v 1')
    $lines += $shards | ForEach-Object { "shard $_ 127.0.0.1:$($RshardBase + $_)" }
    $lines += @('range 0x0 0', 'range 0x555555555555 1', 'range 0xaaaaaaaaaaaa 2')
    Set-Content -LiteralPath $mapFile -Value $lines -Encoding ascii
}
$clusterId = ((Get-Content -LiteralPath $mapFile) | Where-Object { $_ -match '^cluster ' }) -replace '^cluster ', ''

# 3. Three enterprise shards. Each keeps the list of customer roles it hosts
# in pinned_roles_file, which the gateway's API adds to.
foreach ($n in $shards) {
    $econf = Join-Path $Work "enterprise$n.conf"
    if (-not (Test-Path -LiteralPath $econf)) {
        Set-Content -LiteralPath $econf -Value "pinned_roles_file $(Join-Path $Work "shard$n.hosted_roles")" -Encoding ascii
    }
    if (Test-Running "shard$n") { Write-Host "shard $n is running"; continue }
    $dir = Join-Path $Work "shard$n"
    New-Item -ItemType Directory -Force -Path $dir | Out-Null
    Start-Background "shard$n" $server.Source @(
        '--enterprise-config', $econf, '--location', $dir, '--protocol', 'both',
        '--pg-port', "$($PgBase + $n)", '--rdb-port', "$($NativeBase + $n)",
        '--role', 'shard', '--cluster-map', $mapFile, '--shard-id', "$n", '--cluster-id', $clusterId,
        '--shard-listen', "127.0.0.1:$($RshardBase + $n)",
        '--shard-cert', (Join-Path $tls "shard$n.pem"), '--shard-key', (Join-Path $tls "shard$n.key"),
        '--gateway-ca', (Join-Path $tls 'ca.pem'), '--peer-ca', (Join-Path $tls 'ca.pem'),
        '--log-level', 'info')
}
foreach ($n in $shards) { Wait-For ($PgBase + $n) 'require' "shard$n" }

# 4. The enterprise gateway, with per-user routing and its configuration API.
$token = Join-Path $Work 'api.token'
if (-not (Test-Path -LiteralPath $token)) {
    $bytes = New-Object byte[] 24
    [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
    Set-Content -LiteralPath $token -Value (($bytes | ForEach-Object { $_.ToString('x2') }) -join '') -Encoding ascii -NoNewline
    & icacls.exe $token /inheritance:r /grant:r "$($env:USERNAME):F" '*S-1-5-18:F' '*S-1-5-32-544:F' | Out-Null
}
$conf = Join-Path $Work 'gateway.conf'
@(
    "listen = 127.0.0.1:$GatewayPort",
    "map = $mapFile",
    'home_shard = 0',
    "shard_trust = ca:$(Join-Path $tls 'ca.pem')",
    "shard_cert = $(Join-Path $tls 'gateway.pem')",
    "shard_key = $(Join-Path $tls 'gateway.key')",
    'auth = scram',
    'unrouted = fan_out',
    'two_phase = on',
    "user_routing = $UserRouting",
    "api_listen = 127.0.0.1:$ApiPort",
    "api_token_file = $token",
    "config_dir = $(Join-Path $Work 'gateway_config')"
) | Set-Content -LiteralPath $conf -Encoding ascii
if (Test-Running 'gateway') { Write-Host 'the gateway is running' }
else { Start-Background 'gateway' $gateway.Source @('--config', $conf) }
Wait-For $GatewayPort 'disable' 'gateway'

Write-Host ''
Write-Host "Up. Operator, through the gateway: psql `"postgresql://rasterized@127.0.0.1:$GatewayPort/postgres?sslmode=disable`""
Write-Host "Configuration API: http://127.0.0.1:$ApiPort (bearer token in $token)"
Write-Host 'Add a customer:    .\add-customer.ps1 -Customer acme -Shard 1   (password from $env:RDB_CUSTOMER_PASSWORD)'
Write-Host "Stop with: Get-Content $Work\*.pid | ForEach-Object { Stop-Process -Id `$_ }"
add-customer.sh · Linux and macOS (Bash)DOWNLOAD ↓
#!/usr/bin/env bash
# RasterizedDB Enterprise: add a customer to the per-user-shard cluster. The
# gateway's configuration API creates the customer's database and login role
# on the chosen shard and pins the login there.
# Needs release 1.1.0 or later.
#
#   RDB_CUSTOMER=acme RDB_CUSTOMER_SHARD=1 RDB_CUSTOMER_PASSWORD='…' ./add-customer.sh
set -euo pipefail

RDB_WORK="${RDB_WORK:-./per-user-cluster}"          # holds api.token
RDB_API="${RDB_API:-http://127.0.0.1:6480}"
RDB_GATEWAY_PORT="${RDB_GATEWAY_PORT:-6432}"
RDB_CUSTOMER="${RDB_CUSTOMER:-}"                    # required: the customer's database
RDB_CUSTOMER_ROLE="${RDB_CUSTOMER_ROLE:-${RDB_CUSTOMER}_app}"   # its login role
RDB_CUSTOMER_SHARD="${RDB_CUSTOMER_SHARD:-}"        # required: the shard id it lives on

die() { echo "error: $*" >&2; exit 1; }

command -v curl >/dev/null 2>&1 || die "curl is needed"
[ -f "$RDB_WORK/api.token" ] || die "no $RDB_WORK/api.token; run setup.sh first, or set RDB_WORK"
[ -n "$RDB_CUSTOMER" ] || die "set RDB_CUSTOMER to the customer's database name"
[ -n "$RDB_CUSTOMER_SHARD" ] || die "set RDB_CUSTOMER_SHARD to the shard id (0, 1 or 2)"
: "${RDB_CUSTOMER_PASSWORD:?set RDB_CUSTOMER_PASSWORD to the password for the login role}"
for v in "$RDB_CUSTOMER" "$RDB_CUSTOMER_ROLE"; do
  [[ "$v" =~ ^[A-Za-z][A-Za-z0-9_]{0,62}$ ]] || die "$v: start with a letter, then letters, digits and _ (63 at most)"
done
[[ "$RDB_CUSTOMER_SHARD" =~ ^[0-9]+$ ]] || die "RDB_CUSTOMER_SHARD must be a number"
case "$RDB_CUSTOMER_PASSWORD" in *'"'* | *'\'*) die "the password may not contain a double quote or a backslash" ;; esac

# The token and the password go through files and standard input, never the
# command line.
header="$(mktemp)"
trap 'rm -f "$header"' EXIT
chmod 600 "$header"
printf 'Authorization: Bearer %s\n' "$(cat "$RDB_WORK/api.token")" > "$header"
printf '{"database": "%s", "role": "%s", "password": "%s", "shard": %s}' \
  "$RDB_CUSTOMER" "$RDB_CUSTOMER_ROLE" "$RDB_CUSTOMER_PASSWORD" "$RDB_CUSTOMER_SHARD" \
  | curl --fail-with-body -sS -H @"$header" -H 'Content-Type: application/json' --data-binary @- "$RDB_API/v1/customers"
echo
curl --fail-with-body -sS -H @"$header" "$RDB_API/v1/routes"
echo
echo
echo "The customer connects through the gateway, and lands on shard $RDB_CUSTOMER_SHARD:"
echo "  psql \"postgresql://$RDB_CUSTOMER_ROLE@127.0.0.1:$RDB_GATEWAY_PORT/$RDB_CUSTOMER?sslmode=disable\""
add-customer.ps1 · Windows (PowerShell)DOWNLOAD ↓
#Requires -Version 5.1
<#
.SYNOPSIS
  RasterizedDB Enterprise: add a customer to the per-user-shard cluster. The
  gateway's configuration API creates the customer's database and login role
  on the chosen shard and pins the login there.
  Needs release 1.1.0 or later.
.DESCRIPTION
  The login role's password comes from $env:RDB_CUSTOMER_PASSWORD, never from
  the command line.
.EXAMPLE
  $env:RDB_CUSTOMER_PASSWORD = 'acme-secret-123'
  .\add-customer.ps1 -Customer acme -Shard 1
#>
[CmdletBinding()]
param(
    # Holds api.token.
    [string]$Work = $(if ($env:RDB_WORK) { $env:RDB_WORK } else { '.\per-user-cluster' }),
    [string]$Api = $(if ($env:RDB_API) { $env:RDB_API } else { 'http://127.0.0.1:6480' }),
    [int]$GatewayPort = $(if ($env:RDB_GATEWAY_PORT) { [int]$env:RDB_GATEWAY_PORT } else { 6432 }),
    # The customer's database.
    [Parameter(Mandatory = $true)][string]$Customer,
    # Its login role; <Customer>_app by default.
    [string]$Role = '',
    # The shard id it lives on.
    [Parameter(Mandatory = $true)][int]$Shard
)
$ErrorActionPreference = 'Stop'

$tokenFile = Join-Path $Work 'api.token'
if (-not (Test-Path -LiteralPath $tokenFile)) { throw "No $tokenFile; run setup.ps1 first, or pass -Work." }
if (-not $env:RDB_CUSTOMER_PASSWORD) { throw 'Set $env:RDB_CUSTOMER_PASSWORD to the password for the login role.' }
if (-not $Role) { $Role = "${Customer}_app" }
foreach ($v in @($Customer, $Role)) {
    if ($v -notmatch '^[A-Za-z][A-Za-z0-9_]{0,62}$') { throw "${v}: start with a letter, then letters, digits and _ (63 at most)." }
}

$headers = @{ Authorization = 'Bearer ' + (Get-Content -LiteralPath $tokenFile -Raw).Trim() }
$body = @{ database = $Customer; role = $Role; password = $env:RDB_CUSTOMER_PASSWORD; shard = $Shard } | ConvertTo-Json -Compress
$made = Invoke-RestMethod -Method Post -Uri "$Api/v1/customers" -Headers $headers -ContentType 'application/json' -Body $body
$made | ConvertTo-Json -Compress | Write-Host
(Invoke-RestMethod -Method Get -Uri "$Api/v1/routes" -Headers $headers) | ConvertTo-Json -Depth 4 | Write-Host

Write-Host ''
Write-Host "The customer connects through the gateway, and lands on shard ${Shard}:"
Write-Host "  psql `"postgresql://$Role@127.0.0.1:$GatewayPort/${Customer}?sslmode=disable`""
✓ page rendered in 201 µs axum + tera + htmx · no other javascript