forked from metacall/faas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
280 lines (227 loc) · 6.93 KB
/
api.ts
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
import { spawn } from 'child_process';
import colors from 'colors';
import { NextFunction, Request, Response } from 'express';
import { hostname } from 'os';
import * as path from 'path';
import deployDeleteController from './controller/delete';
import uploadController from './controller/upload';
import {
allApplications,
childProcessResponse,
cps,
currentFile,
deleteBody,
deployBody,
fetchBranchListBody,
fetchFilesFromRepoBody,
protocol
} from './constants';
import AppError from './utils/appError';
import {
calculatePackages,
catchAsync,
dirName,
ensureFolderExists,
execPromise,
exists,
getCorrectNameWithVersion,
installDependencies,
isIAllApps,
listDirectoriesWithPrefix
} from './utils/utils';
import { appsDirectory } from './utils/config';
const appsDir = appsDirectory();
colors.enable();
export const callFnByName = (
req: Request,
res: Response,
next: NextFunction
): Response | void => {
if (!(req.params && req.params.name))
next(
new AppError(
'A function name is required in the path; i.e: /call/sum.',
404
)
);
const { appName: app, name } = req.params;
const args = Object.values(req.body);
if (!(app in cps)) {
return res
.status(404)
.send(
`Oops! It looks like the application (${app}) hasn't been deployed yet. Please deploy it before you can call its functions.`
);
}
let responseSent = false; // Flag to track if response has been sent
let errorCame = false;
cps[app].send({
type: protocol.c,
fn: {
name,
args
}
});
cps[app].on('message', (data: childProcessResponse) => {
if (!responseSent) {
// Check if response has already been sent
if (data.type === protocol.r) {
responseSent = true; // Set flag to true to indicate response has been sent
return res.send(JSON.stringify(data.data));
} else {
errorCame = true;
}
}
});
// Default response in case the 'message' event is not triggered
if (!responseSent && errorCame) {
responseSent = true; // Set flag to true to indicate response has been sent
errorCame = false;
return res.send('Function calling error');
}
};
export const serveStatic = catchAsync(
async (req: Request, res: Response, next: NextFunction) => {
if (!req.params) next(new AppError('Invalid API endpoint', 404));
const { app, file } = req.params;
const appLocation = path.join(appsDir, `${app}/${file}`);
// TODO - The best way to handle this is first list all the application which has been deployed and match if there is application or not and then go for file search
if (!(await exists(appLocation)))
next(
new AppError(
"The file you're looking for might not be available or the application may not be deployed.",
404
)
);
res.status(200).sendFile(appLocation);
}
);
export const fetchFiles = (
req: Request,
res: Response,
next: NextFunction
): void => uploadController(req, res, next);
export const fetchFilesFromRepo = catchAsync(
async (
req: Omit<Request, 'body'> & { body: fetchFilesFromRepoBody },
res: Response
) => {
const { branch, url } = req.body;
await ensureFolderExists(appsDir);
const repoName = dirName(url);
const appsWithSameName = listDirectoriesWithPrefix(repoName, appsDir);
const appName = getCorrectNameWithVersion(repoName, appsWithSameName);
await execPromise(
`cd ${appsDir}; git clone --single-branch --depth=1 --branch ${branch} ${url} ${appName}`
);
currentFile['id'] = appName;
currentFile.path = `${appsDir}/${appName}`;
res.status(201).send({ appName });
}
);
export const fetchBranchList = catchAsync(
async (
req: Omit<Request, 'body'> & { body: fetchBranchListBody },
res: Response
) => {
const { stdout } = await execPromise(
`git ls-remote --heads ${req.body.url}`
);
const branches: string[] = [];
JSON.stringify(stdout.toString())
.split('\\n')
.forEach(el => {
if (el.trim().length > 1) {
branches.push(el.split('refs/heads/')[1]);
}
});
res.send({ branches });
}
);
export const fetchFileList = catchAsync(
async (
req: Omit<Request, 'body'> & { body: fetchFilesFromRepoBody },
res: Response
) => {
await ensureFolderExists(appsDir);
const repoName = dirName(req.body.url);
const appsWithSameName = listDirectoriesWithPrefix(repoName, appsDir);
const appName = getCorrectNameWithVersion(repoName, appsWithSameName);
await execPromise(
`cd ${appsDir} ; git clone ${req.body.url} ${appName} --depth=1 --no-checkout`
);
const dirPath = `${appsDir}/${appName}`;
const { stdout } = await execPromise(
`cd ${dirPath} ; git ls-tree -r ${req.body.branch} --name-only; cd .. ; rm -r ${dirPath}`
);
res.send({ files: JSON.stringify(stdout.toString()).split('\\n') });
}
);
export const deploy = catchAsync(
async (
req: Omit<Request, 'body'> & { body: deployBody },
res: Response
) => {
req.body.resourceType == 'Repository' && (await calculatePackages());
// TODO Currently Deploy function will only work for workdir, we will add the addRepo
await installDependencies();
const desiredPath = path.join(__dirname, '/worker/index.js');
const proc = spawn('metacall', [desiredPath], {
stdio: ['pipe', 'pipe', 'pipe', 'ipc']
});
proc.send({
type: protocol.l,
currentFile
});
proc.stdout?.on('data', (data: Buffer) => {
console.log(data.toString().green);
});
proc.stderr?.on('data', (data: Buffer) => {
console.log(data.toString().red);
});
proc.on('message', (data: childProcessResponse) => {
if (data.type === protocol.g) {
if (isIAllApps(data.data)) {
const appName = Object.keys(data.data)[0];
cps[appName] = proc;
allApplications[appName] = data.data[appName];
}
}
});
res.status(200).json({
suffix: hostname(),
prefix: currentFile.id,
version: 'v1'
});
// Handle err == PackageError.Empty, use next function for error handling
}
);
export const showLogs = (req: Request, res: Response): Response => {
return res.send('Demo Logs...');
};
export const deployDelete = (
req: Omit<Request, 'body'> & { body: deleteBody },
res: Response
): Response => deployDeleteController(req, res);
export const validateAndDeployEnabled = (
req: Request,
res: Response
): Response =>
res.status(200).json({
status: 'success',
data: true
});
/**
* deploy
* Provide a mesage that repo has been deployed, use --inspect to know more about deployment
* We can add the type of url in the --inspect
* If there is already metacall.json present then, log found metacall.json and reading it, reading done
* We must an option to go back in the fileselection wizard so that, user dont have to close the connection
* At the end of deployment through deploy cli, we should run the --inspect command so that current deployed file is shown and show only the current deployed app
*
*
* FAAS
* the apps are not getting detected once the server closes, do we need to again deploy them
* find a way to detect metacall.json in the files and dont deploy if there is not because json ke through we are uploading
*
*/