-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathrun.js
330 lines (274 loc) · 11.1 KB
/
run.js
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
const Tail = require('tail').Tail;
const { parse: parseDotenv } = require('dotenv');
const chalk = require('chalk');
const ignore = require("ignore");
const tar = require("tar");
const fs = require("fs");
const chokidar = require('chokidar');
const inquirer = require("inquirer");
const path = require("path");
const { Command } = require("commander");
const { localConfig, globalConfig } = require("../config");
const { paginate } = require('../paginate');
const { functionsListVariables } = require('./functions');
const { questionsRunFunctions } = require("../questions");
const { actionRunner, success, log, warn, error, hint, commandDescriptions, drawTable } = require("../parser");
const { systemHasCommand, isPortTaken, getAllFiles } = require('../utils');
const { runtimeNames, systemTools, JwtManager, Queue } = require('../emulation/utils');
const { dockerStop, dockerCleanup, dockerStart, dockerBuild, dockerPull } = require('../emulation/docker');
const runFunction = async ({ port, functionId, withVariables, reload, userId } = {}) => {
// Selection
if(!functionId) {
const answers = await inquirer.prompt(questionsRunFunctions[0]);
functionId = answers.function;
}
const functions = localConfig.getFunctions();
const func = functions.find((f) => f.$id === functionId);
if (!func) {
throw new Error("Function '" + functionId + "' not found.")
}
const runtimeName = func.runtime.split("-").slice(0, -1).join("-");
const tool = systemTools[runtimeName];
// Configuration: Port
if(port) {
port = +port;
}
if(isNaN(port)) {
port = null;
}
if(port) {
const taken = await isPortTaken(port);
if(taken) {
error(`Port ${port} is already in use by another process.`);
return;
}
}
if(!port) {
let portFound = false;
port = 3000;
while(port < 3100) {
const taken = await isPortTaken(port);
if(!taken) {
portFound = true;
break;
}
port++;
}
if(!portFound) {
error("Could not find an available port. Please select a port with 'appwrite run --port YOUR_PORT' command.");
return;
}
}
// Configuration: Engine
if(!systemHasCommand('docker')) {
return error("Docker Engine is required for local development. Please install Docker using: https://docs.docker.com/engine/install/");
}
// Settings
const settings = {
runtime: func.runtime,
entrypoint: func.entrypoint,
path: func.path,
commands: func.commands,
scopes: func.scopes ?? []
};
drawTable([settings]);
log("If you wish to change your local settings, update the appwrite.json file and rerun the 'appwrite run' command.");
hint("Permissions, events, CRON and timeouts dont apply when running locally.");
await dockerCleanup(func.$id);
process.on('SIGINT', async () => {
log('Cleaning up ...');
await dockerCleanup(func.$id);
success("Local function successfully stopped.");
process.exit();
});
const logsPath = path.join(localConfig.getDirname(), func.path, '.appwrite/logs.txt');
const errorsPath = path.join(localConfig.getDirname(), func.path, '.appwrite/errors.txt');
if(!fs.existsSync(path.dirname(logsPath))) {
fs.mkdirSync(path.dirname(logsPath), { recursive: true });
}
if (!fs.existsSync(logsPath)) {
fs.writeFileSync(logsPath, '');
}
if (!fs.existsSync(errorsPath)) {
fs.writeFileSync(errorsPath, '');
}
const userVariables = {};
const allVariables = {};
if(withVariables) {
try {
const { variables: remoteVariables } = await paginate(functionsListVariables, {
functionId: func['$id'],
parseOutput: false
}, 100, 'variables');
remoteVariables.forEach((v) => {
allVariables[v.key] = v.value;
userVariables[v.key] = v.value;
});
} catch(err) {
warn("Remote variables not fetched. Production environment variables will not be available. Reason: " + err.message);
}
}
const functionPath = path.join(localConfig.getDirname(), func.path);
const envPath = path.join(functionPath, '.env');
if(fs.existsSync(envPath)) {
const env = parseDotenv(fs.readFileSync(envPath).toString() ?? '');
Object.keys(env).forEach((key) => {
allVariables[key] = env[key];
userVariables[key] = env[key];
});
}
allVariables['APPWRITE_FUNCTION_API_ENDPOINT'] = globalConfig.getFrom('endpoint');
allVariables['APPWRITE_FUNCTION_ID'] = func.$id;
allVariables['APPWRITE_FUNCTION_NAME'] = func.name;
allVariables['APPWRITE_FUNCTION_DEPLOYMENT'] = ''; // TODO: Implement when relevant
allVariables['APPWRITE_FUNCTION_PROJECT_ID'] = localConfig.getProject().projectId;
allVariables['APPWRITE_FUNCTION_RUNTIME_NAME'] = runtimeNames[runtimeName] ?? '';
allVariables['APPWRITE_FUNCTION_RUNTIME_VERSION'] = func.runtime;
try {
await JwtManager.setup(userId, func.scopes ?? []);
} catch(err) {
warn("Dynamic API key not generated. Header x-appwrite-key will not be set. Reason: " + err.message);
}
const headers = {};
headers['x-appwrite-key'] = JwtManager.functionJwt ?? '';
headers['x-appwrite-trigger'] = 'http';
headers['x-appwrite-event'] = '';
headers['x-appwrite-user-id'] = userId ?? '';
headers['x-appwrite-user-jwt'] = JwtManager.userJwt ?? '';
allVariables['OPEN_RUNTIMES_HEADERS'] = JSON.stringify(headers);
if(Object.keys(userVariables).length > 0) {
drawTable(Object.keys(userVariables).map((key) => ({
key,
value: userVariables[key].split("").filter((_, i) => i < 16).map(() => "*").join("")
})));
}
await dockerPull(func);
new Tail(logsPath).on("line", function(data) {
process.stdout.write(chalk.white(`${data}\n`));
});
new Tail(errorsPath).on("line", function(data) {
process.stdout.write(chalk.white(`${data}\n`));
});
if(reload) {
const ignorer = ignore();
ignorer.add('.appwrite');
ignorer.add('code.tar.gz');
if (func.ignore) {
ignorer.add(func.ignore);
} else if (fs.existsSync(path.join(functionPath, '.gitignore'))) {
ignorer.add(fs.readFileSync(path.join(functionPath, '.gitignore')).toString());
}
chokidar.watch('.', {
cwd: path.join(localConfig.getDirname(), func.path),
ignoreInitial: true,
ignored: (xpath) => {
const relativePath = path.relative(functionPath, xpath);
if(!relativePath) {
return false;
}
return ignorer.ignores(relativePath);
}
}).on('all', async (_event, filePath) => {
Queue.push(filePath);
});
}
Queue.events.on('reload', async ({ files }) => {
Queue.lock();
try {
await dockerStop(func.$id);
const dependencyFile = files.find((filePath) => tool.dependencyFiles.includes(filePath));
if(tool.isCompiled || dependencyFile) {
log(`Rebuilding the function due to file changes ...`);
await dockerBuild(func, allVariables);
if(!Queue.isEmpty()) {
Queue.unlock();
return;
}
await dockerStart(func, allVariables, port);
} else {
log('Hot-swapping function.. Files with change are ' + files.join(', '));
const hotSwapPath = path.join(functionPath, '.appwrite/hot-swap');
const buildPath = path.join(functionPath, '.appwrite/build.tar.gz');
// Prepare temp folder
if (!fs.existsSync(hotSwapPath)) {
fs.mkdirSync(hotSwapPath, { recursive: true });
} else {
fs.rmSync(hotSwapPath, { recursive: true, force: true });
fs.mkdirSync(hotSwapPath, { recursive: true });
}
await tar
.extract({
keep: true,
gzip: true,
sync: true,
cwd: hotSwapPath,
file: buildPath
});
const ignorer = ignore();
ignorer.add('.appwrite');
if (func.ignore) {
ignorer.add(func.ignore);
} else if (fs.existsSync(path.join(functionPath, '.gitignore'))) {
ignorer.add(fs.readFileSync(path.join(functionPath, '.gitignore')).toString());
}
const filesToCopy = getAllFiles(functionPath).map((file) => path.relative(functionPath, file)).filter((file) => !ignorer.ignores(file));
for(const f of filesToCopy) {
const filePath = path.join(hotSwapPath, f);
if (fs.existsSync(filePath)) {
fs.rmSync(filePath, { force: true });
}
const fileDir = path.dirname(filePath);
if (!fs.existsSync(fileDir)) {
fs.mkdirSync(fileDir, { recursive: true });
}
const sourcePath = path.join(functionPath, f);
fs.copyFileSync(sourcePath, filePath);
}
await tar
.create({
gzip: true,
sync: true,
cwd: hotSwapPath,
file: buildPath
}, ['.']);
await dockerStart(func, allVariables, port);
}
} catch(err) {
console.error(err);
} finally {
Queue.unlock();
}
});
Queue.lock();
log('Building function using Docker ...');
await dockerBuild(func, allVariables);
if(!Queue.isEmpty()) {
Queue.unlock();
return;
}
log('Starting function using Docker ...');
hint('Function automatically restarts when you edit your code.');
await dockerStart(func, allVariables, port);
Queue.unlock();
}
const run = new Command("run")
.description(commandDescriptions['run'])
.configureHelp({
helpWidth: process.stdout.columns || 80
})
.action(actionRunner(async (_options, command) => {
command.help();
}));
run
.command("function")
.alias("functions")
.description("Run functions in the current directory.")
.option(`--function-id <function-id>`, `ID of function to run`)
.option(`--port <port>`, `Local port`)
.option(`--user-id <user-id>`, `ID of user to impersonate`)
.option(`--with-variables`, `Run with function variables from function settings`)
.option(`--no-reload`, `Prevent live reloading of server when changes are made to function files`)
.action(actionRunner(runFunction));
module.exports = {
run
}