File size: 4,349 Bytes
e5f68c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
const fs = require('fs');
const path = require('path');

const DATA_DIR = path.join(__dirname, 'data');
const TASKS_FILE = path.join(DATA_DIR, 'tasks.json');
const CONFIG_FILE = path.join(DATA_DIR, 'config.json');

// In-memory cache to avoid read-modify-write race conditions
let tasksCache = null;

// Write throttling
let writePending = false;
let writeTimer = null;

function ensureDir() {
  if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
  }
}

// Load tasks into memory cache (lazy load)
function loadTasksCache() {
  if (tasksCache === null) {
    try {
      if (fs.existsSync(TASKS_FILE)) {
        const content = fs.readFileSync(TASKS_FILE, 'utf-8');
        const data = JSON.parse(content);
        tasksCache = data.tasks || {};
      } else {
        tasksCache = {};
      }
    } catch (e) {
      console.error('Error loading tasks:', e.message);
      tasksCache = {};
    }
  }
  return tasksCache;
}

// Throttled write - batch writes within 100ms
function scheduleWrite() {
  if (!writePending) {
    writePending = true;
    if (writeTimer) {
      clearTimeout(writeTimer);
    }
    writeTimer = setTimeout(() => {
      writePending = false;
      writeTimer = null;
      try {
        ensureDir();
        fs.writeFileSync(TASKS_FILE, JSON.stringify({ tasks: tasksCache }, null, 2), 'utf-8');
      } catch (e) {
        console.error('Write error:', e.message);
      }
    }, 100);
  }
}

// Immediate write (for critical operations)
function flushWrite() {
  if (writeTimer) {
    clearTimeout(writeTimer);
    writeTimer = null;
  }
  if (tasksCache !== null) {
    try {
      ensureDir();
      fs.writeFileSync(TASKS_FILE, JSON.stringify({ tasks: tasksCache }, null, 2), 'utf-8');
    } catch (e) {
      console.error('Flush write error:', e.message);
    }
  }
  writePending = false;
}

// Read JSON helper for other files
function readJSON(file, defaultValue = {}) {
  try {
    if (fs.existsSync(file)) {
      const content = fs.readFileSync(file, 'utf-8');
      return JSON.parse(content);
    }
  } catch (e) {
    console.error(`Error reading ${file}:`, e.message);
  }
  return defaultValue;
}

// Task persistence - all operations use in-memory cache
function loadTasks() {
  return { tasks: loadTasksCache() };
}

function saveTasks(tasks) {
  tasksCache = tasks;
  scheduleWrite();
}

function getTask(taskId) {
  const cache = loadTasksCache();
  return cache[taskId] || null;
}

function saveTask(taskId, taskData) {
  const cache = loadTasksCache();
  cache[taskId] = taskData;
  scheduleWrite();
}

function deleteTask(taskId) {
  const cache = loadTasksCache();
  delete cache[taskId];
  scheduleWrite();
}

function getAllTasks() {
  return loadTasksCache();
}

// Config persistence
function loadConfig() {
  return readJSON(CONFIG_FILE, {});
}

function saveConfig(config) {
  ensureDir();
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');
}

// Raw tasks.json operations (for config editor)
function getTasksRaw() {
  flushWrite(); // Ensure latest data is written
  return readJSON(TASKS_FILE, { tasks: {} });
}

function saveTasksRaw(content) {
  // Parse and validate
  const data = JSON.parse(content);
  
  // Update cache and write immediately
  tasksCache = data.tasks || {};
  flushWrite();
}

// Check if any task is running
function hasRunningTasks() {
  const tasks = getAllTasks();
  return Object.values(tasks).some(t => t.status === 'running' || t.status === 'paused');
}

// Check if there's pending data to write
function hasPendingWrite() {
  return writePending || writeTimer !== null;
}

// Graceful shutdown - flush all pending data
function shutdown() {
  if (writeTimer) {
    clearTimeout(writeTimer);
    writeTimer = null;
  }
  if (tasksCache !== null && writePending) {
    try {
      ensureDir();
      fs.writeFileSync(TASKS_FILE, JSON.stringify({ tasks: tasksCache }, null, 2), 'utf-8');
      console.log('[Storage] Data flushed on shutdown');
    } catch (e) {
      console.error('[Storage] Shutdown flush error:', e.message);
    }
  }
  writePending = false;
}

module.exports = {
  loadTasks,
  saveTasks,
  getTask,
  saveTask,
  deleteTask,
  getAllTasks,
  loadConfig,
  saveConfig,
  getTasksRaw,
  saveTasksRaw,
  hasRunningTasks,
  flushTasks: flushWrite,
  hasPendingWrite,
  shutdown
};