@certik/skynet 0.22.1 → 0.22.3

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.
Files changed (101) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/build.ts +23 -0
  3. package/dist/abi.d.ts +1 -2
  4. package/dist/abi.js +569 -563
  5. package/dist/address.d.ts +0 -1
  6. package/dist/address.js +22 -21
  7. package/dist/api.d.ts +0 -1
  8. package/dist/api.js +235 -120
  9. package/dist/app.d.ts +1 -2
  10. package/dist/app.js +2030 -276
  11. package/dist/availability.d.ts +0 -1
  12. package/dist/availability.js +126 -56
  13. package/dist/cli.d.ts +0 -1
  14. package/dist/cli.js +28 -24
  15. package/dist/const.d.ts +0 -1
  16. package/dist/const.js +153 -132
  17. package/dist/databricks.d.ts +0 -1
  18. package/dist/databricks.js +198 -58
  19. package/dist/date.d.ts +0 -1
  20. package/dist/date.js +48 -21
  21. package/dist/deploy.d.ts +0 -1
  22. package/dist/deploy.js +427 -292
  23. package/dist/dynamodb.d.ts +3 -4
  24. package/dist/dynamodb.js +432 -281
  25. package/dist/env.d.ts +2 -3
  26. package/dist/env.js +16 -9
  27. package/dist/graphql.d.ts +0 -1
  28. package/dist/graphql.js +26 -23
  29. package/dist/indexer.d.ts +0 -1
  30. package/dist/indexer.js +1050 -441
  31. package/dist/log.d.ts +0 -1
  32. package/dist/log.js +53 -52
  33. package/dist/object-hash.d.ts +0 -1
  34. package/dist/object-hash.js +49 -59
  35. package/dist/opsgenie.d.ts +97 -19
  36. package/dist/opsgenie.js +35 -30
  37. package/dist/por.d.ts +0 -1
  38. package/dist/por.js +113 -123
  39. package/dist/s3.d.ts +7 -8
  40. package/dist/s3.js +103 -91
  41. package/dist/search.d.ts +0 -1
  42. package/dist/search.js +100 -25
  43. package/dist/selector.d.ts +0 -1
  44. package/dist/selector.js +34 -38
  45. package/dist/slack.d.ts +0 -1
  46. package/dist/slack.js +27 -21
  47. package/dist/util.d.ts +0 -1
  48. package/dist/util.js +21 -20
  49. package/examples/api.ts +1 -1
  50. package/examples/indexer.ts +1 -1
  51. package/examples/mode-indexer.ts +1 -1
  52. package/package.json +4 -3
  53. package/{graphql.ts → src/graphql.ts} +1 -1
  54. package/src/opsgenie.ts +176 -0
  55. package/tsconfig.build.json +2 -5
  56. package/tsconfig.json +11 -20
  57. package/dist/abi.d.ts.map +0 -1
  58. package/dist/address.d.ts.map +0 -1
  59. package/dist/api.d.ts.map +0 -1
  60. package/dist/app.d.ts.map +0 -1
  61. package/dist/availability.d.ts.map +0 -1
  62. package/dist/cli.d.ts.map +0 -1
  63. package/dist/const.d.ts.map +0 -1
  64. package/dist/databricks.d.ts.map +0 -1
  65. package/dist/date.d.ts.map +0 -1
  66. package/dist/deploy.d.ts.map +0 -1
  67. package/dist/dynamodb.d.ts.map +0 -1
  68. package/dist/env.d.ts.map +0 -1
  69. package/dist/graphql.d.ts.map +0 -1
  70. package/dist/indexer.d.ts.map +0 -1
  71. package/dist/log.d.ts.map +0 -1
  72. package/dist/object-hash.d.ts.map +0 -1
  73. package/dist/opsgenie.d.ts.map +0 -1
  74. package/dist/por.d.ts.map +0 -1
  75. package/dist/s3.d.ts.map +0 -1
  76. package/dist/search.d.ts.map +0 -1
  77. package/dist/selector.d.ts.map +0 -1
  78. package/dist/slack.d.ts.map +0 -1
  79. package/dist/util.d.ts.map +0 -1
  80. package/opsgenie.ts +0 -69
  81. /package/{abi.ts → src/abi.ts} +0 -0
  82. /package/{address.ts → src/address.ts} +0 -0
  83. /package/{api.ts → src/api.ts} +0 -0
  84. /package/{app.ts → src/app.ts} +0 -0
  85. /package/{availability.ts → src/availability.ts} +0 -0
  86. /package/{cli.ts → src/cli.ts} +0 -0
  87. /package/{const.ts → src/const.ts} +0 -0
  88. /package/{databricks.ts → src/databricks.ts} +0 -0
  89. /package/{date.ts → src/date.ts} +0 -0
  90. /package/{deploy.ts → src/deploy.ts} +0 -0
  91. /package/{dynamodb.ts → src/dynamodb.ts} +0 -0
  92. /package/{env.ts → src/env.ts} +0 -0
  93. /package/{indexer.ts → src/indexer.ts} +0 -0
  94. /package/{log.ts → src/log.ts} +0 -0
  95. /package/{object-hash.ts → src/object-hash.ts} +0 -0
  96. /package/{por.ts → src/por.ts} +0 -0
  97. /package/{s3.ts → src/s3.ts} +0 -0
  98. /package/{search.ts → src/search.ts} +0 -0
  99. /package/{selector.ts → src/selector.ts} +0 -0
  100. /package/{slack.ts → src/slack.ts} +0 -0
  101. /package/{util.ts → src/util.ts} +0 -0
package/dist/app.js CHANGED
@@ -1,328 +1,2082 @@
1
- import { EOL } from "os";
2
- import { createIndexerApp, createModeIndexerApp } from "./indexer";
3
- import { createDeploy, createModeDeploy } from "./deploy";
4
- import { startApiApp } from "./api.js";
5
- import { getBinaryName, detectBin, detectWorkingDirectory } from "./cli.js";
6
- function printAppHelp() {
7
- console.log(`
8
- Usage
1
+ // src/env.ts
2
+ function ensureAndGet(envName, defaultValue) {
3
+ return process.env[envName] || defaultValue;
4
+ }
5
+ function getEnvironment() {
6
+ return ensureAndGet("SKYNET_ENVIRONMENT", "dev");
7
+ }
8
+ function getEnvOrThrow(envName) {
9
+ if (!process.env[envName]) {
10
+ throw new Error(`Must set environment variable ${envName}`);
11
+ }
12
+ return process.env[envName];
13
+ }
14
+ function isProduction() {
15
+ return getEnvironment() === "prd";
16
+ }
17
+ function isDev() {
18
+ return getEnvironment() === "dev";
19
+ }
20
+ // src/util.ts
21
+ function range(startAt, endAt, step) {
22
+ const arr = [];
23
+ for (let i = startAt;i <= endAt; i += step) {
24
+ arr.push([i, Math.min(endAt, i + step - 1)]);
25
+ }
26
+ return arr;
27
+ }
28
+ function arrayGroup(array, groupSize) {
29
+ const groups = [];
30
+ for (let i = 0;i < array.length; i += groupSize) {
31
+ groups.push(array.slice(i, i + groupSize));
32
+ }
33
+ return groups;
34
+ }
35
+ function fillRange(start, end) {
36
+ const result = [];
37
+ for (let i = start;i <= end; i++) {
38
+ result.push(i);
39
+ }
40
+ return result;
41
+ }
42
+ // src/date.ts
43
+ var MS_IN_A_DAY = 3600 * 24 * 1000;
44
+ function getDateOnly(date) {
45
+ return new Date(date).toISOString().split("T")[0];
46
+ }
47
+ function findDateAfter(date, n) {
48
+ const d = new Date(date);
49
+ const after = new Date(d.getTime() + MS_IN_A_DAY * n);
50
+ return getDateOnly(after);
51
+ }
52
+ function daysInRange(from, to) {
53
+ const fromTime = new Date(from).getTime();
54
+ const toTime = new Date(to).getTime();
55
+ if (fromTime > toTime) {
56
+ throw new Error(`range to date couldn't be earlier than range from date`);
57
+ }
58
+ const daysBetween = Math.floor((toTime - fromTime) / MS_IN_A_DAY);
59
+ const dates = [getDateOnly(new Date(fromTime))];
60
+ for (let i = 1;i <= daysBetween; i += 1) {
61
+ dates.push(getDateOnly(new Date(fromTime + i * MS_IN_A_DAY)));
62
+ }
63
+ return dates;
64
+ }
65
+ function dateRange(from, to, step) {
66
+ const days = daysInRange(from, to);
67
+ const windows = arrayGroup(days, step);
68
+ return windows.map((w) => [w[0], w[w.length - 1]]);
69
+ }
70
+ // src/object-hash.ts
71
+ import xh from "@node-rs/xxhash";
72
+ function getHash(obj) {
73
+ const xxh3 = xh.xxh3.Xxh3.withSeed();
74
+ hash(obj, xxh3);
75
+ return xxh3.digest().toString(16);
76
+ }
77
+ function hash(obj, xxh3) {
78
+ if (obj === null) {
79
+ xxh3.update("null");
80
+ } else if (obj === undefined) {
81
+ xxh3.update("undefined");
82
+ } else if (typeof obj === "string") {
83
+ xxh3.update(obj);
84
+ } else if (typeof obj === "number") {
85
+ xxh3.update(obj.toString());
86
+ } else if (typeof obj === "boolean") {
87
+ xxh3.update(obj.toString());
88
+ } else if (typeof obj === "bigint") {
89
+ xxh3.update(obj.toString());
90
+ } else if (obj instanceof Date) {
91
+ xxh3.update(obj.toISOString());
92
+ } else if (Array.isArray(obj)) {
93
+ arrayHash(obj, xxh3);
94
+ } else if (obj instanceof Set) {
95
+ setHash(obj, xxh3);
96
+ } else if (obj instanceof Map) {
97
+ mapHash(obj, xxh3);
98
+ } else if (typeof obj === "object") {
99
+ objectHash(obj, xxh3);
100
+ } else {
101
+ throw new Error(`Unsupported type: ${obj}`);
102
+ }
103
+ }
104
+ function arrayHash(array, xxh3) {
105
+ xxh3.update("[");
106
+ for (const obj of array) {
107
+ hash(obj, xxh3);
108
+ }
109
+ xxh3.update("]");
110
+ }
111
+ function setHash(_set, _xxh3) {
112
+ throw new Error("Set hashing not implemented");
113
+ }
114
+ function mapHash(map, xxh3) {
115
+ const array = Array.from(map.entries()).sort(([aKey], [bKey]) => aKey.localeCompare(bKey));
116
+ for (const [key, value] of array) {
117
+ hash(key, xxh3);
118
+ hash(value, xxh3);
119
+ }
120
+ }
121
+ function objectHash(obj, xxh3) {
122
+ const array = Object.entries(obj).sort(([aKey], [bKey]) => aKey.localeCompare(bKey));
123
+ for (const [key, value] of array) {
124
+ hash(key, xxh3);
125
+ hash(value, xxh3);
126
+ }
127
+ }
9
128
 
