# 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.
#
#   curl -fsSL https://pgrebac.com/quickstart.yml | docker compose -f - run --rm demo
#   curl -fsSL https://pgrebac.com/quickstart.yml | docker compose -f - 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.0
# SQL SHA-256: 653b7d663999df21305ff98daed3f6816c32cc23beed8111908b9fd478b82f98
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.0/pg_rebac--0.3.0.sql && echo '653b7d663999df21305ff98daed3f6816c32cc23beed8111908b9fd478b82f98  /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.0
    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: "curl -fsSL https://pgrebac.com/quickstart.yml | docker compose -f - down -v"
    configs:
      - { source: demo.sh, target: /quickstart/demo.sh }
      - { source: seed.sql, target: /quickstart/seed.sql }
      - { source: demo.sql, target: /quickstart/demo.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.
      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

      psql "$$DB" -v ON_ERROR_STOP=1 -q -P footer=off -f /quickstart/demo.sql
  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;
  demo.sql:
    content: |
      -- The demo: one vector search, two people, what filtering after retrieval would have done instead, and a revocation.
      \set QUIET on
      \pset footer off
      set rebac.tenant = 'acme';
      -- The embedding of the query "salary pay review", in the seed's three dimensions (pay, sales, policy).
      \set q '''[1, 0.05, 0.2]'''

      \echo
      \echo '1. The same vector search, top 5 nearest to "salary pay review", fenced inside the query:'
      \echo
      \echo '   as alice (reads handbook and payroll)'
      -- rebac.fenced_ids picks the path for the reader's breadth: below exact_below_rows candidate rows (every reader
      -- here) an exact sort, above it the fenced HNSW scan. Either way it returns k rows the reader may read, or raises.
      select p.container, p.title
      from rebac.fenced_ids('alice', 'passage', :q::vector, 5) f
      join passage p on p.id::text = f.id
      order by f.distance;

      \echo '   as bob (reads handbook and deals)'
      select p.container, p.title
      from rebac.fenced_ids('bob', 'passage', :q::vector, 5) f
      join passage p on p.id::text = f.id
      order by f.distance;

      \echo '2. Filtering AFTER retrieval instead: take the top 5 for everyone, then drop what bob may not read.'
      \echo '   Passages bob cannot read (board) take 4 of the 5 places. bob asked for 5 rows and gets back:'
      \echo
      select count(*) as rows_left_for_bob
      from (select p.container from passage p order by p.embedding <=> :q limit 5) top5
      where top5.container in (select * from rebac.readable_set('bob'));

      \echo '3. Revoke bob from deals. The revocation is in force when its transaction commits, before rebacd relays it:'
      \echo
      begin;
      set local rebac.tenant = 'acme';
      select rebac.write('delete', 'container:acme/deals', 'member', 'user:acme/bob') \g /dev/null
      commit;
      \echo '   bob, the same search again'
      select p.container, p.title
      from rebac.fenced_ids('bob', 'passage', :q::vector, 5) f
      join passage p on p.id::text = f.id
      order by f.distance;

      \echo '4. A principal nobody has asked about is an error (RB404), never an empty set:'
      \echo
      -- The demo catches the error to print it as one line; an application sees it raised (SQLSTATE RB404).
      do $$$$
      begin
        perform * from rebac.readable_set('mallory');
        perform set_config('demo.mallory', 'returned a set (unexpected)', false);
      exception when sqlstate 'RB404' then
        perform set_config('demo.mallory', sqlstate || ' "' || replace(sqlerrm, 'rebac: ', '') || '"', false);
      end $$$$;
      select current_setting('demo.mallory') as mallory \gset
      \echo '   mallory →' :mallory
      \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).
      \getenv down QUICKSTART_DOWN
      \echo ' ' :down
      \echo 'Docs: https://pgrebac.com/docs/getting-started/'
