# pg_rebac in one command: Postgres with pgvector, SpiceDB, the rebacd daemon, and a demo that runs one vector search
# as two people, then revokes one of them.
#
#   docker compose -f <(curl -fsSL https://pgrebac.com/quickstart.yml) run --rm demo
#   docker compose -f <(curl -fsSL https://pgrebac.com/quickstart.yml) down -v  # stop it and forget everything
#
# Nothing listens on the host. The SpiceDB key and the Postgres password are throwaway values for this demo only.
# Generated by examples/quickstart/bundle.sh in github.com/louvain-ai/pg_rebac; edit the files there, not this one.
# pg_rebac version: 0.3.1
# SQL SHA-256: 1440494594527b87ad12e44f849dcd5b8947659abd9586e646b3e30ad22764f4
name: pg_rebac_quickstart
services:
  postgres:
    image: pgvector/pgvector:pg17
    environment:
      POSTGRES_PASSWORD: quickstart
    healthcheck:
      test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "postgres"]
      interval: 1s
      retries: 30

  spicedb:
    image: authzed/spicedb:v1.56.2
    command: ["serve", "--grpc-preshared-key", "quickstart-key", "--datastore-engine", "memory",
              "--datastore-bootstrap-files", "/quickstart/spicedb.yaml"]
    configs: [{ source: spicedb.yaml, target: /quickstart/spicedb.yaml }]
    healthcheck:
      test: ["CMD", "grpc_health_probe", "-addr=:50051"]
      interval: 1s
      retries: 30

  # The release's SQL, checked against its SHA-256 before anything installs it.
  download:
    image: curlimages/curl:8.17.0
    user: root
    volumes: ["sql:/sql"]
    entrypoint: ["sh", "-c", "curl -fsSL -o /sql/rebac.sql https://github.com/louvain-ai/pg_rebac/releases/download/v0.3.1/pg_rebac--0.3.1.sql && echo '1440494594527b87ad12e44f849dcd5b8947659abd9586e646b3e30ad22764f4  /sql/rebac.sql' | sha256sum -c -s"]

  # Installs the SQL, exactly as you would on your own Postgres: psql -f rebac.sql.
  schema:
    image: pgvector/pgvector:pg17
    depends_on:
      postgres: { condition: service_healthy }
      download: { condition: service_completed_successfully }
    environment:
      PGOPTIONS: "-c client_min_messages=warning"
    volumes: ["sql:/sql:ro"]
    entrypoint: ["psql", "-v", "ON_ERROR_STOP=1", "-q", "postgres://postgres:quickstart@postgres/postgres",
                 "-f", "/sql/rebac.sql"]

  rebacd:
    image: ghcr.io/louvain-ai/rebacd:0.3.1
    depends_on:
      schema: { condition: service_completed_successfully }
      spicedb: { condition: service_healthy }
    environment:
      DATABASE_URL: postgres://postgres:quickstart@postgres/postgres
      SPICEDB_TOKEN: quickstart-key
    configs: [{ source: rebac.toml, target: /etc/rebac.toml }]
    command: ["--config", "/etc/rebac.toml", "run", "--accept-schema"]

  demo:
    image: pgvector/pgvector:pg17
    depends_on:
      rebacd: { condition: service_started }
    environment:
      DB: postgres://postgres:quickstart@postgres/postgres
      PGOPTIONS: "-c client_min_messages=warning"
      QUICKSTART_DOWN: "docker compose -f <(curl -fsSL https://pgrebac.com/quickstart.yml) down -v"
      NO_COLOR: ${NO_COLOR:-}
    configs:
      - { source: demo.sh, target: /quickstart/demo.sh }
      - { source: seed.sql, target: /quickstart/seed.sql }
    entrypoint: ["bash", "/quickstart/demo.sh"]

volumes:
  sql: {}

