Files
Convivo/docs/backend/sidecar.md
T
Lago d24f0ebb88 docs: close round-2 doc gaps — sidecar route table, printing points note, deployment markers, releases index
- sidecar.md HTTP API table now lists the LLM routes (/llm-settings GET/PUT,
  /llm-test, /feedback-summary) it had silently omitted; points at
  feedback-ai.md for contracts
- printing.md: welcome_checkin gained points/points_awarded (+10 on the first
  check-in, same branch as the badge loop; popup promises the award only when
  points_awarded)
- deployment.md: the 2026-10-07 status table is now labelled as that day's
  snapshot with a pointer to releases/ and the current 2026-10-19 bundles,
  migration, backup and rollback tags (old index-Gv3o7AW6/CocPCSGt markers were
  misleading readers about live state)
- new docs/releases/README.md index (7 files existed, docs/README linked only
  one); docs/README.md links it
2026-10-19 22:23:06 +02:00

285 lines
16 KiB
Markdown

# Sidecar — Sessionize sync
The **sidecar** is a small Node HTTP service that syncs an event's agenda from
[Sessionize](https://sessionize.com) into Convivo. It is the only server-side
component that holds the **service-role key**. Sessionize runs on demand from
Admin and automatically for active configured events, initially at startup and
then every 15 minutes. Pretix retains its independent every-minute loop.
- Code: [`apps/sidecar/`](../../apps/sidecar/), HTTP service in
[`src/server.js`](../../apps/sidecar/src/server.js), pure Excel transform in
[`src/transform-excel.js`](../../apps/sidecar/src/transform-excel.js)
- Image: [`apps/sidecar/Dockerfile`](../../apps/sidecar/Dockerfile)
(`node:20-alpine`; runtime dependencies **`xlsx`** (parse the Sessionize Excel
export), **`cheerio`** (parse GridSmart HTML without executing scripts), and
**`pdfkit`** (render the PDF report in the repository's newer server baseline))
- Compose service: `convivo-sidecar` in the root
[`docker-compose.yml`](../../docker-compose.yml) (`:3002`)
- DB side: the `sync_sessionize_event` RPC + `sync_runs` audit table — see
[rpcs.md](./rpcs.md) and [schema.md](./schema.md)
## What it does
The sidecar also provides authenticated, admin-only LLM configuration and manual
feedback summary routes. See [Feedback AI summaries](./feedback-ai.md) for the
provider contract, permissions, limits and privacy requirements.
There are **two import paths**; the source/API path also runs automatically:
**A. API sync** (`POST /run`) — fetches the event's `sessionize_endpoint` and
imports, in order: (1) speakers as contacts (matched by **email**), (2) sessions
(upserted by `external_id`), (3) the agenda/schedule (slots find-or-created by
date/start/end/type + `session_speakers` links). The public `/view/` payload has no
speaker emails, so this path imports sessions + agenda but **skips speakers**
(unless an authenticated `/api/` endpoint + key is configured).
### GridSmart Sources and Polling
The Admin event editor accepts either an HTTPS Sessionize `All` / `GridSmart`
URL or one `<script src="...">` embed. It extracts and stores the URL, never
executes the script, and reports invalid input without saving. The sidecar also
normalizes stored script tags for compatibility. Only the exact
`sessionize.com/api/v2/<id>/view/All` and `.../GridSmart` paths are accepted;
credentials, alternate hosts, ports and HTTP are rejected. Queries and fragments
are removed. Requests have a 30-second timeout and do not follow redirects.
JSON `All` feeds retain their existing transform. For embed responses, the source
reader loads GridSmart HTML using `under=True` and parses stable `data-sessionid`
values, titles, rooms, service/plenum classes and UTC timing attributes. The
loader's explicit event UTC offset converts those times to event-local date/time.
Duplicate rendered cards are deduplicated by ID; conflicting copies, malformed
timings, empty grids, unknown timezones and overnight sessions fail validation.
The grid does not supply email addresses. Existing speaker links, descriptions,
level/area and materials are retained rather than replaced with missing data.
New speaker contacts still require the email-bearing Excel import. Service
sessions receive all event staff. Concurrent service placeholders use separate
service slots instead of being typed as ordinary talks.
Polling selects only active events with a configured source, processes them
sequentially, skips overlapping imports and retries failed sources on the next
pass. Set `SESSIONIZE_SYNC_INTERVAL_MS` in the sidecar container environment to
override the default `900000`; positive values are clamped to at least `60000`,
and `0` disables automatic polling. `/status` reports `sessionizeIntervalMs` and
the last run, including `source_format`. The Admin description reflects the
default interval. Manual Sync remains available for inactive configured events.
Successful imports upsert stable Sessionize IDs; missing entries are not deleted.
Migration `20261011060534_gridsmart_service_identity` also adopts the four
supplemental `manual-service-*` IDs when exactly one service matches the event,
title, date and timing, preserving its session ID and existing links. See the
[deployment record](../releases/2026-10-11.md#gridsmart-automation).
> **Service sessions.** A session is flagged `is_service_session` when
> Sessionize marks it `isServiceSession` **or** `isPlenumSession` (a plenum is a
> full-hall item — breaks, lunch, closing, or a plenary — with no individual
> speaker). The RPC then types its slot `service_session` and links every
> registered **staff** member as a speaker.
**B. Excel import** (`POST /import-excel`) — the admin uploads the Sessionize
`.xlsx` export (generated on the fly by any organizer with admin access to the
event). Supported formats are the legacy **"Sessions and speakers (advanced)"**
export (two sheets: *Accepted sessions* + *Accepted speakers*, with plural
**Speaker Ids**) and the flattened **Accepted sessions and speakers** sheet
(one session/speaker pair per row, with singular **Speaker Id**). The sidecar
parses it and calls the
`sync_sessionize_excel` RPC, which imports, in order: (1) speakers as contacts
(matched by **email** — the Excel carries emails, so this is reliable), (2)
sessions + agenda (slots typed `session` / `service_session` from the
**Session Format** column — `service`/`break`/`lunch`/`closing`/`plenum` →
`service_session` — + `session_speakers` links, with every registered **staff**
member linked as a speaker of service sessions), and (3) **a `speaker`
registration for every speaker** (create, or update `attendee`→`speaker`; never
overrides `staff`/`sponsor`). This is the path that creates the missing speaker
contacts + registrations.
Excel rows are grouped by **Session Id** into one session with all distinct
speaker emails; repeated speakers are emitted once by email. Separate session
and speaker sheets take precedence over a combined sheet if both are present.
Talks without a title, ID, or scheduled time are skipped. Service entries still
require a nonempty title and a positive numeric Excel scheduled time, but may
omit their **Session Id**.
### Services omitted from the accepted-session export
The flattened accepted-session export can omit schedule-only services entirely.
The supplied 2026-10-09 export was checked read-only: one sheet, 25 rows, 23
scheduled rows, 21 importable sessions and **zero service entries**. Its two
excluded scheduled rows have IDs but blank titles and formats; they cannot be
identified as breaks or placeholders. None of the depicted Arrival & Coffee,
Opening Keynote, breaks, Lunch, Coffee or Placeholder entries is recoverable
from this workbook. The importer does not invent titles or fill schedule gaps.
Use the existing **API sync** with an endpoint that actually includes these
service entries, or add their real schedule data to a sheet named **Service
sessions** (trimmed and case-insensitive) in the uploaded workbook. This explicit
sheet is imported alongside either accepted-session format, or on its own. Its
rows are always service sessions; no Session Format is required:
| Header | Value |
|---|---|
| Title | Required actual service title |
| Scheduled At | Required Excel date/time cell (numeric serial, not a date string) |
| Scheduled Duration | Duration in minutes; blank defaults to zero |
| Room | Optional room name |
| Session Id | Optional stable source ID; prefer the actual Sessionize ID when available |
| Description | Optional description |
Alternatively, service rows in the accepted-session sheet can omit Session Id
when **Session Format** matches `service`, `break`, `lunch`, `closing` or
`plenum`. Titles alone do not classify services: a talk mentioning coffee is
not automatically converted.
For ID-less services, the external ID is `excel-service:` plus a SHA-256 digest
of the trimmed title, trimmed room, normalized date and start time. Duplicate
rows merge and repeated imports retain the same identity regardless of row
order, duration or description edits. Changing title, room, date or start time
changes that identity; supply a stable Session Id for entries that may be
renamed or rescheduled. Use the same actual source ID across Excel and API
imports to avoid two identities for the same service. Services use the existing
RPC's service-slot typing and staff assignment; no database migration is needed.
Topic classification uses the first nonempty value of **Themenfeld / Area of
Topic**, **Area**, then **Topic**. Headers are trimmed and matched
case-insensitively; unrelated category headers are not inferred. Values are
trimmed but otherwise preserved as a single string, including comma-separated
topics in their original order. **Level** remains an optional free-text value.
For repeated session rows, the first row supplies session metadata; a later
nonempty topic can fill an initially empty topic, and speaker links are merged.
See [Excel transform tests](./tests.md#sessionize-excel-transform) for the
database-free regression command.
Linking a speaker to a session fires the `session_speakers_speaker_promote`
trigger, which promotes an existing registration to `speaker`.
Both import paths are guarded by the event's configured `start_date` /
`end_date`: any Sessionize session dated outside that inclusive range aborts the
RPC before speakers, sessions, slots, links, registrations, audit rows, or event
sync timestamps are changed. The exception includes the bad date, the configured
range, and the actionable check to verify the Sessionize endpoint, Excel export,
or event dates. Existing historical rows outside the range are retained by later
successful imports; deleting or reconciling them is a separate, explicitly
approved data-repair task.
The date guard lives in
[`20261009225632_guard_sessionize_dates.sql`](../../supabase/migrations/20261009225632_guard_sessionize_dates.sql).
It is not automatically deployed by being present in the repository; apply it
through the normal reviewed migration path for each environment.
## How it reaches things
```mermaid
flowchart LR
ADM["convivo-admin<br/>nginx :3001"] -->|"/sidecar/*"| SC["convivo-sidecar<br/>node :3002"]
SC -->|"service-role key"| K["supabase_kong_Convivo<br/>:8000 (PostgREST)"]
SC -->|"GET (key optional)"| SZ["Sessionize /view/ or /api/"]
K --> PG["Postgres 17"]
```
- **Supabase:** PostgREST at `supabase_kong_Convivo:8000` (Kong's internal port
on the shared network — see [supabase-core.md#ports](./supabase-core.md#ports)),
authenticated with the **service-role key**.
- **Sessionize:** the event's stored `sessionize_endpoint`, normalized and read
as JSON or a non-executed GridSmart embed.
The public `/view/` endpoint needs no key. If `SESSIONIZE_API_KEY` is set it
is sent as the `X-Sessionize-API-Key` header (harmless for `/view/`, required
for an `/api/` endpoint).
> **Key is optional.** The public `/view/` endpoint (the one stored on the
> event) returns sessions, speakers, and rooms **without** speaker email
> addresses. Email is the matching key, so a keyless sync imports sessions +
> agenda but **skips speakers** (reported in `skipped_speakers`). To import
> speakers by email, set `SESSIONIZE_API_KEY` and point the event at the
> authenticated `/api/` endpoint, which returns `email` on each speaker.
## HTTP API
| Method | Path | Body | Returns |
|---|---|---|---|
| `GET` | `/health` | — | `{ ok: true }` (compose healthcheck) |
| `GET` | `/status` | — | `{ ok, running, lastRun, sessionizeIntervalMs, ... }` |
| `POST` | `/run` | `{ event_id }` | **blocking** — the API-sync result (summary + errors) |
| `POST` | `/import-excel` | `multipart/form-data` (`event_id` + `file` = the `.xlsx`) | **blocking** — the Excel-import result (summary + errors) |
| `POST` | `/export` | `{ event_id, format: 'csv' \| 'xlsx' \| 'pdf', tables? }` | **blocking** — `{ filename, mime, content_base64 }` (the event report) |
| `GET` | `/llm-settings` | — | stored LLM settings (never the key itself; `has_api_key` boolean) |
| `PUT` | `/llm-settings` | `{ endpoint, model, api_key? }` | the saved public settings |
| `POST` | `/llm-test` | — | a connection **verdict** (never an exception): `{ ok, model, endpoint, latency_ms, reasoning_disabled, reasoning_tokens, content, warning, error }` |
| `POST` | `/feedback-summary` | `{ scope: 'event', event_id }` or `{ scope: 'session', event_id, session_id }` | the generated summary (stored via service role) |
`/llm-test` runs the SSRF-guarded one-shot request against the **stored**
settings — a bad form state cannot be tested because the key never reaches the
browser. The three-state reasoning verdict (reported 0 / not reported / reported
non-zero) and the redaction rules are in
[Feedback AI summaries](./feedback-ai.md).
`/run` is **blocking**: it reads the event's endpoint, fetches Sessionize,
transforms, calls the RPC, and returns the summary. The admin's "Sync" button and
the Interfaces "Run sync" both call it and show the result inline.
`/import-excel` is **blocking** too: it reads the uploaded `.xlsx` (parsed with
`xlsx`), transforms either supported format into the `sync_sessionize_excel` payload, and
calls that RPC. The admin's Interfaces **"Import Excel"** control posts the file
here and shows the result inline.
`/export` is **blocking** as well: it fetches the event's full dataset
(registrations, check-ins, connections, session feedback, event feedback,
leaderboard, points log — service role, joined for readability) and renders it as
one of three formats:
- **`csv`** — a single combined CSV (a `table` column distinguishes the rows).
- **`xlsx`** — one workbook, one sheet per table (the `tables` array selects
which sheets to include; defaults to all).
- **`pdf`** — a structured post-event report (header, summary, per-session
feedback, top-10 points, event-level feedback comments) rendered with `pdfkit`.
It returns `{ filename, mime, content_base64 }`; the admin's **Reports** view
decodes the base64 and triggers a browser download. Empty tables produce a valid
file with headers only (never an error); an unknown event is a 404.
## Env vars
| Var | Default | Notes |
|---|---|---|
| `SUPABASE_URL` | `http://supabase_kong_Convivo:8000` | Where PostgREST lives |
| `SUPABASE_SERVICE_ROLE_KEY` | standard local service-role JWT | **First server-side holder** of this key (bypasses RLS). Override for a real deployment. |
| `SESSIONIZE_API_KEY` | *(empty)* | **Optional.** Only needed if the endpoint is an authenticated `/api/` URL. Sent as `X-Sessionize-API-Key` when set. |
| `PORT` | `3002` | |
> **Secrets convention:** the anon key ships in the apps (public by design); the
> service-role key is **never in the app** and stays server-side. The sidecar is
> the first consumer of that rule — it holds the key in a container env var,
> defaulting to the standard local key (overridable), mirroring how the anon key
> is defaulted inline in compose. See [rls.md](./rls.md).
## Running
```bash
# With the rest of the stack (recommended)
docker compose up --build # brings up convivo-sidecar on :3002
# Or just the sidecar, against a running core
npm run sidecar:dev # node apps/sidecar/src/server.js (SUPABASE_URL -> 127.0.0.1:54321)
```
The admin app reaches the sidecar through the same-origin `/sidecar/` proxy
(nginx in Docker, Vite in dev) — see [docker.md](./docker.md).
## Verified behavior
- `GET /health` → `{ ok: true }` (direct `:3002` and via `:3001/sidecar/health`).
- `POST /run` against a public `/view/` endpoint (no key) → fetches, transforms,
calls the RPC, and writes sessions/slots (speakers skipped — no emails in the
public payload — reported in `skipped_speakers`).
- `POST /run` with `SESSIONIZE_API_KEY` set + an `/api/` endpoint → speakers
imported by email.
- `POST /run` with a reachable Sessionize endpoint → fetches, transforms, calls
the RPC, and writes contacts/sessions/slots/links (idempotent on re-run).
- `POST /import-excel` with the real "Sessions and speakers (advanced)" export →
creates the speaker contacts, links them to sessions, and creates/updates their
`speaker` registrations (idempotent on re-run). Verified: 21 speakers created,
25 speaker links, 21 speaker registrations, 0 errors.
- `POST /export` for each format against the seeded event → returns a parseable
file: CSV with a `table` column, XLSX with one sheet per table, and a valid
PDF report (verified: CSV ~10 KB, XLSX 7 sheets, PDF `%PDF-1.3`). Unknown
event → 404.