-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3610 lines (3170 loc) · 111 KB
/
server.js
File metadata and controls
3610 lines (3170 loc) · 111 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import crypto from 'crypto';
import cookieParser from 'cookie-parser';
import chokidar from 'chokidar';
import { exec } from 'child_process';
import { promisify } from 'util';
import cron from 'node-cron';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import morgan from 'morgan';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import { createServer } from 'http';
import { Server } from 'socket.io';
import multer from 'multer';
import rateLimit from 'express-rate-limit';
import { body, validationResult } from 'express-validator';
import Logger from './utils/logger.js';
import dotenv from 'dotenv';
import * as layerLoader from './utils/layer-loader.js';
import { initTracer, withSpan, shutdownTracer } from './utils/tracer.js';
import FuncDockMCPServer from './mcp-server.js';
dotenv.config();
import 'tsx';
const execAsync = promisify(exec);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
app.set('trust proxy', 1);
const server = createServer(app);
const GIT_URL_REGEX = /^https:\/\/[\w.-]+(?:\/[\w.-]+)*\/[\w.-]+(?:\.git)?$/i;
const BRANCH_NAME_REGEX = /^[a-zA-Z0-9._/-]+$/;
const COMMIT_SHA_REGEX = /^[0-9a-fA-F]{4,64}$/;
const FUNCTION_NAME_REGEX = /^[a-zA-Z0-9_-]+$/;
const LAYER_NAME_REGEX = /^[a-zA-Z0-9_-]+$/;
function validateGitUrl(url) {
if (!url || typeof url !== 'string') return false;
return GIT_URL_REGEX.test(url);
}
function validateBranchName(branch) {
if (!branch || typeof branch !== 'string') return false;
return BRANCH_NAME_REGEX.test(branch) && !branch.includes('..');
}
function validateCommitSha(sha) {
if (!sha || typeof sha !== 'string') return false;
return COMMIT_SHA_REGEX.test(sha);
}
function validateFunctionName(name) {
if (!name || typeof name !== 'string') return false;
return FUNCTION_NAME_REGEX.test(name) && name.length <= 100;
}
function validateLayerName(name) {
if (!name || typeof name !== 'string') return false;
return LAYER_NAME_REGEX.test(name) && name.length <= 100;
}
function validateFilePath(filePath) {
if (!filePath || typeof filePath !== 'string') return false;
if (filePath.includes('\0')) return false;
if (filePath.includes('..')) return false;
return true;
}
const DASHBOARD_ORIGIN = process.env.DASHBOARD_ORIGIN || false;
const io = new Server(server, {
cors: {
origin:
DASHBOARD_ORIGIN ||
(process.env.NODE_ENV === 'production'
? false
: ['http://localhost:3000', 'http://localhost:5173']),
methods: ['GET', 'POST'],
credentials: true,
},
});
// Environment variables
const JWT_SECRET = process.env.JWT_SECRET;
const ADMIN_USERNAME = process.env.ADMIN_USERNAME;
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD;
const ADMIN_PASSWORD_HASH_ENV = process.env.ADMIN_PASSWORD_HASH;
const MCP_ENABLED = process.env.MCP_ENABLED !== 'false';
const MCP_HTTP_PORT = parseInt(process.env.MCP_HTTP_PORT || '3001', 10);
if (!JWT_SECRET) {
console.error(
'ERROR: JWT_SECRET environment variable is required. Set it to a strong random string (at least 32 characters).'
);
process.exit(1);
}
if (!ADMIN_USERNAME) {
console.error('ERROR: ADMIN_USERNAME environment variable is required.');
process.exit(1);
}
if (!ADMIN_PASSWORD && !ADMIN_PASSWORD_HASH_ENV) {
console.error(
'ERROR: Either ADMIN_PASSWORD or ADMIN_PASSWORD_HASH environment variable is required.'
);
process.exit(1);
}
if (JWT_SECRET.length < 16) {
console.error('ERROR: JWT_SECRET must be at least 16 characters long.');
process.exit(1);
}
if (ADMIN_PASSWORD && ADMIN_PASSWORD.length < 8) {
console.error('ERROR: ADMIN_PASSWORD must be at least 8 characters long.');
process.exit(1);
}
const ADMIN_PASSWORD_HASH = ADMIN_PASSWORD_HASH_ENV || bcrypt.hashSync(ADMIN_PASSWORD, 10);
let mcpServer = null;
// Single-instance in-memory token blacklist for logout.
// For multi-instance deployments, replace with Redis or another shared store.
const tokenBlacklist = new Map();
// Simple mutex for concurrent operations on shared Maps
const mutexes = new Map();
const acquireLock = async (key, timeout = 5000) => {
const start = Date.now();
while (mutexes.get(key)) {
if (Date.now() - start > timeout) {
throw new Error(`Lock timeout for ${key}`);
}
await new Promise((r) => setImmediate(r));
}
mutexes.set(key, true);
return () => mutexes.delete(key);
};
// Function route dispatcher -- stores handler functions keyed by "METHOD /path"
// This allows route removal/replacement without Express router stack accumulation
const functionDispatcher = new Map();
const functionLoggers = new Map();
// Register a function route in the dispatcher
const registerDispatcherRoute = (method, fullPath, functionName, handlerFn) => {
const routeKey = `${method.toUpperCase()} ${fullPath}`;
functionDispatcher.set(routeKey, { functionName, handler: handlerFn });
};
// Unregister all routes for a function from the dispatcher
const _unregisterDispatcherRoutes = (functionName) => {
for (const [key, value] of functionDispatcher.entries()) {
if (value.functionName === functionName) {
functionDispatcher.delete(key);
}
}
};
// Single Express middleware that dispatches to the current handler from the Map
const functionDispatcherMiddleware = async (req, res, next) => {
const routeKey = `${req.method.toUpperCase()} ${req.path}`;
const entry = functionDispatcher.get(routeKey);
if (!entry) {
return next();
}
const { functionName, handler: routeHandlerFunction } = entry;
const funcInfo = loadedFunctions.get(functionName);
const functionDir = funcInfo ? funcInfo.path : '';
const routeHandler = funcInfo ? funcInfo.config?.handler || 'handler.js' : '';
// Cache logger instances per function to avoid creating new streams on every request
let functionLogger = functionLoggers.get(functionName);
if (!functionLogger) {
functionLogger = new Logger({
logLevel: process.env.LOG_LEVEL || 'info',
logToFile: true,
logToConsole: true,
functionName: functionName,
});
functionLoggers.set(functionName, functionLogger);
}
req.functionName = functionName;
req.functionPath = functionDir;
req.logger = functionLogger;
if (funcInfo && funcInfo.envVars) {
req.env = funcInfo.envVars;
}
const start = Date.now();
let statusCode = 200;
const origStatus = res.status;
res.status = function (code) {
statusCode = code;
return origStatus.call(this, code);
};
try {
await withSpan(
`funcdock.invoke.${functionName}.${req.path}.${req.method.toLowerCase()}`,
{
'function.name': functionName,
'http.route': req.path,
'http.method': req.method.toUpperCase(),
'http.url': req.originalUrl || req.url,
},
async () => {
await routeHandlerFunction(req, res, next);
}
);
} catch (err) {
functionLogger.error(`Error in ${req.path} (${functionName}/${routeHandler}): ${err.message}`, {
stack: err.stack,
});
if (!res.headersSent) {
res.status(500).json({
error: 'Internal Server Error',
function: functionName,
handler: routeHandler,
route: req.path,
timestamp: new Date().toISOString(),
});
}
statusCode = 500;
} finally {
const duration = Date.now() - start;
const ip = req.ip || req.connection?.remoteAddress || '';
const userAgent = req.headers['user-agent'] || '';
functionLogger.info('HTTP access', {
level: 'ACCESS',
function: functionName,
method: req.method,
path: req.originalUrl || req.url,
statusCode,
duration,
ip,
userAgent,
});
try {
await functionLogger.flushBuffer();
} catch (flushErr) {
console.error('Failed to flush log buffer:', flushErr.message);
}
}
};
// Middleware
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:', 'https:'],
},
},
})
);
app.use(compression());
const corsOrigin = process.env.CORS_ORIGIN
? process.env.CORS_ORIGIN.split(',').map((o) => o.trim())
: true;
app.use(
cors({
origin: corsOrigin,
credentials: true,
})
);
app.use(cookieParser());
app.use(morgan('combined'));
app.use(
express.json({
limit: '10mb',
verify: (req, res, buf) => {
req.bodyRaw = buf.toString();
},
})
);
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Health check endpoint (must be before auth-required routes and dispatcher)
app.get('/health', (req, res) => {
res.status(200).json({
status: 'healthy',
uptime: process.uptime(),
timestamp: new Date().toISOString(),
});
});
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.',
});
app.use('/api/', limiter);
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
skipSuccessfulRequests: true,
message: 'Too many login attempts from this IP, please try again later.',
});
// Serve static files for dashboard with proper MIME types
app.use(
'/dashboard',
express.static(path.join(__dirname, 'public/dashboard'), {
setHeaders: (res, path) => {
if (path.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript');
} else if (path.endsWith('.css')) {
res.setHeader('Content-Type', 'text/css');
} else if (path.endsWith('.html')) {
res.setHeader('Content-Type', 'text/html');
}
},
})
);
// Deploy API key for CI/CD and CLI tools
const DEPLOY_API_KEY = process.env.DEPLOY_API_KEY || '';
// Auth middleware that accepts either JWT or deploy API key
const requireAuth = (req, res, next) => {
if (DEPLOY_API_KEY && req.headers['x-deploy-api-key'] === DEPLOY_API_KEY) {
return next();
}
authenticateToken(req, res, next);
};
// JWT Authentication middleware
const authenticateToken = (req, res, next) => {
let token = null;
const authHeader = req.headers['authorization'];
if (authHeader && authHeader.startsWith('Bearer ')) {
token = authHeader.split(' ')[1];
}
if (!token) {
token = req.cookies && req.cookies['funcdock-token'];
}
if (!token) {
return res.status(401).json({ message: 'Access token required' });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ message: 'Invalid or expired token' });
}
if (tokenBlacklist.has(token)) {
return res.status(403).json({ message: 'Token has been revoked' });
}
req.user = user;
next();
});
};
// Socket.IO authentication
io.use((socket, next) => {
let token = socket.handshake.auth.token;
if (!token) {
const cookies = socket.handshake.headers.cookie;
if (cookies) {
const cookieObj = cookies.split(';').reduce((acc, cookie) => {
const [key, val] = cookie.trim().split('=');
acc[key] = val;
return acc;
}, {});
token = cookieObj['funcdock-token'];
}
}
if (!token) {
return next(new Error('Authentication error'));
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return next(new Error('Authentication error'));
}
if (tokenBlacklist.has(token)) {
return next(new Error('Token has been revoked'));
}
socket.user = user;
next();
});
});
// Socket.IO connection handling
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
});
});
// Global state
const loadedFunctions = new Map();
const loadedLayers = new Map(); // Track loaded layers
const layerToFunctions = new Map(); // Track which functions use which layers
const registeredRoutes = new Map();
const activeCronJobs = new Map(); // Track active cron jobs
const logger = new Logger();
// Single-instance in-memory OAuth token storage.
// For multi-instance deployments, replace with Redis or another shared store.
const userTokens = {};
// --- GitHub OAuth ---
const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID || 'YOUR_GITHUB_CLIENT_ID';
const GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET || 'YOUR_GITHUB_CLIENT_SECRET';
const GITHUB_REDIRECT_URI =
process.env.GITHUB_REDIRECT_URI || 'http://localhost:3000/api/oauth/github/callback';
// OAuth state storage (state token -> { timestamp, userId })
const oauthStates = new Map();
// Clean up expired OAuth states every 10 minutes
setInterval(() => {
const now = Date.now();
for (const [state, data] of oauthStates.entries()) {
if (now - data.timestamp > 600000) {
oauthStates.delete(state);
}
}
}, 600000);
app.get('/api/oauth/github', authenticateToken, (req, res) => {
const state = crypto.randomBytes(32).toString('hex');
oauthStates.set(state, { timestamp: Date.now(), userId: req.user.username });
const url = `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&redirect_uri=${encodeURIComponent(GITHUB_REDIRECT_URI)}&scope=repo&state=${state}`;
res.json({ url });
});
app.get('/api/oauth/github/callback', async (req, res) => {
const { code, state } = req.query;
if (!code) return res.status(400).send('Missing code');
if (!state || !oauthStates.has(state)) {
return res.status(400).send('Invalid or expired state parameter');
}
const stateData = oauthStates.get(state);
oauthStates.delete(state);
// Check state expiration (10 minutes)
if (Date.now() - stateData.timestamp > 600000) {
return res.status(400).send('Expired state parameter');
}
try {
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: GITHUB_CLIENT_ID,
client_secret: GITHUB_CLIENT_SECRET,
code,
redirect_uri: GITHUB_REDIRECT_URI,
}),
});
const tokenData = await tokenRes.json();
if (!tokenData.access_token) return res.status(400).json({ error: 'No access token' });
// For demo, associate token with user (by username)
const userRes = await fetch('https://api.github.com/user', {
headers: { Authorization: `token ${tokenData.access_token}` },
});
await userRes.json();
const funcDockUser = stateData.userId;
userTokens[`github:${funcDockUser}`] = tokenData.access_token;
// Redirect to dashboard with success (in production, use a better flow)
res.redirect('/dashboard?github=success');
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.get('/api/github/repos', authenticateToken, async (req, res) => {
try {
const username = req.user.username;
const token = userTokens[`github:${username}`];
if (!token) return res.status(401).json({ error: 'Not connected to GitHub' });
const ghRes = await fetch('https://api.github.com/user/repos?per_page=100', {
headers: { Authorization: `token ${token}` },
});
const repos = await ghRes.json();
res.json(repos);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// --- Bitbucket OAuth ---
const BITBUCKET_CLIENT_ID = process.env.BITBUCKET_CLIENT_ID || 'YOUR_BITBUCKET_CLIENT_ID';
const BITBUCKET_CLIENT_SECRET =
process.env.BITBUCKET_CLIENT_SECRET || 'YOUR_BITBUCKET_CLIENT_SECRET';
const BITBUCKET_REDIRECT_URI =
process.env.BITBUCKET_REDIRECT_URI || 'http://localhost:3000/api/oauth/bitbucket/callback';
app.get('/api/oauth/bitbucket', authenticateToken, (req, res) => {
const state = crypto.randomBytes(32).toString('hex');
oauthStates.set(state, { timestamp: Date.now(), userId: req.user.username });
const url = `https://bitbucket.org/site/oauth2/authorize?client_id=${BITBUCKET_CLIENT_ID}&response_type=code&redirect_uri=${encodeURIComponent(BITBUCKET_REDIRECT_URI)}&state=${state}`;
res.json({ url });
});
app.get('/api/oauth/bitbucket/callback', async (req, res) => {
const { code, state } = req.query;
if (!code) return res.status(400).send('Missing code');
if (!state || !oauthStates.has(state)) {
return res.status(400).send('Invalid or expired state parameter');
}
const stateData = oauthStates.get(state);
oauthStates.delete(state);
if (Date.now() - stateData.timestamp > 600000) {
return res.status(400).send('Expired state parameter');
}
try {
const tokenRes = await fetch('https://bitbucket.org/site/oauth2/access_token', {
method: 'POST',
headers: {
Authorization:
'Basic ' +
Buffer.from(`${BITBUCKET_CLIENT_ID}:${BITBUCKET_CLIENT_SECRET}`).toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `grant_type=authorization_code&code=${code}&redirect_uri=${encodeURIComponent(BITBUCKET_REDIRECT_URI)}`,
});
const tokenData = await tokenRes.json();
if (!tokenData.access_token) return res.status(400).json({ error: 'No access token' });
// For demo, associate token with user (by username)
const userRes = await fetch('https://api.bitbucket.org/2.0/user', {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
await userRes.json();
const funcDockUser = stateData.userId;
userTokens[`bitbucket:${funcDockUser}`] = tokenData.access_token;
res.redirect('/dashboard?bitbucket=success');
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.get('/api/bitbucket/repos', authenticateToken, async (req, res) => {
try {
const username = req.user.username;
const token = userTokens[`bitbucket:${username}`];
if (!token) return res.status(401).json({ error: 'Not connected to Bitbucket' });
const bbRes = await fetch('https://api.bitbucket.org/2.0/repositories?role=member', {
headers: { Authorization: `Bearer ${token}` },
});
const data = await bbRes.json();
res.json(data.values || []);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ES modules use ?update= query parameter for cache busting
// Load environment variables from function's .env file
const loadFunctionEnv = async (functionDir) => {
const envPath = path.join(functionDir, '.env');
try {
await fs.access(envPath);
const envContent = await fs.readFile(envPath, 'utf-8');
const envVars = {};
// Parse .env file content, support both '=' and ':' delimiters
envContent.split('\n').forEach((line) => {
line = line.trim();
if (line && !line.startsWith('#')) {
// Accept both KEY=VALUE and KEY: VALUE
let match = line.match(/^([^=:#]+)\s*[:=]\s*(.*)$/);
if (match) {
let key = match[1].trim();
let value = match[2].replace(/^"|"$/g, '').replace(/^'|'$/g, '').trim();
// Strip inline comments
value = value
.replace(/\s+#.*$/, '')
.replace(/\s+\/\/.*$/, '')
.trim();
envVars[key] = value;
}
}
});
logger.info(
`Loaded ${Object.keys(envVars).length} environment variables for function ${path.basename(functionDir)}`
);
return envVars;
} catch {
// .env file doesn't exist, return empty object
return {};
}
};
// Install dependencies for a function
const installDependencies = async (functionPath) => {
const packageJsonPath = path.join(functionPath, 'package.json');
const packageLockPath = path.join(functionPath, 'package-lock.json');
const nodeModulesPath = path.join(functionPath, 'node_modules');
try {
await fs.access(packageJsonPath);
// Check if dependencies are already installed and up to date
let needsInstall = false;
try {
// Check if node_modules exists
await fs.access(nodeModulesPath);
// Check if package-lock.json exists and is newer than package.json
try {
await fs.access(packageLockPath);
const packageJsonStats = await fs.stat(packageJsonPath);
const packageLockStats = await fs.stat(packageLockPath);
// If package.json is newer than package-lock.json, we need to install
if (packageJsonStats.mtime > packageLockStats.mtime) {
needsInstall = true;
}
} catch {
// No package-lock.json, need to install
needsInstall = true;
}
} catch {
// No node_modules, need to install
needsInstall = true;
}
if (!needsInstall) {
logger.info(`Dependencies already up to date for ${path.basename(functionPath)}`);
return true;
}
logger.info(`Installing dependencies for ${path.basename(functionPath)}`);
const { stderr } = await execAsync('npm install --ignore-scripts', {
cwd: functionPath,
timeout: 60000,
});
if (stderr && !stderr.includes('npm WARN')) {
logger.error(
`Dependency installation warnings for ${path.basename(functionPath)}: ${stderr}`,
{ stack: stderr }
);
}
logger.info(`Dependencies installed for ${path.basename(functionPath)}`);
return true;
} catch (error) {
logger.error(
`Failed to install dependencies for ${path.basename(functionPath)}: ${error.message}`,
{ stack: error.stack }
);
return false;
}
};
// Unregister routes for a function
const unregisterFunctionRoutes = (functionName) => {
const routesToRemove = [];
for (const [routeKey, funcName] of registeredRoutes.entries()) {
if (funcName === functionName) {
routesToRemove.push(routeKey);
}
}
routesToRemove.forEach((routeKey) => {
registeredRoutes.delete(routeKey);
functionDispatcher.delete(routeKey);
logger.info(`Unregistered route: ${routeKey}`);
});
};
// Load a single function
const loadFunction = async (functionDir) => {
const functionName = path.basename(functionDir);
const configPath = path.join(functionDir, 'route.config.json');
const releaseLock = await acquireLock(`function:${functionName}`);
let layerName = null;
try {
// Check if config file exists
await fs.access(configPath);
// Read and parse config first to get handler path
const configRaw = await fs.readFile(configPath, 'utf-8');
const config = JSON.parse(configRaw);
// Validate config
if (!config.routes || !Array.isArray(config.routes)) {
throw new Error('Invalid route.config.json: routes array is required');
}
const handlerFileName = config.handler || 'handler.js';
let handlerPath = path.join(functionDir, handlerFileName);
if (!handlerFileName.includes('.')) {
const jsPath = path.join(functionDir, handlerFileName + '.js');
const tsPath = path.join(functionDir, handlerFileName + '.ts');
try {
await fs.access(jsPath);
handlerPath = jsPath;
} catch {
try {
await fs.access(tsPath);
handlerPath = tsPath;
} catch {
throw new Error(`Handler file not found for ${handlerFileName}`);
}
}
} else {
try {
await fs.access(handlerPath);
} catch {
const ext = path.extname(handlerFileName);
if (ext === '.js') {
const tsPath = path.join(functionDir, handlerFileName.replace('.js', '.ts'));
try {
await fs.access(tsPath);
handlerPath = tsPath;
} catch {
throw new Error(
`Handler file not found: ${handlerFileName} or ${handlerFileName.replace('.js', '.ts')}`
);
}
} else {
throw new Error(`Handler file not found: ${handlerPath}`);
}
}
}
// Install dependencies if needed
const depsInstalled = await installDependencies(functionDir);
if (!depsInstalled) {
logger.alert(`Skipping function ${functionName} due to dependency installation failure`);
return false;
}
// Load and setup layer for this function
layerName = null;
const previousFunctionInfo = loadedFunctions.get(functionName);
// Clean up old layer association before reading new one
if (previousFunctionInfo && previousFunctionInfo.layerName) {
const oldLayerName = previousFunctionInfo.layerName;
try {
// Clean up old layer symlink
await layerLoader.removeLayerSymlink(functionDir, oldLayerName, logger);
// Remove from layer-to-function mapping
const functionsUsingLayer = layerToFunctions.get(oldLayerName);
if (functionsUsingLayer) {
functionsUsingLayer.delete(functionName);
if (functionsUsingLayer.size === 0) {
layerToFunctions.delete(oldLayerName);
}
}
} catch (cleanupError) {
// Log but continue - cleanup failure shouldn't block function loading
logger.error(
`Failed to cleanup old layer association for ${functionName}: ${cleanupError.message}`,
{ stack: cleanupError.stack }
);
// Ensure mapping is cleaned up even if symlink removal fails
const functionsUsingLayer = layerToFunctions.get(oldLayerName);
if (functionsUsingLayer) {
functionsUsingLayer.delete(functionName);
if (functionsUsingLayer.size === 0) {
layerToFunctions.delete(oldLayerName);
}
}
}
}
// Read layers.json to get layer name
let functionStatus = 'running';
let layerError = null;
try {
layerName = await layerLoader.readFunctionLayers(functionDir);
if (layerName) {
// Validate layer exists
const layer = loadedLayers.get(layerName);
if (!layer) {
logger.error(
`Function ${functionName} references layer '${layerName}' which is not loaded`
);
logger.alert(
`Function ${functionName} will fail at runtime if it imports from missing layer '${layerName}'`
);
functionStatus = 'error';
layerError = `Layer '${layerName}' not found`;
} else {
// Create symlink to layer
const symlinkCreated = await layerLoader.createLayerSymlink(
functionDir,
layerName,
layer.nodejsPath,
logger
);
if (symlinkCreated) {
// Track layer-to-function dependency
if (!layerToFunctions.has(layerName)) {
layerToFunctions.set(layerName, new Set());
}
layerToFunctions.get(layerName).add(functionName);
logger.info(`Function ${functionName} is using layer: ${layerName}`);
} else {
logger.error(
`Failed to create symlink for layer ${layerName} in function ${functionName}`
);
logger.alert(
`Function ${functionName} will fail at runtime if it imports from layer '${layerName}'`
);
functionStatus = 'error';
layerError = `Failed to create symlink for layer '${layerName}'`;
// Don't add to layerToFunctions map if symlink creation failed
}
}
}
} catch (error) {
logger.error(`Failed to read layers.json for function ${functionName}: ${error.message}`, {
stack: error.stack,
});
// If layers.json exists but is malformed, set error status
try {
await fs.access(path.join(functionDir, 'layers.json'));
functionStatus = 'error';
layerError = `Invalid layers.json format: ${error.message}`;
} catch {
// layers.json doesn't exist, that's fine - no layer specified
}
}
// Clear existing routes for this function
if (loadedFunctions.has(functionName)) {
unregisterFunctionRoutes(functionName);
}
// Import handler with cache busting for hot reload
const handlerModule = await import(`${handlerPath}?update=${Date.now()}`);
const handler = handlerModule.default;
if (typeof handler !== 'function') {
throw new Error('Handler must export a default function');
}
// Register routes
const functionRoutes = [];
const newlyRegisteredRoutes = [];
for (const route of config.routes) {
for (const method of route.methods) {
// Create full path with function name prefix to avoid conflicts
const basePath = config.base || `/${functionName}`;
// Handle dynamic routing - don't use path.join for Express routes
// Express routes can contain path parameters like :id, :userId, etc.
const routePath = route.path.startsWith('/') ? route.path : `/${route.path}`;
const fullPath = `${basePath}${routePath}`;
const routeKey = `${method.toUpperCase()} ${fullPath}`;
// Check for route conflicts
if (registeredRoutes.has(routeKey) && registeredRoutes.get(routeKey) !== functionName) {
logger.alert(
`Route conflict detected: ${routeKey} already registered by ${registeredRoutes.get(routeKey)}`
);
logger.error(`Failed to register ${functionName} due to route conflict`, { stack: null });
// Clean up any routes already registered in this attempt
for (const key of newlyRegisteredRoutes) {
registeredRoutes.delete(key);
functionDispatcher.delete(key);
}
return false;
}
// Determine handler for this specific route
const routeHandler = route.handler || config.handler || 'handler.js';
let routeHandlerPath = path.join(functionDir, routeHandler);
try {
await fs.access(routeHandlerPath);
} catch {
if (routeHandler.endsWith('.js')) {
const tsRouteHandler = routeHandler.replace('.js', '.ts');
routeHandlerPath = path.join(functionDir, tsRouteHandler);
try {
await fs.access(routeHandlerPath);
} catch {
throw new Error(`Route handler not found: ${routeHandler} or ${tsRouteHandler}`);
}
} else {
throw new Error(`Route handler not found: ${routeHandlerPath}`);
}
}
// Load the specific handler for this route
let routeHandlerFunction;
try {
const routeHandlerModule = await import(`${routeHandlerPath}?update=${Date.now()}`);
routeHandlerFunction = routeHandlerModule.default;
if (typeof routeHandlerFunction !== 'function') {
throw new Error(`Handler in ${routeHandler} must export a default function`);
}
} catch (error) {
logger.error(
`Failed to load handler ${routeHandler} for route ${fullPath}: ${error.message}`,
{ stack: error.stack }
);
// Clean up any routes already registered in this attempt
for (const key of newlyRegisteredRoutes) {
registeredRoutes.delete(key);
functionDispatcher.delete(key);
}
return false;
}
// Register the route in the dispatcher (not directly in Express)
registerDispatcherRoute(method, fullPath, functionName, routeHandlerFunction);
registeredRoutes.set(routeKey, functionName);
newlyRegisteredRoutes.push(routeKey);
functionRoutes.push({
method: method.toUpperCase(),
path: fullPath,
handler: routeHandler,
});
logger.info(
`Registered ${method.toUpperCase()} ${fullPath} -> ${functionName}/${routeHandler}`
);
}
}
// Load cron jobs for this function
await loadCronJobs(functionDir);
// Load environment variables for this function
const envVars = await loadFunctionEnv(functionDir);
// Store function info
loadedFunctions.set(functionName, {
name: functionName,
config,
handler,
routes: functionRoutes,
loadedAt: new Date(),
lastDeployed: new Date().toISOString(),
status: functionStatus,
path: functionDir,
envVars,
layerName: layerName || null,
layerError: layerError || null,
});
// Emit socket event for function loaded
io.emit('function:loaded', {
name: functionName,
status: functionStatus,
routes: functionRoutes.length,
cronJobs: activeCronJobs.has(functionName) ? activeCronJobs.get(functionName).length : 0,
layerName: layerName || null,
layerError: layerError || null,
});
logger.info(
`Successfully loaded function: ${functionName} with ${functionRoutes.length} routes`
);
return true;
} catch (error) {
logger.error(`Failed to load function ${functionName}: ${error.message}`, {
stack: error.stack,
});
// Ensure layer dependency tracking is cleaned up if function load fails
if (layerName) {
const functionsUsingLayer = layerToFunctions.get(layerName);
if (functionsUsingLayer) {
functionsUsingLayer.delete(functionName);
if (functionsUsingLayer.size === 0) {
layerToFunctions.delete(layerName);
}
}
}