configs:
  spicedb.yaml:
    content: |
      # The SpiceDB schema the quickstart's daemon derives its closure from. Loaded at start into an in-memory datastore.
      # Relationships are not here: the seed writes them through rebac.write, as an application would.
      schema: |-
        definition user {}

        definition group {
          relation member: user
        }

        definition container {
          relation member: user | group#member
          permission view = member
        }
      relationships: ""
  rebac.toml:
    content: |
      # rebacd for the quickstart: reach SpiceDB by its compose name, listen inside the compose network only.
      spicedb_endpoint = "http://spicedb:50051"
      listen = "0.0.0.0:7341"
  demo.sh:
    content: |
      #!/usr/bin/env bash
      # Seed, wait until rebacd has relayed the relationships to SpiceDB and projected both people, then run the demo: one
      # vector search as two people, what filtering after retrieval would have done instead, a revocation and an unknown
      # principal. Each step prints the SQL it runs, then psql's result; the printed text is the string psql is given.
      set -euo pipefail
      q() { psql "$$DB" -v ON_ERROR_STOP=1 -qAt "$$@"; }

      q -f /quickstart/seed.sql >/dev/null

      echo "Waiting for rebacd to relay the relationships to SpiceDB and project alice and bob..."
      # Ready means the reads the demo makes succeed: both people projected, and the daemon live (heartbeating).
      want="alice:handbook,payroll bob:deals,handbook"
      ready=""
      for _ in $$(seq 1 90); do
        ready=$$(q -c "set rebac.tenant = 'acme'" -c "select string_agg(who || ':' || cs, ' ' order by who) from (
                        select who, (select string_agg(c, ',' order by c) from rebac.readable_set(who) c) as cs
                        from unnest(array['alice', 'bob']) who) x" 2>/dev/null) || ready=""
        [ "$$ready" = "$$want" ] && break
        sleep 1
      done
      if [ "$$ready" != "$$want" ]; then
        echo "rebacd did not project alice and bob within 90 s; see the rebacd service's logs (docker compose ... logs rebacd)" >&2
        exit 1
      fi

      # Colour only on a terminal, and never with NO_COLOR set (https://no-color.org): comments dim, keywords bold, the
      # rebac call in cyan.
      if [ -t 1 ] && [ -z "$${NO_COLOR:-}" ]; then
        show() {
          sed -E -e $$'/^--/{s/.*/\e[2m&\e[0m/;b\n}' \
            -e $$'s/\\b(select|from|join|on|where|in|order by|limit|set|begin|commit)\\b/\e[1m&\e[0m/g' \
            -e $$'s/rebac\\.[a-z_]+\\([^)]*\\)/\e[1;36m&\e[0m/g'
        }
      else
        show() { cat; }
      fi

      # Every step is its own session, and opens with the tenant it reads in.
      tenant="set rebac.tenant = 'acme';"
      # One step: print the SQL on stdin, then run that same string. Extra arguments go to psql.
      step() {
        local sql
        sql="$$(cat)"
        printf '%s\n' "$$sql" | show
        psql "$$DB" -X -q -v ON_ERROR_STOP=1 -c "$$tenant" -c "$$sql" "$$@"
      }

      # The query "salary pay review", embedded in the seed's three dimensions (pay, sales, policy).
      v="'[1,0.05,0.2]'::vector"
      search() {
        cat <<SQL
      select p.container, p.title
      from rebac.fenced_ids('$$1', 'passage', $$v, 5) f
      join passage p on p.id = f.id::bigint
      order by f.distance;
      SQL
      }

      echo
      printf '%s\n' "-- Each step below runs in its own session, which first sets its tenant:" "$$tenant" | show
      echo
      step <<SQL
      -- 1. One vector search, fenced inside the query: the 5 nearest passages alice may read.
      $$(search alice)
      SQL
      step <<SQL
      -- The same search as bob: different rows, still 5.
      $$(search bob)
      SQL
      step <<SQL
      -- 2. Filtering after retrieval instead: the top 5 for everyone, then drop what bob may not read.
      --    Board passages, which bob cannot read, took 4 of the 5 places.
      select p.container, p.title
      from (select container, title from passage
            order by embedding <=> $$v limit 5) p
      where p.container in (select * from rebac.readable_set('bob'));
      SQL
      # rebac.write returns the outbox sequence number it wrote, which says nothing here.
      step -o /dev/null <<SQL
      -- 3. Revoke bob from deals. The revocation is in force when this transaction commits,
      --    before rebacd has relayed it to SpiceDB.
      begin;
      select rebac.write('delete', 'container:acme/deals', 'member', 'user:acme/bob');
      commit;
      SQL
      echo
      step <<SQL
      -- bob, the same search straight after the commit: no deals.
      $$(search bob)
      SQL
      # The error is the result: verbose names its SQLSTATE; the source location in pl_exec.c is left out.
      if out="$$(step -v VERBOSITY=verbose -v SHOW_CONTEXT=never 2>&1 <<SQL
      -- 4. A principal nobody has asked about is an error, never an empty set.
      select * from rebac.readable_set('mallory');
      SQL
      )"; then
        printf '%s\n' "$$out"
        echo "mallory's read returned a set; it must be RB404" >&2
        exit 1
      fi
      grep -v '^LOCATION:' <<< "$$out"
      grep -q '^ERROR:  RB404:' <<< "$$out" || { echo "mallory's read failed, but not with RB404" >&2; exit 1; }

      echo
      echo 'You just saw one vector search return different rows per person, fenced inside the query, and a revocation'
      echo 'in force at commit. Stop it and forget everything:'
      # How this run is stopped: the served file and a clone's compose file each say (QUICKSTART_DOWN).
      echo "  $$QUICKSTART_DOWN"
      echo 'Docs: https://pgrebac.com/docs/getting-started/'
  seed.sql:
    content: |
      -- The sample dataset: one tenant (acme), four containers, seventeen passages, two people.
      --   handbook   everyone, through the group all-staff
      --   payroll    alice, directly
      --   deals      bob, directly
      --   board      neither of them (and the most passages about pay)
      -- Every relationship goes through rebac.write, in an ordinary transaction, as an application would write it.
      -- The embeddings are three numbers each (pay, sales, policy), written by hand so the demo needs no model; a real
      -- table holds a model's vectors, and the fence is the same.

      create extension if not exists vector;

      create table if not exists passage (
        id        int primary key,
        container text not null,
        title     text not null,
        body      text not null,
        embedding vector(3) not null
      );
      create index if not exists passage_container_idx on passage (container);
      create index if not exists passage_embedding_idx on passage using hnsw (embedding vector_cosine_ops);

      insert into passage (id, container, title, body, embedding) values
        (1,  'handbook', 'Pay days',              'Salaries are paid on the last working day of each month.', '[0.90,0.10,0.45]'),
        (2,  'handbook', 'Annual pay review',      'Every salary is reviewed once a year, in March.', '[0.97,0.05,0.21]'),
        (3,  'handbook', 'Expenses',              'Claim expenses within thirty days with a receipt.', '[0.20,0.10,0.95]'),
        (4,  'payroll',  'Salary bands 2026',      'Engineering salary bands rise by four percent in the March pay review.', '[0.92,0.05,0.30]'),
        (5,  'payroll',  'Payroll cut-off',        'Changes to salary must reach payroll by the 20th.', '[0.85,0.10,0.50]'),
        (6,  'deals',    'Kestrel renewal',      'The renewal discount is capped at ten percent; pay terms stay at thirty days.', '[0.30,0.90,0.20]'),
        (7,  'deals',    'Commission plan',        'Sales commission is paid quarterly on salary plus bonus.', '[0.70,0.60,0.10]'),
        (8,  'board',    'CEO salary review',      'The board approved the CEO salary and pay review for 2026.', '[0.99,0.01,0.10]'),
        (9,  'board',    'Executive pay',          'Executive pay and salary increases are set by the remuneration committee.', '[0.98,0.05,0.12]'),
        (10, 'board',    'Pay review budget',      'The pay review budget for salary rises is capped at five percent.', '[0.97,0.02,0.18]'),
        (11, 'board',    'Salary benchmark',       'The salary benchmark compares executive pay with ten peers.', '[0.90,0.15,0.30]'),
        (12, 'board',    'Bonus pool',             'The bonus pool is twelve percent of salary and pay.', '[0.85,0.25,0.20]'),
        (13, 'board',    'Pay ratio',              'The pay ratio of CEO salary to median salary is reported annually.', '[0.92,0.00,0.33]'),
        (14, 'board',    'Remuneration minutes',   'Minutes: salary, pay review, and pay ratio for the executive team.', '[0.96,0.05,0.25]'),
        (15, 'board',    'Severance terms',        'Severance pay is six months of salary.', '[0.80,0.00,0.55]'),
        (16, 'payroll',  'Overtime pay',           'Overtime is paid at one and a half times the hourly salary rate.', '[0.80,0.10,0.55]'),
        (17, 'deals',    'Reseller pay terms',     'Resellers are paid within forty-five days; the review is yearly.', '[0.50,0.80,0.20]')
      on conflict (id) do nothing;

      -- Touched on every run (a touch is idempotent), so a run after the demo's revocation starts from the same grants.
      begin;
      set local rebac.tenant = 'acme';
      select rebac.write('touch', 'group:acme/all-staff',   'member', 'user:acme/alice');
      select rebac.write('touch', 'group:acme/all-staff',   'member', 'user:acme/bob');
      select rebac.write('touch', 'container:acme/handbook', 'member', 'group:acme/all-staff#member');
      select rebac.write('touch', 'container:acme/payroll',  'member', 'user:acme/alice');
      select rebac.write('touch', 'container:acme/deals',    'member', 'user:acme/bob');
      commit;
