@spica/cli 0.13.1 → 0.13.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 (100) hide show
  1. package/index.js +3469 -37
  2. package/package.json +56 -27
  3. package/index.d.ts +0 -2
  4. package/index.js.map +0 -1
  5. package/src/commands/asset/apply.d.ts +0 -2
  6. package/src/commands/asset/apply.js +0 -56
  7. package/src/commands/asset/apply.js.map +0 -1
  8. package/src/commands/asset/delete.d.ts +0 -2
  9. package/src/commands/asset/delete.js +0 -35
  10. package/src/commands/asset/delete.js.map +0 -1
  11. package/src/commands/bucket/orm.d.ts +0 -45
  12. package/src/commands/bucket/orm.js +0 -478
  13. package/src/commands/bucket/orm.js.map +0 -1
  14. package/src/commands/context/ls.d.ts +0 -2
  15. package/src/commands/context/ls.js +0 -23
  16. package/src/commands/context/ls.js.map +0 -1
  17. package/src/commands/context/remove.d.ts +0 -2
  18. package/src/commands/context/remove.js +0 -16
  19. package/src/commands/context/remove.js.map +0 -1
  20. package/src/commands/context/set.d.ts +0 -2
  21. package/src/commands/context/set.js +0 -39
  22. package/src/commands/context/set.js.map +0 -1
  23. package/src/commands/context/switch.d.ts +0 -2
  24. package/src/commands/context/switch.js +0 -22
  25. package/src/commands/context/switch.js.map +0 -1
  26. package/src/commands/function/orm.d.ts +0 -2
  27. package/src/commands/function/orm.js +0 -63
  28. package/src/commands/function/orm.js.map +0 -1
  29. package/src/commands/project/ls.d.ts +0 -2
  30. package/src/commands/project/ls.js +0 -55
  31. package/src/commands/project/ls.js.map +0 -1
  32. package/src/commands/project/remove.d.ts +0 -2
  33. package/src/commands/project/remove.js +0 -82
  34. package/src/commands/project/remove.js.map +0 -1
  35. package/src/commands/project/start.d.ts +0 -2
  36. package/src/commands/project/start.js +0 -409
  37. package/src/commands/project/start.js.map +0 -1
  38. package/src/commands/project/sync.d.ts +0 -171
  39. package/src/commands/project/sync.js +0 -714
  40. package/src/commands/project/sync.js.map +0 -1
  41. package/src/commands/project/upgrade.d.ts +0 -2
  42. package/src/commands/project/upgrade.js +0 -174
  43. package/src/commands/project/upgrade.js.map +0 -1
  44. package/src/compile.d.ts +0 -22
  45. package/src/compile.js +0 -115
  46. package/src/compile.js.map +0 -1
  47. package/src/config.d.ts +0 -9
  48. package/src/config.js +0 -53
  49. package/src/config.js.map +0 -1
  50. package/src/console.d.ts +0 -14
  51. package/src/console.js +0 -47
  52. package/src/console.js.map +0 -1
  53. package/src/context.d.ts +0 -17
  54. package/src/context.js +0 -54
  55. package/src/context.js.map +0 -1
  56. package/src/function/helpers.d.ts +0 -2
  57. package/src/function/helpers.js +0 -12
  58. package/src/function/helpers.js.map +0 -1
  59. package/src/function/index.d.ts +0 -2
  60. package/src/function/index.js +0 -3
  61. package/src/function/index.js.map +0 -1
  62. package/src/function/interface.d.ts +0 -28
  63. package/src/function/interface.js +0 -3
  64. package/src/function/interface.js.map +0 -1
  65. package/src/function/modifier.d.ts +0 -41
  66. package/src/function/modifier.js +0 -64
  67. package/src/function/modifier.js.map +0 -1
  68. package/src/function/triggers/http/index.d.ts +0 -7
  69. package/src/function/triggers/http/index.js +0 -8
  70. package/src/function/triggers/http/index.js.map +0 -1
  71. package/src/function/triggers/http/services/axios.d.ts +0 -46
  72. package/src/function/triggers/http/services/axios.js +0 -163
  73. package/src/function/triggers/http/services/axios.js.map +0 -1
  74. package/src/function/triggers/http/services/index.d.ts +0 -3
  75. package/src/function/triggers/http/services/index.js +0 -4
  76. package/src/function/triggers/http/services/index.js.map +0 -1
  77. package/src/function/triggers/http/transformer.d.ts +0 -16
  78. package/src/function/triggers/http/transformer.js +0 -49
  79. package/src/function/triggers/http/transformer.js.map +0 -1
  80. package/src/function/triggers/index.d.ts +0 -4
  81. package/src/function/triggers/index.js +0 -6
  82. package/src/function/triggers/index.js.map +0 -1
  83. package/src/http.d.ts +0 -11
  84. package/src/http.js +0 -30
  85. package/src/http.js.map +0 -1
  86. package/src/project.d.ts +0 -11
  87. package/src/project.js +0 -63
  88. package/src/project.js.map +0 -1
  89. package/src/range.d.ts +0 -1
  90. package/src/range.js +0 -13
  91. package/src/range.js.map +0 -1
  92. package/src/representative.d.ts +0 -13
  93. package/src/representative.js +0 -120
  94. package/src/representative.js.map +0 -1
  95. package/src/status.d.ts +0 -19
  96. package/src/status.js +0 -39
  97. package/src/status.js.map +0 -1
  98. package/src/validator.d.ts +0 -5
  99. package/src/validator.js +0 -31
  100. package/src/validator.js.map +0 -1
