Luca448 commited on
Commit
71cc73b
·
1 Parent(s): 9f26879

Feat: Persist news state in Supabase to save AI tokens across HF server restarts

Browse files
Files changed (1) hide show
  1. server/news-service.js +38 -16
server/news-service.js CHANGED
@@ -3,6 +3,11 @@ import path from 'path';
3
  import { fileURLToPath } from 'url';
4
  import * as cheerio from 'cheerio';
5
  import express from 'express';
 
 
 
 
 
6
 
7
  const __filename = fileURLToPath(import.meta.url);
8
  const __dirname = path.dirname(__filename);
@@ -17,38 +22,55 @@ let data = {
17
  };
18
 
19
  // Load data
20
- function loadData() {
21
  try {
22
- if (fs.existsSync(DATA_FILE)) {
23
- const fileData = fs.readFileSync(DATA_FILE, 'utf-8');
24
- data = JSON.parse(fileData);
 
 
25
 
 
 
 
 
 
 
26
  if (!data.topics) data.topics = [];
27
  if (!data.articles) data.articles = [];
28
  if (!data.lastRun) data.lastRun = 0;
29
  if (!data.lastTrends) data.lastTrends = [];
30
  if (!data.usedUrls) data.usedUrls = {};
 
31
  } else {
32
- saveData();
 
33
  }
34
  } catch (e) {
35
- console.error('[NewsService] Error loading data:', e);
36
  }
37
  }
38
 
39
- function saveData() {
40
  try {
41
  // Keep only last 50 articles
42
  if (data.articles.length > 50) {
43
  data.articles = data.articles.slice(0, 50);
44
  }
45
- const dir = path.dirname(DATA_FILE);
46
- if (!fs.existsSync(dir)) {
47
- fs.mkdirSync(dir, { recursive: true });
 
 
 
 
 
 
 
 
48
  }
49
- fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
50
  } catch (e) {
51
- console.error('[NewsService] Error saving data:', e);
52
  }
53
  }
54
 
@@ -429,7 +451,7 @@ async function runGenerationCycle(options = {}) {
429
  log.push(`Phase 1: ${topicsToProcess.length} new topics after dedup`);
430
 
431
  if (topicsToProcess.length === 0) {
432
- data.lastRun = Date.now(); saveData();
433
  return { status: 'no_new_topics', log };
434
  }
435
 
@@ -498,7 +520,7 @@ async function runGenerationCycle(options = {}) {
498
  data.lastTrends = topicsToProcess.map(t => t.topic);
499
  data.lastRun = Date.now();
500
  if (data.articles.length > 50) data.articles = data.articles.slice(0, 50);
501
- saveData();
502
 
503
  isGeneratingBackend = false;
504
  return { status: 'complete', newArticles, log };
@@ -510,8 +532,8 @@ async function runGenerationCycle(options = {}) {
510
  }
511
 
512
  // Start up
513
- export function initNewsService() {
514
- loadData();
515
 
516
  const now = Date.now();
517
  const timeSinceLastRun = now - data.lastRun;
 
3
  import { fileURLToPath } from 'url';
4
  import * as cheerio from 'cheerio';
5
  import express from 'express';
6
+ import { createClient } from '@supabase/supabase-js';
7
+
8
+ const supabaseUrl = 'https://cdswrcezmnqskunxsvkg.supabase.co';
9
+ const supabaseKey = 'sb_publishable_E0c1CBw_qxy9zP5Nk45unQ_jahirHee';
10
+ const supabase = createClient(supabaseUrl, supabaseKey);
11
 
12
  const __filename = fileURLToPath(import.meta.url);
13
  const __dirname = path.dirname(__filename);
 
22
  };
23
 
24
  // Load data
25
+ async function loadData() {
26
  try {
27
+ const { data: dbData, error } = await supabase
28
+ .from('server_state')
29
+ .select('data')
30
+ .eq('id', 'news_state')
31
+ .single();
32
 
33
+ if (error && error.code !== 'PGRST116') {
34
+ console.error('[NewsService] Error fetching from Supabase:', error);
35
+ }
36
+
37
+ if (dbData && dbData.data) {
38
+ data = dbData.data;
39
  if (!data.topics) data.topics = [];
40
  if (!data.articles) data.articles = [];
41
  if (!data.lastRun) data.lastRun = 0;
42
  if (!data.lastTrends) data.lastTrends = [];
43
  if (!data.usedUrls) data.usedUrls = {};
44
+ console.log('[NewsService] Successfully loaded state from Supabase');
45
  } else {
46
+ console.log('[NewsService] No existing state in Supabase, saving default.');
47
+ await saveData();
48
  }
49
  } catch (e) {
50
+ console.error('[NewsService] Error loading data from Supabase:', e);
51
  }
52
  }
53
 
54
+ async function saveData() {
55
  try {
56
  // Keep only last 50 articles
57
  if (data.articles.length > 50) {
58
  data.articles = data.articles.slice(0, 50);
59
  }
60
+
61
+ const { error } = await supabase
62
+ .from('server_state')
63
+ .upsert({
64
+ id: 'news_state',
65
+ data: data,
66
+ updated_at: new Date().toISOString()
67
+ });
68
+
69
+ if (error) {
70
+ console.error('[NewsService] Error saving to Supabase:', error);
71
  }
 
72
  } catch (e) {
73
+ console.error('[NewsService] Error saving data to Supabase:', e);
74
  }
75
  }
76
 
 
451
  log.push(`Phase 1: ${topicsToProcess.length} new topics after dedup`);
452
 
453
  if (topicsToProcess.length === 0) {
454
+ data.lastRun = Date.now(); await saveData();
455
  return { status: 'no_new_topics', log };
456
  }
457
 
 
520
  data.lastTrends = topicsToProcess.map(t => t.topic);
521
  data.lastRun = Date.now();
522
  if (data.articles.length > 50) data.articles = data.articles.slice(0, 50);
523
+ await saveData();
524
 
525
  isGeneratingBackend = false;
526
  return { status: 'complete', newArticles, log };
 
532
  }
533
 
534
  // Start up
535
+ export async function initNewsService() {
536
+ await loadData();
537
 
538
  const now = Date.now();
539
  const timeSinceLastRun = now - data.lastRun;