Spaces:
Sleeping
Sleeping
Enhance Docker setup with Swagger UI and proxy integration; update database schema for chat history management
Browse filesFiles changed (5)
- Dockerfile+10-1
- init.sql+47-15
- migrations/0001_chat_history.sqlAdded+74
- proxy.pyAdded+123
- start.sh+5-2
19 unmodified lines20212223242512 unmodified lines3839404142435 unmodified lines4950515253545519 unmodified linespostgresql-client \sudo \xz-utils \&& rm -rf /var/lib/apt/lists/*# --- PostgREST binary (static build from GitHub releases) ---12 unmodified lines&& rm /tmp/postgrest.tar.xz \&& postgrest --version# --- Non-root user (HF Spaces runs containers as a random UID) ---RUN useradd -m -u 10001 appuser \&& mkdir -p /var/lib/postgresql/data /var/run/postgresql \5 unmodified lines# --- Sample schema: a tiny "todos" API to demo PostgREST ---COPY --chown=appuser:appuser init.sql /docker-entrypoint-init.d/init.sqlCOPY --chown=appuser:appuser start.sh /usr/local/bin/start.shRUN chmod +x /usr/local/bin/start.shEXPOSE 786019 unmodified lines2021222324252612 unmodified lines394041424344454647484950515 unmodified lines575859606162636419 unmodified linespostgresql-client \sudo \xz-utils \python3 \&& rm -rf /var/lib/apt/lists/*# --- PostgREST binary (static build from GitHub releases) ---12 unmodified lines&& rm /tmp/postgrest.tar.xz \&& postgrest --version# --- Swagger UI static files (served at /docs by proxy.py) ---RUN curl -fsSL "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.32.15.tgz" \-o /tmp/swagger-ui.tgz \&& mkdir -p /opt/swagger-ui \&& tar -xzf /tmp/swagger-ui.tgz -C /opt/swagger-ui --strip-components=1 \&& rm /tmp/swagger-ui.tgz# --- Non-root user (HF Spaces runs containers as a random UID) ---RUN useradd -m -u 10001 appuser \&& mkdir -p /var/lib/postgresql/data /var/run/postgresql \5 unmodified lines# --- Sample schema: a tiny "todos" API to demo PostgREST ---COPY --chown=appuser:appuser init.sql /docker-entrypoint-init.d/init.sqlCOPY --chown=appuser:appuser start.sh /usr/local/bin/start.shCOPY --chown=appuser:appuser proxy.py /usr/local/bin/proxy.pyRUN chmod +x /usr/local/bin/start.sh /usr/local/bin/proxy.pyEXPOSE 7860
12345 unmodified lines10111213141516171819202122232425262728293031323334353637383940411 unmodified line4344454647-- Schema + roles for PostgREST, executed once at container startup.-- Role PostgREST connects as (anonymous / public access)CREATE ROLE web_anon LOGIN NOINHERIT;5 unmodified linesCREATE SCHEMA api;GRANT USAGE ON SCHEMA api TO web_anon;CREATE TABLE api.todos (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,done boolean NOT NULL DEFAULT false,task text NOT NULL,due timestamptz,created_at timestamptz NOT NULL DEFAULT now());-- Change ownership BEFORE granting: ALTER TABLE ... OWNER TO drops-- privileges granted by the previous owner.ALTER TABLE api.todos OWNER TO authenticator;GRANT SELECT, INSERT, UPDATE, DELETE ON api.todos TO web_anon;GRANT USAGE, SELECT ON SEQUENCE api.todos_id_seq TO web_anon;INSERT INTO api.todos (task, due) VALUES('Try GET /todos', now() + interval '1 day'),('Try POST /todos', now() + interval '2 days'),('Try PATCH /todos?id=eq.1', now() + interval '3 days');-- Expose row counts in Content-Range headersCREATE OR REPLACE FUNCTION api.todos_count()RETURNS bigintLANGUAGE sqlAS $$SELECT count(*) FROM api.todos;$$;-- OpenAPI description endpoint1 unmodified lineRETURNS textLANGUAGE sqlAS $$SELECT 'A demo PostgREST API running on Hugging Face Spaces';$$;1234565 unmodified lines12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172731 unmodified line7576777879-- Schema + roles for PostgREST, executed once at container startup.-- Model: chat history (conversations -> messages).-- (Mirrors migrations/0001_chat_history.sql)-- Role PostgREST connects as (anonymous / public access)CREATE ROLE web_anon LOGIN NOINHERIT;5 unmodified linesCREATE SCHEMA api;GRANT USAGE ON SCHEMA api TO web_anon;-- authenticator owns the tables, so foreign-key checks (which run as the-- table owner) need USAGE on the schema too. NOINHERIT means it does NOT-- inherit web_anon's grants.GRANT USAGE ON SCHEMA api TO authenticator;-- One conversation (a chat thread)CREATE TABLE api.chats (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,title text NOT NULL,created_at timestamptz NOT NULL DEFAULT now());-- Messages belonging to a conversationCREATE TABLE api.messages (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,chat_id bigint NOT NULL REFERENCES api.chats (id) ON DELETE CASCADE,role text NOT NULL CHECK (role IN ('user', 'assistant', 'system')),content text NOT NULL,created_at timestamptz NOT NULL DEFAULT now());CREATE INDEX messages_chat_id_idx ON api.messages (chat_id);-- Change ownership BEFORE granting: ALTER TABLE ... OWNER TO drops-- privileges granted by the previous owner.ALTER TABLE api.chats OWNER TO authenticator;ALTER TABLE api.messages OWNER TO authenticator;GRANT SELECT, INSERT, UPDATE, DELETE ON api.chats TO web_anon;GRANT SELECT, INSERT, UPDATE, DELETE ON api.messages TO web_anon;GRANT USAGE, SELECT ON SEQUENCE api.chats_id_seq TO web_anon;GRANT USAGE, SELECT ON SEQUENCE api.messages_id_seq TO web_anon;INSERT INTO api.chats (title) VALUES('Getting started'),('PostgREST questions');INSERT INTO api.messages (chat_id, role, content) VALUES(1, 'user', 'How do I list all chats?'),(1, 'assistant', 'GET /chats — or GET /chats?select=*,messages(*) to embed messages.'),(2, 'user', 'How do I add a message to chat 1?'),(2, 'assistant', 'POST /messages with {"chat_id": 1, "role": "user", "content": "..."}');-- Row counts for Content-Range headersCREATE OR REPLACE FUNCTION api.chats_count()RETURNS bigintLANGUAGE sqlAS $$SELECT count(*) FROM api.chats;$$;CREATE OR REPLACE FUNCTION api.messages_count()RETURNS bigintLANGUAGE sqlAS $$SELECT count(*) FROM api.messages;$$;-- OpenAPI description endpoint1 unmodified lineRETURNS textLANGUAGE sqlAS $$SELECT 'A demo PostgREST chat-history API running on Hugging Face Spaces';$$;
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374-- Schema + roles for PostgREST, executed once at container startup.-- Model: chat history (conversations -> messages).
-- Role PostgREST connects as (anonymous / public access)CREATE ROLE web_anon LOGIN NOINHERIT;
-- Role used to apply schema changes. Password comes from start.sh-- via psql variable `auth_pw` (sourced from AUTHENTICATOR_PASSWORD).CREATE ROLE authenticator NOINHERIT LOGIN PASSWORD :'auth_pw';GRANT web_anon TO authenticator;
CREATE SCHEMA api;GRANT USAGE ON SCHEMA api TO web_anon;
-- One conversation (a chat thread)CREATE TABLE api.chats ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title text NOT NULL, created_at timestamptz NOT NULL DEFAULT now());
-- Messages belonging to a conversationCREATE TABLE api.messages ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, chat_id bigint NOT NULL REFERENCES api.chats (id) ON DELETE CASCADE, role text NOT NULL CHECK (role IN ('user', 'assistant', 'system')), content text NOT NULL, created_at timestamptz NOT NULL DEFAULT now());
CREATE INDEX messages_chat_id_idx ON api.messages (chat_id);
-- Change ownership BEFORE granting: ALTER TABLE ... OWNER TO drops-- privileges granted by the previous owner.ALTER TABLE api.chats OWNER TO authenticator;ALTER TABLE api.messages OWNER TO authenticator;
GRANT SELECT, INSERT, UPDATE, DELETE ON api.chats TO web_anon;GRANT SELECT, INSERT, UPDATE, DELETE ON api.messages TO web_anon;GRANT USAGE, SELECT ON SEQUENCE api.chats_id_seq TO web_anon;GRANT USAGE, SELECT ON SEQUENCE api.messages_id_seq TO web_anon;
INSERT INTO api.chats (title) VALUES ('Getting started'), ('PostgREST questions');
INSERT INTO api.messages (chat_id, role, content) VALUES (1, 'user', 'How do I list all chats?'), (1, 'assistant', 'GET /chats — or GET /chats?select=*,messages(*) to embed messages.'), (2, 'user', 'How do I add a message to chat 1?'), (2, 'assistant', 'POST /messages with {"chat_id": 1, "role": "user", "content": "..."}');
-- Row counts for Content-Range headersCREATE OR REPLACE FUNCTION api.chats_count()RETURNS bigintLANGUAGE sqlAS $$ SELECT count(*) FROM api.chats;$$;
CREATE OR REPLACE FUNCTION api.messages_count()RETURNS bigintLANGUAGE sqlAS $$ SELECT count(*) FROM api.messages;$$;
-- OpenAPI description endpointCREATE OR REPLACE FUNCTION api.openapi_description()RETURNS textLANGUAGE sqlAS $$ SELECT 'A demo PostgREST chat-history API running on Hugging Face Spaces';$$;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123#!/usr/bin/env python3"""Tiny reverse proxy in front of PostgREST.
- /docs -> Swagger UI (static files from /opt/swagger-ui)- /docs/openapi.json -> OpenAPI spec fetched from PostgREST- everything else -> proxied verbatim to PostgREST on 127.0.0.1:$PGRST_PORT
Uses only the Python standard library. Runs as the same non-root user."""
import jsonimport osimport urllib.requestfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
SWAGGER_DIR = "/opt/swagger-ui"UPSTREAM = f"http://127.0.0.1:{os.environ.get('PGRST_PORT', '3000')}"LISTEN_PORT = int(os.environ.get("PORT", "7860"))
# Swagger UI page that loads /docs/openapi.jsonINDEX_HTML = """<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>PostgREST API Docs</title> <link rel="stylesheet" href="/docs/swagger-ui.css"></head><body> <div id="swagger-ui"></div> <script src="/docs/swagger-ui-bundle.js" charset="UTF-8"></script> <script> window.onload = () => { SwaggerUIBundle({ url: "/docs/openapi.json", dom_id: "#swagger-ui", deepLinking: true, }); }; </script></body></html>"""
class Handler(SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): # Serve static Swagger UI files from SWAGGER_DIR super().__init__(*args, directory=SWAGGER_DIR, **kwargs)
# --- /docs routes ----------------------------------------------------- def _send(self, code, body, ctype): self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(body)
# --- proxying --------------------------------------------------------- def _proxy(self): url = UPSTREAM + self.path req = urllib.request.Request(url, method=self.command) for h in ("Content-Type", "Accept", "Prefer", "Range", "If-Match", "Authorization"): if v := self.headers.get(h): req.add_header(h, v) length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length) if length else None
try: with urllib.request.urlopen(req, body) as r: resp, code, rheaders = r.read(), r.status, r.headers except urllib.error.HTTPError as e: resp, code, rheaders = e.read(), e.code, e.headers except Exception as e: # URLError, timeout, upstream down, ... print(f"proxy error: {self.command} {self.path}: {e!r}", flush=True) resp = json.dumps({"message": str(e)}).encode() code, rheaders = 502, {"Content-Type": "application/json"}
self.send_response(code) for h in ("Content-Type", "Content-Range", "Content-Location", "Location", "ETag", "Preference-Applied", "Accept-Profile", "Content-Profile"): if v := rheaders.get(h): self.send_header(h, v) self.send_header("Content-Length", str(len(resp))) self.end_headers() self.wfile.write(resp)
def do_GET(self): if self.path == "/docs" or self.path.startswith("/docs?"): self._send(200, INDEX_HTML.encode(), "text/html; charset=utf-8") elif self.path == "/docs/openapi.json": # Fetch the spec and rewrite its host so "Try it out" requests # hit the public origin instead of PostgREST's internal port import json spec = json.loads(urllib.request.urlopen(f"{UPSTREAM}/").read()) spec["host"] = self.headers.get("Host") or f"localhost:{LISTEN_PORT}" spec["schemes"] = ["https"] if self.headers.get( "X-Forwarded-Proto") == "https" else ["http"] body = json.dumps(spec).encode() self._send(200, body, "application/openapi+json") elif self.path.startswith("/docs/"): # static assets: strip the /docs prefix self.path = self.path[len("/docs"):] super().do_GET() else: self._proxy()
def do_HEAD(self): self.do_GET()
def _proxy_with_body(self): self._proxy()
do_POST = do_PATCH = do_PUT = do_DELETE = do_OPTIONS = _proxy_with_body
def log_message(self, fmt, *args): print("%s - %s" % (self.address_string(), fmt % args), flush=True)
if __name__ == "__main__": ThreadingHTTPServer(("0.0.0.0", LISTEN_PORT), Handler).serve_forever()42 unmodified lines434445464748493 unmodified lines5354555642 unmodified linesexport PGRST_DB_URI="postgresql://authenticator:${AUTHENTICATOR_PASSWORD:-secret}@/postgres?host=$SOCKET_DIR&port=5432"export PGRST_DB_SCHEMA="${PGRST_DB_SCHEMA:-api}"export PGRST_DB_ANON_ROLE="${PGRST_DB_ANON_ROLE:-web_anon}"export PGRST_SERVER_PORT="${PORT:-7860}"# PGRST_JWT_ROLE_CLAIM_KEY must be a JSON path (".role", ".payload.role",# '."https://example.com/role"' or "[\"role\"]"). A bare value like "role"3 unmodified linesexport PGRST_JWT_ROLE_CLAIM_KEY=".$PGRST_JWT_ROLE_CLAIM_KEY"fiexec postgrest42 unmodified lines434445464748493 unmodified lines5354555657585942 unmodified linesexport PGRST_DB_URI="postgresql://authenticator:${AUTHENTICATOR_PASSWORD:-secret}@/postgres?host=$SOCKET_DIR&port=5432"export PGRST_DB_SCHEMA="${PGRST_DB_SCHEMA:-api}"export PGRST_DB_ANON_ROLE="${PGRST_DB_ANON_ROLE:-web_anon}"export PGRST_SERVER_PORT="${PGRST_PORT:-3000}"# PGRST_JWT_ROLE_CLAIM_KEY must be a JSON path (".role", ".payload.role",# '."https://example.com/role"' or "[\"role\"]"). A bare value like "role"3 unmodified linesexport PGRST_JWT_ROLE_CLAIM_KEY=".$PGRST_JWT_ROLE_CLAIM_KEY"fi# PostgREST listens on the internal port; the proxy serves it (plus# Swagger UI at /docs) on the public $PORT.postgrest &exec python3 /usr/local/bin/proxy.py
Dockerfile+10-1
init.sql+47-15
migrations/0001_chat_history.sqlAdded+74
proxy.pyAdded+123
start.sh+5-2