-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcore.ts
421 lines (381 loc) · 11.8 KB
/
core.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
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
/**
* The entry point for all API calls to wikis is the
* mwn#request() method in bot.ts. This function uses
* the Request and Response classes defined in this file.
*/
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import axiosCookieJarSupport from 'axios-cookiejar-support';
import * as FormData from 'form-data';
import * as OAuth from 'oauth-1.0a';
import type { ApiParams, Mwn } from './bot';
import { log } from './log';
import { MwnError, rejectWithError } from './error';
import { merge, mergeDeep1, sleep } from './utils';
import { ApiResponse } from './api_response_types';
axiosCookieJarSupport(axios);
export interface RawRequestParams extends AxiosRequestConfig {
retryNumber?: number;
}
export class Request {
apiParams: ApiParams;
requestParams: RawRequestParams;
bot: Mwn;
constructor(bot: Mwn, apiParams: ApiParams, requestParams: RawRequestParams) {
this.bot = bot;
this.apiParams = apiParams;
this.requestParams = requestParams;
}
async process() {
this.apiParams = merge(this.bot.options.defaultParams, this.apiParams);
this.preprocessParams();
await this.fillRequestOptions();
}
getMethod() {
if (this.apiParams.action === 'query') {
return 'get';
}
if (this.apiParams.action === 'parse' && !this.apiParams.text) {
return 'get';
}
return 'post';
}
MULTIPART_THRESHOLD = 8000;
hasLongFields = false;
preprocessParams() {
let params = this.apiParams;
Object.entries(params).forEach(([key, val]) => {
if (Array.isArray(val)) {
if (!val.join('').includes('|')) {
params[key] = val.join('|');
} else {
params[key] = '\x1f' + val.join('\x1f');
}
}
if (val === false || val === undefined) {
delete params[key];
} else if (val === true) {
params[key] = '1'; // booleans cause error with multipart/form-data requests
} else if (val instanceof Date) {
params[key] = val.toISOString();
} else if (String(params[key]).length > this.MULTIPART_THRESHOLD) {
// use multipart/form-data if there are large fields, for better performance
this.hasLongFields = true;
}
});
}
async fillRequestOptions() {
let method = this.getMethod();
this.requestParams = mergeDeep1(
{
url: this.bot.options.apiUrl,
method,
// retryNumber isn't actually used by the API, but this is
// included here for tracking our maxlag retry count.
retryNumber: 0,
},
this.bot.requestOptions,
this.requestParams
);
if (method === 'get') {
this.handleGet();
} else {
await this.handlePost();
}
this.applyAuthentication();
}
applyAuthentication() {
let requestOptions = this.requestParams;
if (this.bot.usingOAuth2) {
// OAuth 2 authentication
requestOptions.headers['Authorization'] = `Bearer ${this.bot.options.OAuth2AccessToken}`;
} else if (this.bot.usingOAuth) {
// OAuth 1a authentication
requestOptions.headers = {
...requestOptions.headers,
...this.makeOAuthHeader({
url: requestOptions.url,
method: requestOptions.method,
data: requestOptions.data instanceof FormData ? {} : this.apiParams,
}),
};
} else {
// BotPassword authentication
requestOptions.jar = this.bot.cookieJar;
requestOptions.withCredentials = true;
}
}
/**
* Get OAuth Authorization header
*/
makeOAuthHeader(params: OAuth.RequestOptions): OAuth.Header {
return this.bot.oauth.toHeader(
this.bot.oauth.authorize(params, {
key: this.bot.options.OAuthCredentials.accessToken,
secret: this.bot.options.OAuthCredentials.accessSecret,
})
);
}
handleGet() {
// axios takes care of stringifying to URL query string
this.requestParams.params = this.apiParams;
}
async handlePost() {
// Shift the token to the end of the query string, to prevent
// incomplete data sent from being accepted meaningfully by the server
let params = this.apiParams;
if (params.token) {
let token = params.token;
delete params.token;
params.token = token;
}
if (this.useMultipartFormData()) {
await this.handlePostMultipartFormData();
} else {
// use application/x-www-form-urlencoded (default)
// requestOptions.data = params;
this.requestParams.data = Object.entries(params)
.map(([key, val]) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(val as string);
})
.join('&');
}
}
useMultipartFormData() {
let ctype = this.requestParams?.headers?.['Content-Type'];
if (ctype === 'multipart/form-data') {
return true;
} else if (this.hasLongFields && ctype === undefined) {
return true;
}
return false;
}
async handlePostMultipartFormData() {
let params = this.apiParams,
requestOptions = this.requestParams;
let form = new FormData();
for (let [key, val] of Object.entries(params)) {
if (val instanceof Object && 'stream' in val) {
// TypeScript facepalm
form.append(key, val.stream, val.name);
} else {
form.append(key, val);
}
}
requestOptions.data = form;
requestOptions.headers = await new Promise((resolve, reject) => {
form.getLength((err, length) => {
if (err) {
reject(err);
}
resolve({
...requestOptions.headers,
...form.getHeaders(),
'Content-Length': length,
});
});
});
}
}
export class Response {
bot: Mwn;
params: ApiParams;
requestOptions: RawRequestParams;
rawResponse: AxiosResponse<ApiResponse>;
response: ApiResponse;
constructor(bot: Mwn, params: ApiParams, requestOptions: RawRequestParams) {
this.bot = bot;
this.params = params;
this.requestOptions = requestOptions;
}
async process(rawResponse: AxiosResponse<ApiResponse>) {
this.rawResponse = rawResponse;
this.response = rawResponse.data;
await this.initialCheck();
this.showWarnings();
return (await this.handleErrors()) || this.response;
}
async initialCheck(): Promise<void> {
if (typeof this.response !== 'object') {
if (this.params.format !== 'json') {
return rejectWithError({
code: 'mwn_invalidformat',
info: 'Must use format=json!',
response: this.response,
});
}
return rejectWithError({
code: 'invalidjson',
info: 'No valid JSON response',
response: this.response,
});
}
}
showWarnings() {
if (this.response.warnings && !this.bot.options.suppressAPIWarnings) {
if (Array.isArray(this.response.warnings)) {
// new error formats
for (let { code, module, info, html, text } of this.response.warnings) {
if (code === 'deprecation-help') {
// skip
continue;
}
const msg =
info || // errorformat=bc
text || // errorformat=wikitext/plaintext
html; // errorformat=html
log(`[W] Warning received from API: ${module}: ${msg}`);
}
} else {
// legacy error format (bc)
for (let [key, info] of Object.entries(this.response.warnings)) {
// @ts-ignore
log(`[W] Warning received from API: ${key}: ${info.warnings}`);
}
}
}
}
async handleErrors(): Promise<void | ApiResponse> {
let error =
this.response.error || // errorformat=bc (default)
this.response.errors?.[0]; // other error formats
if (error) {
error = new MwnError(error);
if (this.requestOptions.retryNumber < this.bot.options.maxRetries) {
switch (error.code) {
// This will not work if the token type to be used is defined by an
// extension, and not a part of mediawiki core
case 'badtoken':
log(`[W] Encountered badtoken error, fetching new token and retrying`);
return Promise.all([
this.bot.getTokenType(this.params.action as string),
this.bot.getTokens(),
]).then(([tokentype]) => {
if (!tokentype || !this.bot.state[tokentype + 'token']) {
return this.dieWithError(error);
}
this.params.token = this.bot.state[tokentype + 'token'];
return this.retry();
});
case 'readonly':
log(
`[W] Encountered readonly error, waiting for ${
this.bot.options.retryPause / 1000
} seconds before retrying`
);
return sleep(this.bot.options.retryPause).then(() => {
return this.retry();
});
case 'maxlag':
// Handle maxlag, see https://www.mediawiki.org/wiki/Manual:Maxlag_parameter
// eslint-disable-next-line no-case-declarations
let pause = parseInt(this.rawResponse.headers['retry-after']); // axios uses lowercase headers
// retry-after appears to be usually 5 for WMF wikis
if (isNaN(pause)) {
pause = this.bot.options.retryPause / 1000;
}
log(
`[W] Encountered maxlag: ${error.lag} seconds lagged. Waiting for ${pause} seconds before retrying`
);
return sleep(pause * 1000).then(() => {
return this.retry();
});
case 'assertbotfailed':
case 'assertuserfailed':
// this shouldn't have happened if we're using OAuth
if (this.bot.usingOAuth) {
return this.dieWithError(error);
}
// Possibly due to session loss: retry after logging in again
log(`[W] Received ${error.code}, attempting to log in and retry`);
return this.bot.login().then(() => {
return this.retry();
});
case 'mwoauth-invalid-authorization':
// Per https://phabricator.wikimedia.org/T106066, "Nonce already used" indicates
// an upstream memcached/redis failure which is transient
// Also handled in mwclient (https://github.com/mwclient/mwclient/pull/165/commits/d447c333e)
// and pywikibot (https://gerrit.wikimedia.org/r/c/pywikibot/core/+/289582/1/pywikibot/data/api.py)
// Some discussion in https://github.com/mwclient/mwclient/issues/164
if (error.info.includes('Nonce already used')) {
log(
`[W] Retrying failed OAuth authentication in ${
this.bot.options.retryPause / 1000
} seconds`
);
return sleep(this.bot.options.retryPause).then(() => {
return this.retry();
});
} else {
return this.dieWithError(error);
}
default:
return this.dieWithError(error);
}
} else {
return this.dieWithError(error);
}
}
}
retry() {
this.requestOptions.retryNumber += 1;
return this.bot.request(this.params, this.requestOptions);
}
dieWithError(error: any): Promise<never> {
let response = this.rawResponse,
requestOptions = this.requestOptions;
let errorData = Object.assign({}, error, {
// Enhance error object with additional information:
// the full API response: everything in AxiosResponse object except
// config (not needed) and request (included as errorData.request instead)
response: {
data: response.data,
status: response.status,
statusText: response.statusText,
headers: response.headers,
},
// the original request, should the client want to retry the request
request: requestOptions,
});
return rejectWithError(errorData);
}
/**
* This handles errors at the network level
* @param {Object} error
*/
handleRequestFailure(error: any) {
if (
!error.disableRetry &&
!(error instanceof TypeError) &&
this.requestOptions.retryNumber < this.bot.options.maxRetries &&
// ENOTFOUND usually means bad apiUrl is provided, retrying is pointless and annoying
error.code !== 'ENOTFOUND' &&
(!error.response?.status ||
// Vaguely retriable error codes
[408, 409, 425, 429, 500, 502, 503, 504].includes(error.response.status))
) {
// error might be transient, give it another go!
this.logError(error);
return sleep(this.bot.options.retryPause).then(() => {
return this.retry();
});
}
error.request = this.requestOptions;
return rejectWithError(error);
}
logError(err: any) {
log(`[W] Retrying in ${this.bot.options.retryPause / 1000} seconds: encountered ${err}`);
const errorData = {
request: {
method: err?.request?.method,
path: err?.request?.path,
},
response: {
status: err?.response?.status,
statusText: err?.response?.statusText,
headers: err?.response?.headers,
data: err?.response?.data,
},
};
console.log(errorData);
}
}