10
- $ ${getBinaryName()} run <options>
11
- $ ${getBinaryName()} deploy <options>
12
- $ ${getBinaryName()} delete <options>
13
- `);
129
+ // src/availability.ts
130
+ import pThrottle from "p-throttle";
131
+ import pMemoize from "p-memoize";
132
+ import QuickLRU from "quick-lru";
133
+ async function wait(time) {
134
+ return new Promise((resolve) => {
135
+ setTimeout(resolve, time);
136
+ });
14
137
  }
15
- function isDeleteCommand(command) {
16
- return ["delete", "stop", "remove"].includes(command);
138
+ async function exponentialRetry(func, {
139
+ maxRetry,
140
+ initialDuration,
141
+ growFactor,
142
+ test,
143
+ verbose
144
+ }) {
145
+ let retries = maxRetry;
146
+ let duration = initialDuration || 5000;
147
+ const growFactorFinal = growFactor || 2;
148
+ let result = await func();
149
+ while (!test(result) && retries > 0) {
150
+ if (verbose) {
151
+ console.log("failed attempt result", result);
152
+ console.log(`sleep for ${duration}ms after failed attempt, remaining ${retries} attempts`);
153
+ }
154
+ retries = retries - 1;
155
+ await wait(duration);
156
+ result = await func();
157
+ duration = duration * growFactorFinal;
158
+ }
159
+ if (verbose) {
160
+ console.log(`function to retry ends with status ${test(result)}, number of retries done: ${maxRetry - retries}}`);
161
+ }
162
+ return result;
17
163
  }
18
- function checkAndSetEnv(env) {
19
- const missingEnvs = [];
20
- for (const key of Object.keys(env)) {
21
- if (env[key]) {
22
- process.env[key] = env[key];
23
- }
24
- else if (!process.env[key]) {
25
- missingEnvs.push(key);
164
+ function withRetry(func, options) {
165
+ let retries = options?.maxRetry || 3;
166
+ let duration = options?.initialDuration || 500;
167
+ const growFactorFinal = options?.growFactor || 2;
168
+ return async (...args) => {
169
+ do {
170
+ try {
171
+ return await func(...args);
172
+ } catch (error) {
173
+ retries = retries - 1;
174
+ if (retries <= 0) {
175
+ throw error;
26
176
  }
177
+ await wait(duration);
178
+ duration = duration * growFactorFinal;
179
+ }
180
+ } while (retries > 0);
181
+ throw new Error("unreachable");
182
+ };
183
+ }
184
+ function memoize(func, options) {
185
+ if (!options) {
186
+ options = {};
187
+ }
188
+ if (!options.cache) {
189
+ options.cache = new QuickLRU({ maxSize: options.lruMaxSize || 1e4 });
190
+ }
191
+ if (!options.cacheKey) {
192
+ options.cacheKey = (args) => getHash(args);
193
+ }
194
+ return pMemoize(func, options);
195
+ }
196
+ // src/log.ts
197
+ function isObject(a) {
198
+ return !!a && a.constructor === Object;
199
+ }
200
+ function print(o) {
201
+ if (Array.isArray(o)) {
202
+ return `[${o.map(print).join(", ")}]`;
203
+ }
204
+ if (isObject(o)) {
205
+ return `{${Object.keys(o).map((k) => `${k}: ${o[k]}`).join(", ")}}`;
206
+ }
207
+ return `${o}`;
208
+ }
209
+ function getLine(params) {
210
+ let line = "";
211
+ for (let i = 0, l = params.length;i < l; i++) {
212
+ line += `${print(params[i])} `.replace(/\n/gm, "\t");
213
+ }
214
+ return line.trim();
215
+ }
216
+ function timestamp() {
217
+ return new Date().toISOString();
218
+ }
219
+ var inline = {
220
+ debug: function(...args) {
221
+ if (true) {
222
+ console.log(`${timestamp()} ${getLine(args)}`);
27
223
  }
28
- if (missingEnvs.length > 0) {
29
- console.log(`The following environment value shouldn't be empty:${EOL}- ${missingEnvs.join(EOL + "- ")}`);
30
- process.exit(1);
224
+ },
225
+ log: function(...args) {
226
+ if (true) {
227
+ console.log(`${timestamp()} ${getLine(args)}`);
228
+ }
229
+ },
230
+ error: function(...args) {
231
+ if (true) {
232
+ console.error(`${timestamp()} ${getLine(args)}`);
233
+ }
234
+ }
235
+ };
236
+ var logger = {
237
+ debug: function(...args) {
238
+ if (true) {
239
+ console.log(`[${timestamp()}]`, ...args);
240
+ }
241
+ },
242
+ log: function(...args) {
243
+ if (true) {
244
+ console.log(`[${timestamp()}]`, ...args);
31
245
  }
246
+ },
247
+ error: function(...args) {
248
+ if (true) {
249
+ console.error(`[${timestamp()}]`, ...args);
250
+ }
251
+ }
252
+ };
253
+ // src/dynamodb.ts
254
+ import {
255
+ DynamoDBDocumentClient,
256
+ ScanCommand,
257
+ BatchWriteCommand,
258
+ GetCommand,
259
+ PutCommand,
260
+ QueryCommand,
261
+ UpdateCommand
262
+ } from "@aws-sdk/lib-dynamodb";
263
+ import { DynamoDBClient, DescribeTableCommand } from "@aws-sdk/client-dynamodb";
264
+ var _dynamoDB;
265
+ var _docClient;
266
+ function getDynamoDB(forceNew = false) {
267
+ if (!_dynamoDB || forceNew) {
268
+ _dynamoDB = new DynamoDBClient;
269
+ }
270
+ return _dynamoDB;
271
+ }
272
+ function getDocClient(forceNew = false) {
273
+ const marshallOptions = {
274
+ convertEmptyValues: true,
275
+ removeUndefinedValues: true,
276
+ convertClassInstanceToMap: true
277
+ };
278
+ const unmarshallOptions = {
279
+ wrapNumbers: false
280
+ };
281
+ if (!_docClient || forceNew) {
282
+ _docClient = DynamoDBDocumentClient.from(getDynamoDB(), {
283
+ marshallOptions,
284
+ unmarshallOptions
285
+ });
286
+ }
287
+ return _docClient;
32
288
  }
