-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
381 lines (359 loc) · 11.4 KB
/
server.js
File metadata and controls
381 lines (359 loc) · 11.4 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
const http = require("http");
const sqlite3 = require("sqlite3").verbose();
const fs = require("fs");
const fsp = fs.promises;
const path = require("path");
const url = require("url");
const DEFAULT_PORT = 5000;
const DEFAULT_HOST = '0.0.0.0'
const PORT = process.env.PORT ? parseInt(process.env.PORT) : DEFAULT_PORT;
const HOST = process.env.HOST || DEFAULT_HOST || '0.0.0.0'
const DEFAULT_ROOT_FOLDER = "./databases";
const ROOT_FOLDER =
process.env.ROOT_FOLDER === undefined
? DEFAULT_ROOT_FOLDER
: process.env.ROOT_FOLDER === ""
? ""
: process.env.ROOT_FOLDER;
const MAX_READ_CONNECTIONS = 1;
const MAX_WRITE_CONNECTIONS = 1;
const DEFAULT_QUERY_TIMEOUT = 5000; // Milliseconds
const DEFAULT_DB_NAME = "default.db";
const DEFAULT_DB_PATH_ENV =
process.env.DEFAULT_DB_PATH ||
path.join(DEFAULT_ROOT_FOLDER, DEFAULT_DB_NAME);
const DEFAULT_DB_DIR = path.dirname(DEFAULT_DB_PATH_ENV);
const CLIENT_FOLDER = path.join(__dirname, "client");
const INDEX_HTML_PATH = path.join(CLIENT_FOLDER, "index.html");
const API_PREFIX = "/api";
const dbConnections = {};
function ensureDirectoryExists(dirPath) {
if (dirPath && !fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}
function getDatabasePath(dbName) {
return dbName ? path.join(ROOT_FOLDER, dbName) : DEFAULT_DB_PATH_ENV;
}
async function getOrCreateDatabaseConnection(dbPath, readOnly = false) {
if (!dbPath) {
return null; // Không có đường dẫn DB
}
if (!fs.existsSync(dbPath)) {
return new Promise((resolve, reject) => {
const newDb = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error("Failed to create database:", err.message);
reject(err);
} else {
console.log(`Database created at: ${dbPath}`);
const connection = getDatabaseConnectionInternal(dbPath, readOnly);
resolve(connection);
newDb.close();
}
});
});
}
return getDatabaseConnectionInternal(dbPath, readOnly);
}
function getDatabaseConnectionInternal(dbPath, readOnly = false) {
if (!dbConnections[dbPath]) {
dbConnections[dbPath] = {
read: [],
readwrite: [],
};
}
const connections = readOnly
? dbConnections[dbPath].read
: dbConnections[dbPath].readwrite;
const maxConnections = readOnly
? MAX_READ_CONNECTIONS
: MAX_WRITE_CONNECTIONS;
if (connections.length < maxConnections) {
const db = new sqlite3.Database(
dbPath,
readOnly ? sqlite3.OPEN_READONLY : sqlite3.OPEN_READWRITE,
(err) => {
if (err) {
console.error("Failed to connect to database:", err.message);
return null;
}
}
);
connections.push(db);
return db;
}
return connections[0]; // Trả về kết nối hiện có
}
function releaseDatabaseConnection(dbPath, db) {
if (dbConnections[dbPath]) {
const connections = dbConnections[dbPath].read.includes(db)
? dbConnections[dbPath].read
: dbConnections[dbPath].readwrite;
const index = connections.indexOf(db);
if (index > -1) {
connections.splice(index, 1);
db.close((err) => {
if (err) {
console.error("Failed to close database:", err.message);
}
});
}
if (
dbConnections[dbPath].read.length === 0 &&
dbConnections[dbPath].readwrite.length === 0
) {
delete dbConnections[dbPath];
}
}
}
function closeAllConnections() {
for (const dbPath in dbConnections) {
if (dbConnections.hasOwnProperty(dbPath)) {
dbConnections[dbPath].read.forEach((db) => {
db.close((err) => {
if (err) {
console.error(
`Failed to close read connection for ${dbPath}:`,
err.message
);
}
});
});
dbConnections[dbPath].readwrite.forEach((db) => {
db.close((err) => {
if (err) {
console.error(
`Failed to close readwrite connection for ${dbPath}:`,
err.message
);
}
});
});
}
}
console.log("All database connections closed.");
}
process.on("SIGINT", () => {
console.log("Shutting down server...");
closeAllConnections();
process.exit(0);
});
const server = http.createServer(async (req, res) => {
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
const req_query = parsedUrl.query;
let req_body = {};
let method = req.method || "GET";
if (method === "POST") {
let body = "";
for await (const chunk of req) {
body += chunk;
}
try {
req_body = JSON.parse(body);
} catch (error) {
// Ignore invalid JSON, body might not always be JSON
}
}
if (pathname.startsWith(API_PREFIX + "/")) {
let reqPath = pathname.replace(API_PREFIX, "");
res.setHeader("Content-Type", "application/json");
if (reqPath === `/create-db` && method === "POST") {
const dbName = req_body.name || req_query.name;
if (!dbName) {
res.writeHead(400);
return res.end(JSON.stringify({ error: "Missing database name" }));
}
const dbPath = getDatabasePath(dbName);
ensureDirectoryExists(path.dirname(dbPath));
const db = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error("Failed to create database:", err.message);
res.writeHead(500);
return res.end(
JSON.stringify({ error: "Failed to create database" })
);
}
db.close();
res.writeHead(200);
res.end(
JSON.stringify({
message: `Database "${dbName}" created successfully at "${dbPath}"`,
})
);
});
} else if (reqPath === `/query` && method === "POST") {
const dbName = req_body.db || req_query.db;
const query = req_query.sql || req_body.query;
const params = req_body.param;
const readOnlyParam = req_body.readOnly || req_query.readOnly;
const readOnly = readOnlyParam === "true";
const timeoutParam = parseInt(req_body.timeout || req_query.timeout);
const timeout = isNaN(timeoutParam)
? DEFAULT_QUERY_TIMEOUT
: timeoutParam;
const createIfNotExistParam =
req_body.createIfNotExist || req_query.createIfNotExist;
const createIfNotExist = createIfNotExistParam === "true";
const effectiveDbName = dbName;
const dbPath = getDatabasePath(effectiveDbName);
if ((!effectiveDbName && !DEFAULT_DB_PATH_ENV) || !query) {
res.writeHead(400);
return res.end(
JSON.stringify({ error: "Missing database name or query" })
);
}
let dbInstance;
try {
const finalDbPath = effectiveDbName ? dbPath : DEFAULT_DB_PATH_ENV;
ensureDirectoryExists(path.dirname(finalDbPath));
if (createIfNotExist) {
dbInstance = await getOrCreateDatabaseConnection(
finalDbPath,
readOnly
);
if (!dbInstance) {
res.writeHead(500);
return res.end(
JSON.stringify({
error: "Failed to get or create database connection",
})
);
}
} else {
dbInstance = getDatabaseConnectionInternal(finalDbPath, readOnly);
if (!dbInstance) {
res.writeHead(404);
return res.end(
JSON.stringify({
error: `Database "${
effectiveDbName || DEFAULT_DB_NAME
}" not found`,
})
);
}
}
const executeQueryWithTimeout = (db, sql, parameters, timeoutMs) => {
return new Promise((resolve, reject) => {
let timedOut = false;
const timeoutId = setTimeout(() => {
timedOut = true;
reject(new Error("Query execution timeout"));
}, timeoutMs);
db.all(sql, parameters, (err, rows) => {
clearTimeout(timeoutId);
if (timedOut) return;
if (err) {
reject(err);
return;
}
resolve(rows);
});
});
};
let t = Date.now();
const results = await executeQueryWithTimeout(
dbInstance,
query,
params || [],
timeout
);
t = Date.now() - t;
res.writeHead(200);
res.end(JSON.stringify({ results, time: t }));
} catch (error) {
if (error.message === "Query execution timeout") {
console.error(
`Query timeout (${timeout}ms) for database: ${
effectiveDbName || DEFAULT_DB_NAME
}, query: ${query}`
);
res.writeHead(408); // Request Timeout
return res.end(JSON.stringify({ error: "Query execution timeout" }));
}
if (
readOnly &&
error.message.includes("attempt to write a readonly database")
) {
res.writeHead(403);
return res.end(
JSON.stringify({
error: "Read-only connection cannot execute write operations",
details: error.message,
})
);
}
console.error("Query error:", error.message);
res.writeHead(500);
return res.end(JSON.stringify({ error: error.message }));
} finally {
if (dbInstance)
releaseDatabaseConnection(
effectiveDbName || DEFAULT_DB_PATH_ENV,
dbInstance
);
}
} else if (reqPath === `/listdb` && method === "GET") {
let files = await fsp.readdir(ROOT_FOLDER);
files = files.filter((f) => f.endsWith(".db"));
return res.end(JSON.stringify({ results: files }));
} else {
res.writeHead(404);
return res.end(JSON.stringify({ error: "Not Found" }));
}
} else {
// Serve static files from client folder
const filePath = path.join(
CLIENT_FOLDER,
!pathname || pathname === "/" ? "index.html" : pathname
);
try {
const data = await fsp.readFile(filePath);
const extname = path.extname(filePath);
let contentType = "text/html";
switch (extname) {
case ".js":
contentType = "application/javascript";
break;
case ".css":
contentType = "text/css";
break;
case ".json":
contentType = "application/json";
break;
case ".png":
contentType = "image/png";
break;
case ".jpg":
case ".jpeg":
contentType = "image/jpg";
break;
}
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
} catch (error) {
// If file not found, serve index.html (SPA behavior)
if (error.code === "ENOENT") {
try {
const indexHTML = await fsp.readFile(INDEX_HTML_PATH);
res.writeHead(200, { "Content-Type": "text/html" });
res.end(indexHTML);
} catch (err) {
console.error("Error serving index.html:", err);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal Server Error");
}
} else {
console.error("Error serving static file:", error);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal Server Error");
}
}
}
});
server.listen(PORT, HOST, () => {
console.log(`Server listening on http://${HOST}:${PORT}`);
ensureDirectoryExists(DEFAULT_DB_DIR);
ensureDirectoryExists(CLIENT_FOLDER);
});