@certik/skynet 0.25.0 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.js ADDED
@@ -0,0 +1,2077 @@
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
+ }
128
+
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
+ });
137
+ }
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;
163
+ }
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;
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)}`);
223
+ }
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);
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;
288
+ }
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`);
770
+ process.exit(1);
771
+ }
772
+ await runRange(selectorFlags, from, from, verbose);
773
+ } else if (mode === "range") {
774
+ if (!from || !to) {
775
+ inline.log(`[MODE INDEXER] must provide --from and --to option for range mode`);
776
+ process.exit(1);
777
+ }
778
+ await runRange(selectorFlags, from, to, verbose);
779
+ } else {
780
+ const stateItem = await getRecordByKey(STATE_TABLE_NAME, {
781
+ name: `${name}RebuildState(${toSelectorString(selectorFlags)})`
782
+ });
783
+ if (!stateItem || stateItem.value !== "succeed") {
784
+ inline.log("[MODE INDEXER] skip because rebuild hasn't done yet");
785
+ process.exit(0);
786
+ }
787
+ const latestId = await getIndexerLatestId(name, selectorFlags);
788
+ if (!latestId) {
789
+ throw new Error(`[MODE INDEXER] cannot find the latest ${finalState.type}`);
790
+ }
791
+ const deltaFrom = increaseId(finalState.type, latestId, 1);
792
+ const deltaTo = await state.getMaxId(selectorFlags);
793
+ await runDelta(selectorFlags, deltaFrom, deltaTo, verbose);
794
+ }
795
+ }
796
+ async function runRange(selectorFlags, from, to, verbose) {
797
+ const startTime = Date.now();
798
+ inline.log(`[MODE INDEXER] building range, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}, batchSize=${buildBatchSize}, concurrency=${buildConcurrency}`);
799
+ const failedIds = await execBuild(selectorFlags, from, to, verbose, false);
800
+ if (failedIds.length > 0) {
801
+ inline.log(`[MODE INDEXER] built with some failed ${finalState.type}`, failedIds);
802
+ process.exit(1);
803
+ } else {
804
+ inline.log(`[MODE INDEXER] built successfully in ${Date.now() - startTime}ms`);
805
+ process.exit(0);
806
+ }
807
+ }
808
+ async function runValidate(selectorFlags, from, to, shouldSaveState, verbose) {
809
+ if (!validate) {
810
+ inline.log(`[MODE INDEXER] the indexer doesn't support validate mode, validate function not implemented`);
811
+ process.exit(1);
812
+ }
813
+ const startTime = Date.now();
814
+ inline.log(`[MODE INDEXER] validating, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}, batchSize=${validateBatchSize}, concurrency=${validateConcurrency}`);
815
+ const windows = range2(from, to, validateBatchSize * validateConcurrency);
816
+ inline.log(`[MODE INDEXER] from=${from}, to=${to}, batchSize=${validateBatchSize}, concurrency=${validateConcurrency}`);
817
+ for (const [windowStart, windowEnd] of windows) {
818
+ inline.log(`[MODE INDEXER] validating window ${windowStart}~${windowEnd}, concurrency=${validateConcurrency}`);
819
+ const batches = range2(windowStart, windowEnd, validateBatchSize);
820
+ await Promise.all(batches.map(async ([batchStart, batchEnd]) => {
821
+ const result = await exponentialRetry(async () => {
822
+ try {
823
+ await validate({
824
+ ...selectorFlags,
825
+ from: batchStart,
826
+ to: batchEnd,
827
+ verbose
828
+ });
829
+ return true;
830
+ } catch (err) {
831
+ inline.error(`got error in validation`, err);
832
+ return false;
833
+ }
834
+ }, {
835
+ maxRetry,
836
+ test: (r) => r,
837
+ verbose
838
+ });
839
+ if (!result) {
840
+ throw new Error(`Terminate validation due to critical errors, from=${batchStart}, to=${batchEnd}`);
841
+ }
842
+ }));
843
+ if (shouldSaveState) {
844
+ await createRecord(STATE_TABLE_NAME, {
845
+ name: `${name}Validate(${toSelectorString(selectorFlags)})`,
846
+ value: to
847
+ });
848
+ if (verbose) {
849
+ inline.log(`[MODE INDEXER] updated processed ${finalState.type} to ${windowEnd}`);
850
+ }
851
+ }
852
+ }
853
+ inline.log(`[MODE INDEXER] validated ${offsetRange(from, to)} ${finalState.type} successfully in ${Date.now() - startTime}ms`);
854
+ }
855
+ async function execBuild(selectorFlags, from, to, verbose, shouldSaveState = false) {
856
+ let failedIds = [];
857
+ const windows = range2(from, to, buildBatchSize * buildConcurrency);
858
+ for (const [windowStart, windowEnd] of windows) {
859
+ inline.log(`[MODE INDEXER] building window ${windowStart}~${windowEnd}, concurrency = ${buildConcurrency}`);
860
+ const batches = range2(windowStart, windowEnd, buildBatchSize);
861
+ const batchResults = await Promise.all(batches.map(async ([batchStart, batchEnd]) => await exponentialRetry(async () => {
862
+ try {
863
+ const ids = await build({
864
+ ...selectorFlags,
865
+ from: batchStart,
866
+ to: batchEnd,
867
+ verbose
868
+ });
869
+ if (ids && ids.length > 0) {
870
+ return ids;
871
+ } else {
872
+ return false;
873
+ }
874
+ } catch (err) {
875
+ inline.error(`[MODE INDEXER] got error in build`, err);
876
+ return fillRange2(batchStart, batchEnd);
877
+ }
878
+ }, {
879
+ maxRetry,
880
+ test: (r) => !r,
881
+ verbose
882
+ })));
883
+ if (shouldSaveState) {
884
+ await createRecord(STATE_TABLE_NAME, {
885
+ name: `${name}Since(${toSelectorString(selectorFlags)})`,
886
+ value: windowEnd
887
+ });
888
+ if (verbose) {
889
+ inline.log(`[MODE INDEXER] updated processed ${finalState.type} to ${windowEnd}`);
890
+ }
891
+ }
892
+ batchResults.forEach((ids) => {
893
+ if (ids) {
894
+ failedIds = failedIds.concat(ids);
895
+ }
896
+ });
897
+ }
898
+ failedIds.sort();
899
+ return failedIds;
900
+ }
901
+ async function runRebuild(selectorFlags, from, to, verbose) {
902
+ const startTime = Date.now();
903
+ inline.log(`[MODE INDEXER] rebuilding, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}, batchSize=${buildBatchSize}, concurrency=${buildConcurrency}`);
904
+ await createRecord(STATE_TABLE_NAME, {
905
+ name: `${name}RebuildState(${toSelectorString(selectorFlags)})`,
906
+ value: "running"
907
+ });
908
+ const failedIds = await execBuild(selectorFlags, from, to, verbose, true);
909
+ await createRecord(STATE_TABLE_NAME, {
910
+ name: `${name}Since(${toSelectorString(selectorFlags)})`,
911
+ value: to
912
+ });
913
+ await createRecord(STATE_TABLE_NAME, {
914
+ name: `${name}RebuildState(${toSelectorString(selectorFlags)})`,
915
+ value: "succeed"
916
+ });
917
+ if (failedIds.length > 0) {
918
+ inline.log(`[MODE INDEXER] built ${offsetRange(from, to)} ${finalState.type}(s) with some failed ${finalState.type}`, failedIds);
919
+ process.exit(1);
920
+ } else {
921
+ inline.log(`[MODE INDEXER] built ${offsetRange(from, to)} ${finalState.type}(s) successfully in ${Date.now() - startTime}ms`);
922
+ process.exit(0);
923
+ }
924
+ }
925
+ async function runDelta(selectorFlags, from, to, verbose) {
926
+ const startTime = Date.now();
927
+ if (to < from) {
928
+ inline.log(`[MODE INDEXER] skip delta, there're no more items need to be processed, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}`);
929
+ return;
930
+ }
931
+ inline.log(`[MODE INDEXER] starting delta, from=${from}, to=${to}, ${toSelectorString(selectorFlags, ", ")}, batchSize=${buildBatchSize}, concurrency=${buildConcurrency}`);
932
+ try {
933
+ const failedIds = await execBuild(selectorFlags, from, to, verbose, true);
934
+ if (failedIds.length > 0) {
935
+ inline.log("[MODE INDEXER] built with some failed txs", failedIds);
936
+ await createRecord(STATE_TABLE_NAME, {
937
+ name: `${name}DeltaState(${toSelectorString(selectorFlags)})`,
938
+ value: "failed"
939
+ });
940
+ await createRecord(STATE_TABLE_NAME, {
941
+ name: `${name}Since(${toSelectorString(selectorFlags)})`,
942
+ value: to < failedIds[0] ? to : failedIds[0]
943
+ });
944
+ process.exit(1);
945
+ } else {
946
+ await createRecord(STATE_TABLE_NAME, {
947
+ name: `${name}DeltaState(${toSelectorString(selectorFlags)})`,
948
+ value: "succeed"
949
+ });
950
+ await createRecord(STATE_TABLE_NAME, {
951
+ name: `${name}Since(${toSelectorString(selectorFlags)})`,
952
+ value: to
953
+ });
954
+ inline.log(`[MODE INDEXER] built successfully in ${Date.now() - startTime}ms`);
955
+ process.exit(0);
956
+ }
957
+ } catch (err) {
958
+ inline.error("[MODE INDEXER] delta build failed", from, to, err);
959
+ process.exit(1);
960
+ }
961
+ }
962
+ async function runReset(selectorFlags) {
963
+ const startTime = Date.now();
964
+ inline.log(`[MODE INDEXER] starting reset, ${toSelectorString(selectorFlags, ", ")}`);
965
+ inline.log("[MODE INDEXER] reset state", STATE_TABLE_NAME);
966
+ await createRecord(STATE_TABLE_NAME, {
967
+ name: `${name}Since(${toSelectorString(selectorFlags)})`,
968
+ value: 0
969
+ });
970
+ await createRecord(STATE_TABLE_NAME, {
971
+ name: `${name}Validate(${toSelectorString(selectorFlags)})`,
972
+ value: 0
973
+ });
974
+ await createRecord(STATE_TABLE_NAME, {
975
+ name: `${name}RebuildState(${toSelectorString(selectorFlags)})`,
976
+ value: "init"
977
+ });
978
+ inline.log(`[MODE INDEXER] reset successfully in ${Date.now() - startTime}ms`);
979
+ }
980
+ async function run() {
981
+ if (!binaryName) {
982
+ binaryName = getBinaryName();
983
+ }
984
+ const cli = meow(`
985
+ Usage
986
+
987
+ $ ${binaryName} <options>
988
+
989
+ Options
990
+ ${selector ? getSelectorDesc(selector) : ""}
991
+ --mode could be delta/rebuild/resume-rebuild/validate/one/range/reset
992
+ --from min ${finalState.type} to build
993
+ --to max ${finalState.type} to build
994
+ --status print status of indexer and exit
995
+ --verbose Output debug messages
996
+ `, {
997
+ importMeta: import.meta,
998
+ description: false,
999
+ flags: {
1000
+ ...getSelectorFlags(selector),
1001
+ mode: {
1002
+ type: "string",
1003
+ default: "delta"
1004
+ },
1005
+ from: {
1006
+ aliases: ["since"],
1007
+ type: "string"
1008
+ },
1009
+ to: {
1010
+ aliases: ["until"],
1011
+ type: "string"
1012
+ },
1013
+ status: {
1014
+ type: "boolean",
1015
+ default: false
1016
+ },
1017
+ verbose: {
1018
+ type: "boolean",
1019
+ default: false
1020
+ }
1021
+ }
1022
+ });
1023
+ try {
1024
+ return runMode(cli.flags);
1025
+ } catch (err) {
1026
+ inline.error(err);
1027
+ process.exit(1);
1028
+ }
1029
+ }
1030
+ return { run };
1031
+ }
1032
+ function createIndexerApp({
1033
+ binaryName,
1034
+ selector = {},
1035
+ build,
1036
+ maxRetry = 2
1037
+ }) {
1038
+ async function run() {
1039
+ if (!binaryName) {
1040
+ binaryName = getBinaryName();
1041
+ }
1042
+ const cli = meow(`
1043
+ Usage
1044
+ $ ${binaryName} <options>
1045
+
1046
+ Options
1047
+ ${selector ? getSelectorDesc(selector) : ""}
1048
+ --verbose Output debug messages
1049
+ `, {
1050
+ importMeta: import.meta,
1051
+ description: false,
1052
+ flags: {
1053
+ ...getSelectorFlags(selector),
1054
+ verbose: {
1055
+ type: "boolean",
1056
+ default: false
1057
+ }
1058
+ }
1059
+ });
1060
+ async function runBuild(flags) {
1061
+ const { verbose: untypedVerbose, ...untypedSelectorFlags } = flags;
1062
+ const verbose = untypedVerbose;
1063
+ const selectorFlags = untypedSelectorFlags;
1064
+ const startTime = Date.now();
1065
+ if (Object.keys(selectorFlags).length > 0) {
1066
+ inline.log(`[INDEXER] starting build, ${toSelectorString(selectorFlags, ", ")}`);
1067
+ } else {
1068
+ inline.log(`[INDEXER] starting build`);
1069
+ }
1070
+ const result = await exponentialRetry(async () => {
1071
+ try {
1072
+ await build(flags);
1073
+ return true;
1074
+ } catch (err) {
1075
+ inline.log(`[INDEXER] got error in build`, err);
1076
+ return false;
1077
+ }
1078
+ }, {
1079
+ maxRetry,
1080
+ test: (r) => r,
1081
+ verbose
1082
+ });
1083
+ if (!result) {
1084
+ throw new Error(`[INDEXER] Build failed due to critical errors`);
1085
+ }
1086
+ inline.log(`[INDEXER] build successfully in ${Date.now() - startTime}ms`);
1087
+ }
1088
+ return runBuild(cli.flags).catch((err) => {
1089
+ inline.error(err);
1090
+ process.exit(1);
1091
+ });
1092
+ }
1093
+ return { run };
1094
+ }
1095
+ // src/deploy.ts
1096
+ import fs2 from "fs/promises";
1097
+ import fso from "fs";
1098
+ import { execa } from "execa";
1099
+ import meow2 from "meow";
1100
+ import chalk from "chalk";
1101
+ import which from "which";
1102
+ var INTERVAL_ALIASES = {
1103
+ secondly: "*/1 * * * * * *",
1104
+ "@secondly": "*/1 * * * * * *",
1105
+ minutely: "0 * * * * * *",
1106
+ "@minutely": "0 * * * * * *",
1107
+ hourly: "0 0 * * * * *",
1108
+ "@hourly": "0 0 * * * * *",
1109
+ daily: "0 0 0 * * * *",
1110
+ "@daily": "0 0 0 * * * *",
1111
+ weekly: "0 0 0 * * 0 *",
1112
+ "@weekly": "0 0 0 * * 0 *"
1113
+ };
1114
+ var genConfig = ({
1115
+ jobName,
1116
+ workingDirectory,
1117
+ cmd,
1118
+ cron,
1119
+ count,
1120
+ restart,
1121
+ killTimeout,
1122
+ cpu,
1123
+ mem,
1124
+ service,
1125
+ additionalEnv = {},
1126
+ type = "batch",
1127
+ region = "skynet-dc1",
1128
+ isProduction: isProduction2
1129
+ }) => `job "${jobName}" {
1130
+ datacenters = ["${region}"]
1131
+
1132
+ type = "${type}"
1133
+
1134
+ ${cron ? `# Triggers periodically
1135
+ periodic {
1136
+ crons = ["${cron}"]
1137
+ prohibit_overlap = true
1138
+ }` : ""}
1139
+
1140
+ constraint {
1141
+ attribute = "\${meta.has_nodejs}"
1142
+ value = "true"
1143
+ }
1144
+
1145
+ constraint {
1146
+ attribute = "\${meta.has_skynet}"
1147
+ value = "true"
1148
+ }
1149
+
1150
+ group "default" {
1151
+ ${count && count > 1 ? `count = ${count}` : ""}
1152
+ ${count && count > 1 ? `# Rolling Update
1153
+ update {
1154
+ max_parallel = 1
1155
+ min_healthy_time = "10s"
1156
+ }` : ""}
1157
+
1158
+ reschedule {
1159
+ attempts = 0
1160
+ unlimited = false
1161
+ }
1162
+
1163
+ ${service ? `# Setup Service Network
1164
+ network {
1165
+ port "http" {
1166
+ static = ${service.port}
1167
+ }
1168
+ }` : ""}
1169
+
1170
+ task "main" {
1171
+ driver = "raw_exec"
1172
+
1173
+ config {
1174
+ command = "sh"
1175
+ args = [
1176
+ "-c",
1177
+ "cd \${meta.skynet_code_path}/${workingDirectory} && if [ -e bun.lockb ]; then bun install --silent; else yarn install --silent; fi && exec ${cmd}"
1178
+ ]
1179
+ }
1180
+
1181
+ ${service ? `# Setup API Routes
1182
+ service {
1183
+ name = "${jobName}"
1184
+ port = "http"
1185
+
1186
+ tags = [
1187
+ "urlprefix-${service.prefix} strip=${service.prefix}",
1188
+ ]
1189
+
1190
+ check {
1191
+ type = "http"
1192
+ path = "/"
1193
+ interval = "10s"
1194
+ timeout = "2s"
1195
+ }
1196
+ }
1197
+ ` : ""}
1198
+
1199
+ # doppler integration support
1200
+ # it is always there but a project can decide to not use it
1201
+ template {
1202
+ change_mode = "restart"
1203
+ destination = "secrets/context.env"
1204
+ env = true
1205
+ data = "DOPPLER_TOKEN={{key \\"infra-nomad/doppler-token\\"}}"
1206
+ }
1207
+
1208
+ # always update SKYNET_DEPLOYED_AT so that new deployment always triggers
1209
+ env {
1210
+ SKYNET_DEPLOYED_AT="${new Date().toISOString()}"
1211
+ HOME="/root"
1212
+ DOPPLER_PROJECT="${workingDirectory}"
1213
+ DOPPLER_CONFIG="${isProduction2 ? "prd" : "dev"}"
1214
+ SKYNET_ENVIRONMENT="${isProduction2 ? "prd" : "dev"}"
1215
+ ${Object.entries(additionalEnv).filter((kv) => !!kv[1]).map(([key, value]) => `${key}="${value}"`).join(`
1216
+ `)}
1217
+ }
1218
+
1219
+ kill_timeout = "${killTimeout || "60s"}"
1220
+
1221
+ # Specify the maximum resources required to run the task,
1222
+ # include CPU and memory.
1223
+ resources {
1224
+ cpu = ${cpu} # MHz
1225
+ memory = ${mem} # MB
1226
+ }
1227
+
1228
+ # Setting the server task as the leader of the task group allows Nomad to
1229
+ # signal the log shipper task to gracefully shutdown when the server exits.
1230
+ leader = true
1231
+
1232
+ ${restart ? `
1233
+ # Restart the job if it fails
1234
+ restart {
1235
+ attempts = ${restart.attempts ?? 2}
1236
+ mode = "${restart.mode ?? "fail"}"
1237
+ interval = "${restart.interval ?? "30m"}"
1238
+ delay = "${restart.delay ?? "15s"}"
1239
+ }
1240
+ ` : `
1241
+ # do not retry from the periodical job will reschedule anyway
1242
+ restart {
1243
+ attempts = 0
1244
+ mode = "fail"
1245
+ }`}
1246
+ }
1247
+ }
1248
+ }`;
1249
+ async function prepareNomad(isProduction2) {
1250
+ if (isProduction2) {
1251
+ console.log("Deploy to Production");
1252
+ } else {
1253
+ const skynetDir = detectSkynetDirectory();
1254
+ if (!fso.existsSync("/tmp/skynet")) {
1255
+ await execa("ln", ["-s", skynetDir, "/tmp/skynet"]);
1256
+ }
1257
+ console.log("Deploy locally, please start nomad server in a separate terminal");
1258
+ console.log(`You can start nomad server by running ${chalk.inverse(`${skynetDir}/infra-nomad/dev/start.sh`)}`);
1259
+ console.log(`Then you can visit ${chalk.underline("http://localhost:4646/ui/jobs")} to check submitted dev jobs.
1260
+ `);
1261
+ }
1262
+ }
1263
+ function getNomadAddr(isProduction2) {
1264
+ return isProduction2 ? getEnvOrThrow("NOMAD_ADDR") : "http://127.0.0.1:4646";
1265
+ }
1266
+ async function getNomadPath() {
1267
+ try {
1268
+ return await which("nomad");
1269
+ } catch (missingNomad) {
1270
+ console.log(`Deploy requires ${chalk.bold("nomad")} binary, please follow ${chalk.underline("https://learn.hashicorp.com/tutorials/nomad/get-started-install")} for installation`, missingNomad);
1271
+ throw new Error("missing nomad binary");
1272
+ }
1273
+ }
1274
+ async function runNomadJob(nomadPath, nomadAddr, jobName, nomadJobDefinition, isStop, isDryRun) {
1275
+ try {
1276
+ if (isStop) {
1277
+ const nomad = execa(nomadPath, ["job", "stop", jobName], {
1278
+ env: {
1279
+ NOMAD_ADDR: nomadAddr
1280
+ }
1281
+ });
1282
+ nomad.stdout.pipe(process.stdout);
1283
+ await nomad;
1284
+ console.log(chalk.green(`Stopped nomad job ${jobName} in ${nomadAddr}`));
1285
+ } else if (isDryRun) {
1286
+ console.log("Definition for", jobName);
1287
+ console.log("========================================");
1288
+ console.log(nomadJobDefinition);
1289
+ } else {
1290
+ const jobFileName = `/tmp/job-${jobName}`;
1291
+ await fs2.writeFile(jobFileName, nomadJobDefinition);
1292
+ const nomad = execa(nomadPath, ["job", "run", jobFileName], {
1293
+ env: {
1294
+ NOMAD_ADDR: nomadAddr
1295
+ }
1296
+ });
1297
+ nomad.stdout.pipe(process.stdout);
1298
+ await nomad;
1299
+ console.log(chalk.green(`Deployed nomad job ${jobName} to ${nomadAddr}`));
1300
+ }
1301
+ } catch (nomadExecErr) {
1302
+ if (nomadExecErr instanceof Error) {
1303
+ console.log("Nomad Execution Error:");
1304
+ console.log(nomadExecErr.message);
1305
+ console.log("");
1306
+ }
1307
+ console.log(`Failed to run ${chalk.bold("nomad")} commands, please ensure nomad server is accessible at ${chalk.bold(nomadAddr)}`);
1308
+ throw new Error("nomad execution error");
1309
+ }
1310
+ }
1311
+ function createModeDeploy({
1312
+ binaryName,
1313
+ name,
1314
+ workingDirectory,
1315
+ bin = "bin/indexer",
1316
+ selector = {},
1317
+ env = {},
1318
+ region = "skynet-dc1",
1319
+ deltaSchedule,
1320
+ validateSchedule,
1321
+ deltaKillTimeout,
1322
+ deltaCpu,
1323
+ deltaMem,
1324
+ rebuildKillTimeout,
1325
+ rebuildCpu,
1326
+ rebuildMem,
1327
+ validateKillTimeout,
1328
+ validateCpu,
1329
+ validateMem
1330
+ }) {
1331
+ async function deployMode({
1332
+ mode,
1333
+ from,
1334
+ to,
1335
+ stop,
1336
+ production,
1337
+ dryRun,
1338
+ verbose,
1339
+ schedule: cmdSchedule,
1340
+ ...selectorFlags
1341
+ }) {
1342
+ if (mode === "delta") {
1343
+ from = 0;
1344
+ to = 0;
1345
+ }
1346
+ const isPeriodic = from === 0 && to === 0 && ["delta", "validate"].includes(mode);
1347
+ const jobName = getJobName(name, selectorFlags, mode);
1348
+ const selectorCmdPart = Object.entries(selectorFlags).sort().map(([name2, value]) => `--${name2} ${value}`).join(" ");
1349
+ let args = `--mode ${mode} ${selectorCmdPart}`;
1350
+ if (verbose) {
1351
+ args += ` --verbose`;
1352
+ }
1353
+ let rangeArgs = "";
1354
+ if (from > 0) {
1355
+ rangeArgs += ` --from ${from}`;
1356
+ }
1357
+ if (to > 0) {
1358
+ rangeArgs += ` --to ${to}`;
1359
+ }
1360
+ const modeResouces = {
1361
+ rebuild: { cpu: rebuildCpu, mem: rebuildMem, killTimeout: rebuildKillTimeout },
1362
+ "resume-rebuild": { cpu: rebuildCpu, mem: rebuildMem, killTimeout: rebuildKillTimeout },
1363
+ validate: {
1364
+ cpu: validateCpu || rebuildCpu,
1365
+ mem: validateMem || rebuildMem,
1366
+ killTimeout: validateKillTimeout || rebuildKillTimeout
1367
+ },
1368
+ delta: { cpu: deltaCpu, mem: deltaMem, killTimeout: deltaKillTimeout }
1369
+ };
1370
+ const cpu = modeResouces[mode]?.cpu || deltaCpu;
1371
+ const mem = modeResouces[mode]?.mem || deltaMem;
1372
+ const killTimeout = modeResouces[mode]?.killTimeout || deltaKillTimeout;
1373
+ let deltaCron = typeof deltaSchedule === "function" ? deltaSchedule(jobName) : deltaSchedule;
1374
+ if (deltaSchedule && cmdSchedule) {
1375
+ deltaCron = cmdSchedule;
1376
+ }
1377
+ let validateCron = typeof validateSchedule === "function" ? validateSchedule(jobName) : validateSchedule;
1378
+ if (validateSchedule && cmdSchedule) {
1379
+ validateCron = cmdSchedule;
1380
+ }
1381
+ const modeIntervals = {
1382
+ delta: deltaCron ? INTERVAL_ALIASES[deltaCron] || deltaCron : undefined,
1383
+ validate: validateCron ? INTERVAL_ALIASES[validateCron] || validateCron : undefined
1384
+ };
1385
+ const mainJobDefinition = genConfig({
1386
+ jobName,
1387
+ cron: isPeriodic ? modeIntervals[mode] : undefined,
1388
+ workingDirectory,
1389
+ additionalEnv: env,
1390
+ region,
1391
+ cmd: `${bin} ${args} ${rangeArgs}`,
1392
+ killTimeout,
1393
+ cpu,
1394
+ mem,
1395
+ isProduction: production
1396
+ });
1397
+ const nomadPath = await getNomadPath();
1398
+ await prepareNomad(production);
1399
+ const nomadAddr = getNomadAddr(production);
1400
+ await runNomadJob(nomadPath, nomadAddr, jobName, mainJobDefinition, stop, dryRun);
1401
+ }
1402
+ async function deploy() {
1403
+ if (!binaryName) {
1404
+ binaryName = getBinaryName();
1405
+ }
1406
+ const cli = meow2(`
1407
+ Usage
1408
+
1409
+ $ ${binaryName} <options>
1410
+
1411
+ Options
1412
+ ${getSelectorDesc(selector)}
1413
+ --mode could be delta/rebuild/resume-rebuild/validate/one/range/reset
1414
+ --from min id to build
1415
+ --to max id to build
1416
+ --stop stop job instead of running the job
1417
+ --production deploy to production, default is development
1418
+ --schedule override default schedule, support aliases: secondly, minutely, hourly, daily, weekly
1419
+ --verbose Output debug messages
1420
+ --dry-run print nomad job file but do not really execute it
1421
+
1422
+ Examples
1423
+ ${binaryName} --mode delta
1424
+ ${binaryName} --mode rebuild
1425
+ ${binaryName} --mode validate
1426
+ `, {
1427
+ importMeta: import.meta,
1428
+ description: false,
1429
+ flags: {
1430
+ ...getSelectorFlags(selector),
1431
+ mode: {
1432
+ type: "string",
1433
+ default: "delta"
1434
+ },
1435
+ from: {
1436
+ aliases: ["since"],
1437
+ type: "number",
1438
+ default: 0
1439
+ },
1440
+ to: {
1441
+ aliases: ["until"],
1442
+ type: "number",
1443
+ default: 0
1444
+ },
1445
+ schedule: {
1446
+ type: "string"
1447
+ },
1448
+ verbose: {
1449
+ type: "boolean",
1450
+ default: false
1451
+ },
1452
+ production: {
1453
+ aliases: ["prd"],
1454
+ type: "boolean",
1455
+ default: false
1456
+ },
1457
+ dryRun: {
1458
+ type: "boolean",
1459
+ default: false
1460
+ },
1461
+ stop: {
1462
+ type: "boolean",
1463
+ default: false
1464
+ }
1465
+ }
1466
+ });
1467
+ try {
1468
+ return deployMode(cli.flags);
1469
+ } catch (err) {
1470
+ console.error(err);
1471
+ process.exit(1);
1472
+ }
1473
+ }
1474
+ return { deploy };
1475
+ }
1476
+ function createDeploy({
1477
+ binaryName,
1478
+ name,
1479
+ workingDirectory,
1480
+ bin = "bin/indexer",
1481
+ selector = {},
1482
+ region = "skynet-dc1",
1483
+ type = "batch",
1484
+ env = {},
1485
+ count,
1486
+ schedule,
1487
+ restart,
1488
+ killTimeout,
1489
+ cpu,
1490
+ mem,
1491
+ service
1492
+ }) {
1493
+ async function deployModeless({
1494
+ production,
1495
+ stop,
1496
+ dryRun,
1497
+ verbose,
1498
+ schedule: cmdSchedule,
1499
+ ...selectorFlags
1500
+ }) {
1501
+ const jobName = getJobName(name, selectorFlags);
1502
+ const selectorCmdPart = Object.entries(selectorFlags).sort().map(([name2, value]) => `--${name2} ${value}`).join(" ");
1503
+ let args = `${selectorCmdPart}`;
1504
+ if (verbose) {
1505
+ args += ` --verbose`;
1506
+ }
1507
+ let cron = typeof schedule === "function" ? schedule(jobName) : schedule;
1508
+ if (schedule && cmdSchedule) {
1509
+ cron = cmdSchedule;
1510
+ }
1511
+ const nomadJobDefinition = genConfig({
1512
+ jobName,
1513
+ cron: cron ? INTERVAL_ALIASES[cron] || cron : undefined,
1514
+ count,
1515
+ restart,
1516
+ workingDirectory,
1517
+ additionalEnv: env,
1518
+ region,
1519
+ type,
1520
+ cmd: `${bin} ${args}`,
1521
+ killTimeout,
1522
+ cpu,
1523
+ mem,
1524
+ service,
1525
+ isProduction: production
1526
+ });
1527
+ const nomadPath = await getNomadPath();
1528
+ await prepareNomad(production);
1529
+ const nomadAddr = getNomadAddr(production);
1530
+ await runNomadJob(nomadPath, nomadAddr, jobName, nomadJobDefinition, stop, dryRun);
1531
+ }
1532
+ async function deploy() {
1533
+ if (!binaryName) {
1534
+ binaryName = getBinaryName();
1535
+ }
1536
+ const cli = meow2(`
1537
+ Usage
1538
+
1539
+ $ ${binaryName} <options>
1540
+
1541
+ Options
1542
+ ${getSelectorDesc(selector)}
1543
+ --stop stop job instead of running the job
1544
+ --production deploy to production, default is development
1545
+ --schedule override default schedule, support aliases: secondly, minutely, hourly, daily, weekly
1546
+ --verbose Output debug messages
1547
+ --dry-run print nomad job file but do not really execute it
1548
+ `, {
1549
+ importMeta: import.meta,
1550
+ description: false,
1551
+ flags: {
1552
+ ...getSelectorFlags(selector),
1553
+ schedule: {
1554
+ type: "string"
1555
+ },
1556
+ verbose: {
1557
+ type: "boolean",
1558
+ default: false
1559
+ },
1560
+ production: {
1561
+ aliases: ["prd"],
1562
+ type: "boolean",
1563
+ default: false
1564
+ },
1565
+ dryRun: {
1566
+ type: "boolean",
1567
+ default: false
1568
+ },
1569
+ stop: {
1570
+ type: "boolean",
1571
+ default: false
1572
+ }
1573
+ }
1574
+ });
1575
+ try {
1576
+ return deployModeless(cli.flags);
1577
+ } catch (err) {
1578
+ console.error(err);
1579
+ process.exit(1);
1580
+ }
1581
+ }
1582
+ return { deploy };
1583
+ }
1584
+ // src/api.ts
1585
+ import osModule from "os";
1586
+ import express from "express";
1587
+ import meow3 from "meow";
1588
+ async function logStartMiddleware(_, res, next) {
1589
+ const start = new Date;
1590
+ res.set("x-requested-at", start.toISOString());
1591
+ next();
1592
+ }
1593
+ async function contextMiddleware(_, res, next) {
1594
+ res.set("x-instance-id", osModule.hostname());
1595
+ next();
1596
+ }
1597
+ async function logEndMiddleware(req, res, next) {
1598
+ const requestedAt = res.get("x-requested-at");
1599
+ if (!requestedAt) {
1600
+ inline.log("missing x-requested-at header");
1601
+ next();
1602
+ return;
1603
+ }
1604
+ const start = new Date(requestedAt).getTime();
1605
+ const end = new Date().getTime();
1606
+ const logInfo = {
1607
+ start,
1608
+ end,
1609
+ elapsed: `${end - start}ms`,
1610
+ endpoint: req.path,
1611
+ host: req.hostname,
1612
+ status: res.statusCode
1613
+ };
1614
+ if (res.statusMessage) {
1615
+ logInfo.errorMessage = res.statusMessage;
1616
+ }
1617
+ inline.log(JSON.stringify(logInfo));
1618
+ next();
1619
+ }
1620
+ var apiKeyMiddleware = (key) => {
1621
+ async function requireAPIKey(req, res, next) {
1622
+ try {
1623
+ const apiKey = req.get("x-api-key") || req.query["api-key"];
1624
+ if (!apiKey) {
1625
+ inline.log("request without api key");
1626
+ res.status(400).send("require x-api-key header");
1627
+ return;
1628
+ }
1629
+ if (typeof key === "string") {
1630
+ if (apiKey !== key) {
1631
+ inline.log("request has an invalid api key");
1632
+ res.status(400).send("invalid api key");
1633
+ return;
1634
+ }
1635
+ inline.log(`requested by valid key ${key.slice(0, 6)}`);
1636
+ } else {
1637
+ const name = key[apiKey];
1638
+ if (!name) {
1639
+ inline.log("request has an invalid api key");
1640
+ res.status(400).send("invalid api key");
1641
+ return;
1642
+ }
1643
+ inline.log(`requested by authorized user ${name}`);
1644
+ }
1645
+ next();
1646
+ } catch (err) {
1647
+ inline.log("check api key error", err);
1648
+ res.status(500).send("internal error");
1649
+ }
1650
+ }
1651
+ return requireAPIKey;
1652
+ };
1653
+ async function startApiApp({
1654
+ binaryName,
1655
+ name,
1656
+ selector = {},
1657
+ routes,
1658
+ serve,
1659
+ beforeListen
1660
+ }) {
1661
+ const app = express();
1662
+ app.use(express.json({ limit: "20mb" }));
1663
+ const cli = meow3(`
1664
+ Usage
1665
+ $ ${binaryName} <options>
1666
+
1667
+ Options
1668
+ ${getSelectorDesc(selector)}
1669
+ --verbose Output debug messages
1670
+ `, {
1671
+ importMeta: import.meta,
1672
+ description: false,
1673
+ flags: {
1674
+ ...getSelectorFlags(selector),
1675
+ verbose: {
1676
+ type: "boolean",
1677
+ default: false
1678
+ }
1679
+ }
1680
+ });
1681
+ const { verbose, ...selectorFlags } = cli.flags;
1682
+ for (const route of routes) {
1683
+ const method = route.method ? route.method.toLowerCase() : "get";
1684
+ const middlewares = route.middlewares || [];
1685
+ if (route.protected) {
1686
+ if (!serve.apiKey) {
1687
+ throw new Error("serve.apiKey is required for protected route");
1688
+ }
1689
+ middlewares.unshift(apiKeyMiddleware(serve.apiKey));
1690
+ }
1691
+ if (app[method]) {
1692
+ if (verbose) {
1693
+ inline.log(`registering ${method} ${route.path}`);
1694
+ }
1695
+ app[method](route.path, contextMiddleware, logStartMiddleware, ...middlewares, async (req, res, next) => {
1696
+ try {
1697
+ await route.handler({ req, res, ...selectorFlags });
1698
+ } catch (routeErr) {
1699
+ if (routeErr instanceof Error) {
1700
+ inline.log("caught route err", routeErr, routeErr.stack);
1701
+ res.status(500).send(`internal server error: ${routeErr.message}`);
1702
+ } else {
1703
+ inline.log("caught route err", routeErr);
1704
+ res.status(500).send("internal server error");
1705
+ }
1706
+ }
1707
+ next();
1708
+ }, logEndMiddleware);
1709
+ }
1710
+ }
1711
+ if (!routes.some((r) => r.path === "/" && r.method?.toUpperCase() === "GET")) {
1712
+ app.get("/", (_, res) => {
1713
+ res.send("ok");
1714
+ });
1715
+ }
1716
+ if (beforeListen) {
1717
+ await beforeListen({ app });
1718
+ }
1719
+ app.listen(serve.port, () => {
1720
+ if (isProduction()) {
1721
+ inline.log(`${name} listening at https://api.wf.corp.certik.com${serve.prefix}`);
1722
+ } else {
1723
+ inline.log(`${name} listening at http://localhost:${serve.port}`);
1724
+ }
1725
+ });
1726
+ }
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
+ };