33
- function createApp({ parameterErrors, env, onRun, onDeploy, }) {
34
- if (parameterErrors.length > 0) {
35
- console.log(`Parameter Validation Failed:${EOL}- ${parameterErrors.join(EOL + "- ")}`);
289
+ async function scanWholeTable(options) {
290
+ const dynamodb = getDocClient();
291
+ let items = [];
292
+ let count = 0;
293
+ let scannedCount = 0;
294
+ let data = await dynamodb.send(new ScanCommand(options));
295
+ while (data.LastEvaluatedKey) {
296
+ if (data.Items) {
297
+ items = items.concat(data.Items);
298
+ }
299
+ count += data.Count || 0;
300
+ scannedCount += data.ScannedCount || 0;
301
+ data = await dynamodb.send(new ScanCommand({ ...options, ExclusiveStartKey: data.LastEvaluatedKey }));
302
+ }
303
+ if (data.Items) {
304
+ items = items.concat(data.Items);
305
+ }
306
+ count += data.Count || 0;
307
+ scannedCount += data.ScannedCount || 0;
308
+ return {
309
+ Items: items,
310
+ Count: count,
311
+ ScannedCount: scannedCount
312
+ };
313
+ }
314
+ async function batchCreateRecords(tableName, records, maxWritingCapacity, verbose = false) {
315
+ if (verbose) {
316
+ console.log(`creating ${records.length} items in ${tableName}`);
317
+ }
318
+ const docClient = getDocClient();
319
+ let remainingItems = records;
320
+ let prevRemainingCount = remainingItems.length + 1;
321
+ let factor = 1;
322
+ let rejection = undefined;
323
+ while (remainingItems.length > 0 && factor <= 128 && !rejection) {
324
+ if (prevRemainingCount === remainingItems.length) {
325
+ await wait(5000 * factor);
326
+ factor = factor * 2;
327
+ }
328
+ if (factor >= 32) {
329
+ console.log(`WARNING: no progress for a long time for batchCreateRecords, please check`);
330
+ }
331
+ const slices = arrayGroup(remainingItems.slice(0, maxWritingCapacity), 25);
332
+ const results = await Promise.allSettled(slices.map((rs) => docClient.send(new BatchWriteCommand({
333
+ RequestItems: {
334
+ [tableName]: rs.map((record) => ({ PutRequest: { Item: record } }))
335
+ }
336
+ }))));
337
+ const isFulfilled = (p) => p.status === "fulfilled";
338
+ const isRejected = (p) => p.status === "rejected";
339
+ prevRemainingCount = remainingItems.length;
340
+ remainingItems = remainingItems.slice(maxWritingCapacity);
341
+ results.forEach((rs, idx) => {
342
+ if (isRejected(rs)) {
343
+ remainingItems = remainingItems.concat(slices[idx]);
344
+ rejection = rs;
345
+ } else if (isFulfilled(rs) && rs.value.UnprocessedItems && Object.keys(rs.value.UnprocessedItems).length > 0) {
346
+ const unprocessedItems = rs.value.UnprocessedItems[tableName].map((it) => it.PutRequest?.Item ?? []).flat();
347
+ remainingItems = remainingItems.concat(unprocessedItems);
348
+ }
349
+ });
350
+ if (verbose) {
351
+ console.log(`processed=${prevRemainingCount - remainingItems.length}, remaining=${remainingItems.length}`);
352
+ }
353
+ }
354
+ if (rejection) {
355
+ console.log("batchCreateRecords rejected", rejection);
356
+ throw new Error(`batchCreateRecords rejected, failed items=${remainingItems.length}`);
357
+ }
358
+ if (remainingItems.length > 0) {
359
+ console.log(`failed batchCreateRecords, failed items=${remainingItems.length}`);
360
+ throw new Error(`batchCreateRecords retry failed, failed items=${remainingItems.length}`);
361
+ }
362
+ }
363
+ async function createRecord(tableName, fields, verbose = false) {
364
+ if (verbose) {
365
+ console.log("creating", tableName, fields);
366
+ }
367
+ const docClient = getDocClient();
368
+ const params = {
369
+ TableName: tableName,
370
+ Item: fields
371
+ };
372
+ return docClient.send(new PutCommand(params));
373
+ }
374
+ async function readRecord(tableName, key, verbose = false) {
375
+ if (verbose) {
376
+ console.log("reading", tableName, key);
377
+ }
378
+ const docClient = getDocClient();
379
+ const record = await docClient.send(new GetCommand({
380
+ TableName: tableName,
381
+ Key: key
382
+ }));
383
+ return record.Item;
384
+ }
385
+ async function getRecordsByKey(tableName, keys, indexName) {
386
+ const docClient = getDocClient();
387
+ const keyNames = Object.keys(keys);
388
+ const conditionExpression = keyNames.map((key) => `#${key} = :${key}`).join(" and ");
389
+ const params = {
390
+ TableName: tableName,
391
+ KeyConditionExpression: conditionExpression,
392
+ ExpressionAttributeNames: generateExpressionNames(keyNames),
393
+ ExpressionAttributeValues: generateExpressionValues(keyNames, keys)
394
+ };
395
+ if (indexName) {
396
+ params.IndexName = indexName;
397
+ }
398
+ try {
399
+ let data = await docClient.send(new QueryCommand(params));
400
+ let items = data.Items ?? [];
401
+ while (data.LastEvaluatedKey) {
402
+ data = await docClient.send(new QueryCommand({
403
+ ...params,
404
+ ExclusiveStartKey: data.LastEvaluatedKey
405
+ }));
406
+ if (data.Items) {
407
+ items = items.concat(data.Items);
408
+ }
409
+ }
410
+ return items;
411
+ } catch (err) {
412
+ console.log(err);
413
+ if (err instanceof Error && "statusCode" in err && err.statusCode === 400) {
414
+ return null;
415
+ }
416
+ throw err;
417
+ }
418
+ }
419
+ async function getRecordByKey(tableName, keys, indexName) {
420
+ if (indexName) {
421
+ const records = await getRecordsByKey(tableName, keys, indexName);
422
+ if (records) {
423
+ return records[0];
424
+ } else {
425
+ return null;
426
+ }
427
+ } else {
428
+ return readRecord(tableName, keys);
429
+ }
430
+ }
431
+ function generateExpressionNames(keys) {
432
+ return keys.reduce((acc, key) => ({ ...acc, [`#${key}`]: key }), {});
433
+ }
434
+ function generateExpressionValues(keys, fields) {
435
+ return keys.reduce((acc, key) => ({ ...acc, [`:${key}`]: fields[key] }), {});
436
+ }
437
+ async function updateRecordByKey(tableName, idKey, fields, conditionExpressions = null, verbose = false) {
438
+ if (verbose) {
439
+ console.log("update", tableName, idKey, fields);
440
+ }
441
+ const docClient = getDocClient();
442
+ const idKeyNames = Object.keys(idKey);
443
+ const fieldsToDelete = Object.keys(fields).filter((f) => fields[f] === undefined);
444
+ const fieldsToUpdate = Object.keys(fields).filter((k) => !idKeyNames.includes(k) && !fieldsToDelete.includes(k));
445
+ let data;
446
+ if (fieldsToDelete.length > 0) {
447
+ if (verbose) {
448
+ console.log("delete fields", tableName, fieldsToDelete);
449
+ }
450
+ const deleteParams = {
451
+ TableName: tableName,
452
+ Key: idKey,
453
+ ExpressionAttributeNames: generateExpressionNames(fieldsToDelete),
454
+ UpdateExpression: `REMOVE ${fieldsToDelete.map((f) => `#${f}`).join(", ")}`,
455
+ ReturnValues: "ALL_NEW"
456
+ };
457
+ if (conditionExpressions) {
458
+ deleteParams.ConditionExpression = conditionExpressions;
459
+ }
460
+ data = await docClient.send(new UpdateCommand(deleteParams));
461
+ }
462
+ if (fieldsToUpdate.length > 0) {
463
+ if (verbose) {
464
+ console.log("update fields", tableName, fieldsToUpdate);
465
+ }
466
+ const updateExpressions = fieldsToUpdate.map((key) => `#${key} = :${key}`);
467
+ const params = {
468
+ TableName: tableName,
469
+ Key: idKey,
470
+ ExpressionAttributeNames: generateExpressionNames(fieldsToUpdate),
471
+ ExpressionAttributeValues: generateExpressionValues(fieldsToUpdate, fields),
472
+ UpdateExpression: `SET ${updateExpressions.join(", ")}`,
473
+ ReturnValues: "ALL_NEW"
474
+ };
475
+ if (conditionExpressions) {
476
+ params.ConditionExpression = conditionExpressions;
477
+ }
478
+ data = await docClient.send(new UpdateCommand(params));
479
+ }
480
+ return data?.Attributes;
481
+ }
482
+ async function batchDeleteRecords(tableName, keys) {
483
+ const docClient = getDocClient();
484
+ for (let start = 0;start < keys.length; start += 25) {
485
+ const slice = keys.slice(start, start + 25);
486
+ await docClient.send(new BatchWriteCommand({
487
+ RequestItems: {
488
+ [tableName]: slice.map((key) => {
489
+ return { DeleteRequest: { Key: key } };
490
+ })
491
+ }
492
+ }));
493
+ }
494
+ }
495
+ function getKeyName(keySchema, type) {
496
+ const key = keySchema.find((k) => k.KeyType === type);
497
+ return key?.AttributeName;
498
+ }
499
+ function getIndexKeyName(globalSecondaryIndexes, indexName, type) {
500
+ const idx = globalSecondaryIndexes.find((i) => i.IndexName === indexName);
501
+ return idx?.KeySchema && getKeyName(idx.KeySchema, type);
502
+ }
503
+ async function deleteRecordsByHashKey(tableName, indexName, hashKeyValue, verbose = false) {
504
+ const docClient = getDocClient();
505
+ const meta = await getDynamoDB().send(new DescribeTableCommand({ TableName: tableName }));
506
+ if (!meta.Table) {
507
+ throw new Error(`cannot find table ${tableName}`);
508
+ }
509
+ if (indexName && !meta.Table.GlobalSecondaryIndexes) {
510
+ throw new Error(`cannot find global secondary indexes for table ${tableName}`);
511
+ }
512
+ if (!meta.Table.KeySchema) {
513
+ throw new Error(`cannot find key schema for table ${tableName}`);
514
+ }
515
+ const hashKeyName = indexName ? getIndexKeyName(meta.Table.GlobalSecondaryIndexes, indexName, "HASH") : getKeyName(meta.Table.KeySchema, "HASH");
516
+ if (!hashKeyName) {
517
+ throw new Error(`cannot find hash key name for table ${tableName}`);
518
+ }
519
+ const mainHashKeyName = getKeyName(meta.Table.KeySchema, "HASH");
520
+ if (!mainHashKeyName) {
521
+ throw new Error(`cannot find main hash key name for table ${tableName}`);
522
+ }
523
+ const mainRangeKeyName = getKeyName(meta.Table.KeySchema, "RANGE");
524
+ if (!mainRangeKeyName) {
525
+ throw new Error(`cannot find main range key name for table ${tableName}`);
526
+ }
527
+ let totalDeleted = 0;
528
+ const params = {
529
+ TableName: tableName,
530
+ KeyConditionExpression: "#hashKeyName = :hashKeyValue",
531
+ ExpressionAttributeNames: { "#hashKeyName": hashKeyName },
532
+ ExpressionAttributeValues: { ":hashKeyValue": hashKeyValue }
533
+ };
534
+ if (indexName) {
535
+ params.IndexName = indexName;
536
+ }
537
+ let data = await docClient.send(new QueryCommand(params));
538
+ if (data.Items) {
539
+ await batchDeleteRecords(tableName, data.Items.map((item) => mainRangeKeyName ? {
540
+ [mainHashKeyName]: item[mainHashKeyName],
541
+ [mainRangeKeyName]: item[mainRangeKeyName]
542
+ } : {
543
+ [mainHashKeyName]: item[mainHashKeyName]
544
+ }));
545
+ totalDeleted += data.Items.length;
546
+ }
547
+ while (data.LastEvaluatedKey) {
548
+ data = await docClient.send(new QueryCommand({
549
+ ...params,
550
+ ExclusiveStartKey: data.LastEvaluatedKey
551
+ }));
552
+ if (data.Items) {
553
+ await batchDeleteRecords(tableName, data.Items.map((item) => mainRangeKeyName ? {
554
+ [mainHashKeyName]: item[mainHashKeyName],
555
+ [mainRangeKeyName]: item[mainRangeKeyName]
556
+ } : {
557
+ [mainHashKeyName]: item[mainHashKeyName]
558
+ }));
559
+ totalDeleted += data.Items.length;
560
+ }
561
+ }
562
+ if (verbose) {
563
+ console.log(`successfully delete ${totalDeleted} items`);
564
+ }
565
+ return totalDeleted;
566
+ }
567
+ // src/selector.ts
568
+ function getSelectorDesc(selector) {
569
+ return Object.keys(selector).map((name) => {
570
+ return ` --${name.padEnd(14)}${selector[name].desc || selector[name].description || ""}`;
571
+ }).join(`
572
+ `);
573
+ }
574
+ function getSelectorFlags(selector) {
575
+ return Object.keys(selector).reduce((acc, name) => {
576
+ const flag = {
577
+ type: selector[name].type || "string",
578
+ ...selector[name]
579
+ };
580
+ if (!selector[name].optional && selector[name].isRequired !== false) {
581
+ flag.isRequired = true;
582
+ }
583
+ return { ...acc, [name]: flag };
584
+ }, {});
585
+ }
586
+ function toSelectorString(selectorFlags, delim = ",") {
587
+ return Object.keys(selectorFlags).sort().map((flag) => {
588
+ return `${flag}=${selectorFlags[flag]}`;
589
+ }).join(delim);
590
+ }
591
+ function normalizeSelectorValue(v) {
592
+ return v.replace(/[^A-Za-z0-9]+/g, "-");
593
+ }
594
+ function getJobName(name, selectorFlags, mode) {
595
+ const selectorNamePart = Object.keys(selectorFlags).sort().map((name2) => selectorFlags[name2]).join("-");
596
+ let jobName = name;
597
+ if (mode) {
598
+ jobName += `-${mode}`;
599
+ }
600
+ if (selectorNamePart.length > 0) {
601
+ jobName += `-${normalizeSelectorValue(selectorNamePart)}`;
602
+ }
603
+ return jobName;
604
+ }
605
+ // src/cli.ts
606
+ import path from "path";
607
+ import fs from "fs";
608
+ function getBinaryName() {
609
+ const binaryNameParts = process.argv[1].split(path.sep);
610
+ const binaryName = binaryNameParts[binaryNameParts.length - 1];
611
+ return binaryName;
612
+ }
613
+ function detectSkynetDirectory() {
614
+ return detectDirectory(process.argv[1], "SkynetAPIDefinitions.yml");
615
+ }
616
+ function detectWorkingDirectory() {
617
+ const wd = detectDirectory(process.argv[1], "package.json");
618
+ const skynetd = detectDirectory(process.argv[1], "SkynetAPIDefinitions.yml");
619
+ return wd.slice(skynetd.length + path.sep.length).replace(path.sep, "/");
620
+ }
621
+ function detectDirectory(fullBinPath, sentinel = "package.json") {
622
+ let parentFolder = path.dirname(fullBinPath);
623
+ while (parentFolder) {
624
+ const sentinelPath = path.join(parentFolder, sentinel);
625
+ if (fs.existsSync(sentinelPath)) {
626
+ return parentFolder;
627
+ }
628
+ const newParentFolder = path.dirname(parentFolder);
629
+ if (newParentFolder === parentFolder) {
630
+ break;
631
+ }
632
+ parentFolder = newParentFolder;
633
+ }
634
+ throw new Error("Cannot detect current working directory");
635
+ }
636
+ function detectBin() {
637
+ const wd = detectDirectory(process.argv[1], "package.json");
638
+ return process.argv[1].slice(wd.length + path.sep.length).replace(path.sep, "/");
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`);
36
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);
37
806
  }
38
- return async () => {
39
- const subCommand = process.argv[2];
40
- // emulate command line call without subcmd
41
- process.argv = [process.argv[0], process.argv[1], ...process.argv.slice(3)];
42
- if (subCommand === "run") {
43
- checkAndSetEnv(env);
44
- await onRun();
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}`);
45
841
  }
46
- else if (subCommand === "deploy" || isDeleteCommand(subCommand)) {
47
- if (isDeleteCommand(subCommand)) {
48
- process.argv.push("--stop");
49
- }
50
- await onDeploy();
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}`);
51
850
  }
52
- else {
53
- printAppHelp();
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);
54
877
  }
55
- };
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
+ version: false,
1000
+ flags: {
1001
+ ...getSelectorFlags(selector),
1002
+ mode: {
1003
+ type: "string",
1004
+ default: "delta"
1005
+ },
1006
+ from: {
1007
+ aliases: ["since"],
1008
+ type: "string"
1009
+ },
1010
+ to: {
1011
+ aliases: ["until"],
1012
+ type: "string"
1013
+ },
1014
+ status: {
1015
+ type: "boolean",
1016
+ default: false
1017
+ },
1018
+ verbose: {
1019
+ type: "boolean",
1020
+ default: false
1021
+ }
1022
+ }
1023
+ });
1024
+ try {
1025
+ return runMode(cli.flags);
1026
+ } catch (err) {
1027
+ inline.error(err);
1028
+ process.exit(1);
1029
+ }
1030
+ }
1031
+ return { run };
56
1032
  }
57
- function checkEnvParameter(env) {
58
- const errors = [];
59
- const envKeys = Object.keys(env);
60
- envKeys.forEach((k) => {
61
- if (!env[k] && env[k] !== SENSITIVE_VALUE) {
62
- errors.push(`must have valid non-empty value for env.${k}`);
1033
+ function createIndexerApp({
1034
+ binaryName,
1035
+ selector = {},
1036
+ build,
1037
+ maxRetry = 2
1038
+ }) {
1039
+ async function run() {
1040
+ if (!binaryName) {
1041
+ binaryName = getBinaryName();
1042
+ }
1043
+ const cli = meow(`
1044
+ Usage
1045
+ $ ${binaryName} <options>
1046
+
1047
+ Options
1048
+ ${selector ? getSelectorDesc(selector) : ""}
1049
+ --verbose Output debug messages
1050
+ `, {
1051
+ importMeta: import.meta,
1052
+ description: false,
1053
+ version: false,
1054
+ flags: {
1055
+ ...getSelectorFlags(selector),
1056
+ verbose: {
1057
+ type: "boolean",
1058
+ default: false
1059
+ }
1060
+ }
1061
+ });
1062
+ async function runBuild(flags) {
1063
+ const { verbose: untypedVerbose, ...untypedSelectorFlags } = flags;
1064
+ const verbose = untypedVerbose;
1065
+ const selectorFlags = untypedSelectorFlags;
1066
+ const startTime = Date.now();
1067
+ if (Object.keys(selectorFlags).length > 0) {
1068
+ inline.log(`[INDEXER] starting build, ${toSelectorString(selectorFlags, ", ")}`);
1069
+ } else {
1070
+ inline.log(`[INDEXER] starting build`);
1071
+ }
1072
+ const result = await exponentialRetry(async () => {
1073
+ try {
1074
+ await build(flags);
1075
+ return true;
1076
+ } catch (err) {
1077
+ inline.log(`[INDEXER] got error in build`, err);
1078
+ return false;
63
1079
  }
1080
+ }, {
1081
+ maxRetry,
1082
+ test: (r) => r,
1083
+ verbose
1084
+ });
1085
+ if (!result) {
1086
+ throw new Error(`[INDEXER] Build failed due to critical errors`);
1087
+ }
1088
+ inline.log(`[INDEXER] build successfully in ${Date.now() - startTime}ms`);
1089
+ }
1090
+ return runBuild(cli.flags).catch((err) => {
1091
+ inline.error(err);
1092
+ process.exit(1);
64
1093
  });
65
- return errors;
1094
+ }
1095
+ return { run };
66
1096
  }
67
- function checkIndexerBuildParameter(build) {
68
- const errors = [];
69
- if (!build?.func) {
70
- errors.push("must define build.func");
1097
+ // src/deploy.ts
1098
+ import fs2 from "fs/promises";
1099
+ import fso from "fs";
1100
+ import { execa } from "execa";
1101
+ import meow2 from "meow";
1102
+ import chalk from "chalk";
1103
+ import which from "which";
1104
+ var INTERVAL_ALIASES = {
1105
+ secondly: "*/1 * * * * * *",
1106
+ "@secondly": "*/1 * * * * * *",
1107
+ minutely: "0 * * * * * *",
1108
+ "@minutely": "0 * * * * * *",
1109
+ hourly: "0 0 * * * * *",
1110
+ "@hourly": "0 0 * * * * *",
1111
+ daily: "0 0 0 * * * *",
1112
+ "@daily": "0 0 0 * * * *",
1113
+ weekly: "0 0 0 * * 0 *",
1114
+ "@weekly": "0 0 0 * * 0 *"
1115
+ };
1116
+ var genConfig = ({
1117
+ jobName,
1118
+ workingDirectory,
1119
+ cmd,
1120
+ cron,
1121
+ count,
1122
+ restart,
1123
+ killTimeout,
1124
+ cpu,
1125
+ mem,
1126
+ service,
1127
+ additionalEnv = {},
1128
+ type = "batch",
1129
+ region = "skynet-dc1",
1130
+ isProduction: isProduction2
1131
+ }) => `job "${jobName}" {
1132
+ datacenters = ["${region}"]
1133
+
1134
+ type = "${type}"
1135
+
1136
+ ${cron ? `# Triggers periodically
1137
+ periodic {
1138
+ crons = ["${cron}"]
1139
+ prohibit_overlap = true
1140
+ }` : ""}
1141
+
1142
+ constraint {
1143
+ attribute = "\${meta.has_nodejs}"
1144
+ value = "true"
1145
+ }
1146
+
1147
+ constraint {
1148
+ attribute = "\${meta.has_skynet}"
1149
+ value = "true"
1150
+ }
1151
+
1152
+ group "default" {
1153
+ ${count && count > 1 ? `count = ${count}` : ""}
1154
+ ${count && count > 1 ? `# Rolling Update
1155
+ update {
1156
+ max_parallel = 1
1157
+ min_healthy_time = "10s"
1158
+ }` : ""}
1159
+
1160
+ reschedule {
1161
+ attempts = 0
1162
+ unlimited = false
71
1163
  }
72
- if (!build?.cpu) {
73
- errors.push("must define build.cpu");
1164
+
1165
+ ${service ? `# Setup Service Network
1166
+ network {
1167
+ port "http" {
1168
+ static = ${service.port}
1169
+ }
1170
+ }` : ""}
1171
+
1172
+ task "main" {
1173
+ driver = "raw_exec"
1174
+
1175
+ config {
1176
+ command = "sh"
1177
+ args = [
1178
+ "-c",
1179
+ "cd \${meta.skynet_code_path}/${workingDirectory} && if [ -e bun.lockb ]; then bun install --silent; else yarn install --silent; fi && exec ${cmd}"
1180
+ ]
1181
+ }
1182
+
1183
+ ${service ? `# Setup API Routes
1184
+ service {
1185
+ name = "${jobName}"
1186
+ port = "http"
1187
+
1188
+ tags = [
1189
+ "urlprefix-${service.prefix} strip=${service.prefix}",
1190
+ ]
1191
+
1192
+ check {
1193
+ type = "http"
1194
+ path = "/"
1195
+ interval = "10s"
1196
+ timeout = "2s"
1197
+ }
1198
+ }
1199
+ ` : ""}
1200
+
1201
+ # doppler integration support
1202
+ # it is always there but a project can decide to not use it
1203
+ template {
1204
+ change_mode = "restart"
1205
+ destination = "secrets/context.env"
1206
+ env = true
1207
+ data = "DOPPLER_TOKEN={{key \\"infra-nomad/doppler-token\\"}}"
1208
+ }
1209
+
1210
+ # always update SKYNET_DEPLOYED_AT so that new deployment always triggers
1211
+ env {
1212
+ SKYNET_DEPLOYED_AT="${new Date().toISOString()}"
1213
+ HOME="/root"
1214
+ DOPPLER_PROJECT="${workingDirectory}"
1215
+ DOPPLER_CONFIG="${isProduction2 ? "prd" : "dev"}"
1216
+ SKYNET_ENVIRONMENT="${isProduction2 ? "prd" : "dev"}"
1217
+ ${Object.entries(additionalEnv).filter((kv) => !!kv[1]).map(([key, value]) => `${key}="${value}"`).join(`
1218
+ `)}
1219
+ }
1220
+
1221
+ kill_timeout = "${killTimeout || "60s"}"
1222
+
1223
+ # Specify the maximum resources required to run the task,
1224
+ # include CPU and memory.
1225
+ resources {
1226
+ cpu = ${cpu} # MHz
1227
+ memory = ${mem} # MB
1228
+ }
1229
+
1230
+ # Setting the server task as the leader of the task group allows Nomad to
1231
+ # signal the log shipper task to gracefully shutdown when the server exits.
1232
+ leader = true
1233
+
1234
+ ${restart ? `
1235
+ # Restart the job if it fails
1236
+ restart {
1237
+ attempts = ${restart.attempts ?? 2}
1238
+ mode = "${restart.mode ?? "fail"}"
1239
+ interval = "${restart.interval ?? "30m"}"
1240
+ delay = "${restart.delay ?? "15s"}"
1241
+ }
1242
+ ` : `
1243
+ # do not retry from the periodical job will reschedule anyway
1244
+ restart {
1245
+ attempts = 0
1246
+ mode = "fail"
1247
+ }`}
74
1248
  }
75
- if (!build?.mem) {
76
- errors.push("must define build.mem");
1249
+ }
1250
+ }`;
1251
+ async function prepareNomad(isProduction2) {
1252
+ if (isProduction2) {
1253
+ console.log("Deploy to Production");
1254
+ } else {
1255
+ const skynetDir = detectSkynetDirectory();
1256
+ if (!fso.existsSync("/tmp/skynet")) {
1257
+ await execa("ln", ["-s", skynetDir, "/tmp/skynet"]);
77
1258
  }
78
- return errors;
1259
+ console.log("Deploy locally, please start nomad server in a separate terminal");
1260
+ console.log(`You can start nomad server by running ${chalk.inverse(`${skynetDir}/infra-nomad/dev/start.sh`)}`);
1261
+ console.log(`Then you can visit ${chalk.underline("http://localhost:4646/ui/jobs")} to check submitted dev jobs.
1262
+ `);
1263
+ }
79
1264
  }
80
- function checkStateParameter(state) {
81
- const errors = [];
82
- if (!state?.type) {
83
- errors.push("must define state.type");
1265
+ function getNomadAddr(isProduction2) {
1266
+ return isProduction2 ? getEnvOrThrow("NOMAD_ADDR") : "http://127.0.0.1:4646";
1267
+ }
1268
+ async function getNomadPath() {
1269
+ try {
1270
+ return await which("nomad");
1271
+ } catch (missingNomad) {
1272
+ console.log(`Deploy requires ${chalk.bold("nomad")} binary, please follow ${chalk.underline("https://learn.hashicorp.com/tutorials/nomad/get-started-install")} for installation`, missingNomad);
1273
+ throw new Error("missing nomad binary");
1274
+ }
1275
+ }
1276
+ async function runNomadJob(nomadPath, nomadAddr, jobName, nomadJobDefinition, isStop, isDryRun) {
1277
+ try {
1278
+ if (isStop) {
1279
+ const nomad = execa(nomadPath, ["job", "stop", jobName], {
1280
+ env: {
1281
+ NOMAD_ADDR: nomadAddr
1282
+ }
1283
+ });
1284
+ nomad.stdout.pipe(process.stdout);
1285
+ await nomad;
1286
+ console.log(chalk.green(`Stopped nomad job ${jobName} in ${nomadAddr}`));
1287
+ } else if (isDryRun) {
1288
+ console.log("Definition for", jobName);
1289
+ console.log("========================================");
1290
+ console.log(nomadJobDefinition);
1291
+ } else {
1292
+ const jobFileName = `/tmp/job-${jobName}`;
1293
+ await fs2.writeFile(jobFileName, nomadJobDefinition);
1294
+ const nomad = execa(nomadPath, ["job", "run", jobFileName], {
1295
+ env: {
1296
+ NOMAD_ADDR: nomadAddr
1297
+ }
1298
+ });
1299
+ nomad.stdout.pipe(process.stdout);
1300
+ await nomad;
1301
+ console.log(chalk.green(`Deployed nomad job ${jobName} to ${nomadAddr}`));
84
1302
  }
85
- if (!state?.getMaxId) {
86
- errors.push("must define state.getMaxId");
1303
+ } catch (nomadExecErr) {
1304
+ if (nomadExecErr instanceof Error) {
1305
+ console.log("Nomad Execution Error:");
1306
+ console.log(nomadExecErr.message);
1307
+ console.log("");
87
1308
  }
88
- return errors;
1309
+ console.log(`Failed to run ${chalk.bold("nomad")} commands, please ensure nomad server is accessible at ${chalk.bold(nomadAddr)}`);
1310
+ throw new Error("nomad execution error");
1311
+ }
89
1312
  }
90
- function indexer({ name, selector, build, env = {}, region = "skynet-dc1", }) {
91
- return createApp({
92
- parameterErrors: [...checkIndexerBuildParameter(build), ...checkEnvParameter(env)],
93
- env,
94
- onRun: () => {
95
- const { run } = createIndexerApp({
96
- binaryName: `${getBinaryName()} run`,
97
- selector,
98
- build: build.func,
99
- maxRetry: build.maxRetry,
100
- });
101
- process.title = name;
102
- return run();
1313
+ function createModeDeploy({
1314
+ binaryName,
1315
+ name,
1316
+ workingDirectory,
1317
+ bin = "bin/indexer",
1318
+ selector = {},
1319
+ env = {},
1320
+ region = "skynet-dc1",
1321
+ deltaSchedule,
1322
+ validateSchedule,
1323
+ deltaKillTimeout,
1324
+ deltaCpu,
1325
+ deltaMem,
1326
+ rebuildKillTimeout,
1327
+ rebuildCpu,
1328
+ rebuildMem,
1329
+ validateKillTimeout,
1330
+ validateCpu,
1331
+ validateMem
1332
+ }) {
1333
+ async function deployMode({
1334
+ mode,
1335
+ from,
1336
+ to,
1337
+ stop,
1338
+ production,
1339
+ dryRun,
1340
+ verbose,
1341
+ schedule: cmdSchedule,
1342
+ ...selectorFlags
1343
+ }) {
1344
+ if (mode === "delta") {
1345
+ from = 0;
1346
+ to = 0;
1347
+ }
1348
+ const isPeriodic = from === 0 && to === 0 && ["delta", "validate"].includes(mode);
1349
+ const jobName = getJobName(name, selectorFlags, mode);
1350
+ const selectorCmdPart = Object.entries(selectorFlags).sort().map(([name2, value]) => `--${name2} ${value}`).join(" ");
1351
+ let args = `--mode ${mode} ${selectorCmdPart}`;
1352
+ if (verbose) {
1353
+ args += ` --verbose`;
1354
+ }
1355
+ let rangeArgs = "";
1356
+ if (from > 0) {
1357
+ rangeArgs += ` --from ${from}`;
1358
+ }
1359
+ if (to > 0) {
1360
+ rangeArgs += ` --to ${to}`;
1361
+ }
1362
+ const modeResouces = {
1363
+ rebuild: { cpu: rebuildCpu, mem: rebuildMem, killTimeout: rebuildKillTimeout },
1364
+ "resume-rebuild": { cpu: rebuildCpu, mem: rebuildMem, killTimeout: rebuildKillTimeout },
1365
+ validate: {
1366
+ cpu: validateCpu || rebuildCpu,
1367
+ mem: validateMem || rebuildMem,
1368
+ killTimeout: validateKillTimeout || rebuildKillTimeout
1369
+ },
1370
+ delta: { cpu: deltaCpu, mem: deltaMem, killTimeout: deltaKillTimeout }
1371
+ };
1372
+ const cpu = modeResouces[mode]?.cpu || deltaCpu;
1373
+ const mem = modeResouces[mode]?.mem || deltaMem;
1374
+ const killTimeout = modeResouces[mode]?.killTimeout || deltaKillTimeout;
1375
+ let deltaCron = typeof deltaSchedule === "function" ? deltaSchedule(jobName) : deltaSchedule;
1376
+ if (deltaSchedule && cmdSchedule) {
1377
+ deltaCron = cmdSchedule;
1378
+ }
1379
+ let validateCron = typeof validateSchedule === "function" ? validateSchedule(jobName) : validateSchedule;
1380
+ if (validateSchedule && cmdSchedule) {
1381
+ validateCron = cmdSchedule;
1382
+ }
1383
+ const modeIntervals = {
1384
+ delta: deltaCron ? INTERVAL_ALIASES[deltaCron] || deltaCron : undefined,
1385
+ validate: validateCron ? INTERVAL_ALIASES[validateCron] || validateCron : undefined
1386
+ };
1387
+ const mainJobDefinition = genConfig({
1388
+ jobName,
1389
+ cron: isPeriodic ? modeIntervals[mode] : undefined,
1390
+ workingDirectory,
1391
+ additionalEnv: env,
1392
+ region,
1393
+ cmd: `${bin} ${args} ${rangeArgs}`,
1394
+ killTimeout,
1395
+ cpu,
1396
+ mem,
1397
+ isProduction: production
1398
+ });
1399
+ const nomadPath = await getNomadPath();
1400
+ await prepareNomad(production);
1401
+ const nomadAddr = getNomadAddr(production);
1402
+ await runNomadJob(nomadPath, nomadAddr, jobName, mainJobDefinition, stop, dryRun);
1403
+ }
1404
+ async function deploy() {
1405
+ if (!binaryName) {
1406
+ binaryName = getBinaryName();
1407
+ }
1408
+ const cli = meow2(`
1409
+ Usage
1410
+
1411
+ $ ${binaryName} <options>
1412
+
1413
+ Options
1414
+ ${getSelectorDesc(selector)}
1415
+ --mode could be delta/rebuild/resume-rebuild/validate/one/range/reset
1416
+ --from min id to build
1417
+ --to max id to build
1418
+ --stop stop job instead of running the job
1419
+ --production deploy to production, default is development
1420
+ --schedule override default schedule, support aliases: secondly, minutely, hourly, daily, weekly
1421
+ --verbose Output debug messages
1422
+ --dry-run print nomad job file but do not really execute it
1423
+
1424
+ Examples
1425
+ ${binaryName} --mode delta
1426
+ ${binaryName} --mode rebuild
1427
+ ${binaryName} --mode validate
1428
+ `, {
1429
+ importMeta: import.meta,
1430
+ description: false,
1431
+ version: false,
1432
+ flags: {
1433
+ ...getSelectorFlags(selector),
1434
+ mode: {
1435
+ type: "string",
1436
+ default: "delta"
103
1437
  },
104
- onDeploy: () => {
105
- const bin = detectBin();
106
- const needDoppler = Object.values(env).some((v) => v === SENSITIVE_VALUE);
107
- const { deploy } = createDeploy({
108
- binaryName: `${getBinaryName()} deploy`,
109
- name,
110
- workingDirectory: detectWorkingDirectory(),
111
- bin: needDoppler ? `doppler run -- ${bin} run` : `${bin} run`,
112
- selector,
113
- region,
114
- env,
115
- schedule: build.schedule,
116
- restart: build.restart,
117
- killTimeout: build.killTimeout,
118
- cpu: build.cpu,
119
- mem: build.mem,
120
- });
121
- return deploy();
1438
+ from: {
1439
+ aliases: ["since"],
1440
+ type: "number",
1441
+ default: 0
122
1442
  },
1443
+ to: {
1444
+ aliases: ["until"],
1445
+ type: "number",
1446
+ default: 0
1447
+ },
1448
+ schedule: {
1449
+ type: "string"
1450
+ },
1451
+ verbose: {
1452
+ type: "boolean",
1453
+ default: false
1454
+ },
1455
+ production: {
1456
+ aliases: ["prd"],
1457
+ type: "boolean",
1458
+ default: false
1459
+ },
1460
+ dryRun: {
1461
+ type: "boolean",
1462
+ default: false
1463
+ },
1464
+ stop: {
1465
+ type: "boolean",
1466
+ default: false
1467
+ }
1468
+ }
123
1469
  });
1470
+ try {
1471
+ return deployMode(cli.flags);
1472
+ } catch (err) {
1473
+ console.error(err);
1474
+ process.exit(1);
1475
+ }
1476
+ }
1477
+ return { deploy };
124
1478
  }
125
- function checkModeIndexerBuildParameter(build) {
126
- const errors = [];
127
- if (!build?.func) {
128
- errors.push("must define build.func");
1479
+ function createDeploy({
1480
+ binaryName,
1481
+ name,
1482
+ workingDirectory,
1483
+ bin = "bin/indexer",
1484
+ selector = {},
1485
+ region = "skynet-dc1",
1486
+ type = "batch",
1487
+ env = {},
1488
+ count,
1489
+ schedule,
1490
+ restart,
1491
+ killTimeout,
1492
+ cpu,
1493
+ mem,
1494
+ service
1495
+ }) {
1496
+ async function deployModeless({
1497
+ production,
1498
+ stop,
1499
+ dryRun,
1500
+ verbose,
1501
+ schedule: cmdSchedule,
1502
+ ...selectorFlags
1503
+ }) {
1504
+ const jobName = getJobName(name, selectorFlags);
1505
+ const selectorCmdPart = Object.entries(selectorFlags).sort().map(([name2, value]) => `--${name2} ${value}`).join(" ");
1506
+ let args = `${selectorCmdPart}`;
1507
+ if (verbose) {
1508
+ args += ` --verbose`;
129
1509
  }
130
- if (!build?.cpu) {
131
- errors.push("must define build.cpu");
1510
+ let cron = typeof schedule === "function" ? schedule(jobName) : schedule;
1511
+ if (schedule && cmdSchedule) {
1512
+ cron = cmdSchedule;
132
1513
  }
133
- if (!build?.mem) {
134
- errors.push("must define build.mem");
1514
+ const nomadJobDefinition = genConfig({
1515
+ jobName,
1516
+ cron: cron ? INTERVAL_ALIASES[cron] || cron : undefined,
1517
+ count,
1518
+ restart,
1519
+ workingDirectory,
1520
+ additionalEnv: env,
1521
+ region,
1522
+ type,
1523
+ cmd: `${bin} ${args}`,
1524
+ killTimeout,
1525
+ cpu,
1526
+ mem,
1527
+ service,
1528
+ isProduction: production
1529
+ });
1530
+ const nomadPath = await getNomadPath();
1531
+ await prepareNomad(production);
1532
+ const nomadAddr = getNomadAddr(production);
1533
+ await runNomadJob(nomadPath, nomadAddr, jobName, nomadJobDefinition, stop, dryRun);
1534
+ }
1535
+ async function deploy() {
1536
+ if (!binaryName) {
1537
+ binaryName = getBinaryName();
135
1538
  }
136
- return errors;
1539
+ const cli = meow2(`
1540
+ Usage
1541
+
1542
+ $ ${binaryName} <options>
1543
+
1544
+ Options
1545
+ ${getSelectorDesc(selector)}
1546
+ --stop stop job instead of running the job
1547
+ --production deploy to production, default is development
1548
+ --schedule override default schedule, support aliases: secondly, minutely, hourly, daily, weekly
1549
+ --verbose Output debug messages
1550
+ --dry-run print nomad job file but do not really execute it
1551
+ `, {
1552
+ importMeta: import.meta,
1553
+ description: false,
1554
+ version: false,
1555
+ flags: {
1556
+ ...getSelectorFlags(selector),
1557
+ schedule: {
1558
+ type: "string"
1559
+ },
1560
+ verbose: {
1561
+ type: "boolean",
1562
+ default: false
1563
+ },
1564
+ production: {
1565
+ aliases: ["prd"],
1566
+ type: "boolean",
1567
+ default: false
1568
+ },
1569
+ dryRun: {
1570
+ type: "boolean",
1571
+ default: false
1572
+ },
1573
+ stop: {
1574
+ type: "boolean",
1575
+ default: false
1576
+ }
1577
+ }
1578
+ });
1579
+ try {
1580
+ return deployModeless(cli.flags);
1581
+ } catch (err) {
1582
+ console.error(err);
1583
+ process.exit(1);
1584
+ }
1585
+ }
1586
+ return { deploy };
137
1587
  }
138
- function checkModeIndexerValidateParameter(validate) {
139
- const errors = [];
140
- if (validate) {
141
- if (!validate.func) {
142
- errors.push("must define validate.func");
1588
+ // src/api.ts
1589
+ import osModule from "os";
1590
+ import express from "express";
1591
+ import meow3 from "meow";
1592
+ async function logStartMiddleware(_, res, next) {
1593
+ const start = new Date;
1594
+ res.set("x-requested-at", start.toISOString());
1595
+ next();
1596
+ }
1597
+ async function contextMiddleware(_, res, next) {
1598
+ res.set("x-instance-id", osModule.hostname());
1599
+ next();
1600
+ }
1601
+ async function logEndMiddleware(req, res, next) {
1602
+ const requestedAt = res.get("x-requested-at");
1603
+ if (!requestedAt) {
1604
+ inline.log("missing x-requested-at header");
1605
+ next();
1606
+ return;
1607
+ }
1608
+ const start = new Date(requestedAt).getTime();
1609
+ const end = new Date().getTime();
1610
+ const logInfo = {
1611
+ start,
1612
+ end,
1613
+ elapsed: `${end - start}ms`,
1614
+ endpoint: req.path,
1615
+ host: req.hostname,
1616
+ status: res.statusCode
1617
+ };
1618
+ if (res.statusMessage) {
1619
+ logInfo.errorMessage = res.statusMessage;
1620
+ }
1621
+ inline.log(JSON.stringify(logInfo));
1622
+ next();
1623
+ }
1624
+ var apiKeyMiddleware = (key) => {
1625
+ async function requireAPIKey(req, res, next) {
1626
+ try {
1627
+ const apiKey = req.get("x-api-key") || req.query["api-key"];
1628
+ if (!apiKey) {
1629
+ inline.log("request without api key");
1630
+ res.status(400).send("require x-api-key header");
1631
+ return;
1632
+ }
1633
+ if (typeof key === "string") {
1634
+ if (apiKey !== key) {
1635
+ inline.log("request has an invalid api key");
1636
+ res.status(400).send("invalid api key");
1637
+ return;
143
1638
  }
144
- if (!validate.cpu) {
145
- errors.push("must define validate.cpu");
1639
+ inline.log(`requested by valid key ${key.slice(0, 6)}`);
1640
+ } else {
1641
+ const name = key[apiKey];
1642
+ if (!name) {
1643
+ inline.log("request has an invalid api key");
1644
+ res.status(400).send("invalid api key");
1645
+ return;
146
1646
  }
147
- if (!validate.mem) {
148
- errors.push("must define validate.mem");
1647
+ inline.log(`requested by authorized user ${name}`);
1648
+ }
1649
+ next();
1650
+ } catch (err) {
1651
+ inline.log("check api key error", err);
1652
+ res.status(500).send("internal error");
1653
+ }
1654
+ }
1655
+ return requireAPIKey;
1656
+ };
1657
+ async function startApiApp({
1658
+ binaryName,
1659
+ name,
1660
+ selector = {},
1661
+ routes,
1662
+ serve,
1663
+ beforeListen
1664
+ }) {
1665
+ const app = express();
1666
+ app.use(express.json({ limit: "20mb" }));
1667
+ const cli = meow3(`
1668
+ Usage
1669
+ $ ${binaryName} <options>
1670
+
1671
+ Options
1672
+ ${getSelectorDesc(selector)}
1673
+ --verbose Output debug messages
1674
+ `, {
1675
+ importMeta: import.meta,
1676
+ description: false,
1677
+ version: false,
1678
+ flags: {
1679
+ ...getSelectorFlags(selector),
1680
+ verbose: {
1681
+ type: "boolean",
1682
+ default: false
1683
+ }
1684
+ }
1685
+ });
1686
+ const { verbose, ...selectorFlags } = cli.flags;
1687
+ for (const route of routes) {
1688
+ const method = route.method ? route.method.toLowerCase() : "get";
1689
+ const middlewares = route.middlewares || [];
1690
+ if (route.protected) {
1691
+ if (!serve.apiKey) {
1692
+ throw new Error("serve.apiKey is required for protected route");
1693
+ }
1694
+ middlewares.unshift(apiKeyMiddleware(serve.apiKey));
1695
+ }
1696
+ if (app[method]) {
1697
+ if (verbose) {
1698
+ inline.log(`registering ${method} ${route.path}`);
1699
+ }
1700
+ app[method](route.path, contextMiddleware, logStartMiddleware, ...middlewares, async (req, res, next) => {
1701
+ try {
1702
+ await route.handler({ req, res, ...selectorFlags });
1703
+ } catch (routeErr) {
1704
+ if (routeErr instanceof Error) {
1705
+ inline.log("caught route err", routeErr, routeErr.stack);
1706
+ res.status(500).send(`internal server error: ${routeErr.message}`);
1707
+ } else {
1708
+ inline.log("caught route err", routeErr);
1709
+ res.status(500).send("internal server error");
1710
+ }
149
1711
  }
1712
+ next();
1713
+ }, logEndMiddleware);
150
1714
  }
151
- return errors;
152
- }
153
- function modeIndexer({ name, selector, state, build, validate, env = {}, region = "skynet-dc1", }) {
154
- return createApp({
155
- parameterErrors: [
156
- ...checkModeIndexerBuildParameter(build),
157
- ...checkModeIndexerValidateParameter(validate),
158
- ...checkStateParameter(state),
159
- ...checkEnvParameter(env),
160
- ],
161
- env,
162
- onRun: () => {
163
- const { run } = createModeIndexerApp({
164
- binaryName: `${getBinaryName()} run`,
165
- name,
166
- selector,
167
- build: build.func,
168
- maxRetry: build.maxRetry,
169
- buildBatchSize: build.batchSize,
170
- buildConcurrency: build.concurrency,
171
- validate: validate && validate.func,
172
- validateBatchSize: validate && validate.batchSize,
173
- validateConcurrency: validate && validate.concurrency,
174
- state,
175
- });
176
- process.title = name;
177
- return run();
178
- },
179
- onDeploy: () => {
180
- const bin = detectBin();
181
- const needDoppler = Object.values(env).some((v) => v === SENSITIVE_VALUE);
182
- const { deploy } = createModeDeploy({
183
- binaryName: `${getBinaryName()} deploy`,
184
- name,
185
- workingDirectory: detectWorkingDirectory(),
186
- bin: needDoppler ? `doppler run -- ${bin} run` : `${bin} run`,
187
- selector,
188
- region,
189
- env,
190
- deltaSchedule: build.schedule,
191
- deltaKillTimeout: build.killTimeout,
192
- deltaCpu: build.cpu,
193
- deltaMem: build.mem,
194
- rebuildKillTimeout: build.killTimeout,
195
- rebuildCpu: build.cpu,
196
- rebuildMem: build.mem,
197
- validateSchedule: validate && validate.schedule,
198
- validateKillTimeout: validate && validate.killTimeout,
199
- validateCpu: validate && validate.cpu,
200
- validateMem: validate && validate.mem,
201
- });
202
- return deploy();
203
- },
1715
+ }
1716
+ if (!routes.some((r) => r.path === "/" && r.method?.toUpperCase() === "GET")) {
1717
+ app.get("/", (_, res) => {
1718
+ res.send("ok");
204
1719
  });
1720
+ }
1721
+ if (beforeListen) {
1722
+ await beforeListen({ app });
1723
+ }
1724
+ app.listen(serve.port, () => {
1725
+ if (isProduction()) {
1726
+ inline.log(`${name} listening at https://api.wf.corp.certik.com${serve.prefix}`);
1727
+ } else {
1728
+ inline.log(`${name} listening at http://localhost:${serve.port}`);
1729
+ }
1730
+ });
205
1731
  }