@@ -1,714 +0,0 @@
1
- import caporalCore from "@caporal/core";
2
- const { CaporalValidator } = caporalCore;
3
- import { spin } from "../../console.js";
4
- import { httpService } from "../../http.js";
5
- import { availableSyncModules, validateSyncModules } from "../../validator.js";
6
- import { bold, green, red } from "colorette";
7
- import lodash from "lodash";
8
- const { isEqual } = lodash;
9
- let IGNORE_ERRORS;
10
- let CONCURRENCY_LIMIT;
11
- async function sync({ options: { sourceUrl, sourceApikey, targetUrl, targetApikey, modules, dryRun, syncFnEnv, ignoreErrors, concurrencyLimit } }) {
12
- IGNORE_ERRORS = ignoreErrors;
13
- CONCURRENCY_LIMIT = concurrencyLimit;
14
- const sourceService = httpService.create({
15
- baseUrl: sourceUrl.toString(),
16
- authorization: `APIKEY ${sourceApikey}`
17
- });
18
- const targetService = httpService.create({
19
- baseUrl: targetUrl.toString(),
20
- authorization: `APIKEY ${targetApikey}`
21
- });
22
- modules = modules
23
- .toString()
24
- .split(",")
25
- .map(m => m.trim());
26
- const coreSynchronizers = [
27
- FunctionSynchronizer,
28
- BucketSynchronizer,
29
- ApikeySynchronizer,
30
- PolicySynchronizer
31
- ];
32
- const synchronizers = [];
33
- for (const Ctor of coreSynchronizers) {
34
- const synchronizer = new Ctor(sourceService, targetService, { syncFnEnv });
35
- const subSynchronizers = await synchronizer.initialize().catch(e => {
36
- return Promise.reject(returnErrorMessage(e));
37
- });
38
- synchronizers.push(synchronizer);
39
- synchronizers.push(...subSynchronizers);
40
- }
41
- for (const name of modules) {
42
- const moduleSynchronizers = synchronizers.filter(s => s.moduleName == name);
43
- if (!moduleSynchronizers.length) {
44
- return Promise.reject(`Module ${name} does not exist.`);
45
- }
46
- for (const synchronizer of moduleSynchronizers) {
47
- const { insertions, updations, deletions } = await synchronizer.analyze().catch(e => {
48
- return Promise.reject(returnErrorMessage(e));
49
- });
50
- if (dryRun) {
51
- printActions({
52
- insertions,
53
- updations,
54
- deletions,
55
- field: synchronizer.primaryField,
56
- moduleName: synchronizer.getDisplayableModuleName()
57
- });
58
- }
59
- else {
60
- try {
61
- await synchronizer.synchronize();
62
- }
63
- catch (error) {
64
- Promise.reject(returnErrorMessage(error));
65
- }
66
- console.log(`\n${synchronizer.getDisplayableModuleName()} synchronization has been completed!`.toUpperCase());
67
- }
68
- }
69
- }
70
- }
71
- export default function (program) {
72
- return program
73
- .command("project sync", `Synchronize selected module objects between two spica instances(local or remote).
74
- ${red("ATTENTION")}: Source and target instance versions must be minimum v0.9.19 and for the best results both instance versions should be the same.
75
- Also this command will perform adding, overwriting and removing actions of the target instance and it's irreversible.
76
- We highly recommend you to use --dry-run=true and check the changes that will be applied before start.`)
77
- .option("--source-url", "API address of the instance where objects will be synchronized from", {
78
- required: true,
79
- validator: CaporalValidator.STRING
80
- })
81
- .option("--source-apikey", "Apikey of the instance where objects will be synchronized from", {
82
- required: true,
83
- validator: CaporalValidator.STRING
84
- })
85
- .option("--target-url", "API address of the instance where objects will be synchronized to", {
86
- required: true,
87
- validator: CaporalValidator.STRING
88
- })
89
- .option("--target-apikey", "API address of the instance where objects will be synchronized to", {
90
- required: true,
91
- validator: CaporalValidator.STRING
92
- })
93
- .option("--modules", `Module names of objects that will be synchronized. Available modules: ${green(availableSyncModules.join(","))}`, {
94
- required: true,
95
- validator: validateSyncModules
96
- })
97
- .option("--dry-run", "Shows the changes that will be applied to the target instance.", {
98
- default: false
99
- })
100
- .option("--sync-fn-env", "Set true if you need to sync function environment variables as well.", {
101
- default: false
102
- })
103
- .option("--ignore-errors", "Set true if you don't want to interrupt sync process because of failed requests.", {
104
- default: false
105
- })
106
- .option("--concurrency-limit", "Increase(if you want to speed up), decrease(if you get some error like ECONNRESET) this value to adjust how many parallel requests that will be sent to the target instance", {
107
- default: 100,
108
- validator: CaporalValidator.NUMBER
109
- })
110
- .action(sync);
111
- }
112
- export class ResourceGroupComparisor {
113
- constructor(sources, targets, uniqueField = "_id", ignoredFields = []) {
114
- this.sources = sources;
115
- this.targets = targets;
116
- this.uniqueField = uniqueField;
117
- this.ignoredFields = ignoredFields;
118
- this.existings = [];
119
- this.existingIds = [];
120
- this.existings = targets.filter(target => sources.some(source => source[this.uniqueField] == target[this.uniqueField]));
121
- this.existingIds = this.existings.map(existing => existing[this.uniqueField]);
122
- }
123
- updations() {
124
- const updations = [];
125
- for (const existing of this.existings) {
126
- const source = this.sources.find(source => source[this.uniqueField] == existing[this.uniqueField]);
127
- if (this.ignoredFields.length) {
128
- this.ignoredFields.forEach(field => {
129
- delete source[field];
130
- delete existing[field];
131
- });
132
- }
133
- if (!isEqual(source, existing)) {
134
- updations.push(source);
135
- }
136
- }
137
- return updations;
138
- }
139
- insertions() {
140
- return this.sources.filter(source => this.existingIds.indexOf(source[this.uniqueField]) == -1);
141
- }
142
- deletions() {
143
- return this.targets.filter(target => this.existingIds.indexOf(target[this.uniqueField]) == -1);
144
- }
145
- }
146
- export class FunctionSynchronizer {
147
- constructor(sourceService, targetService, options) {
148
- this.sourceService = sourceService;
149
- this.targetService = targetService;
150
- this.options = options;
151
- this.moduleName = "function";
152
- this.primaryField = "name";
153
- this.insertions = [];
154
- this.updations = [];
155
- this.deletions = [];
156
- }
157
- async initialize() {
158
- const synchronizers = [];
159
- const sourceFns = await this.sourceService.get("function");
160
- for (const fn of sourceFns) {
161
- synchronizers.push(new FunctionDependencySynchronizer(this.sourceService, this.targetService, fn));
162
- }
163
- synchronizers.push(new FunctionIndexSynchronizer(this.sourceService, this.targetService));
164
- return synchronizers;
165
- }
166
- async analyze() {
167
- console.log();
168
- let sourceFns = await spin({
169
- text: "Fetching functions from source instance",
170
- op: () => this.sourceService.get("function")
171
- });
172
- const targetFns = await spin({
173
- text: "Fetching functions from target instance",
174
- op: () => this.targetService.get("function")
175
- });
176
- if (!this.options.syncFnEnv) {
177
- sourceFns = sourceFns.map(fn => {
178
- fn.env = {};
179
- return fn;
180
- });
181
- for (const target of targetFns) {
182
- const index = sourceFns.findIndex(srcFn => srcFn._id == target._id);
183
- if (index != -1) {
184
- sourceFns[index].env = target.env;
185
- }
186
- }
187
- }
188
- const decider = new ResourceGroupComparisor(sourceFns, targetFns);
189
- this.insertions = decider.insertions();
190
- this.updations = decider.updations();
191
- this.deletions = decider.deletions();
192
- return {
193
- insertions: this.insertions,
194
- updations: this.updations,
195
- deletions: this.deletions
196
- };
197
- }
198
- async synchronize() {
199
- console.log();
200
- const insertPromiseFactories = this.insertions.map(fn => () => this.targetService.post("function", fn).catch(e => handleRejection({
201
- action: "insert",
202
- e,
203
- objectName: this.moduleName + " " + fn.name
204
- })));
205
- await spinUntilPromiseEnd(insertPromiseFactories, "Inserting functions to the target instance");
206
- const updatePromiseFactories = this.updations.map(fn => () => this.targetService.put(`function/${fn._id}`, fn).catch(e => handleRejection({
207
- action: "update",
208
- e,
209
- objectName: this.moduleName + " " + fn.name
210
- })));
211
- await spinUntilPromiseEnd(updatePromiseFactories, "Updating target instance functions");
212
- const deletePromiseFactories = this.deletions.map(fn => () => this.targetService.delete(`function/${fn._id}`).catch(e => handleRejection({
213
- action: "delete",
214
- objectName: this.moduleName + " " + fn.name,
215
- e
216
- })));
217
- await spinUntilPromiseEnd(deletePromiseFactories, "Deleting target instance functions");
218
- }
219
- getDisplayableModuleName() {
220
- return this.moduleName;
221
- }
222
- }
223
- export class FunctionDependencySynchronizer {
224
- constructor(sourceService, targetService, fn) {
225
- this.sourceService = sourceService;
226
- this.targetService = targetService;
227
- this.fn = fn;
228
- this.moduleName = "function";
229
- this.subModuleName = "dependency";
230
- this.primaryField = "name";
231
- this.insertions = [];
232
- this.updations = [];
233
- this.deletions = [];
234
- }
235
- initialize() {
236
- return Promise.resolve([]);
237
- }
238
- async analyze() {
239
- const deleteTypes = deps => deps.map(d => {
240
- delete d.types;
241
- return d;
242
- });
243
- const sourceDeps = await this.sourceService
244
- .get(`function/${this.fn._id}/dependencies`)
245
- .then(deleteTypes);
246
- const targetDeps = await this.targetService
247
- .get(`function/${this.fn._id}/dependencies`)
248
- .then(deleteTypes)
249
- .catch(e => {
250
- if (isNotFoundException(e)) {
251
- return [];
252
- }
253
- return Promise.reject(e.data);
254
- });
255
- const decider = new ResourceGroupComparisor(sourceDeps, targetDeps, "name");
256
- this.insertions = decider.insertions();
257
- this.updations = decider.updations();
258
- this.deletions = decider.deletions();
259
- return {
260
- insertions: this.insertions,
261
- updations: this.updations,
262
- deletions: this.deletions
263
- };
264
- }
265
- async synchronize() {
266
- console.log();
267
- const promiseFactories = [];
268
- const insertBody = [...this.insertions, ...this.updations].reduce((acc, dep) => {
269
- const depName = `${dep.name}@${dep.version.slice(1)}`;
270
- acc.name.push(depName);
271
- return acc;
272
- }, { name: [] });
273
- if (insertBody.name.length) {
274
- promiseFactories.push(() => this.targetService.post(`function/${this.fn._id}/dependencies`, insertBody).catch(e => {
275
- handleRejection({
276
- action: "insert",
277
- e,
278
- objectName: this.getDisplayableModuleName()
279
- });
280
- }));
281
- }
282
- const deletePromiseFactories = this.deletions.map(dep => () => this.targetService.delete(`function/${this.fn._id}/dependencies/${dep.name}`).catch(e => handleRejection({
283
- action: "update",
284
- e,
285
- objectName: this.getDisplayableModuleName()
286
- })));
287
- if (deletePromiseFactories.length) {
288
- promiseFactories.push(...deletePromiseFactories);
289
- }
290
- return spinUntilPromiseEnd(promiseFactories, `Updating function '${this.fn.name}' dependencies`);
291
- }
292
- getDisplayableModuleName() {
293
- return `${this.moduleName} '${this.fn.name}' ${this.subModuleName}`;
294
- }
295
- }
296
- export class FunctionIndexSynchronizer {
297
- constructor(sourceService, targetService) {
298
- this.sourceService = sourceService;
299
- this.targetService = targetService;
300
- this.moduleName = "function";
301
- this.subModuleName = "index";
302
- this.primaryField = "name";
303
- this.insertions = [];
304
- this.updations = [];
305
- this.deletions = [];
306
- }
307
- initialize() {
308
- return Promise.resolve([]);
309
- }
310
- async analyze() {
311
- const sourceFns = await this.sourceService.get("function");
312
- const sourceFnIndexes = await Promise.all(sourceFns.map(fn => this.sourceService.get(`function/${fn._id}/index`).then(res => {
313
- return {
314
- _id: fn._id,
315
- name: fn.name,
316
- index: res.index
317
- };
318
- })));
319
- const targetFnIndexes = await Promise.all(sourceFns.map(fn => this.targetService
320
- .get(`function/${fn._id}/index`)
321
- .then(res => {
322
- return {
323
- _id: fn._id,
324
- name: fn.name,
325
- index: res.index
326
- };
327
- })
328
- .catch(e => {
329
- if (isNotFoundException(e)) {
330
- return false;
331
- }
332
- return Promise.reject(e.data);
333
- }))).then(indexes => indexes.filter(Boolean));
334
- const decider = new ResourceGroupComparisor(sourceFnIndexes, targetFnIndexes);
335
- this.insertions = decider.insertions();
336
- this.updations = decider.updations();
337
- this.deletions = decider.deletions();
338
- return {
339
- insertions: this.insertions,
340
- updations: this.updations,
341
- deletions: this.deletions
342
- };
343
- }
344
- synchronize() {
345
- const promiseFactories = [...this.insertions, ...this.updations].map(fn => () => this.targetService.post(`function/${fn._id}/index`, { index: fn.index }).catch(e => handleRejection({
346
- action: "insert",
347
- objectName: this.getDisplayableModuleName() + " " + fn.name,
348
- e
349
- })));
350
- return spinUntilPromiseEnd(promiseFactories, "Writing indexes to the target instance functions");
351
- }
352
- getDisplayableModuleName() {
353
- return this.moduleName + " " + this.subModuleName;
354
- }
355
- }
356
- export class BucketDataSynchronizer {
357
- constructor(sourceService, targetService, bucket) {
358
- this.sourceService = sourceService;
359
- this.targetService = targetService;
360
- this.bucket = bucket;
361
- this.moduleName = "bucket-data";
362
- this.insertions = [];
363
- this.updations = [];
364
- this.deletions = [];
365
- this.primaryField = this.bucket.primary;
366
- }
367
- initialize() {
368
- return Promise.resolve([]);
369
- }
370
- async analyze() {
371
- const params = {
372
- localize: false
373
- };
374
- const sourceData = await this.sourceService.get(`bucket/${this.bucket._id}/data`, {
375
- params
376
- });
377
- const targetData = await this.targetService
378
- .get(`bucket/${this.bucket._id}/data`, {
379
- params
380
- })
381
- .catch(e => {
382
- if (isNotFoundException(e)) {
383
- return [];
384
- }
385
- return Promise.reject(e.data);
386
- });
387
- const decider = new ResourceGroupComparisor(sourceData, targetData);
388
- this.insertions = decider.insertions();
389
- this.updations = decider.updations();
390
- this.deletions = decider.deletions();
391
- return {
392
- insertions: this.insertions,
393
- updations: this.updations,
394
- deletions: this.deletions
395
- };
396
- }
397
- async synchronize() {
398
- console.log();
399
- const insertPromiseFactories = this.insertions.map(data => () => this.targetService.post(`bucket/${this.bucket._id}/data`, data).catch(e => handleRejection({
400
- action: "insert",
401
- objectName: this.getDisplayableModuleName() + " " + data[this.primaryField],
402
- e
403
- })));
404
- await spinUntilPromiseEnd(insertPromiseFactories, `Inserting bucket ${this.bucket.title} data to the target instance`);
405
- const updatePromiseFactories = this.updations.map(data => () => this.targetService.put(`bucket/${this.bucket._id}/data/${data._id}`, data).catch(e => handleRejection({
406
- action: "update",
407
- e,
408
- objectName: this.getDisplayableModuleName() + " " + data[this.primaryField]
409
- })));
410
- await spinUntilPromiseEnd(updatePromiseFactories, `Updating bucket ${this.bucket.title} data on the target instance`);
411
- const deletePromiseFactories = this.deletions.map(data => () => this.targetService.delete(`bucket/${this.bucket._id}/data/${data._id}`).catch(e => handleRejection({
412
- action: "delete",
413
- objectName: this.getDisplayableModuleName() + " " + data[this.primaryField],
414
- e
415
- })));
416
- await spinUntilPromiseEnd(deletePromiseFactories, `Deleting bucket ${this.bucket.title} data from the target instance`);
417
- }
418
- getDisplayableModuleName() {
419
- return `${this.moduleName} '${this.bucket.title}'`;
420
- }
421
- }
422
- export class BucketSynchronizer {
423
- constructor(sourceService, targetService) {
424
- this.sourceService = sourceService;
425
- this.targetService = targetService;
426
- this.moduleName = "bucket";
427
- this.primaryField = "title";
428
- this.insertions = [];
429
- this.updations = [];
430
- this.deletions = [];
431
- }
432
- async initialize() {
433
- const synchronizers = [];
434
- const sourceBuckets = await this.sourceService.get("bucket");
435
- for (const bucket of sourceBuckets) {
436
- synchronizers.push(new BucketDataSynchronizer(this.sourceService, this.targetService, bucket));
437
- }
438
- return synchronizers;
439
- }
440
- async analyze() {
441
- console.log();
442
- const sourceBuckets = await spin({
443
- text: "Fetching buckets from source instance",
444
- op: () => this.sourceService.get("bucket")
445
- });
446
- const targetBuckets = await spin({
447
- text: "Fetching buckets from target instance",
448
- op: () => this.targetService.get("bucket")
449
- });
450
- const decider = new ResourceGroupComparisor(sourceBuckets, targetBuckets);
451
- this.insertions = decider.insertions();
452
- this.updations = decider.updations();
453
- this.deletions = decider.deletions();
454
- return {
455
- insertions: this.insertions,
456
- updations: this.updations,
457
- deletions: this.deletions
458
- };
459
- }
460
- async synchronize() {
461
- console.log();
462
- const insertPromiseFactories = this.insertions.map(bucket => () => this.targetService.post("bucket", bucket).catch(e => handleRejection({
463
- action: "insert",
464
- objectName: this.getDisplayableModuleName() + " " + bucket.title,
465
- e
466
- })));
467
- await spinUntilPromiseEnd(insertPromiseFactories, "Inserting buckets to the target instance");
468
- const updatePromiseFactories = this.updations.map(bucket => () => this.targetService.put(`bucket/${bucket._id}`, bucket).catch(e => handleRejection({
469
- action: "update",
470
- objectName: this.getDisplayableModuleName() + " " + bucket.title,
471
- e
472
- })));
473
- await spinUntilPromiseEnd(updatePromiseFactories, "Updating buckets on the target instance");
474
- const deletePromiseFactories = this.deletions.map(bucket => () => this.targetService.delete(`bucket/${bucket._id}`).catch(e => handleRejection({
475
- action: "delete",
476
- objectName: bucket.title,
477
- e
478
- })));
479
- await spinUntilPromiseEnd(deletePromiseFactories, "Deleting bucket from the target instance");
480
- }
481
- getDisplayableModuleName() {
482
- return this.moduleName;
483
- }
484
- }
485
- export class ApikeySynchronizer {
486
- constructor(sourceService, targetService) {
487
- this.sourceService = sourceService;
488
- this.targetService = targetService;
489
- this.moduleName = "apikey";
490
- this.primaryField = "name";
491
- this.insertions = [];
492
- this.updations = [];
493
- this.deletions = [];
494
- }
495
- initialize() {
496
- return Promise.resolve([]);
497
- }
498
- async analyze() {
499
- console.log();
500
- const sourceApikeys = await spin({
501
- text: "Fetching apikeys from source instance",
502
- op: () => this.sourceService
503
- .get("passport/apikey")
504
- .then(r => r.data)
505
- });
506
- const targetApikeys = await spin({
507
- text: "Fetching apikeys from target instance",
508
- op: () => this.targetService
509
- .get("passport/apikey")
510
- .then(r => r.data)
511
- });
512
- const decider = new ResourceGroupComparisor(sourceApikeys, targetApikeys);
513
- this.insertions = decider.insertions();
514
- this.updations = decider.updations();
515
- this.deletions = decider.deletions();
516
- return {
517
- insertions: this.insertions,
518
- updations: this.updations,
519
- deletions: this.deletions
520
- };
521
- }
522
- async synchronize() {
523
- console.log();
524
- const insertPromiseFactories = this.insertions.map(apikey => () => {
525
- const insertRejectionHandler = e => handleRejection({
526
- action: "insert",
527
- objectName: this.getDisplayableModuleName() + " " + apikey.name,
528
- e
529
- });
530
- const policies = [...apikey.policies];
531
- delete apikey.policies;
532
- const apikeyInsertPromise = this.targetService
533
- .post("passport/apikey", apikey)
534
- .catch(e => insertRejectionHandler(e));
535
- return apikeyInsertPromise.then(() => {
536
- const policyAttachPromises = policies.map(policy => this.targetService
537
- .put(`passport/apikey/${apikey._id}/policy/${policy}`)
538
- .catch(e => insertRejectionHandler(e)));
539
- return Promise.all(policyAttachPromises);
540
- });
541
- });
542
- await spinUntilPromiseEnd(insertPromiseFactories, "Inserting apikeys to the target instance");
543
- const updatePromiseFactories = this.updations.map(apikey => () => {
544
- const rejectionHandler = e => {
545
- handleRejection({
546
- action: "update",
547
- objectName: this.getDisplayableModuleName() + " " + apikey.name,
548
- e
549
- });
550
- };
551
- const policies = [...apikey.policies];
552
- delete apikey.policies;
553
- const apikeyDeletePromise = this.targetService
554
- .delete(`passport/apikey/${apikey._id}`)
555
- .catch(e => rejectionHandler(e));
556
- const apikeyInsertPromise = apikeyDeletePromise.then(() => this.targetService.post(`passport/apikey`, apikey).catch(e => rejectionHandler(e)));
557
- return apikeyInsertPromise.then(() => {
558
- const policyAttachPromises = policies.map(policy => this.targetService
559
- .put(`passport/apikey/${apikey._id}/policy/${policy}`)
560
- .catch(e => rejectionHandler(e)));
561
- return Promise.all(policyAttachPromises);
562
- });
563
- });
564
- await spinUntilPromiseEnd(updatePromiseFactories, "Updating apikeys on the target instance");
565
- const deletePromiseFactories = this.deletions.map(apikey => () => this.targetService.delete(`passport/apikey/${apikey._id}`).catch(e => handleRejection({
566
- action: "delete",
567
- objectName: apikey.name,
568
- e
569
- })));
570
- await spinUntilPromiseEnd(deletePromiseFactories, "Deleting apikeys from the target instance");
571
- }
572
- getDisplayableModuleName() {
573
- return this.moduleName;
574
- }
575
- }
576
- export class PolicySynchronizer {
577
- constructor(sourceService, targetService) {
578
- this.sourceService = sourceService;
579
- this.targetService = targetService;
580
- this.moduleName = "policy";
581
- this.primaryField = "name";
582
- this.insertions = [];
583
- this.updations = [];
584
- this.deletions = [];
585
- }
586
- initialize() {
587
- return Promise.resolve([]);
588
- }
589
- async analyze() {
590
- console.log();
591
- const sourcePolicies = await spin({
592
- text: "Fetching policies from source instance",
593
- op: () => this.sourceService
594
- .get("passport/policy")
595
- .then(r => r.data)
596
- });
597
- const targetPolicies = await spin({
598
- text: "Fetching policies from target instance",
599
- op: () => this.targetService
600
- .get("passport/policy")
601
- .then(r => r.data)
602
- });
603
- const decider = new ResourceGroupComparisor(sourcePolicies, targetPolicies);
604
- this.insertions = decider.insertions();
605
- this.updations = decider.updations();
606
- this.deletions = decider.deletions();
607
- return {
608
- insertions: this.insertions,
609
- updations: this.updations,
610
- deletions: this.deletions
611
- };
612
- }
613
- async synchronize() {
614
- console.log();
615
- const insertPromiseFactories = this.insertions.map(policy => () => {
616
- delete policy.system;
617
- return this.targetService.post("passport/policy", policy).catch(e => handleRejection({
618
- action: "insert",
619
- objectName: this.getDisplayableModuleName() + " " + policy.name,
620
- e
621
- }));
622
- });
623
- await spinUntilPromiseEnd(insertPromiseFactories, "Inserting policies to the target instance");
624
- const updatePromiseFactories = this.updations.map(policy => () => {
625
- delete policy.system;
626
- return this.targetService.put(`passport/policy/${policy._id}`, policy).catch(e => handleRejection({
627
- action: "update",
628
- objectName: this.getDisplayableModuleName() + " " + policy.name,
629
- e
630
- }));
631
- });
632
- await spinUntilPromiseEnd(updatePromiseFactories, "Updating policies on the target instance");
633
- const deletePromiseFactories = this.deletions.map(policy => () => this.targetService.delete(`passport/policy/${policy._id}`).catch(e => handleRejection({
634
- action: "delete",
635
- objectName: policy.name,
636
- e
637
- })));
638
- await spinUntilPromiseEnd(deletePromiseFactories, "Deleting policies from the target instance");
639
- }
640
- getDisplayableModuleName() {
641
- return this.moduleName;
642
- }
643
- }
644
- function printActions({ insertions, updations, deletions, field, moduleName }) {
645
- const joinActions = (actions) => {
646
- const MAX_LINES = 20;
647
- actions = actions.map(a => `- ${a[field]}`);
648
- if (actions.length > MAX_LINES) {
649
- actions = actions.slice(0, MAX_LINES);
650
- actions.push("...more");
651
- }
652
- return actions.join("\n");
653
- };
654
- console.log();
655
- console.log(`----- ${moduleName.toUpperCase()} -----`);
656
- console.log(`\n* Found ${bold(insertions.length)} objects to ${bold("insert")}:
657
- ${joinActions(insertions)}`);
658
- console.log(`\n* Found ${bold(updations.length)} objects to ${bold("update")}:
659
- ${joinActions(updations)}`);
660
- console.log(`\n* Found ${bold(deletions.length)} objects to ${bold("delete")}:
661
- ${joinActions(deletions)}`);
662
- }
663
- export var SendingPromiseStrategy;
664
- (function (SendingPromiseStrategy) {
665
- SendingPromiseStrategy[SendingPromiseStrategy["All"] = 0] = "All";
666
- SendingPromiseStrategy[SendingPromiseStrategy["OneByOne"] = 1] = "OneByOne";
667
- SendingPromiseStrategy[SendingPromiseStrategy["Batch"] = 2] = "Batch";
668
- SendingPromiseStrategy[SendingPromiseStrategy["Retry"] = 3] = "Retry";
669
- })(SendingPromiseStrategy || (SendingPromiseStrategy = {}));
670
- function spinUntilPromiseEnd(promiseFactories, label) {
671
- if (!promiseFactories.length) {
672
- return;
673
- }
674
- return spin({
675
- text: label,
676
- op: async (spinner) => {
677
- let progress = 0;
678
- let count = 0;
679
- const concurrency = Math.min(promiseFactories.length, CONCURRENCY_LIMIT);
680
- let batchPromises = [];
681
- for (let i = 0; i < promiseFactories.length; i++) {
682
- batchPromises.push(promiseFactories[i]);
683
- if (batchPromises.length == concurrency || i == promiseFactories.length - 1) {
684
- await Promise.all(batchPromises.map(b => b()));
685
- batchPromises = [];
686
- }
687
- count++;
688
- progress = (100 / promiseFactories.length) * count;
689
- spinner.text = `${label} (%${Math.round(progress)})`;
690
- }
691
- return;
692
- }
693
- });
694
- }
695
- function handleRejection({ action, objectName, e }) {
696
- const errorMessage = returnErrorMessage(e);
697
- const msg = `
698
- Failed to ${action} ${bold(objectName)}.
699
- ${errorMessage}`;
700
- if (IGNORE_ERRORS) {
701
- return console.warn(msg);
702
- }
703
- else {
704
- return Promise.reject(msg);
705
- }
706
- }
707
- function returnErrorMessage(e) {
708
- return e.data ? e.data.message || e.data : e;
709
- }
710
- function isNotFoundException(e) {
711
- const code = 404;
712
- return e.status == code || e.statusCode == code || (e.data && e.data.statusCode == code);
713
- }
714
- //# sourceMappingURL=sync.js.map