@certik/skynet 0.25.0 → 0.25.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.vscode/settings.json +5 -0
- package/CHANGELOG.md +10 -0
- package/README.md +8 -2
- package/dist/abi.d.ts +111 -0
- package/dist/abi.js +571 -0
- package/dist/address.d.ts +2 -0
- package/dist/address.js +24 -0
- package/dist/api.d.ts +31 -0
- package/dist/api.js +260 -0
- package/dist/app.d.ts +101 -0
- package/dist/app.js +2077 -0
- package/dist/availability.d.ts +23 -0
- package/dist/availability.js +133 -0
- package/dist/cli.d.ts +5 -0
- package/dist/cli.js +41 -0
- package/dist/const.d.ts +34 -0
- package/dist/const.js +162 -0
- package/dist/date.d.ts +5 -0
- package/dist/date.js +56 -0
- package/dist/deploy.d.ts +75 -0
- package/dist/deploy.js +587 -0
- package/dist/dynamodb.d.ts +16 -0
- package/dist/dynamodb.js +479 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +26 -0
- package/dist/goalert.d.ts +19 -0
- package/dist/goalert.js +43 -0
- package/dist/graphql.d.ts +6 -0
- package/dist/graphql.js +35 -0
- package/dist/indexer.d.ts +69 -0
- package/dist/indexer.js +1099 -0
- package/dist/log.d.ts +13 -0
- package/dist/log.js +63 -0
- package/dist/object-hash.d.ts +1 -0
- package/dist/object-hash.js +61 -0
- package/dist/por.d.ts +37 -0
- package/dist/por.js +120 -0
- package/dist/s3.d.ts +20 -0
- package/dist/s3.js +122 -0
- package/dist/search.d.ts +5 -0
- package/dist/search.js +105 -0
- package/dist/selector.d.ts +17 -0
- package/dist/selector.js +44 -0
- package/dist/slack.d.ts +14 -0
- package/dist/slack.js +29 -0
- package/dist/util.d.ts +4 -0
- package/dist/util.js +27 -0
- package/examples/api.ts +0 -0
- package/examples/indexer.ts +0 -0
- package/examples/mode-indexer.ts +0 -0
- package/package.json +1 -1
- package/src/deploy.ts +1 -1
package/dist/indexer.js
ADDED
|
@@ -0,0 +1,1099 @@
|
|
|
1
|
+
// src/selector.ts
|
|
2
|
+
function getSelectorDesc(selector) {
|
|
3
|
+
return Object.keys(selector).map((name) => {
|
|
4
|
+
return ` --${name.padEnd(14)}${selector[name].desc || selector[name].description || ""}`;
|
|
5
|
+
}).join(`
|
|
6
|
+
`);
|
|
7
|
+
}
|
|
8
|
+
function getSelectorFlags(selector) {
|
|
9
|
+
return Object.keys(selector).reduce((acc, name) => {
|
|
10
|
+
const flag = {
|
|
11
|
+
type: selector[name].type || "string",
|
|
12
|
+
...selector[name]
|
|
13
|
+
};
|
|
14
|
+
if (!selector[name].optional && selector[name].isRequired !== false) {
|
|
15
|
+
flag.isRequired = true;
|
|
16
|
+
}
|
|
17
|
+
return { ...acc, [name]: flag };
|
|
18
|
+
}, {});
|
|
19
|
+
}
|
|
20
|
+
function toSelectorString(selectorFlags, delim = ",") {
|
|
21
|
+
return Object.keys(selectorFlags).sort().map((flag) => {
|
|
22
|
+
return `${flag}=${selectorFlags[flag]}`;
|
|
23
|
+
}).join(delim);
|
|
24
|
+
}
|
|
25
|
+
function normalizeSelectorValue(v) {
|
|
26
|
+
return v.replace(/[^A-Za-z0-9]+/g, "-");
|
|
27
|
+
}
|
|
28
|
+
function getJobName(name, selectorFlags, mode) {
|
|
29
|
+
const selectorNamePart = Object.keys(selectorFlags).sort().map((name2) => selectorFlags[name2]).join("-");
|
|
30
|
+
let jobName = name;
|
|
31
|
+
if (mode) {
|
|
32
|
+
jobName += `-${mode}`;
|
|
33
|
+
}
|
|
34
|
+
if (selectorNamePart.length > 0) {
|
|
35
|
+
jobName += `-${normalizeSelectorValue(selectorNamePart)}`;
|
|
36
|
+
}
|
|
37
|
+
return jobName;
|
|
38
|
+
}
|
|
39
|
+
// src/env.ts
|
|
40
|
+
function ensureAndGet(envName, defaultValue) {
|
|
41
|
+
return process.env[envName] || defaultValue;
|
|
42
|
+
}
|
|
43
|
+
function getEnvironment() {
|
|
44
|
+
return ensureAndGet("SKYNET_ENVIRONMENT", "dev");
|
|
45
|
+
}
|
|
46
|
+
function getEnvOrThrow(envName) {
|
|
47
|
+
if (!process.env[envName]) {
|
|
48
|
+
throw new Error(`Must set environment variable ${envName}`);
|
|
49
|
+
}
|
|
50
|
+
return process.env[envName];
|
|
51
|
+
}
|
|
52
|
+
function isProduction() {
|
|
53
|
+
return getEnvironment() === "prd";
|
|
54
|
+
}
|
|
55
|
+
function isDev() {
|
|
56
|
+
return getEnvironment() === "dev";
|
|
57
|
+
}
|
|
58
|
+
// src/log.ts
|
|
59
|
+
function isObject(a) {
|
|
60
|
+
return !!a && a.constructor === Object;
|
|
61
|
+
}
|
|
62
|
+
function print(o) {
|
|
63
|
+
if (Array.isArray(o)) {
|
|
64
|
+
return `[${o.map(print).join(", ")}]`;
|
|
65
|
+
}
|
|
66
|
+
if (isObject(o)) {
|
|
67
|
+
return `{${Object.keys(o).map((k) => `${k}: ${o[k]}`).join(", ")}}`;
|
|
68
|
+
}
|
|
69
|
+
return `${o}`;
|
|
70
|
+
}
|
|
71
|
+
function getLine(params) {
|
|
72
|
+
let line = "";
|
|
73
|
+
for (let i = 0, l = params.length;i < l; i++) {
|
|
74
|
+
line += `${print(params[i])} `.replace(/\n/gm, "\t");
|
|
75
|
+
}
|
|
76
|
+
return line.trim();
|
|
77
|
+
}
|
|
78
|
+
function timestamp() {
|
|
79
|
+
return new Date().toISOString();
|
|
80
|
+
}
|
|
81
|
+
var inline = {
|
|
82
|
+
debug: function(...args) {
|
|
83
|
+
if (true) {
|
|
84
|
+
console.log(`${timestamp()} ${getLine(args)}`);
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
log: function(...args) {
|
|
88
|
+
if (true) {
|
|
89
|
+
console.log(`${timestamp()} ${getLine(args)}`);
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
error: function(...args) {
|
|
93
|
+
if (true) {
|
|
94
|
+
console.error(`${timestamp()} ${getLine(args)}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
var logger = {
|
|
99
|
+
debug: function(...args) {
|
|
100
|
+
if (true) {
|
|
101
|
+
console.log(`[${timestamp()}]`, ...args);
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
log: function(...args) {
|
|
105
|
+
if (true) {
|
|
106
|
+
console.log(`[${timestamp()}]`, ...args);
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
error: function(...args) {
|
|
110
|
+
if (true) {
|
|
111
|
+
console.error(`[${timestamp()}]`, ...args);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
// src/object-hash.ts
|
|
116
|
+
import xh from "@node-rs/xxhash";
|
|
117
|
+
function getHash(obj) {
|
|
118
|
+
const xxh3 = xh.xxh3.Xxh3.withSeed();
|
|
119
|
+
hash(obj, xxh3);
|
|
120
|
+
return xxh3.digest().toString(16);
|
|
121
|
+
}
|
|
122
|
+
function hash(obj, xxh3) {
|
|
123
|
+
if (obj === null) {
|
|
124
|
+
xxh3.update("null");
|
|
125
|
+
} else if (obj === undefined) {
|
|
126
|
+
xxh3.update("undefined");
|
|
127
|
+
} else if (typeof obj === "string") {
|
|
128
|
+
xxh3.update(obj);
|
|
129
|
+
} else if (typeof obj === "number") {
|
|
130
|
+
xxh3.update(obj.toString());
|
|
131
|
+
} else if (typeof obj === "boolean") {
|
|
132
|
+
xxh3.update(obj.toString());
|
|
133
|
+
} else if (typeof obj === "bigint") {
|
|
134
|
+
xxh3.update(obj.toString());
|
|
135
|
+
} else if (obj instanceof Date) {
|
|
136
|
+
xxh3.update(obj.toISOString());
|
|
137
|
+
} else if (Array.isArray(obj)) {
|
|
138
|
+
arrayHash(obj, xxh3);
|
|
139
|
+
} else if (obj instanceof Set) {
|
|
140
|
+
setHash(obj, xxh3);
|
|
141
|
+
} else if (obj instanceof Map) {
|
|
142
|
+
mapHash(obj, xxh3);
|
|
143
|
+
} else if (typeof obj === "object") {
|
|
144
|
+
objectHash(obj, xxh3);
|
|
145
|
+
} else {
|
|
146
|
+
throw new Error(`Unsupported type: ${obj}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function arrayHash(array, xxh3) {
|
|
150
|
+
xxh3.update("[");
|
|
151
|
+
for (const obj of array) {
|
|
152
|
+
hash(obj, xxh3);
|
|
153
|
+
}
|
|
154
|
+
xxh3.update("]");
|
|
155
|
+
}
|
|
156
|
+
function setHash(_set, _xxh3) {
|
|
157
|
+
throw new Error("Set hashing not implemented");
|
|
158
|
+
}
|
|
159
|
+
function mapHash(map, xxh3) {
|
|
160
|
+
const array = Array.from(map.entries()).sort(([aKey], [bKey]) => aKey.localeCompare(bKey));
|
|
161
|
+
for (const [key, value] of array) {
|
|
162
|
+
hash(key, xxh3);
|
|
163
|
+
hash(value, xxh3);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function objectHash(obj, xxh3) {
|
|
167
|
+
const array = Object.entries(obj).sort(([aKey], [bKey]) => aKey.localeCompare(bKey));
|
|
168
|
+
for (const [key, value] of array) {
|
|
169
|
+
hash(key, xxh3);
|
|
170
|
+
hash(value, xxh3);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// src/availability.ts
|
|
175
|
+
import pThrottle from "p-throttle";
|
|
176
|
+
import pMemoize from "p-memoize";
|
|
177
|
+
import QuickLRU from "quick-lru";
|
|
178
|
+
async function wait(time) {
|
|
179
|
+
return new Promise((resolve) => {
|
|
180
|
+
setTimeout(resolve, time);
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
async function exponentialRetry(func, {
|
|
184
|
+
maxRetry,
|
|
185
|
+
initialDuration,
|
|
186
|
+
growFactor,
|
|
187
|
+
test,
|
|
188
|
+
verbose
|
|
189
|
+
}) {
|
|
190
|
+
let retries = maxRetry;
|
|
191
|
+
let duration = initialDuration || 5000;
|
|
192
|
+
const growFactorFinal = growFactor || 2;
|
|
193
|
+
let result = await func();
|
|
194
|
+
while (!test(result) && retries > 0) {
|
|
195
|
+
if (verbose) {
|
|
196
|
+
console.log("failed attempt result", result);
|
|
197
|
+
console.log(`sleep for ${duration}ms after failed attempt, remaining ${retries} attempts`);
|
|
198
|
+
}
|
|
199
|
+
retries = retries - 1;
|
|
200
|
+
await wait(duration);
|
|
201
|
+
result = await func();
|
|
202
|
+
duration = duration * growFactorFinal;
|
|
203
|
+
}
|
|
204
|
+
if (verbose) {
|
|
205
|
+
console.log(`function to retry ends with status ${test(result)}, number of retries done: ${maxRetry - retries}}`);
|
|
206
|
+
}
|
|
207
|
+
return result;
|
|
208
|
+
}
|
|
209
|
+
function withRetry(func, options) {
|
|
210
|
+
let retries = options?.maxRetry || 3;
|
|
211
|
+
let duration = options?.initialDuration || 500;
|
|
212
|
+
const growFactorFinal = options?.growFactor || 2;
|
|
213
|
+
return async (...args) => {
|
|
214
|
+
do {
|
|
215
|
+
try {
|
|
216
|
+
return await func(...args);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
retries = retries - 1;
|
|
219
|
+
if (retries <= 0) {
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
await wait(duration);
|
|
223
|
+
duration = duration * growFactorFinal;
|
|
224
|
+
}
|
|
225
|
+
} while (retries > 0);
|
|
226
|
+
throw new Error("unreachable");
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
function memoize(func, options) {
|
|
230
|
+
if (!options) {
|
|
231
|
+
options = {};
|
|
232
|
+
}
|
|
233
|
+
if (!options.cache) {
|
|
234
|
+
options.cache = new QuickLRU({ maxSize: options.lruMaxSize || 1e4 });
|
|
235
|
+
}
|
|
236
|
+
if (!options.cacheKey) {
|
|
237
|
+
options.cacheKey = (args) => getHash(args);
|
|
238
|
+
}
|
|
239
|
+
return pMemoize(func, options);
|
|
240
|
+
}
|
|
241
|
+
// src/util.ts
|
|
242
|
+
function range(startAt, endAt, step) {
|
|
243
|
+
const arr = [];
|
|
244
|
+
for (let i = startAt;i <= endAt; i += step) {
|
|
245
|
+
arr.push([i, Math.min(endAt, i + step - 1)]);
|
|
246
|
+
}
|
|
247
|
+
return arr;
|
|
248
|
+
}
|
|
249
|
+
function arrayGroup(array, groupSize) {
|
|
250
|
+
const groups = [];
|
|
251
|
+
for (let i = 0;i < array.length; i += groupSize) {
|
|
252
|
+
groups.push(array.slice(i, i + groupSize));
|
|
253
|
+
}
|
|
254
|
+
return groups;
|
|
255
|
+
}
|
|
256
|
+
function fillRange(start, end) {
|
|
257
|
+
const result = [];
|
|
258
|
+
for (let i = start;i <= end; i++) {
|
|
259
|
+
result.push(i);
|
|
260
|
+
}
|
|
261
|
+
return result;
|
|
262
|
+
}
|
|
263
|
+
// src/dynamodb.ts
|
|
264
|
+
import {
|
|
265
|
+
DynamoDBDocumentClient,
|
|
266
|
+
ScanCommand,
|
|
267
|
+
BatchWriteCommand,
|
|
268
|
+
GetCommand,
|
|
269
|
+
PutCommand,
|
|
270
|
+
QueryCommand,
|
|
271
|
+
UpdateCommand
|
|
272
|
+
} from "@aws-sdk/lib-dynamodb";
|
|
273
|
+
import { DynamoDBClient, DescribeTableCommand } from "@aws-sdk/client-dynamodb";
|
|
274
|
+
var _dynamoDB;
|
|
275
|
+
var _docClient;
|
|
276
|
+
function getDynamoDB(forceNew = false) {
|
|
277
|
+
if (!_dynamoDB || forceNew) {
|
|
278
|
+
_dynamoDB = new DynamoDBClient;
|
|
279
|
+
}
|
|
280
|
+
return _dynamoDB;
|
|
281
|
+
}
|
|
282
|
+
function getDocClient(forceNew = false) {
|
|
283
|
+
const marshallOptions = {
|
|
284
|
+
convertEmptyValues: true,
|
|
285
|
+
removeUndefinedValues: true,
|
|
286
|
+
convertClassInstanceToMap: true
|
|
287
|
+
};
|
|
288
|
+
const unmarshallOptions = {
|
|
289
|
+
wrapNumbers: false
|
|
290
|
+
};
|
|
291
|
+
if (!_docClient || forceNew) {
|
|
292
|
+
_docClient = DynamoDBDocumentClient.from(getDynamoDB(), {
|
|
293
|
+
marshallOptions,
|
|
294
|
+
unmarshallOptions
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
return _docClient;
|
|
298
|
+
}
|
|
299
|
+
async function scanWholeTable(options) {
|
|
300
|
+
const dynamodb = getDocClient();
|
|
301
|
+
let items = [];
|
|
302
|
+
let count = 0;
|
|
303
|
+
let scannedCount = 0;
|
|
304
|
+
let data = await dynamodb.send(new ScanCommand(options));
|
|
305
|
+
while (data.LastEvaluatedKey) {
|
|
306
|
+
if (data.Items) {
|
|
307
|
+
items = items.concat(data.Items);
|
|
308
|
+
}
|
|
309
|
+
count += data.Count || 0;
|
|
310
|
+
scannedCount += data.ScannedCount || 0;
|
|
311
|
+
data = await dynamodb.send(new ScanCommand({ ...options, ExclusiveStartKey: data.LastEvaluatedKey }));
|
|
312
|
+
}
|
|
313
|
+
if (data.Items) {
|
|
314
|
+
items = items.concat(data.Items);
|
|
315
|
+
}
|
|
316
|
+
count += data.Count || 0;
|
|
317
|
+
scannedCount += data.ScannedCount || 0;
|
|
318
|
+
return {
|
|
319
|
+
Items: items,
|
|
320
|
+
Count: count,
|
|
321
|
+
ScannedCount: scannedCount
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
async function batchCreateRecords(tableName, records, maxWritingCapacity, verbose = false) {
|
|
325
|
+
if (verbose) {
|
|
326
|
+
console.log(`creating ${records.length} items in ${tableName}`);
|
|
327
|
+
}
|
|
328
|
+
const docClient = getDocClient();
|
|
329
|
+
let remainingItems = records;
|
|
330
|
+
let prevRemainingCount = remainingItems.length + 1;
|
|
331
|
+
let factor = 1;
|
|
332
|
+
let rejection = undefined;
|
|
333
|
+
while (remainingItems.length > 0 && factor <= 128 && !rejection) {
|
|
334
|
+
if (prevRemainingCount === remainingItems.length) {
|
|
335
|
+
await wait(5000 * factor);
|
|
336
|
+
factor = factor * 2;
|
|
337
|
+
}
|
|
338
|
+
if (factor >= 32) {
|
|
339
|
+
console.log(`WARNING: no progress for a long time for batchCreateRecords, please check`);
|
|
340
|
+
}
|
|
341
|
+
const slices = arrayGroup(remainingItems.slice(0, maxWritingCapacity), 25);
|
|
342
|
+
const results = await Promise.allSettled(slices.map((rs) => docClient.send(new BatchWriteCommand({
|
|
343
|
+
RequestItems: {
|
|
344
|
+
[tableName]: rs.map((record) => ({ PutRequest: { Item: record } }))
|
|
345
|
+
}
|
|
346
|
+
}))));
|
|
347
|
+
const isFulfilled = (p) => p.status === "fulfilled";
|
|
348
|
+
const isRejected = (p) => p.status === "rejected";
|
|
349
|
+
prevRemainingCount = remainingItems.length;
|
|
350
|
+
remainingItems = remainingItems.slice(maxWritingCapacity);
|
|
351
|
+
results.forEach((rs, idx) => {
|
|
352
|
+
if (isRejected(rs)) {
|
|
353
|
+
remainingItems = remainingItems.concat(slices[idx]);
|
|
354
|
+
rejection = rs;
|
|
355
|
+
} else if (isFulfilled(rs) && rs.value.UnprocessedItems && Object.keys(rs.value.UnprocessedItems).length > 0) {
|
|
356
|
+
const unprocessedItems = rs.value.UnprocessedItems[tableName].map((it) => it.PutRequest?.Item ?? []).flat();
|
|
357
|
+
remainingItems = remainingItems.concat(unprocessedItems);
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
if (verbose) {
|
|
361
|
+
console.log(`processed=${prevRemainingCount - remainingItems.length}, remaining=${remainingItems.length}`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (rejection) {
|
|
365
|
+
console.log("batchCreateRecords rejected", rejection);
|
|
366
|
+
throw new Error(`batchCreateRecords rejected, failed items=${remainingItems.length}`);
|
|
367
|
+
}
|
|
368
|
+
if (remainingItems.length > 0) {
|
|
369
|
+
console.log(`failed batchCreateRecords, failed items=${remainingItems.length}`);
|
|
370
|
+
throw new Error(`batchCreateRecords retry failed, failed items=${remainingItems.length}`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
async function createRecord(tableName, fields, verbose = false) {
|
|
374
|
+
if (verbose) {
|
|
375
|
+
console.log("creating", tableName, fields);
|
|
376
|
+
}
|
|
377
|
+
const docClient = getDocClient();
|
|
378
|
+
const params = {
|
|
379
|
+
TableName: tableName,
|
|
380
|
+
Item: fields
|
|
381
|
+
};
|
|
382
|
+
return docClient.send(new PutCommand(params));
|
|
383
|
+
}
|
|
384
|
+
async function readRecord(tableName, key, verbose = false) {
|
|
385
|
+
if (verbose) {
|
|
386
|
+
console.log("reading", tableName, key);
|
|
387
|
+
}
|
|
388
|
+
const docClient = getDocClient();
|
|
389
|
+
const record = await docClient.send(new GetCommand({
|
|
390
|
+
TableName: tableName,
|
|
391
|
+
Key: key
|
|
392
|
+
}));
|
|
393
|
+
return record.Item;
|
|
394
|
+
}
|
|
395
|
+
async function getRecordsByKey(tableName, keys, indexName) {
|
|
396
|
+
const docClient = getDocClient();
|
|
397
|
+
const keyNames = Object.keys(keys);
|
|
398
|
+
const conditionExpression = keyNames.map((key) => `#${key} = :${key}`).join(" and ");
|
|
399
|
+
const params = {
|
|
400
|
+
TableName: tableName,
|
|
401
|
+
KeyConditionExpression: conditionExpression,
|
|
402
|
+
ExpressionAttributeNames: generateExpressionNames(keyNames),
|
|
403
|
+
ExpressionAttributeValues: generateExpressionValues(keyNames, keys)
|
|
404
|
+
};
|
|
405
|
+
if (indexName) {
|
|
406
|
+
params.IndexName = indexName;
|
|
407
|
+
}
|
|
408
|
+
try {
|
|
409
|
+
let data = await docClient.send(new QueryCommand(params));
|
|
410
|
+
let items = data.Items ?? [];
|
|
411
|
+
while (data.LastEvaluatedKey) {
|
|
412
|
+
data = await docClient.send(new QueryCommand({
|
|
413
|
+
...params,
|
|
414
|
+
ExclusiveStartKey: data.LastEvaluatedKey
|
|
415
|
+
}));
|
|
416
|
+
if (data.Items) {
|
|
417
|
+
items = items.concat(data.Items);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return items;
|
|
421
|
+
} catch (err) {
|
|
422
|
+
console.log(err);
|
|
423
|
+
if (err instanceof Error && "statusCode" in err && err.statusCode === 400) {
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
throw err;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
async function getRecordByKey(tableName, keys, indexName) {
|
|
430
|
+
if (indexName) {
|
|
431
|
+
const records = await getRecordsByKey(tableName, keys, indexName);
|
|
432
|
+
if (records) {
|
|
433
|
+
return records[0];
|
|
434
|
+
} else {
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
} else {
|
|
438
|
+
return readRecord(tableName, keys);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
function generateExpressionNames(keys) {
|
|
442
|
+
return keys.reduce((acc, key) => ({ ...acc, [`#${key}`]: key }), {});
|
|
443
|
+
}
|
|
444
|
+
function generateExpressionValues(keys, fields) {
|
|
445
|
+
return keys.reduce((acc, key) => ({ ...acc, [`:${key}`]: fields[key] }), {});
|
|
446
|
+
}
|
|
447
|
+
async function updateRecordByKey(tableName, idKey, fields, conditionExpressions = null, verbose = false) {
|
|
448
|
+
if (verbose) {
|
|
449
|
+
console.log("update", tableName, idKey, fields);
|
|
450
|
+
}
|
|
451
|
+
const docClient = getDocClient();
|
|
452
|
+
const idKeyNames = Object.keys(idKey);
|
|
453
|
+
const fieldsToDelete = Object.keys(fields).filter((f) => fields[f] === undefined);
|
|
454
|
+
const fieldsToUpdate = Object.keys(fields).filter((k) => !idKeyNames.includes(k) && !fieldsToDelete.includes(k));
|
|
455
|
+
let data;
|
|
456
|
+
if (fieldsToDelete.length > 0) {
|
|
457
|
+
if (verbose) {
|
|
458
|
+
console.log("delete fields", tableName, fieldsToDelete);
|
|
459
|
+
}
|
|
460
|
+
const deleteParams = {
|
|
461
|
+
TableName: tableName,
|
|
462
|
+
Key: idKey,
|
|
463
|
+
ExpressionAttributeNames: generateExpressionNames(fieldsToDelete),
|
|
464
|
+
UpdateExpression: `REMOVE ${fieldsToDelete.map((f) => `#${f}`).join(", ")}`,
|
|
465
|
+
ReturnValues: "ALL_NEW"
|
|
466
|
+
};
|
|
467
|
+
if (conditionExpressions) {
|
|
468
|
+
deleteParams.ConditionExpression = conditionExpressions;
|
|
469
|
+
}
|
|
470
|
+
data = await docClient.send(new UpdateCommand(deleteParams));
|
|
471
|
+
}
|
|
472
|
+
if (fieldsToUpdate.length > 0) {
|
|
473
|
+
if (verbose) {
|
|
474
|
+
console.log("update fields", tableName, fieldsToUpdate);
|
|
475
|
+
}
|
|
476
|
+
const updateExpressions = fieldsToUpdate.map((key) => `#${key} = :${key}`);
|
|
477
|
+
const params = {
|
|
478
|
+
TableName: tableName,
|
|
479
|
+
Key: idKey,
|
|
480
|
+
ExpressionAttributeNames: generateExpressionNames(fieldsToUpdate),
|
|
481
|
+
ExpressionAttributeValues: generateExpressionValues(fieldsToUpdate, fields),
|
|
482
|
+
UpdateExpression: `SET ${updateExpressions.join(", ")}`,
|
|
483
|
+
ReturnValues: "ALL_NEW"
|
|
484
|
+
};
|
|
485
|
+
if (conditionExpressions) {
|
|
486
|
+
params.ConditionExpression = conditionExpressions;
|
|
487
|
+
}
|
|
488
|
+
data = await docClient.send(new UpdateCommand(params));
|
|
489
|
+
}
|
|
490
|
+
return data?.Attributes;
|
|
491
|
+
}
|
|
492
|
+
async function batchDeleteRecords(tableName, keys) {
|
|
493
|
+
const docClient = getDocClient();
|
|
494
|
+
for (let start = 0;start < keys.length; start += 25) {
|
|
495
|
+
const slice = keys.slice(start, start + 25);
|
|
496
|
+
await docClient.send(new BatchWriteCommand({
|
|
497
|
+
RequestItems: {
|
|
498
|
+
[tableName]: slice.map((key) => {
|
|
499
|
+
return { DeleteRequest: { Key: key } };
|
|
500
|
+
})
|
|
501
|
+
}
|
|
502
|
+
}));
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
function getKeyName(keySchema, type) {
|
|
506
|
+
const key = keySchema.find((k) => k.KeyType === type);
|
|
507
|
+
return key?.AttributeName;
|
|
508
|
+
}
|
|
509
|
+
function getIndexKeyName(globalSecondaryIndexes, indexName, type) {
|
|
510
|
+
const idx = globalSecondaryIndexes.find((i) => i.IndexName === indexName);
|
|
511
|
+
return idx?.KeySchema && getKeyName(idx.KeySchema, type);
|
|
512
|
+
}
|
|
513
|
+
async function deleteRecordsByHashKey(tableName, indexName, hashKeyValue, verbose = false) {
|
|
514
|
+
const docClient = getDocClient();
|
|
515
|
+
const meta = await getDynamoDB().send(new DescribeTableCommand({ TableName: tableName }));
|
|
516
|
+
if (!meta.Table) {
|
|
517
|
+
throw new Error(`cannot find table ${tableName}`);
|
|
518
|
+
}
|
|
519
|
+
if (indexName && !meta.Table.GlobalSecondaryIndexes) {
|
|
520
|
+
throw new Error(`cannot find global secondary indexes for table ${tableName}`);
|
|
521
|
+
}
|
|
522
|
+
if (!meta.Table.KeySchema) {
|
|
523
|
+
throw new Error(`cannot find key schema for table ${tableName}`);
|
|
524
|
+
}
|
|
525
|
+
const hashKeyName = indexName ? getIndexKeyName(meta.Table.GlobalSecondaryIndexes, indexName, "HASH") : getKeyName(meta.Table.KeySchema, "HASH");
|
|
526
|
+
if (!hashKeyName) {
|
|
527
|
+
throw new Error(`cannot find hash key name for table ${tableName}`);
|
|
528
|
+
}
|
|
529
|
+
const mainHashKeyName = getKeyName(meta.Table.KeySchema, "HASH");
|
|
530
|
+
if (!mainHashKeyName) {
|
|
531
|
+
throw new Error(`cannot find main hash key name for table ${tableName}`);
|
|
532
|
+
}
|
|
533
|
+
const mainRangeKeyName = getKeyName(meta.Table.KeySchema, "RANGE");
|
|
534
|
+
if (!mainRangeKeyName) {
|
|
535
|
+
throw new Error(`cannot find main range key name for table ${tableName}`);
|
|
536
|
+
}
|
|
537
|
+
let totalDeleted = 0;
|
|
538
|
+
const params = {
|
|
539
|
+
TableName: tableName,
|
|
540
|
+
KeyConditionExpression: "#hashKeyName = :hashKeyValue",
|
|
541
|
+
ExpressionAttributeNames: { "#hashKeyName": hashKeyName },
|
|
542
|
+
ExpressionAttributeValues: { ":hashKeyValue": hashKeyValue }
|
|
543
|
+
};
|
|
544
|
+
if (indexName) {
|
|
545
|
+
params.IndexName = indexName;
|
|
546
|
+
}
|
|
547
|
+
let data = await docClient.send(new QueryCommand(params));
|
|
548
|
+
if (data.Items) {
|
|
549
|
+
await batchDeleteRecords(tableName, data.Items.map((item) => mainRangeKeyName ? {
|
|
550
|
+
[mainHashKeyName]: item[mainHashKeyName],
|
|
551
|
+
[mainRangeKeyName]: item[mainRangeKeyName]
|
|
552
|
+
} : {
|
|
553
|
+
[mainHashKeyName]: item[mainHashKeyName]
|
|
554
|
+
}));
|
|
555
|
+
totalDeleted += data.Items.length;
|
|
556
|
+
}
|
|
557
|
+
while (data.LastEvaluatedKey) {
|
|
558
|
+
data = await docClient.send(new QueryCommand({
|
|
559
|
+
...params,
|
|
560
|
+
ExclusiveStartKey: data.LastEvaluatedKey
|
|
561
|
+
}));
|
|
562
|
+
if (data.Items) {
|
|
563
|
+
await batchDeleteRecords(tableName, data.Items.map((item) => mainRangeKeyName ? {
|
|
564
|
+
[mainHashKeyName]: item[mainHashKeyName],
|
|
565
|
+
[mainRangeKeyName]: item[mainRangeKeyName]
|
|
566
|
+
} : {
|
|
567
|
+
[mainHashKeyName]: item[mainHashKeyName]
|
|
568
|
+
}));
|
|
569
|
+
totalDeleted += data.Items.length;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
if (verbose) {
|
|
573
|
+
console.log(`successfully delete ${totalDeleted} items`);
|
|
574
|
+
}
|
|
575
|
+
return totalDeleted;
|
|
576
|
+
}
|
|
577
|
+
// src/cli.ts
|
|
578
|
+
import path from "path";
|
|
579
|
+
import fs from "fs";
|
|
580
|
+
function getBinaryName() {
|
|
581
|
+
const binaryNameParts = process.argv[1].split(path.sep);
|
|
582
|
+
const binaryName = binaryNameParts[binaryNameParts.length - 1];
|
|
583
|
+
return binaryName;
|
|
584
|
+
}
|
|
585
|
+
function detectSkynetDirectory() {
|
|
586
|
+
return detectDirectory(process.argv[1], "SkynetAPIDefinitions.yml");
|
|
587
|
+
}
|
|
588
|
+
function detectWorkingDirectory() {
|
|
589
|
+
const wd = detectDirectory(process.argv[1], "package.json");
|
|
590
|
+
const skynetd = detectDirectory(process.argv[1], "SkynetAPIDefinitions.yml");
|
|
591
|
+
return wd.slice(skynetd.length + path.sep.length).replace(path.sep, "/");
|
|
592
|
+
}
|
|
593
|
+
function detectDirectory(fullBinPath, sentinel = "package.json") {
|
|
594
|
+
let parentFolder = path.dirname(fullBinPath);
|
|
595
|
+
while (parentFolder) {
|
|
596
|
+
const sentinelPath = path.join(parentFolder, sentinel);
|
|
597
|
+
if (fs.existsSync(sentinelPath)) {
|
|
598
|
+
return parentFolder;
|
|
599
|
+
}
|
|
600
|
+
const newParentFolder = path.dirname(parentFolder);
|
|
601
|
+
if (newParentFolder === parentFolder) {
|
|
602
|
+
break;
|
|
603
|
+
}
|
|
604
|
+
parentFolder = newParentFolder;
|
|
605
|
+
}
|
|
606
|
+
throw new Error("Cannot detect current working directory");
|
|
607
|
+
}
|
|
608
|
+
function detectBin() {
|
|
609
|
+
const wd = detectDirectory(process.argv[1], "package.json");
|
|
610
|
+
return process.argv[1].slice(wd.length + path.sep.length).replace(path.sep, "/");
|
|
611
|
+
}
|
|
612
|
+
// src/date.ts
|
|
613
|
+
var MS_IN_A_DAY = 3600 * 24 * 1000;
|
|
614
|
+
function getDateOnly(date) {
|
|
615
|
+
return new Date(date).toISOString().split("T")[0];
|
|
616
|
+
}
|
|
617
|
+
function findDateAfter(date, n) {
|
|
618
|
+
const d = new Date(date);
|
|
619
|
+
const after = new Date(d.getTime() + MS_IN_A_DAY * n);
|
|
620
|
+
return getDateOnly(after);
|
|
621
|
+
}
|
|
622
|
+
function daysInRange(from, to) {
|
|
623
|
+
const fromTime = new Date(from).getTime();
|
|
624
|
+
const toTime = new Date(to).getTime();
|
|
625
|
+
if (fromTime > toTime) {
|
|
626
|
+
throw new Error(`range to date couldn't be earlier than range from date`);
|
|
627
|
+
}
|
|
628
|
+
const daysBetween = Math.floor((toTime - fromTime) / MS_IN_A_DAY);
|
|
629
|
+
const dates = [getDateOnly(new Date(fromTime))];
|
|
630
|
+
for (let i = 1;i <= daysBetween; i += 1) {
|
|
631
|
+
dates.push(getDateOnly(new Date(fromTime + i * MS_IN_A_DAY)));
|
|
632
|
+
}
|
|
633
|
+
return dates;
|
|
634
|
+
}
|
|
635
|
+
function dateRange(from, to, step) {
|
|
636
|
+
const days = daysInRange(from, to);
|
|
637
|
+
const windows = arrayGroup(days, step);
|
|
638
|
+
return windows.map((w) => [w[0], w[w.length - 1]]);
|
|
639
|
+
}
|
|
640
|
+
// src/indexer.ts
|
|
641
|
+
import meow from "meow";
|
|
642
|
+
var STATE_TABLE_NAME = "skynet-" + getEnvironment() + "-indexer-state";
|
|
643
|
+
async function getIndexerLatestId(name, selectorFlags) {
|
|
644
|
+
const record = await getRecordByKey(STATE_TABLE_NAME, {
|
|
645
|
+
name: `${name}Since(${toSelectorString(selectorFlags)})`
|
|
646
|
+
});
|
|
647
|
+
return record?.value;
|
|
648
|
+
}
|
|
649
|
+
async function getIndexerValidatedId(name, selectorFlags) {
|
|
650
|
+
const record = await getRecordByKey(STATE_TABLE_NAME, {
|
|
651
|
+
name: `${name}Validate(${toSelectorString(selectorFlags)})`
|
|
652
|
+
});
|
|
653
|
+
if (record) {
|
|
654
|
+
return record.value;
|
|
655
|
+
}
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
function increaseId(type, currentId, n) {
|
|
659
|
+
if (type === "date") {
|
|
660
|
+
if (typeof currentId !== "string") {
|
|
661
|
+
throw new Error("invalid type for date id");
|
|
662
|
+
}
|
|
663
|
+
return findDateAfter(currentId, n);
|
|
664
|
+
}
|
|
665
|
+
if (typeof currentId !== "number") {
|
|
666
|
+
throw new Error("Invalid type for numeric id");
|
|
667
|
+
}
|
|
668
|
+
return currentId + n;
|
|
669
|
+
}
|
|
670
|
+
function createModeIndexerApp({
|
|
671
|
+
binaryName,
|
|
672
|
+
name,
|
|
673
|
+
selector = {},
|
|
674
|
+
build,
|
|
675
|
+
buildBatchSize = 1,
|
|
676
|
+
buildConcurrency = 1,
|
|
677
|
+
validate,
|
|
678
|
+
validateBatchSize = 1,
|
|
679
|
+
validateConcurrency = 1,
|
|
680
|
+
maxRetry = 2,
|
|
681
|
+
state
|
|
682
|
+
}) {
|
|
683
|
+
const defaultState = {
|
|
684
|
+
type: "block",
|
|
685
|
+
getMinId: async () => 1,
|
|
686
|
+
getMaxId: async () => {
|
|
687
|
+
throw new Error("must implement getMaxId");
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
const finalState = {
|
|
691
|
+
...defaultState,
|
|
692
|
+
...state
|
|
693
|
+
};
|
|
694
|
+
function range2(from, to, step) {
|
|
695
|
+
if (typeof from === "string" && typeof to === "string") {
|
|
696
|
+
if (finalState.type === "date") {
|
|
697
|
+
return dateRange(from, to, step);
|
|
698
|
+
}
|
|
699
|
+
throw new Error("Invalid type for numeric range");
|
|
700
|
+
}
|
|
701
|
+
if (typeof from === "number" && typeof to === "number") {
|
|
702
|
+
return range(from, to, step);
|
|
703
|
+
}
|
|
704
|
+
throw new Error("Invalid type for range");
|
|
705
|
+
}
|
|
706
|
+
function fillRange2(from, to) {
|
|
707
|
+
if (typeof from === "string" && typeof to === "string") {
|
|
708
|
+
if (finalState.type === "date") {
|
|
709
|
+
return daysInRange(from, to);
|
|
710
|
+
}
|
|
711
|
+
throw new Error("Invalid type for numeric range");
|
|
712
|
+
}
|
|
713
|
+
if (typeof from === "number" && typeof to === "number") {
|
|
714
|
+
return fillRange(from, to);
|
|
715
|
+
}
|
|
716
|
+
throw new Error("Invalid type for range");
|
|
717
|
+
}
|
|
718
|
+
function offsetRange(from, to) {
|
|
719
|
+
return fillRange2(from, to).length;
|
|
720
|
+
}
|
|
721
|
+
async function runMode(flags) {
|
|
722
|
+
const { mode, from: fromUntyped, to: toUntyped, status, verbose: verboseUntyped, ...untypeSelectorFlags } = flags;
|
|
723
|
+
const from = fromUntyped;
|
|
724
|
+
const to = toUntyped;
|
|
725
|
+
const verbose = verboseUntyped;
|
|
726
|
+
const selectorFlags = untypeSelectorFlags;
|
|
727
|
+
if (status) {
|
|
728
|
+
const stateItem = await getRecordByKey(STATE_TABLE_NAME, {
|
|
729
|
+
name: `${name}RebuildState(${toSelectorString(selectorFlags)})`
|
|
730
|
+
});
|
|
731
|
+
const fromItem = await getRecordByKey(STATE_TABLE_NAME, {
|
|
732
|
+
name: `${name}Since(${toSelectorString(selectorFlags)})`
|
|
733
|
+
});
|
|
734
|
+
const validateItem = await getRecordByKey(STATE_TABLE_NAME, {
|
|
735
|
+
name: `${name}Validate(${toSelectorString(selectorFlags)})`
|
|
736
|
+
});
|
|
737
|
+
inline.log(`RebuildState=${stateItem?.value} Since=${fromItem?.value} Validated=${validateItem?.value}`);
|
|
738
|
+
process.exit(0);
|
|
739
|
+
}
|
|
740
|
+
inline.log(`[MODE INDEXER] mode=${mode}, env=${getEnvironment()}, ${toSelectorString(selectorFlags, ", ")}`);
|
|
741
|
+
if (mode === "reset") {
|
|
742
|
+
await runReset(selectorFlags);
|
|
743
|
+
} else if (mode === "rebuild") {
|
|
744
|
+
const rebuildFrom = from || await finalState.getMinId(selectorFlags);
|
|
745
|
+
const rebuildTo = to || await finalState.getMaxId(selectorFlags);
|
|
746
|
+
await runReset(selectorFlags);
|
|
747
|
+
await runRebuild(selectorFlags, rebuildFrom, rebuildTo, verbose);
|
|
748
|
+
} else if (mode === "resume-rebuild") {
|
|
749
|
+
const previousRebuildEnds = await getIndexerLatestId(name, selectorFlags);
|
|
750
|
+
const rebuildFrom = from || previousRebuildEnds !== undefined && increaseId(finalState.type, previousRebuildEnds, 1) || await finalState.getMinId(selectorFlags);
|
|
751
|
+
const rebuildTo = to || await finalState.getMaxId(selectorFlags);
|
|
752
|
+
await runRebuild(selectorFlags, rebuildFrom, rebuildTo, verbose);
|
|
753
|
+
} else if (mode === "validate" || mode === "validation") {
|
|
754
|
+
const previousRebuildEnds = await getIndexerLatestId(name, selectorFlags);
|
|
755
|
+
if (!previousRebuildEnds) {
|
|
756
|
+
inline.log(`[MODE INDEXER] cannot validate without a successful rebuild`);
|
|
757
|
+
process.exit(0);
|
|
758
|
+
}
|
|
759
|
+
const previousValidatedTo = await getIndexerValidatedId(name, selectorFlags);
|
|
760
|
+
const validateFrom = from || previousValidatedTo || await finalState.getMinId(selectorFlags);
|
|
761
|
+
const validateTo = to || previousRebuildEnds;
|
|
762
|
+
const shouldSaveState = !to;
|
|
763
|
+
await runValidate(selectorFlags, validateFrom, validateTo, shouldSaveState, verbose);
|
|
764
|
+
} else if (mode === "one") {
|
|
765
|
+
if (to) {
|
|
766
|
+
inline.log("[MODE INDEXER] one mode ignores --to option. you may want to use range mode instead");
|
|
767
|
+
}
|
|
768
|
+
if (!from) {
|
|
769
|
+
inline.log(`[MODE INDEXER] must provide --from option for one mode`);
|
|
770
|
+
process.exit(1);
|
|
771
|
+
}
|
|
772
|
+
await runRange(selectorFlags, from, from, verbose);
|
|
773
|
+
} else if (mode === "range") {
|
|
774
|
+
if (!from || !to) {
|
|
775
|
+
inline.log(`[MODE INDEXER] must provide --from and --to option for range mode`);
|
|
776
|
+
process.exit(1);
|
|
777
|
+
}
|
|
778
|
+
await runRange(selectorFlags, from, to, verbose);
|
|
779
|
+
} else {
|
|
780
|
+
const stateItem = await getRecordByKey(STATE_TABLE_NAME, {
|
|
781
|
+
name: `${name}RebuildState(${toSelectorString(selectorFlags)})`
|
|
782
|
+
});
|
|
783
|
+
if (!stateItem || stateItem.value !== "succeed") {
|
|
784
|
+
inline.log("[MODE INDEXER] skip because rebuild hasn't done yet");
|
|
785
|
+
process.exit(0);
|
|
786
|
+
}
|
|
787
|
+
const latestId = await getIndexerLatestId(name, selectorFlags);
|
|
788
|
+
if (!latestId) {
|
|
789
|
+
throw new Error(`[MODE INDEXER] cannot find the latest ${finalState.type}`);
|
|
790
|
+
}
|
|
791
|
+
const deltaFrom = increaseId(finalState.type, latestId, 1);
|
|
792
|
+
const deltaTo = await state.getMaxId(selectorFlags);
|
|
793
|
+
await runDelta(selectorFlags, deltaFrom, deltaTo, verbose);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
async function runRange(selectorFlags, from, to, verbose) {
|
|
797
|
+
const startTime = Date.now();
|
|
798
|
+
inline.log(`[MODE INDEXER] building range, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}, batchSize=${buildBatchSize}, concurrency=${buildConcurrency}`);
|
|
799
|
+
const failedIds = await execBuild(selectorFlags, from, to, verbose, false);
|
|
800
|
+
if (failedIds.length > 0) {
|
|
801
|
+
inline.log(`[MODE INDEXER] built with some failed ${finalState.type}`, failedIds);
|
|
802
|
+
process.exit(1);
|
|
803
|
+
} else {
|
|
804
|
+
inline.log(`[MODE INDEXER] built successfully in ${Date.now() - startTime}ms`);
|
|
805
|
+
process.exit(0);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
async function runValidate(selectorFlags, from, to, shouldSaveState, verbose) {
|
|
809
|
+
if (!validate) {
|
|
810
|
+
inline.log(`[MODE INDEXER] the indexer doesn't support validate mode, validate function not implemented`);
|
|
811
|
+
process.exit(1);
|
|
812
|
+
}
|
|
813
|
+
const startTime = Date.now();
|
|
814
|
+
inline.log(`[MODE INDEXER] validating, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}, batchSize=${validateBatchSize}, concurrency=${validateConcurrency}`);
|
|
815
|
+
const windows = range2(from, to, validateBatchSize * validateConcurrency);
|
|
816
|
+
inline.log(`[MODE INDEXER] from=${from}, to=${to}, batchSize=${validateBatchSize}, concurrency=${validateConcurrency}`);
|
|
817
|
+
for (const [windowStart, windowEnd] of windows) {
|
|
818
|
+
inline.log(`[MODE INDEXER] validating window ${windowStart}~${windowEnd}, concurrency=${validateConcurrency}`);
|
|
819
|
+
const batches = range2(windowStart, windowEnd, validateBatchSize);
|
|
820
|
+
await Promise.all(batches.map(async ([batchStart, batchEnd]) => {
|
|
821
|
+
const result = await exponentialRetry(async () => {
|
|
822
|
+
try {
|
|
823
|
+
await validate({
|
|
824
|
+
...selectorFlags,
|
|
825
|
+
from: batchStart,
|
|
826
|
+
to: batchEnd,
|
|
827
|
+
verbose
|
|
828
|
+
});
|
|
829
|
+
return true;
|
|
830
|
+
} catch (err) {
|
|
831
|
+
inline.error(`got error in validation`, err);
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
}, {
|
|
835
|
+
maxRetry,
|
|
836
|
+
test: (r) => r,
|
|
837
|
+
verbose
|
|
838
|
+
});
|
|
839
|
+
if (!result) {
|
|
840
|
+
throw new Error(`Terminate validation due to critical errors, from=${batchStart}, to=${batchEnd}`);
|
|
841
|
+
}
|
|
842
|
+
}));
|
|
843
|
+
if (shouldSaveState) {
|
|
844
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
845
|
+
name: `${name}Validate(${toSelectorString(selectorFlags)})`,
|
|
846
|
+
value: to
|
|
847
|
+
});
|
|
848
|
+
if (verbose) {
|
|
849
|
+
inline.log(`[MODE INDEXER] updated processed ${finalState.type} to ${windowEnd}`);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
inline.log(`[MODE INDEXER] validated ${offsetRange(from, to)} ${finalState.type} successfully in ${Date.now() - startTime}ms`);
|
|
854
|
+
}
|
|
855
|
+
async function execBuild(selectorFlags, from, to, verbose, shouldSaveState = false) {
|
|
856
|
+
let failedIds = [];
|
|
857
|
+
const windows = range2(from, to, buildBatchSize * buildConcurrency);
|
|
858
|
+
for (const [windowStart, windowEnd] of windows) {
|
|
859
|
+
inline.log(`[MODE INDEXER] building window ${windowStart}~${windowEnd}, concurrency = ${buildConcurrency}`);
|
|
860
|
+
const batches = range2(windowStart, windowEnd, buildBatchSize);
|
|
861
|
+
const batchResults = await Promise.all(batches.map(async ([batchStart, batchEnd]) => await exponentialRetry(async () => {
|
|
862
|
+
try {
|
|
863
|
+
const ids = await build({
|
|
864
|
+
...selectorFlags,
|
|
865
|
+
from: batchStart,
|
|
866
|
+
to: batchEnd,
|
|
867
|
+
verbose
|
|
868
|
+
});
|
|
869
|
+
if (ids && ids.length > 0) {
|
|
870
|
+
return ids;
|
|
871
|
+
} else {
|
|
872
|
+
return false;
|
|
873
|
+
}
|
|
874
|
+
} catch (err) {
|
|
875
|
+
inline.error(`[MODE INDEXER] got error in build`, err);
|
|
876
|
+
return fillRange2(batchStart, batchEnd);
|
|
877
|
+
}
|
|
878
|
+
}, {
|
|
879
|
+
maxRetry,
|
|
880
|
+
test: (r) => !r,
|
|
881
|
+
verbose
|
|
882
|
+
})));
|
|
883
|
+
if (shouldSaveState) {
|
|
884
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
885
|
+
name: `${name}Since(${toSelectorString(selectorFlags)})`,
|
|
886
|
+
value: windowEnd
|
|
887
|
+
});
|
|
888
|
+
if (verbose) {
|
|
889
|
+
inline.log(`[MODE INDEXER] updated processed ${finalState.type} to ${windowEnd}`);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
batchResults.forEach((ids) => {
|
|
893
|
+
if (ids) {
|
|
894
|
+
failedIds = failedIds.concat(ids);
|
|
895
|
+
}
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
failedIds.sort();
|
|
899
|
+
return failedIds;
|
|
900
|
+
}
|
|
901
|
+
async function runRebuild(selectorFlags, from, to, verbose) {
|
|
902
|
+
const startTime = Date.now();
|
|
903
|
+
inline.log(`[MODE INDEXER] rebuilding, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}, batchSize=${buildBatchSize}, concurrency=${buildConcurrency}`);
|
|
904
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
905
|
+
name: `${name}RebuildState(${toSelectorString(selectorFlags)})`,
|
|
906
|
+
value: "running"
|
|
907
|
+
});
|
|
908
|
+
const failedIds = await execBuild(selectorFlags, from, to, verbose, true);
|
|
909
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
910
|
+
name: `${name}Since(${toSelectorString(selectorFlags)})`,
|
|
911
|
+
value: to
|
|
912
|
+
});
|
|
913
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
914
|
+
name: `${name}RebuildState(${toSelectorString(selectorFlags)})`,
|
|
915
|
+
value: "succeed"
|
|
916
|
+
});
|
|
917
|
+
if (failedIds.length > 0) {
|
|
918
|
+
inline.log(`[MODE INDEXER] built ${offsetRange(from, to)} ${finalState.type}(s) with some failed ${finalState.type}`, failedIds);
|
|
919
|
+
process.exit(1);
|
|
920
|
+
} else {
|
|
921
|
+
inline.log(`[MODE INDEXER] built ${offsetRange(from, to)} ${finalState.type}(s) successfully in ${Date.now() - startTime}ms`);
|
|
922
|
+
process.exit(0);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
async function runDelta(selectorFlags, from, to, verbose) {
|
|
926
|
+
const startTime = Date.now();
|
|
927
|
+
if (to < from) {
|
|
928
|
+
inline.log(`[MODE INDEXER] skip delta, there're no more items need to be processed, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}`);
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
inline.log(`[MODE INDEXER] starting delta, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}, batchSize=${buildBatchSize}, concurrency=${buildConcurrency}`);
|
|
932
|
+
try {
|
|
933
|
+
const failedIds = await execBuild(selectorFlags, from, to, verbose, true);
|
|
934
|
+
if (failedIds.length > 0) {
|
|
935
|
+
inline.log("[MODE INDEXER] built with some failed txs", failedIds);
|
|
936
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
937
|
+
name: `${name}DeltaState(${toSelectorString(selectorFlags)})`,
|
|
938
|
+
value: "failed"
|
|
939
|
+
});
|
|
940
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
941
|
+
name: `${name}Since(${toSelectorString(selectorFlags)})`,
|
|
942
|
+
value: to < failedIds[0] ? to : failedIds[0]
|
|
943
|
+
});
|
|
944
|
+
process.exit(1);
|
|
945
|
+
} else {
|
|
946
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
947
|
+
name: `${name}DeltaState(${toSelectorString(selectorFlags)})`,
|
|
948
|
+
value: "succeed"
|
|
949
|
+
});
|
|
950
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
951
|
+
name: `${name}Since(${toSelectorString(selectorFlags)})`,
|
|
952
|
+
value: to
|
|
953
|
+
});
|
|
954
|
+
inline.log(`[MODE INDEXER] built successfully in ${Date.now() - startTime}ms`);
|
|
955
|
+
process.exit(0);
|
|
956
|
+
}
|
|
957
|
+
} catch (err) {
|
|
958
|
+
inline.error("[MODE INDEXER] delta build failed", from, to, err);
|
|
959
|
+
process.exit(1);
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
async function runReset(selectorFlags) {
|
|
963
|
+
const startTime = Date.now();
|
|
964
|
+
inline.log(`[MODE INDEXER] starting reset, ${toSelectorString(selectorFlags, ", ")}`);
|
|
965
|
+
inline.log("[MODE INDEXER] reset state", STATE_TABLE_NAME);
|
|
966
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
967
|
+
name: `${name}Since(${toSelectorString(selectorFlags)})`,
|
|
968
|
+
value: 0
|
|
969
|
+
});
|
|
970
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
971
|
+
name: `${name}Validate(${toSelectorString(selectorFlags)})`,
|
|
972
|
+
value: 0
|
|
973
|
+
});
|
|
974
|
+
await createRecord(STATE_TABLE_NAME, {
|
|
975
|
+
name: `${name}RebuildState(${toSelectorString(selectorFlags)})`,
|
|
976
|
+
value: "init"
|
|
977
|
+
});
|
|
978
|
+
inline.log(`[MODE INDEXER] reset successfully in ${Date.now() - startTime}ms`);
|
|
979
|
+
}
|
|
980
|
+
async function run() {
|
|
981
|
+
if (!binaryName) {
|
|
982
|
+
binaryName = getBinaryName();
|
|
983
|
+
}
|
|
984
|
+
const cli = meow(`
|
|
985
|
+
Usage
|
|
986
|
+
|
|
987
|
+
$ ${binaryName} <options>
|
|
988
|
+
|
|
989
|
+
Options
|
|
990
|
+
${selector ? getSelectorDesc(selector) : ""}
|
|
991
|
+
--mode could be delta/rebuild/resume-rebuild/validate/one/range/reset
|
|
992
|
+
--from min ${finalState.type} to build
|
|
993
|
+
--to max ${finalState.type} to build
|
|
994
|
+
--status print status of indexer and exit
|
|
995
|
+
--verbose Output debug messages
|
|
996
|
+
`, {
|
|
997
|
+
importMeta: import.meta,
|
|
998
|
+
description: false,
|
|
999
|
+
flags: {
|
|
1000
|
+
...getSelectorFlags(selector),
|
|
1001
|
+
mode: {
|
|
1002
|
+
type: "string",
|
|
1003
|
+
default: "delta"
|
|
1004
|
+
},
|
|
1005
|
+
from: {
|
|
1006
|
+
aliases: ["since"],
|
|
1007
|
+
type: "string"
|
|
1008
|
+
},
|
|
1009
|
+
to: {
|
|
1010
|
+
aliases: ["until"],
|
|
1011
|
+
type: "string"
|
|
1012
|
+
},
|
|
1013
|
+
status: {
|
|
1014
|
+
type: "boolean",
|
|
1015
|
+
default: false
|
|
1016
|
+
},
|
|
1017
|
+
verbose: {
|
|
1018
|
+
type: "boolean",
|
|
1019
|
+
default: false
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
});
|
|
1023
|
+
try {
|
|
1024
|
+
return runMode(cli.flags);
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
inline.error(err);
|
|
1027
|
+
process.exit(1);
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
return { run };
|
|
1031
|
+
}
|
|
1032
|
+
function createIndexerApp({
|
|
1033
|
+
binaryName,
|
|
1034
|
+
selector = {},
|
|
1035
|
+
build,
|
|
1036
|
+
maxRetry = 2
|
|
1037
|
+
}) {
|
|
1038
|
+
async function run() {
|
|
1039
|
+
if (!binaryName) {
|
|
1040
|
+
binaryName = getBinaryName();
|
|
1041
|
+
}
|
|
1042
|
+
const cli = meow(`
|
|
1043
|
+
Usage
|
|
1044
|
+
$ ${binaryName} <options>
|
|
1045
|
+
|
|
1046
|
+
Options
|
|
1047
|
+
${selector ? getSelectorDesc(selector) : ""}
|
|
1048
|
+
--verbose Output debug messages
|
|
1049
|
+
`, {
|
|
1050
|
+
importMeta: import.meta,
|
|
1051
|
+
description: false,
|
|
1052
|
+
flags: {
|
|
1053
|
+
...getSelectorFlags(selector),
|
|
1054
|
+
verbose: {
|
|
1055
|
+
type: "boolean",
|
|
1056
|
+
default: false
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
});
|
|
1060
|
+
async function runBuild(flags) {
|
|
1061
|
+
const { verbose: untypedVerbose, ...untypedSelectorFlags } = flags;
|
|
1062
|
+
const verbose = untypedVerbose;
|
|
1063
|
+
const selectorFlags = untypedSelectorFlags;
|
|
1064
|
+
const startTime = Date.now();
|
|
1065
|
+
if (Object.keys(selectorFlags).length > 0) {
|
|
1066
|
+
inline.log(`[INDEXER] starting build, ${toSelectorString(selectorFlags, ", ")}`);
|
|
1067
|
+
} else {
|
|
1068
|
+
inline.log(`[INDEXER] starting build`);
|
|
1069
|
+
}
|
|
1070
|
+
const result = await exponentialRetry(async () => {
|
|
1071
|
+
try {
|
|
1072
|
+
await build(flags);
|
|
1073
|
+
return true;
|
|
1074
|
+
} catch (err) {
|
|
1075
|
+
inline.log(`[INDEXER] got error in build`, err);
|
|
1076
|
+
return false;
|
|
1077
|
+
}
|
|
1078
|
+
}, {
|
|
1079
|
+
maxRetry,
|
|
1080
|
+
test: (r) => r,
|
|
1081
|
+
verbose
|
|
1082
|
+
});
|
|
1083
|
+
if (!result) {
|
|
1084
|
+
throw new Error(`[INDEXER] Build failed due to critical errors`);
|
|
1085
|
+
}
|
|
1086
|
+
inline.log(`[INDEXER] build successfully in ${Date.now() - startTime}ms`);
|
|
1087
|
+
}
|
|
1088
|
+
return runBuild(cli.flags).catch((err) => {
|
|
1089
|
+
inline.error(err);
|
|
1090
|
+
process.exit(1);
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
return { run };
|
|
1094
|
+
}
|
|
1095
|
+
export {
|
|
1096
|
+
increaseId,
|
|
1097
|
+
createModeIndexerApp,
|
|
1098
|
+
createIndexerApp
|
|
1099
|
+
};
|