forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
251 lines (214 loc) · 8.29 KB
/
index.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
import type {IncomingMessage, ServerResponse} from 'http';
import {createServer} from 'http';
import type {NativeCommand, TestResult} from '@libs/E2E/client';
import type {NetworkCacheMap, TestConfig} from '@libs/E2E/types';
import config from '../config';
import * as nativeCommands from '../nativeCommands';
import * as Logger from '../utils/logger';
import Routes from './routes';
type NetworkCache = {
appInstanceId: string;
cache: NetworkCacheMap;
};
type RequestData = TestResult | NativeCommand | NetworkCache;
type TestStartedListener = (testConfig?: TestConfig) => void;
type TestDoneListener = () => void;
type TestResultListener = (testResult: TestResult) => void;
type AddListener<TListener> = (listener: TListener) => () => void;
type ClearAllListeners = () => void;
type ServerInstance = {
setTestConfig: (testConfig: TestConfig) => void;
getTestConfig: () => TestConfig;
addTestStartedListener: AddListener<TestStartedListener>;
addTestResultListener: AddListener<TestResultListener>;
addTestDoneListener: AddListener<TestDoneListener>;
clearAllTestDoneListeners: ClearAllListeners;
forceTestCompletion: () => void;
setReadyToAcceptTestResults: (isReady: boolean) => void;
isReadyToAcceptTestResults: boolean;
start: () => Promise<void>;
stop: () => Promise<Error | undefined>;
};
const PORT = process.env.PORT ?? config.SERVER_PORT;
// Gets the request data as a string
const getReqData = (req: IncomingMessage): Promise<string> => {
let data = '';
req.on('data', (chunk: string) => {
data += chunk;
});
return new Promise((resolve) => {
req.on('end', () => {
resolve(data);
});
});
};
// Expects a POST request with JSON data. Returns parsed JSON data.
const getPostJSONRequestData = <TRequestData extends RequestData>(req: IncomingMessage, res: ServerResponse<IncomingMessage>): Promise<TRequestData | undefined> | undefined => {
if (req.method !== 'POST') {
res.statusCode = 400;
res.end('Unsupported method');
return;
}
return getReqData(req).then((data): TRequestData | undefined => {
try {
return JSON.parse(data) as TRequestData;
} catch (e) {
Logger.info('❌ Failed to parse request data', data);
res.statusCode = 400;
res.end('Invalid JSON');
}
});
};
const createListenerState = <TListener>(): [TListener[], AddListener<TListener>, ClearAllListeners] => {
const listeners: TListener[] = [];
const addListener = (listener: TListener) => {
listeners.push(listener);
return () => {
const index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
};
};
const clearAllListeners = () => {
listeners.splice(0, listeners.length);
};
return [listeners, addListener, clearAllListeners];
};
/**
* Creates a new http server.
* The server just has two endpoints:
*
* - POST: /test_results, expects a {@link TestResult} as JSON body.
* Send test results while a test runs.
* - GET: /test_done, expected to be called when test run signals it's done
*
* It returns an instance to which you can add listeners for the test results, and test done events.
*/
const createServerInstance = (): ServerInstance => {
const [testStartedListeners, addTestStartedListener] = createListenerState<TestStartedListener>();
const [testResultListeners, addTestResultListener] = createListenerState<TestResultListener>();
const [testDoneListeners, addTestDoneListener, clearAllTestDoneListeners] = createListenerState<TestDoneListener>();
let isReadyToAcceptTestResults = true;
const setReadyToAcceptTestResults = (isReady: boolean) => {
isReadyToAcceptTestResults = isReady;
};
const forceTestCompletion = () => {
testDoneListeners.forEach((listener) => {
listener();
});
};
let activeTestConfig: TestConfig | undefined;
const networkCache: Record<string, NetworkCacheMap> = {};
const setTestConfig = (testConfig: TestConfig) => {
activeTestConfig = testConfig;
};
const getTestConfig = (): TestConfig => {
if (!activeTestConfig) {
throw new Error('No test config set');
}
return activeTestConfig;
};
const server = createServer((req, res): ServerResponse<IncomingMessage> | void => {
res.statusCode = 200;
switch (req.url) {
case Routes.testConfig: {
testStartedListeners.forEach((listener) => listener(activeTestConfig));
if (!activeTestConfig) {
throw new Error('No test config set');
}
return res.end(JSON.stringify(activeTestConfig));
}
case Routes.testResults: {
if (!isReadyToAcceptTestResults) {
return res.end('ok');
}
getPostJSONRequestData<TestResult>(req, res)?.then((data) => {
if (!data) {
// The getPostJSONRequestData function already handled the response
return;
}
testResultListeners.forEach((listener) => {
listener(data);
});
res.end('ok');
});
break;
}
case Routes.testDone: {
forceTestCompletion();
return res.end('ok');
}
case Routes.testNativeCommand: {
getPostJSONRequestData<NativeCommand>(req, res)
?.then((data) => {
const status = nativeCommands.executeFromPayload(data?.actionName, data?.payload);
if (status) {
res.end('ok');
return;
}
res.statusCode = 500;
res.end('Error executing command');
})
.catch((error: string) => {
Logger.error('Error executing command', error);
res.statusCode = 500;
res.end('Error executing command');
});
break;
}
case Routes.testGetNetworkCache: {
getPostJSONRequestData<NetworkCache>(req, res)?.then((data) => {
const appInstanceId = data?.appInstanceId;
if (!appInstanceId) {
res.statusCode = 400;
res.end('Invalid request missing appInstanceId');
return;
}
const cachedData = networkCache[appInstanceId] ?? {};
res.end(JSON.stringify(cachedData));
});
break;
}
case Routes.testUpdateNetworkCache: {
getPostJSONRequestData<NetworkCache>(req, res)?.then((data) => {
const appInstanceId = data?.appInstanceId;
const cache = data?.cache;
if (!appInstanceId || !cache) {
res.statusCode = 400;
res.end('Invalid request missing appInstanceId or cache');
return;
}
networkCache[appInstanceId] = cache;
res.end('ok');
});
break;
}
default:
res.statusCode = 404;
res.end('Page not found!');
}
});
return {
setReadyToAcceptTestResults,
get isReadyToAcceptTestResults() {
return isReadyToAcceptTestResults;
},
setTestConfig,
getTestConfig,
addTestStartedListener,
addTestResultListener,
addTestDoneListener,
clearAllTestDoneListeners,
forceTestCompletion,
start: () =>
new Promise<void>((resolve) => {
server.listen(PORT, resolve);
}),
stop: () =>
new Promise<Error | undefined>((resolve) => {
server.close(resolve);
}),
};
};
export default createServerInstance;