feat: add sidecar service for Sessionize sync
- Introduced a new Node HTTP service (sidecar) to sync event agendas from Sessionize into Convivo. - Implemented two import paths: API sync and Excel import for session and speaker data. - Added necessary database migrations for sessionize integration, including new columns and audit tables. - Created functions for handling speaker and session imports, ensuring proper error handling and logging. - Established row-level security and grants for new functions to restrict access to service-role only. Co-authored-by: Stephan Charles <[email protected]> Co-authored-by: Amelia Hernandez <[email protected]> Co-authored-by: Markus Franz <[email protected]> Co-authored-by: Sabrina Hota <[email protected]> Co-authored-by: Nilüfer Doğan <[email protected]>
This commit is contained in:
1 parent
a0bcf866dc
commit
5f8ded56f6
31 files changed
+2729
-390
No files matched your search
@@ -0,0 +1,23 @@
|
||||
# Convivo sidecar — Sessionize sync (on-demand).
|
||||
#
|
||||
# A small Node HTTP service driven by the APPE Admin "Interfaces" menu. It
|
||||
# fetches an event's Sessionize data (authenticated API) and writes it to
|
||||
# Supabase via the service-role-only sync_sessionize_event RPC.
|
||||
#
|
||||
# It joins the shared Supabase network and reaches PostgREST at
|
||||
# supabase_kong_Convivo:8000 (Kong's internal port). It is the first
|
||||
# server-side holder of the service-role key (see docs/backend/sidecar.md).
|
||||
#
|
||||
# One runtime dependency (xlsx, for parsing the Sessionize .xlsx export).
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json ./
|
||||
RUN npm install --omit=dev
|
||||
COPY src/ ./src/
|
||||
|
||||
ENV NODE_ENV=production
|
||||
EXPOSE 3002
|
||||
|
||||
CMD ["node", "src/server.js"]
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "convivo-sidecar",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Convivo Sessionize sync sidecar (on-demand, driven by APPE Admin).",
|
||||
"main": "src/server.js",
|
||||
"scripts": {
|
||||
"start": "node src/server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"xlsx": "^0.18.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
// Convivo sidecar — Sessionize sync (on-demand).
|
||||
//
|
||||
// A tiny Node HTTP service driven by the APPE Admin "Interfaces" menu.
|
||||
// Endpoints:
|
||||
// GET /health -> { ok: true }
|
||||
// GET /status -> { ok, running, lastRun }
|
||||
// POST /run -> { event_id } (blocking) -> API sync result
|
||||
// POST /import-excel -> { event_id, file_base64, filename? } (blocking)
|
||||
// -> parses the Sessionize "Sessions and speakers
|
||||
// (advanced)" .xlsx and imports it
|
||||
//
|
||||
// Flow for /run:
|
||||
// 1. Read the event's sessionize_endpoint from Supabase (service role).
|
||||
// 2. Fetch it as-is (the public /view/ endpoint needs no key).
|
||||
// 3. If SESSIONIZE_API_KEY is set, send it as X-Sessionize-API-Key
|
||||
// (harmless for /view/, required if the endpoint is an /api/ URL).
|
||||
// 4. Transform the response into the sync_sessionize_event payload.
|
||||
// 5. Call the service-role-only sync_sessionize_event RPC (blocking).
|
||||
// 6. Return the RPC summary (and record it as lastRun).
|
||||
//
|
||||
// Note: the public /view/ payload does NOT include speaker emails, so a
|
||||
// keyless sync imports sessions + agenda but skips speakers (reported in
|
||||
// skipped_speakers). Set SESSIONIZE_API_KEY + an /api/ endpoint to get emails.
|
||||
//
|
||||
// Env:
|
||||
// SUPABASE_URL (default http://supabase_kong_Convivo:8000)
|
||||
// SUPABASE_SERVICE_ROLE_KEY (default = standard local service-role JWT)
|
||||
// SESSIONIZE_API_KEY (optional — only needed for /api/ endpoints)
|
||||
// PORT (default 3002)
|
||||
|
||||
const http = require('http');
|
||||
const XLSX = require('xlsx');
|
||||
|
||||
const SUPABASE_URL = (process.env.SUPABASE_URL || 'http://supabase_kong_Convivo:8000').replace(/\/$/, '');
|
||||
const SERVICE_ROLE_KEY =
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY ||
|
||||
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';
|
||||
const SESSIONIZE_API_KEY = process.env.SESSIONIZE_API_KEY || '';
|
||||
const PORT = parseInt(process.env.PORT || '3002', 10);
|
||||
|
||||
// In-memory last-run state (the sidecar is otherwise stateless).
|
||||
let running = false;
|
||||
let lastRun = null;
|
||||
|
||||
function log(...args) {
|
||||
console.log(new Date().toISOString(), ...args);
|
||||
}
|
||||
|
||||
function json(res, status, body) {
|
||||
res.writeHead(status, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
function readBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let data = '';
|
||||
req.on('data', (c) => {
|
||||
data += c;
|
||||
if (data.length > 10e6) req.destroy(); // 10 MB cap (base64 xlsx uploads)
|
||||
});
|
||||
req.on('end', () => {
|
||||
try {
|
||||
resolve(data ? JSON.parse(data) : {});
|
||||
} catch {
|
||||
reject(new Error('invalid JSON body'));
|
||||
}
|
||||
});
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
// Supabase (PostgREST) helper using the service-role key.
|
||||
async function supabaseFetch(path, { method = 'GET', body } = {}) {
|
||||
const res = await fetch(SUPABASE_URL + path, {
|
||||
method,
|
||||
headers: {
|
||||
apikey: SERVICE_ROLE_KEY,
|
||||
Authorization: `Bearer ${SERVICE_ROLE_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
const text = await res.text();
|
||||
let parsed;
|
||||
try {
|
||||
parsed = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
parsed = text;
|
||||
}
|
||||
if (!res.ok) {
|
||||
const msg = (parsed && (parsed.message || parsed.error || parsed.hint)) || text || res.statusText;
|
||||
throw new Error(`Supabase ${method} ${path} -> ${res.status}: ${msg}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
// Transform the Sessionize API response into the sync_sessionize_event payload.
|
||||
// Speakers are matched by email (the key); speakers without an email are
|
||||
// skipped and reported. Sessions carry their speakers as a list of emails.
|
||||
function transform(data) {
|
||||
const speakerByEmail = new Map();
|
||||
const roomName = new Map();
|
||||
for (const r of data.rooms || []) roomName.set(r.id, r.name);
|
||||
for (const s of data.speakers || []) {
|
||||
if (s.email) speakerByEmail.set(s.id, s.email);
|
||||
}
|
||||
|
||||
const speakers = [];
|
||||
const skippedSpeakers = [];
|
||||
for (const s of data.speakers || []) {
|
||||
if (s.email && s.fullName) {
|
||||
speakers.push({ email: s.email, full_name: s.fullName, external_id: s.id });
|
||||
} else {
|
||||
skippedSpeakers.push(s.fullName || s.id || '<unknown>');
|
||||
}
|
||||
}
|
||||
|
||||
const sessions = [];
|
||||
for (const s of data.sessions || []) {
|
||||
if (!s.id || !s.title || !s.startsAt || !s.endsAt) continue;
|
||||
const speakerEmails = (s.speakers || []).map((id) => speakerByEmail.get(id)).filter(Boolean);
|
||||
sessions.push({
|
||||
external_id: s.id,
|
||||
title: s.title,
|
||||
description: s.description || null,
|
||||
room: roomName.get(s.roomId) || null,
|
||||
date: s.startsAt.slice(0, 10),
|
||||
start_time: s.startsAt.slice(11, 19),
|
||||
end_time: s.endsAt.slice(11, 19),
|
||||
is_service_session: Boolean(s.isServiceSession),
|
||||
speakers: speakerEmails,
|
||||
});
|
||||
}
|
||||
|
||||
return { payload: { speakers, sessions }, skippedSpeakers };
|
||||
}
|
||||
|
||||
// Excel serial date (days since 1899-12-30) -> { date, start_time, end_time }.
|
||||
// Sessionize exports "Scheduled At" as an Excel serial and "Scheduled Duration"
|
||||
// in minutes. The epoch is 1899-12-30 (the Excel 1900 system, incl. its
|
||||
// spurious 1900 leap day, which is irrelevant for modern dates).
|
||||
function excelSerialToTime(serial, durationMin) {
|
||||
const ms = Math.round((serial - 25569) * 86400 * 1000);
|
||||
const d = new Date(ms);
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
const date = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
|
||||
const start = `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`;
|
||||
const endMs = ms + (durationMin || 0) * 60 * 1000;
|
||||
const e = new Date(endMs);
|
||||
const end = `${pad(e.getUTCHours())}:${pad(e.getUTCMinutes())}:${pad(e.getUTCSeconds())}`;
|
||||
return { date, start_time: start, end_time: end };
|
||||
}
|
||||
|
||||
// Transform the Sessionize "Sessions and speakers (advanced)" .xlsx into the
|
||||
// sync_sessionize_excel payload. Two sheets:
|
||||
// "Accepted sessions" -> sessions (Speaker Ids -> emails via the speakers sheet)
|
||||
// "Accepted speakers" -> speakers (matched by email)
|
||||
function transformExcel(buffer) {
|
||||
const wb = XLSX.read(buffer, { type: 'buffer' });
|
||||
const sheetName = (n) => wb.SheetNames.find((s) => s.toLowerCase().includes(n)) || null;
|
||||
const toRows = (name) => {
|
||||
const sn = sheetName(name);
|
||||
if (!sn) return [];
|
||||
return XLSX.utils.sheet_to_json(wb.Sheets[sn], { defval: '' });
|
||||
};
|
||||
|
||||
const speakerRows = toRows('speaker');
|
||||
const sessionRows = toRows('session');
|
||||
|
||||
// Speaker Id -> { email, full_name, linkedin_url }.
|
||||
const speakerById = new Map();
|
||||
const speakers = [];
|
||||
for (const r of speakerRows) {
|
||||
const id = String(r['Speaker Id'] ?? '').trim();
|
||||
const email = String(r['Email'] ?? '').trim();
|
||||
const first = String(r['FirstName'] ?? '').trim();
|
||||
const last = String(r['LastName'] ?? '').trim();
|
||||
const full = [first, last].filter(Boolean).join(' ').trim();
|
||||
if (!id || !email || !full) continue;
|
||||
const linkedin = String(r['LinkedIn'] ?? '').trim() || null;
|
||||
speakerById.set(id, { email, full_name: full, linkedin_url: linkedin });
|
||||
speakers.push({ email, full_name: full, external_id: id, linkedin_url: linkedin });
|
||||
}
|
||||
|
||||
const sessions = [];
|
||||
for (const r of sessionRows) {
|
||||
const id = String(r['Session Id'] ?? '').trim();
|
||||
const title = String(r['Title'] ?? '').trim();
|
||||
const schedAt = Number(r['Scheduled At']);
|
||||
const dur = Number(r['Scheduled Duration']);
|
||||
if (!id || !title || !schedAt) continue;
|
||||
const { date, start_time, end_time } = excelSerialToTime(schedAt, dur);
|
||||
const speakerIds = String(r['Speaker Ids'] ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const speakerEmails = speakerIds.map((sid) => speakerById.get(sid)?.email).filter(Boolean);
|
||||
sessions.push({
|
||||
external_id: id,
|
||||
title,
|
||||
description: String(r['Description'] ?? '').trim() || null,
|
||||
room: String(r['Room'] ?? '').trim() || null,
|
||||
date,
|
||||
start_time,
|
||||
end_time,
|
||||
is_service_session: /service|break|lunch|closing/i.test(String(r['Session Format'] ?? '')),
|
||||
speakers: speakerEmails,
|
||||
});
|
||||
}
|
||||
|
||||
return { payload: { speakers, sessions } };
|
||||
}
|
||||
|
||||
async function runSync(eventId) {
|
||||
if (running) throw new Error('a sync is already running');
|
||||
running = true;
|
||||
const startedAt = new Date().toISOString();
|
||||
log('run: start', { eventId });
|
||||
try {
|
||||
// 1. Read the event's Sessionize endpoint.
|
||||
const events = await supabaseFetch(
|
||||
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=id,name,sessionize_endpoint`,
|
||||
);
|
||||
const event = Array.isArray(events) ? events[0] : null;
|
||||
if (!event) throw new Error('event not found');
|
||||
if (!event.sessionize_endpoint) {
|
||||
throw new Error(`event "${event.name}" has no sessionize_endpoint set`);
|
||||
}
|
||||
|
||||
// 2. Fetch the Sessionize data. The public /view/ endpoint needs no key;
|
||||
// if a key is configured we send it (required for /api/ endpoints).
|
||||
const szUrl = event.sessionize_endpoint.trim();
|
||||
log('run: fetching Sessionize', { szUrl, hasKey: Boolean(SESSIONIZE_API_KEY) });
|
||||
const szHeaders = {};
|
||||
if (SESSIONIZE_API_KEY) szHeaders['X-Sessionize-API-Key'] = SESSIONIZE_API_KEY;
|
||||
const szRes = await fetch(szUrl, { headers: szHeaders });
|
||||
if (!szRes.ok) {
|
||||
const t = await szRes.text();
|
||||
throw new Error(`Sessionize ${szRes.status}: ${t.slice(0, 200)}`);
|
||||
}
|
||||
const szData = await szRes.json();
|
||||
|
||||
// 3. Transform.
|
||||
const { payload, skippedSpeakers } = transform(szData);
|
||||
log('run: transformed', {
|
||||
speakers: payload.speakers.length,
|
||||
sessions: payload.sessions.length,
|
||||
skippedSpeakers: skippedSpeakers.length,
|
||||
});
|
||||
|
||||
// 4. Call the service-role RPC (blocking).
|
||||
const summary = await supabaseFetch('/rest/v1/rpc/sync_sessionize_event', {
|
||||
method: 'POST',
|
||||
body: { p_event_id: event.id, p_payload: payload },
|
||||
});
|
||||
|
||||
const finishedAt = new Date().toISOString();
|
||||
const result = {
|
||||
event_id: event.id,
|
||||
event_name: event.name,
|
||||
started_at: startedAt,
|
||||
finished_at: finishedAt,
|
||||
status: 'success',
|
||||
summary,
|
||||
skipped_speakers: skippedSpeakers,
|
||||
};
|
||||
lastRun = result;
|
||||
log('run: done', { summary });
|
||||
return result;
|
||||
} catch (e) {
|
||||
const finishedAt = new Date().toISOString();
|
||||
lastRun = {
|
||||
event_id: eventId,
|
||||
started_at: startedAt,
|
||||
finished_at: finishedAt,
|
||||
status: 'error',
|
||||
error: e.message,
|
||||
};
|
||||
log('run: error', { error: e.message });
|
||||
throw e;
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Excel import: parse the uploaded .xlsx and call sync_sessionize_excel.
|
||||
async function runExcelImport(eventId, fileBase64) {
|
||||
if (running) throw new Error('a sync is already running');
|
||||
running = true;
|
||||
const startedAt = new Date().toISOString();
|
||||
log('import-excel: start', { eventId });
|
||||
try {
|
||||
const events = await supabaseFetch(
|
||||
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=id,name`,
|
||||
);
|
||||
const event = Array.isArray(events) ? events[0] : null;
|
||||
if (!event) throw new Error('event not found');
|
||||
|
||||
const buffer = Buffer.from(fileBase64, 'base64');
|
||||
if (buffer.length === 0) throw new Error('empty file');
|
||||
|
||||
const { payload } = transformExcel(buffer);
|
||||
log('import-excel: transformed', {
|
||||
speakers: payload.speakers.length,
|
||||
sessions: payload.sessions.length,
|
||||
});
|
||||
if (payload.sessions.length === 0) {
|
||||
throw new Error('no sessions found in the file (expected an "Accepted sessions" sheet)');
|
||||
}
|
||||
|
||||
const summary = await supabaseFetch('/rest/v1/rpc/sync_sessionize_excel', {
|
||||
method: 'POST',
|
||||
body: { p_event_id: event.id, p_payload: payload },
|
||||
});
|
||||
|
||||
const finishedAt = new Date().toISOString();
|
||||
const result = {
|
||||
event_id: event.id,
|
||||
event_name: event.name,
|
||||
started_at: startedAt,
|
||||
finished_at: finishedAt,
|
||||
status: 'success',
|
||||
summary,
|
||||
};
|
||||
lastRun = result;
|
||||
log('import-excel: done', { summary });
|
||||
return result;
|
||||
} catch (e) {
|
||||
const finishedAt = new Date().toISOString();
|
||||
lastRun = {
|
||||
event_id: eventId,
|
||||
started_at: startedAt,
|
||||
finished_at: finishedAt,
|
||||
status: 'error',
|
||||
error: e.message,
|
||||
};
|
||||
log('import-excel: error', { error: e.message });
|
||||
throw e;
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
||||
const path = url.pathname;
|
||||
try {
|
||||
if (req.method === 'GET' && path === '/health') {
|
||||
return json(res, 200, { ok: true });
|
||||
}
|
||||
if (req.method === 'GET' && path === '/status') {
|
||||
return json(res, 200, { ok: true, running, lastRun });
|
||||
}
|
||||
if (req.method === 'POST' && path === '/run') {
|
||||
const body = await readBody(req);
|
||||
const eventId = body && body.event_id;
|
||||
if (!eventId) return json(res, 400, { error: 'event_id is required' });
|
||||
const result = await runSync(eventId);
|
||||
return json(res, 200, result);
|
||||
}
|
||||
if (req.method === 'POST' && path === '/import-excel') {
|
||||
const body = await readBody(req);
|
||||
const eventId = body && body.event_id;
|
||||
const fileBase64 = body && body.file_base64;
|
||||
if (!eventId) return json(res, 400, { error: 'event_id is required' });
|
||||
if (!fileBase64) return json(res, 400, { error: 'file_base64 is required' });
|
||||
const result = await runExcelImport(eventId, fileBase64);
|
||||
return json(res, 200, result);
|
||||
}
|
||||
return json(res, 404, { error: 'not found' });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(PORT, () => {
|
||||
log('sidecar listening', {
|
||||
port: PORT,
|
||||
supabase: SUPABASE_URL,
|
||||
hasSessionizeKey: Boolean(SESSIONIZE_API_KEY),
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user