nomadro/scripts/check-services-pocketbase.py
Eric 499f2d3e26 Ship coffeechat scheduling, notify PB access, and social/admin UI polish for .com.
Document the 2026-11-05 UI/UX upgrade and keep roster/live gates aligned with face-check and presence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 18:19:37 +08:00

99 lines
7.1 KiB
Python

"""Run with the VPS Python venv and PB binary against a disposable empty database."""
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
import json
import os
from pathlib import Path
import secrets
import socket
import subprocess
import sys
import tempfile
import time
from urllib.request import urlopen
from unittest.mock import patch
binary, services = sys.argv[1:3]
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
email, password = 'isolated@example.test', secrets.token_hex(32)
report = []
with tempfile.TemporaryDirectory(prefix='nomadro-pb-check-') as temporary:
directory = Path(temporary)
migration = subprocess.run([binary, 'migrate', 'up', '--dir=' + temporary], capture_output=True, input=b'')
assert migration.returncode == 0 and b'Error:' not in migration.stdout, 'isolated PocketBase schema initialization failed'
setup = subprocess.run([binary, 'admin', 'create', email, password, '--dir=' + temporary], capture_output=True)
assert setup.returncode == 0 and b'Error:' not in setup.stdout, 'isolated PocketBase admin setup failed'
with (directory / 'server.log').open('wb') as log:
process = subprocess.Popen([binary, 'serve', '--http=127.0.0.1:' + str(port), '--dir=' + temporary], stdout=log, stderr=log)
try:
for attempt in range(40):
try:
with urlopen(f'http://127.0.0.1:{port}/api/health', timeout=1) as res:
if res.status == 200: break
except OSError: time.sleep(0.25)
else: raise RuntimeError('isolated PocketBase did not start')
os.environ.update(PB_INTERNAL_URL=f'http://127.0.0.1:{port}', PB_ADMIN_EMAIL=email, PB_ADMIN_PASSWORD=password,
PB_URL=f'http://127.0.0.1:{port}', POCKETBASE_URL=f'http://127.0.0.1:{port}',
POCKETBASE_INTERNAL_URL=f'http://127.0.0.1:{port}', POCKETBASE_EMAIL=email, POCKETBASE_PASSWORD=password,
COFFEE_SEED_DEMO='0', NOTIFY_INTERNAL_TOKEN='isolated-test-token')
sys.path.insert(0, services)
from fastapi import FastAPI
from fastapi.testclient import TestClient
from coffee_svc.routers.api import router as coffee_router
from coffee_svc import store as coffee
from notify_svc.routers.api import router as notify_router
from notify_svc import store as notify
from nomadro_pb import get_pb
assert get_pb().base_url == f'http://127.0.0.1:{port}', 'integration checks must use the isolated server'
# Explicit credentials also support older deployed config loaders.
get_pb().email = email
get_pb().password = password
coffee.init_db(); notify.init_db()
app = FastAPI()
app.include_router(coffee_router, prefix='/api/coffee/v1')
app.include_router(notify_router, prefix='/api/notify/v1')
def valid(response, status=200):
assert response.status_code == status, f'Expected {status}, got {response.status_code}: {response.text[:200]}'
return response.json()
with TestClient(app) as client, patch('social_svc.notify_bridge.notify_coffee_invite'):
host = {'X-Social-Guest-Id': 'isolated-host', 'X-Coffee-Key': 'a' * 64}
guest = {'X-Social-Guest-Id': 'isolated-attendee', 'X-Coffee-Key': 'b' * 64}
valid(client.put('/api/coffee/v1/me', headers=host, json={'name': 'Isolated host', 'timezone': 'America/New_York'}))
valid(client.get('/api/coffee/v1/me', headers=host))
valid(client.put('/api/coffee/v1/me', headers={**host, 'X-Coffee-Key': 'c' * 64}, json={'name': 'Untrusted', 'timezone': 'UTC'}), 403)
valid(client.patch('/api/coffee/v1/hosts/isolated-host/schedule', headers=host, json={'availability': [{'days': ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'], 'startTime': 600, 'endTime': 660}]}))
day = (datetime.now(timezone.utc) + timedelta(days=2)).date().isoformat()
slots_url = '/api/coffee/v1/hosts/isolated-host/event-types/30min/slots?day=' + day
slots = valid(client.get(slots_url))['slots']
assert len(slots) == 2
body = {'username': 'isolated-host', 'event_slug': '30min', 'start': slots[0]['start'], 'attendee_name': 'Isolated attendee'}
with ThreadPoolExecutor(max_workers=4) as pool:
responses = list(pool.map(lambda _: client.post('/api/coffee/v1/bookings', headers=guest, json=body), range(4)))
assert sorted(response.status_code for response in responses) == [200,409,409,409]
booking = next(response.json()['booking'] for response in responses if response.status_code == 200)
assert len(valid(client.get('/api/coffee/v1/bookings', headers=guest))['bookings']) == 1
assert len(valid(client.get('/api/coffee/v1/bookings?host=isolated-host', headers=host))['bookings']) == 1
valid(client.post('/api/coffee/v1/bookings/' + booking['id'] + '/cancel', headers=guest))
assert len(valid(client.get(slots_url))['slots']) == 2
report.append('coffee: real persistence, private ownership, availability, concurrent conflict, list, cancellation')
valid(client.put('/api/notify/v1/subscribers/isolated-attendee/preferences', headers=guest, json={'channels': {'timezone': 'UTC'}}))
valid(client.get('/api/notify/v1/subscribers/isolated-attendee/preferences', headers=guest))
valid(client.post('/api/notify/v1/events/trigger', headers={'X-Notify-Internal-Token': 'isolated-test-token'}, json={'workflow_id': 'welcome', 'subscriber_id': 'isolated-attendee'}))
inbox = valid(client.get('/api/notify/v1/inbox?subscriber_id=isolated-attendee', headers=guest))
assert len(inbox['messages']) == 1
valid(client.post('/api/notify/v1/inbox/read-all', headers=guest, json={'subscriber_id': 'isolated-attendee'}))
valid(client.delete('/api/notify/v1/inbox/' + inbox['messages'][0]['id'], headers=guest))
assert valid(client.get('/api/notify/v1/inbox?subscriber_id=isolated-attendee', headers=guest))['messages'] == []
report.append('notify: real preferences, internal in-app trigger, inbox, mark read, delete')
for name in ['coffee_hosts','coffee_bookings','notify_subscribers','notify_messages']:
schema = get_pb().get_collection(name)
assert all(schema.get(rule) is None for rule in ['listRule','viewRule','createRule','updateRule','deleteRule'])
report.append('PocketBase: private collection rules verified')
finally:
process.terminate()
try: process.wait(timeout=10)
except subprocess.TimeoutExpired: process.kill(); process.wait(timeout=5)
print(json.dumps({'passed': True, 'checks': report, 'productionDataWritten': False}))