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