feat(bridge): importar agenda FPA para BD local em vez de ws.fpa.pt em runtime (BIT-26500)
Tests / writer-pipeline tests (push) Successful in 31s
Tests / bridge tests (push) Successful in 32s
Tests / frontend lib tests (push) Successful in 32s
Tests / writer-pipeline tests (pull_request) Successful in 31s
Tests / bridge tests (pull_request) Successful in 31s
Tests / frontend lib tests (pull_request) Successful in 32s
Tests / writer-pipeline tests (push) Successful in 31s
Tests / bridge tests (push) Successful in 32s
Tests / frontend lib tests (push) Successful in 32s
Tests / writer-pipeline tests (pull_request) Successful in 31s
Tests / bridge tests (pull_request) Successful in 31s
Tests / frontend lib tests (pull_request) Successful in 32s
- fpa-store.ts: lê/escreve agenda em JSON persistente (FPA_STORE_PATH) - fpa-import.ts: script standalone que importa de ws.fpa.pt e escreve na store - fpa-sync.ts: rota POST /fpa/sync para importação on-demand + GET /fpa/status - fpa-agenda.ts: get_fpa_agenda_from_store() lê da store; fallback live só se store vazia - homepage.ts: usa get_fpa_agenda_from_store() — ws.fpa.pt nunca é chamado por requests de utilizador - systemd timer: news-fpa-import.timer dispara diariamente às 05:30 Europe/Lisbon - andeboltv.ts: corrige build_stream_url para usar event_id (fix anterior BIT-26494) Paperclip-Issue: BIT-26500 Paperclip-Agent: coo
This commit is contained in:
1 parent
c0a1787b93
commit
6e82cc0106
10 files changed
+171
-13
No files matched your search
+2
-2
@@ -9,8 +9,8 @@
|
||||
"build": "tsc",
|
||||
"start": "node dist/server.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "npm run build && node --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/fpa-stream-match.test.js",
|
||||
"test:coverage": "npm run build && node --experimental-test-coverage --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/fpa-stream-match.test.js"
|
||||
"test": "npm run build && node --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/andeboltv.test.js dist/services/fpa-stream-match.test.js",
|
||||
"test:coverage": "npm run build && node --experimental-test-coverage --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/andeboltv.test.js dist/services/fpa-stream-match.test.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^9.0.1",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { fetch_fpa_agenda } from '../services/fpa-agenda.js';
|
||||
import { write_fpa_store, read_fpa_store } from '../services/fpa-store.js';
|
||||
import { cache_invalidate } from '../services/cache.js';
|
||||
|
||||
/** Simple bearer token guard (set FPA_SYNC_TOKEN in env; omit to require no token). */
|
||||
const SYNC_TOKEN = process.env['FPA_SYNC_TOKEN'] ?? '';
|
||||
|
||||
export async function fpa_sync_routes(app: FastifyInstance): Promise<void> {
|
||||
/** POST /fpa/sync — trigger on-demand import from ws.fpa.pt */
|
||||
app.post('/fpa/sync', async (req, reply) => {
|
||||
if (SYNC_TOKEN) {
|
||||
const auth = req.headers['authorization'] ?? '';
|
||||
if (auth !== `Bearer ${SYNC_TOKEN}`) {
|
||||
return reply.code(401).send({ error: 'Unauthorized' });
|
||||
}
|
||||
}
|
||||
|
||||
app.log.info('FPA sync requested');
|
||||
|
||||
try {
|
||||
const games = await fetch_fpa_agenda();
|
||||
await write_fpa_store(games);
|
||||
|
||||
// Bust the SWR cache so the next homepage request sees fresh data
|
||||
const site_keys = ['andebol.net:fpa:agenda', 'andebol.pt:fpa:agenda'];
|
||||
await Promise.all(site_keys.map((k) => cache_invalidate(k)));
|
||||
|
||||
app.log.info({ count: games.length }, 'FPA sync completed');
|
||||
return reply.send({ ok: true, count: games.length, imported_at: new Date().toISOString() });
|
||||
} catch (err) {
|
||||
app.log.error({ err }, 'FPA sync failed');
|
||||
return reply.code(502).send({ error: 'FPA import failed', detail: String(err) });
|
||||
}
|
||||
});
|
||||
|
||||
/** GET /fpa/status — show when the store was last imported */
|
||||
app.get('/fpa/status', async (_req, reply) => {
|
||||
const entry = await read_fpa_store();
|
||||
if (!entry) {
|
||||
return reply.send({ store: 'empty' });
|
||||
}
|
||||
return reply.send({
|
||||
store: 'ok',
|
||||
imported_at: entry.imported_at,
|
||||
count: entry.games.length,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { swr_fetch } from '../services/cache.js';
|
||||
import type { ArticleListItem, FpaAgendaGame, HomepageData } from '../types.js';
|
||||
import type { AndebolTvStreamEvent } from '../services/andeboltv.js';
|
||||
import { fetch_andeboltv_stream_events } from '../services/andeboltv.js';
|
||||
import { fetch_fpa_agenda } from '../services/fpa-agenda.js';
|
||||
import { get_fpa_agenda_from_store } from '../services/fpa-agenda.js';
|
||||
import { enrich_fpa_agenda_with_streams } from '../services/fpa-stream-match.js';
|
||||
|
||||
// Number of articles per section
|
||||
@@ -141,7 +141,7 @@ export async function homepage_routes(app: FastifyInstance): Promise<void> {
|
||||
? await swr_fetch<FpaAgendaGame[]>(`${host}:fpa:agenda`, async () => {
|
||||
try {
|
||||
const [games, streams] = await Promise.all([
|
||||
fetch_fpa_agenda(),
|
||||
get_fpa_agenda_from_store(),
|
||||
swr_fetch<AndebolTvStreamEvent[]>(`${host}:andeboltv:streams`, async () => {
|
||||
try {
|
||||
return await fetch_andeboltv_stream_events();
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Standalone import script — fetches FPA agenda + club logos from ws.fpa.pt and
|
||||
* writes to the local JSON store so the bridge never calls ws.fpa.pt on user requests.
|
||||
*
|
||||
* Run: node dist/scripts/fpa-import.js
|
||||
* Schedule: see deploy/systemd/news-fpa-import.timer (daily at 05:30)
|
||||
*/
|
||||
import { fetch_fpa_agenda } from '../services/fpa-agenda.js';
|
||||
import { write_fpa_store } from '../services/fpa-store.js';
|
||||
|
||||
async function main(): Promise<void> {
|
||||
console.log('[fpa-import] starting import from ws.fpa.pt …');
|
||||
const games = await fetch_fpa_agenda();
|
||||
console.log(`[fpa-import] fetched ${games.length} game(s)`);
|
||||
await write_fpa_store(games);
|
||||
console.log('[fpa-import] store written successfully');
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[fpa-import] FAILED:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import { articles_routes } from './routes/articles.js';
|
||||
import { categories_routes } from './routes/categories.js';
|
||||
import { homepage_routes } from './routes/homepage.js';
|
||||
import { writers_routes } from './routes/writers.js';
|
||||
import { fpa_sync_routes } from './routes/fpa-sync.js';
|
||||
|
||||
// BitReport error reporting (env: ERROR_REPORTING_TOKEN, ERROR_REPORTING_ENDPOINT)
|
||||
initReporter();
|
||||
@@ -66,6 +67,7 @@ await app.register(articles_routes);
|
||||
await app.register(categories_routes);
|
||||
await app.register(homepage_routes);
|
||||
await app.register(writers_routes);
|
||||
await app.register(fpa_sync_routes);
|
||||
|
||||
// 404 fallback
|
||||
app.setNotFoundHandler((_req, reply) => {
|
||||
|
||||
@@ -69,9 +69,9 @@ export function pixellot_ms_to_lisbon_date(ms: number): string {
|
||||
}).format(new Date(ms));
|
||||
}
|
||||
|
||||
function build_stream_url(reference_id: string): string {
|
||||
function build_stream_url(event_id: string): string {
|
||||
const base = ANDEBOLTV_PORTAL_URL.replace(/\/$/, '');
|
||||
return `${base}/events/${encodeURIComponent(reference_id)}`;
|
||||
return `${base}/events/${encodeURIComponent(event_id)}`;
|
||||
}
|
||||
|
||||
function parse_entry(entry: PixellotListEntry, status: AndebolTvEventStatus): AndebolTvStreamEvent | null {
|
||||
@@ -81,7 +81,7 @@ function parse_entry(entry: PixellotListEntry, status: AndebolTvEventStatus): An
|
||||
const away_team = as_trimmed_string(entry.eventTeams?.awayTeam?.name);
|
||||
const event_ms = entry.gameStartDate ?? entry.event_date;
|
||||
|
||||
if (!reference_id || !event_id || !home_team || !away_team || !event_ms) {
|
||||
if (!event_id || !home_team || !away_team || !event_ms) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ function parse_entry(entry: PixellotListEntry, status: AndebolTvEventStatus): An
|
||||
away_team,
|
||||
date: pixellot_ms_to_lisbon_date(event_ms),
|
||||
status,
|
||||
stream_url: build_stream_url(reference_id),
|
||||
stream_url: build_stream_url(event_id),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ async function fetch_status_list(status: AndebolTvEventStatus): Promise<AndebolT
|
||||
|
||||
/**
|
||||
* Fetch handball events with AndebolTV streams (live + upcoming).
|
||||
* Deduplicates by `reference_id`, preferring `live` over `upcoming`.
|
||||
* Deduplicates by `event_id`, preferring `live` over `upcoming`.
|
||||
*/
|
||||
export async function fetch_andeboltv_stream_events(): Promise<AndebolTvStreamEvent[]> {
|
||||
const [live, upcoming] = await Promise.all([
|
||||
@@ -147,14 +147,14 @@ export async function fetch_andeboltv_stream_events(): Promise<AndebolTvStreamEv
|
||||
fetch_status_list('upcoming'),
|
||||
]);
|
||||
|
||||
const by_ref = new Map<string, AndebolTvStreamEvent>();
|
||||
const by_id = new Map<string, AndebolTvStreamEvent>();
|
||||
|
||||
for (const event of upcoming) {
|
||||
by_ref.set(event.reference_id, event);
|
||||
by_id.set(event.event_id, event);
|
||||
}
|
||||
for (const event of live) {
|
||||
by_ref.set(event.reference_id, event);
|
||||
by_id.set(event.event_id, event);
|
||||
}
|
||||
|
||||
return [...by_ref.values()];
|
||||
return [...by_id.values()];
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { FpaAgendaGame } from '../types.js';
|
||||
import { read_fpa_store, is_store_fresh } from './fpa-store.js';
|
||||
|
||||
/** Public FPA JSON feed used by portal.fpa.pt for national competition fixtures. */
|
||||
const FPA_AGENDA_URL =
|
||||
@@ -134,3 +135,26 @@ export async function fetch_fpa_agenda(): Promise<FpaAgendaGame[]> {
|
||||
away_logo_url: away_club_id ? logos.get(away_club_id) ?? null : null,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Read FPA agenda from the local persistent store (populated by the import job).
|
||||
* Falls back to live ws.fpa.pt fetch when the store is absent or stale beyond 26 h.
|
||||
* This is the function the homepage should call — ws.fpa.pt is never hit on user paths
|
||||
* once the import job has run at least once.
|
||||
*/
|
||||
export async function get_fpa_agenda_from_store(): Promise<FpaAgendaGame[]> {
|
||||
const entry = await read_fpa_store();
|
||||
|
||||
if (entry && entry.games.length > 0) {
|
||||
if (!is_store_fresh(entry)) {
|
||||
console.warn(
|
||||
`[fpa-agenda] store is stale (imported_at=${entry.imported_at}); serving cached data`,
|
||||
);
|
||||
}
|
||||
return entry.games;
|
||||
}
|
||||
|
||||
// No store yet — bootstrap from live feed and log so ops can schedule the import job
|
||||
console.warn('[fpa-agenda] store empty/missing; falling back to live ws.fpa.pt fetch');
|
||||
return fetch_fpa_agenda();
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { readFile, writeFile, mkdir } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import type { FpaAgendaGame } from '../types.js';
|
||||
|
||||
/** Path to the persistent JSON store. Override with FPA_STORE_PATH env var. */
|
||||
const STORE_PATH =
|
||||
process.env['FPA_STORE_PATH'] ?? '/var/lib/news-platform/fpa-agenda.json';
|
||||
|
||||
/** After this many ms the store is considered stale (but still served). Default: 26h. */
|
||||
const STALE_AFTER_MS =
|
||||
parseInt(process.env['FPA_STORE_STALE_MS'] ?? String(26 * 60 * 60 * 1000), 10);
|
||||
|
||||
export interface FpaStoreEntry {
|
||||
games: FpaAgendaGame[];
|
||||
imported_at: string;
|
||||
}
|
||||
|
||||
export async function read_fpa_store(): Promise<FpaStoreEntry | null> {
|
||||
try {
|
||||
const raw = await readFile(STORE_PATH, 'utf-8');
|
||||
return JSON.parse(raw) as FpaStoreEntry;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function write_fpa_store(games: FpaAgendaGame[]): Promise<void> {
|
||||
const entry: FpaStoreEntry = { games, imported_at: new Date().toISOString() };
|
||||
await mkdir(dirname(STORE_PATH), { recursive: true });
|
||||
await writeFile(STORE_PATH, JSON.stringify(entry, null, 2), 'utf-8');
|
||||
}
|
||||
|
||||
/** True when the store was written within STALE_AFTER_MS. */
|
||||
export function is_store_fresh(entry: FpaStoreEntry): boolean {
|
||||
return Date.now() - new Date(entry.imported_at).getTime() < STALE_AFTER_MS;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[Unit]
|
||||
Description=News Platform — FPA agenda importer (BIT-26500)
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=www-data
|
||||
Group=www-data
|
||||
WorkingDirectory=/opt/news-platform/bridge
|
||||
EnvironmentFile=/etc/news-platform/bridge.env
|
||||
ExecStart=/usr/bin/node dist/scripts/fpa-import.js
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=news-fpa-import
|
||||
|
||||
NoNewPrivileges=true
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=FPA agenda import — daily at 05:30 Europe/Lisbon
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 05:30:00 Europe/Lisbon
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
Reference in new issue
Block a user