206
- function checkApiServeParameter(serve, routes) {
207
- const errors = [];
208
- if (!serve?.prefix) {
209
- errors.push("must define serve.prefix");
1732
+
1733
+ // src/app.ts
1734
+ import { EOL } from "os";
1735
+ function printAppHelp() {
1736
+ console.log(`
1737
+ Usage
1738
+
1739
+ $ ${getBinaryName()} run <options>
1740
+ $ ${getBinaryName()} deploy <options>
1741
+ $ ${getBinaryName()} delete <options>
1742
+ `);
1743
+ }
1744
+ function isDeleteCommand(command) {
1745
+ return ["delete", "stop", "remove"].includes(command);
1746
+ }
1747
+ function checkAndSetEnv(env) {
1748
+ const missingEnvs = [];
1749
+ for (const key of Object.keys(env)) {
1750
+ if (env[key]) {
1751
+ process.env[key] = env[key];
1752
+ } else if (!process.env[key]) {
1753
+ missingEnvs.push(key);
1754
+ }
1755
+ }
1756
+ if (missingEnvs.length > 0) {
1757
+ console.log(`The following environment value shouldn't be empty:${EOL}- ${missingEnvs.join(EOL + "- ")}`);
1758
+ process.exit(1);
1759
+ }
1760
+ }
1761
+ function createApp({
1762
+ parameterErrors,
1763
+ env,
1764
+ onRun,
1765
+ onDeploy
1766
+ }) {
1767
+ if (parameterErrors.length > 0) {
1768
+ console.log(`Parameter Validation Failed:${EOL}- ${parameterErrors.join(EOL + "- ")}`);
1769
+ process.exit(1);
1770
+ }
1771
+ return async () => {
1772
+ const subCommand = process.argv[2];
1773
+ process.argv = [process.argv[0], process.argv[1], ...process.argv.slice(3)];
1774
+ if (subCommand === "run") {
1775
+ checkAndSetEnv(env);
1776
+ await onRun();
1777
+ } else if (subCommand === "deploy" || isDeleteCommand(subCommand)) {
1778
+ if (isDeleteCommand(subCommand)) {
1779
+ process.argv.push("--stop");
1780
+ }
1781
+ await onDeploy();
1782
+ } else {
1783
+ printAppHelp();
210
1784
  }
211
- else if (!serve.prefix.startsWith("/")) {
212
- errors.push("server.prefix must start with /, e.g. /my-api");
1785
+ };
1786
+ }
1787
+ function checkEnvParameter(env) {
1788
+ const errors = [];
1789
+ const envKeys = Object.keys(env);
1790
+ envKeys.forEach((k) => {
1791
+ if (!env[k] && env[k] !== SENSITIVE_VALUE) {
1792
+ errors.push(`must have valid non-empty value for env.${k}`);
213
1793
  }
214
- if (!serve?.port) {
215
- errors.push("must define serve.port");
1794
+ });
1795
+ return errors;
1796
+ }
1797
+ function checkIndexerBuildParameter(build) {
1798
+ const errors = [];
1799
+ if (!build?.func) {
1800
+ errors.push("must define build.func");
1801
+ }
1802
+ if (!build?.cpu) {
1803
+ errors.push("must define build.cpu");
1804
+ }
1805
+ if (!build?.mem) {
1806
+ errors.push("must define build.mem");
1807
+ }
1808
+ return errors;
1809
+ }
1810
+ function checkStateParameter(state) {
1811
+ const errors = [];
1812
+ if (!state?.type) {
1813
+ errors.push("must define state.type");
1814
+ }
1815
+ if (!state?.getMaxId) {
1816
+ errors.push("must define state.getMaxId");
1817
+ }
1818
+ return errors;
1819
+ }
1820
+ function indexer({
1821
+ name,
1822
+ selector,
1823
+ build,
1824
+ env = {},
1825
+ region = "skynet-dc1"
1826
+ }) {
1827
+ return createApp({
1828
+ parameterErrors: [...checkIndexerBuildParameter(build), ...checkEnvParameter(env)],
1829
+ env,
1830
+ onRun: () => {
1831
+ const { run } = createIndexerApp({
1832
+ binaryName: `${getBinaryName()} run`,
1833
+ selector,
1834
+ build: build.func,
1835
+ maxRetry: build.maxRetry
1836
+ });
1837
+ process.title = name;
1838
+ return run();
1839
+ },
1840
+ onDeploy: () => {
1841
+ const bin = detectBin();
1842
+ const needDoppler = Object.values(env).some((v) => v === SENSITIVE_VALUE);
1843
+ const { deploy } = createDeploy({
1844
+ binaryName: `${getBinaryName()} deploy`,
1845
+ name,
1846
+ workingDirectory: detectWorkingDirectory(),
1847
+ bin: needDoppler ? `doppler run -- ${bin} run` : `${bin} run`,
1848
+ selector,
1849
+ region,
1850
+ env,
1851
+ schedule: build.schedule,
1852
+ restart: build.restart,
1853
+ killTimeout: build.killTimeout,
1854
+ cpu: build.cpu,
1855
+ mem: build.mem
1856
+ });
1857
+ return deploy();
216
1858
  }
217
- if (!serve?.cpu) {
218
- errors.push("must define serve.cpu");
1859
+ });
1860
+ }
1861
+ function checkModeIndexerBuildParameter(build) {
1862
+ const errors = [];
1863
+ if (!build?.func) {
1864
+ errors.push("must define build.func");
1865
+ }
1866
+ if (!build?.cpu) {
1867
+ errors.push("must define build.cpu");
1868
+ }
1869
+ if (!build?.mem) {
1870
+ errors.push("must define build.mem");
1871
+ }
1872
+ return errors;
1873
+ }
1874
+ function checkModeIndexerValidateParameter(validate) {
1875
+ const errors = [];
1876
+ if (validate) {
1877
+ if (!validate.func) {
1878
+ errors.push("must define validate.func");
219
1879
  }
220
- if (!serve?.mem) {
221
- errors.push("must define serve.mem");
1880
+ if (!validate.cpu) {
1881
+ errors.push("must define validate.cpu");
222
1882
  }
223
- if (routes.some((r) => r.protected) && !serve.apiKey) {
224
- errors.push("must define serve.apiKey since some routes are protected");
1883
+ if (!validate.mem) {
1884
+ errors.push("must define validate.mem");
225
1885
  }
226
- return errors;
1886
+ }
1887
+ return errors;
1888
+ }
1889
+ function modeIndexer({
1890
+ name,
1891
+ selector,
1892
+ state,
1893
+ build,
1894
+ validate,
1895
+ env = {},
1896
+ region = "skynet-dc1"
1897
+ }) {
1898
+ return createApp({
1899
+ parameterErrors: [
1900
+ ...checkModeIndexerBuildParameter(build),
1901
+ ...checkModeIndexerValidateParameter(validate),
1902
+ ...checkStateParameter(state),
1903
+ ...checkEnvParameter(env)
1904
+ ],
1905
+ env,
1906
+ onRun: () => {
1907
+ const { run } = createModeIndexerApp({
1908
+ binaryName: `${getBinaryName()} run`,
1909
+ name,
1910
+ selector,
1911
+ build: build.func,
1912
+ maxRetry: build.maxRetry,
1913
+ buildBatchSize: build.batchSize,
1914
+ buildConcurrency: build.concurrency,
1915
+ validate: validate && validate.func,
1916
+ validateBatchSize: validate && validate.batchSize,
1917
+ validateConcurrency: validate && validate.concurrency,
1918
+ state
1919
+ });
1920
+ process.title = name;
1921
+ return run();
1922
+ },
1923
+ onDeploy: () => {
1924
+ const bin = detectBin();
1925
+ const needDoppler = Object.values(env).some((v) => v === SENSITIVE_VALUE);
1926
+ const { deploy } = createModeDeploy({
1927
+ binaryName: `${getBinaryName()} deploy`,
1928
+ name,
1929
+ workingDirectory: detectWorkingDirectory(),
1930
+ bin: needDoppler ? `doppler run -- ${bin} run` : `${bin} run`,
1931
+ selector,
1932
+ region,
1933
+ env,
1934
+ deltaSchedule: build.schedule,
1935
+ deltaKillTimeout: build.killTimeout,
1936
+ deltaCpu: build.cpu,
1937
+ deltaMem: build.mem,
1938
+ rebuildKillTimeout: build.killTimeout,
1939
+ rebuildCpu: build.cpu,
1940
+ rebuildMem: build.mem,
1941
+ validateSchedule: validate && validate.schedule,
1942
+ validateKillTimeout: validate && validate.killTimeout,
1943
+ validateCpu: validate && validate.cpu,
1944
+ validateMem: validate && validate.mem
1945
+ });
1946
+ return deploy();
1947
+ }
1948
+ });
1949
+ }
1950
+ function checkApiServeParameter(serve, routes) {
1951
+ const errors = [];
1952
+ if (!serve?.prefix) {
1953
+ errors.push("must define serve.prefix");
1954
+ } else if (!serve.prefix.startsWith("/")) {
1955
+ errors.push("server.prefix must start with /, e.g. /my-api");
1956
+ }
1957
+ if (!serve?.port) {
1958
+ errors.push("must define serve.port");
1959
+ }
1960
+ if (!serve?.cpu) {
1961
+ errors.push("must define serve.cpu");
1962
+ }
1963
+ if (!serve?.mem) {
1964
+ errors.push("must define serve.mem");
1965
+ }
1966
+ if (routes.some((r) => r.protected) && !serve.apiKey) {
1967
+ errors.push("must define serve.apiKey since some routes are protected");
1968
+ }
1969
+ return errors;
227
1970
  }
228
1971
  function checkApiRoutesParameter(routes) {
229
- const errors = [];
230
- if (!Array.isArray(routes)) {
231
- errors.push("routes must be an array");
232
- }
233
- else {
234
- for (let i = 0; i < routes.length; i++) {
235
- const route = routes[i];
236
- if (!route.path) {
237
- errors.push(`routes[${i}] must define path`);
238
- }
239
- if (!route.handler) {
240
- errors.push(`routes[${i}] must define handler`);
241
- }
242
- if (route.middlewares && !Array.isArray(route.middlewares)) {
243
- errors.push(`routes[${i}].middlewares must be an array`);
244
- }
245
- }
1972
+ const errors = [];
1973
+ if (!Array.isArray(routes)) {
1974
+ errors.push("routes must be an array");
1975
+ } else {
1976
+ for (let i = 0;i < routes.length; i++) {
1977
+ const route = routes[i];
1978
+ if (!route.path) {
1979
+ errors.push(`routes[${i}] must define path`);
1980
+ }
1981
+ if (!route.handler) {
1982
+ errors.push(`routes[${i}] must define handler`);
1983
+ }
1984
+ if (route.middlewares && !Array.isArray(route.middlewares)) {
1985
+ errors.push(`routes[${i}].middlewares must be an array`);
1986
+ }
246
1987
  }
247
- return errors;
248
- }
249
- function api({ name, routes, serve, beforeListen, env = {}, region = "skynet-dc1", }) {
250
- // do not support selector for now
251
- const selector = {};
252
- return createApp({
253
- parameterErrors: [
254
- ...checkApiRoutesParameter(routes),
255
- ...checkApiServeParameter(serve, routes),
256
- ...checkEnvParameter(env),
257
- ],
1988
+ }
1989
+ return errors;
1990
+ }
1991
+ function api({
1992
+ name,
1993
+ routes,
1994
+ serve,
1995
+ beforeListen,
1996
+ env = {},
1997
+ region = "skynet-dc1"
1998
+ }) {
1999
+ const selector = {};
2000
+ return createApp({
2001
+ parameterErrors: [
2002
+ ...checkApiRoutesParameter(routes),
2003
+ ...checkApiServeParameter(serve, routes),
2004
+ ...checkEnvParameter(env)
2005
+ ],
2006
+ env,
2007
+ onRun: () => {
2008
+ process.title = name;
2009
+ return startApiApp({
2010
+ binaryName: `${getBinaryName()} run`,
2011
+ name,
2012
+ selector,
2013
+ routes,
2014
+ serve,
2015
+ beforeListen
2016
+ });
2017
+ },
2018
+ onDeploy: () => {
2019
+ const bin = detectBin();
2020
+ const needDoppler = Object.values(env).some((v) => v === SENSITIVE_VALUE);
2021
+ const { deploy } = createDeploy({
2022
+ binaryName: `${getBinaryName()} deploy`,
2023
+ name,
2024
+ workingDirectory: detectWorkingDirectory(),
2025
+ bin: needDoppler ? `doppler run -- ${bin} run` : `${bin} run`,
2026
+ selector,
2027
+ region,
258
2028
  env,
259
- onRun: () => {
260
- process.title = name;
261
- return startApiApp({
262
- binaryName: `${getBinaryName()} run`,
263
- name,
264
- selector,
265
- routes,
266
- serve,
267
- beforeListen,
268
- });
2029
+ type: "service",
2030
+ restart: {
2031
+ attempts: 3,
2032
+ delay: "15s",
2033
+ mode: "delay",
2034
+ interval: "2m"
269
2035
  },
270
- onDeploy: () => {
271
- const bin = detectBin();
272
- const needDoppler = Object.values(env).some((v) => v === SENSITIVE_VALUE);
273
- const { deploy } = createDeploy({
274
- binaryName: `${getBinaryName()} deploy`,
275
- name,
276
- workingDirectory: detectWorkingDirectory(),
277
- bin: needDoppler ? `doppler run -- ${bin} run` : `${bin} run`,
278
- selector,
279
- region,
280
- env,
281
- type: "service",
282
- restart: {
283
- attempts: 3,
284
- delay: "15s",
285
- mode: "delay",
286
- interval: "2m",
287
- },
288
- count: serve.instances,
289
- killTimeout: serve.killTimeout,
290
- cpu: serve.cpu,
291
- mem: serve.mem,
292
- service: {
293
- prefix: serve.prefix,
294
- port: serve.port,
295
- },
296
- });
297
- return deploy();
298
- },
299
- });
300
- }
301
- const SENSITIVE_VALUE = null;
302
- const every = (n = 1) => {
303
- if (n === 1) {
304
- return {
305
- second: "*/1 * * * * * *",
306
- seconds: "*/1 * * * * * *",
307
- minute: "0 * * * * * *",
308
- minutes: "0 * * * * * *",
309
- hour: "0 0 * * * * *",
310
- hours: "0 0 * * * * *",
311
- day: "0 0 0 * * * *",
312
- days: "0 0 0 * * * *",
313
- week: "0 0 0 * * 0 *",
314
- weeks: "0 0 0 * * 0 *",
315
- };
2036
+ count: serve.instances,
2037
+ killTimeout: serve.killTimeout,
2038
+ cpu: serve.cpu,
2039
+ mem: serve.mem,
2040
+ service: {
2041
+ prefix: serve.prefix,
2042
+ port: serve.port
2043
+ }
2044
+ });
2045
+ return deploy();
316
2046
  }
2047
+ });
2048
+ }
2049
+ var SENSITIVE_VALUE = null;
2050
+ var every = (n = 1) => {
2051
+ if (n === 1) {
317
2052
  return {
318
- second: `*/${n} * * * * * *`,
319
- seconds: `*/${n} * * * * * *`,
320
- minute: `0 */${n} * * * * *`,
321
- minutes: `0 */${n} * * * * *`,
322
- hour: `0 0 */${n} * * * *`,
323
- hours: `0 0 */${n} * * * *`,
324
- day: `0 0 0 */${n} * * *`,
325
- days: `0 0 0 */${n} * * *`,
2053
+ second: "*/1 * * * * * *",
2054
+ seconds: "*/1 * * * * * *",
2055
+ minute: "0 * * * * * *",
2056
+ minutes: "0 * * * * * *",
2057
+ hour: "0 0 * * * * *",
2058
+ hours: "0 0 * * * * *",
2059
+ day: "0 0 0 * * * *",
2060
+ days: "0 0 0 * * * *",
2061
+ week: "0 0 0 * * 0 *",
2062
+ weeks: "0 0 0 * * 0 *"
326
2063
  };
2064
+ }
2065
+ return {
2066
+ second: `*/${n} * * * * * *`,
2067
+ seconds: `*/${n} * * * * * *`,
2068
+ minute: `0 */${n} * * * * *`,
2069
+ minutes: `0 */${n} * * * * *`,
2070
+ hour: `0 0 */${n} * * * *`,
2071
+ hours: `0 0 */${n} * * * *`,
2072
+ day: `0 0 0 */${n} * * *`,
2073
+ days: `0 0 0 */${n} * * *`
2074
+ };
2075
+ };
2076
+ export {
2077
+ modeIndexer,
2078
+ indexer,
2079
+ every,
2080
+ api,
2081
+ SENSITIVE_VALUE
327
2082
  };
328
- export { indexer, modeIndexer, api, every, SENSITIVE_VALUE };