@faable/faable 4.29.0 → 4.30.0

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.
@@ -400,6 +400,29 @@ class FaableApi {
400
400
  async undoVolumeOperation(team, operation_id) {
401
401
  return data(this.client.post(`/volume-operation/${operation_id}/undo`, undefined, { headers: projectHeader(team) }));
402
402
  }
403
+ async listDatabases(team, app_id) {
404
+ return data(this.client.get(`/database`, {
405
+ params: { app_id },
406
+ headers: projectHeader(team)
407
+ }));
408
+ }
409
+ async exportDatabase(team, database_id) {
410
+ return data(this.client.post(`/database/${database_id}/export`, undefined, { headers: projectHeader(team) }));
411
+ }
412
+ async getDatabaseExport(team, database_id, export_id) {
413
+ return data(this.client.get(`/database/${database_id}/export/${export_id}`, { headers: projectHeader(team) }));
414
+ }
415
+ async importDatabase(team, database_id) {
416
+ return data(this.client.post(`/database/${database_id}/import`, undefined, {
417
+ headers: projectHeader(team)
418
+ }));
419
+ }
420
+ async getDatabaseImport(team, database_id, import_id) {
421
+ return data(this.client.get(`/database/${database_id}/import/${import_id}`, { headers: projectHeader(team) }));
422
+ }
423
+ async applyDatabaseImport(team, database_id, import_id) {
424
+ return data(this.client.post(`/database/${database_id}/import/${import_id}/apply`, undefined, { headers: projectHeader(team) }));
425
+ }
403
426
  async restoreVolume(team, volume_id, backup_id) {
404
427
  return data(this.client.post(`/volume/${volume_id}/restore`, { backup_id }, { headers: projectHeader(team) }));
405
428
  }
@@ -0,0 +1,140 @@
1
+ import axios from 'axios';
2
+ import { CliError } from '../../../lib/errors.js';
3
+ import { confirm } from '../../../lib/interactive.js';
4
+ import { print_json, json_option } from '../../../lib/listing.js';
5
+ import { log } from '../../../log.js';
6
+ import { resolve_volume, volume_option } from './shared.js';
7
+ import { require_completed, wait_operation, state_label } from './operation.js';
8
+ import { app_option } from '../schedule/shared.js';
9
+
10
+ const POLL_MS = 3000;
11
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
12
+ /** Polls `get` until `done` says so; the database side has no operation row. */
13
+ const poll = async (get, done) => {
14
+ for (;;) {
15
+ const v = await get();
16
+ if (done(v))
17
+ return v;
18
+ await sleep(POLL_MS);
19
+ }
20
+ };
21
+ /** The one ready database of an app, or a clear refusal. */
22
+ const database_of = async (api, team, app_id, name) => {
23
+ const { results } = await api.listDatabases(team, app_id);
24
+ const ready = results.filter(d => d.state === 'ready');
25
+ if (ready.length !== 1) {
26
+ throw new CliError('not_found', ready.length === 0
27
+ ? `${name} has no ready database to clone ${results.length ? `(it is ${results[0].state})` : ''}`.trim()
28
+ : `${name} has ${ready.length} databases: clone them by hand (database export/import)`);
29
+ }
30
+ return ready[0];
31
+ };
32
+ /**
33
+ * The source database's dump into the target's: export, stream the .sql.gz
34
+ * from its signed download straight to the import's signed upload (nothing
35
+ * on disk), apply — which backs the target database up first.
36
+ */
37
+ const clone_database = async (api, team, from, to, quiet) => {
38
+ const src = await database_of(api, team, from.id, from.name);
39
+ const dst = await database_of(api, team, to.id, to.name);
40
+ if (!quiet)
41
+ log.info(`🗃 Exporting ${from.name}'s database`);
42
+ const { export_id } = await api.exportDatabase(team, src.id);
43
+ const exp = await poll(() => api.getDatabaseExport(team, src.id, export_id), e => e.state === 'completed' || e.state === 'failed');
44
+ if (exp.state !== 'completed' || !exp.url) {
45
+ throw new CliError('operation_failed', `The export of ${from.name}'s database failed: ${exp.error ?? 'no reason given'}`);
46
+ }
47
+ const imp = await api.importDatabase(team, dst.id);
48
+ if (!quiet)
49
+ log.info(`🗃 Loading it into ${to.name}'s database (a backup of it goes first)`);
50
+ const download = await axios.get(exp.url, {
51
+ responseType: 'stream',
52
+ timeout: 0
53
+ });
54
+ const length = download.headers['content-length'] ?? exp.size_bytes;
55
+ await axios.put(imp.upload_url, download.data, {
56
+ headers: length != null ? { 'content-length': String(length) } : {},
57
+ maxBodyLength: Infinity,
58
+ timeout: 0
59
+ });
60
+ await api.applyDatabaseImport(team, dst.id, imp.import_id);
61
+ const done = await poll(() => api.getDatabaseImport(team, dst.id, imp.import_id), i => i.state === 'completed' || i.state === 'failed');
62
+ if (done.state !== 'completed') {
63
+ throw new CliError('operation_failed', `The import into ${to.name}'s database failed: ${done.error ?? 'no reason given'}`);
64
+ }
65
+ return { export_id, import_id: imp.import_id };
66
+ };
67
+ const volumes_clone = {
68
+ command: 'clone',
69
+ describe: "Make an app a copy of another of the project: its volume (and with --database its database) replaced by the other's",
70
+ builder: yargs => volume_option(app_option(json_option(yargs)))
71
+ .option('from', {
72
+ type: 'string',
73
+ demandOption: true,
74
+ description: 'The app to copy (id, name or slug), in the same project'
75
+ })
76
+ .option('backup', {
77
+ type: 'string',
78
+ description: 'Copy one of its backups instead of what it holds now (see volumes backups -a <it>)'
79
+ })
80
+ .option('database', {
81
+ type: 'boolean',
82
+ default: false,
83
+ description: "Its database's data too (each app has its own)"
84
+ })
85
+ .option('yes', {
86
+ alias: 'y',
87
+ type: 'boolean',
88
+ default: false,
89
+ description: 'Skip the confirmation prompt'
90
+ })
91
+ .example('$0 deploy volumes clone --from my-blog --database -a my-blog-staging', 'A WordPress staging: the files and the database of my-blog')
92
+ .showHelpOnFail(false),
93
+ handler: async (args) => {
94
+ const to = await resolve_volume(args.app, args.volume);
95
+ const from = await resolve_volume(args.from, args.volume);
96
+ if (from.app_id === to.app_id) {
97
+ throw new CliError('usage', 'An app is not cloned onto itself: -a is the copy, --from the original');
98
+ }
99
+ if (from.team !== to.team) {
100
+ throw new CliError('usage', `${from.app.name} and ${to.app.name} are in different projects`);
101
+ }
102
+ const { api, team } = to;
103
+ const go = await confirm({
104
+ message: `Replace everything in ${to.app.name}/${to.volume.name}${args.database ? ' and its database' : ''} with a copy of ${from.app.name}${args.backup ? ` (backup ${args.backup})` : ''}? ${to.app.name} stops while it restores; what it holds now is backed up first.`,
105
+ yes: args.yes
106
+ });
107
+ if (!go) {
108
+ log.info('Cancelled.');
109
+ return;
110
+ }
111
+ const quiet = !!args.json;
112
+ const onState = (s) => {
113
+ if (!quiet && s !== 'completed' && s !== 'failed')
114
+ log.info(state_label[s]);
115
+ };
116
+ let backup_id = args.backup;
117
+ if (!backup_id) {
118
+ if (!quiet)
119
+ log.info(`🗄 Backing up ${from.app.name}/${from.volume.name}, the copy`);
120
+ const b = await api.createVolumeOperation(team, from.volume.id, 'backup');
121
+ backup_id = require_completed(await wait_operation(api, team, b, { onState })).id;
122
+ }
123
+ if (!quiet)
124
+ log.info(`♻️ Restoring it into ${to.app.name}/${to.volume.name} (its current contents are backed up first)`);
125
+ const r = await api.restoreVolume(team, to.volume.id, backup_id);
126
+ const restored = require_completed(await wait_operation(api, team, r, { onState }));
127
+ const db = args.database
128
+ ? await clone_database(api, team, { id: from.app_id, name: from.app.name }, { id: to.app_id, name: to.app.name }, quiet)
129
+ : null;
130
+ if (args.json)
131
+ return print_json({ backup_id, restore: restored, database: db });
132
+ log.info(`✅ ${to.app.name} is a copy of ${from.app.name}.`);
133
+ log.info(`To undo the files: faable deploy volumes restore ${restored.after_id ?? '<the backup before it>'} -a ${to.app.name}`);
134
+ // Files and data come as they are, and some of them name the original.
135
+ log.info(`⚠️ What names ${from.app.name}'s domain came along: in a WordPress, a WP_HOME in wp-config-local.php, and the links in the database. ` +
136
+ `faable deploy run -a ${to.app.name} -- wp search-replace https://${from.app.url} https://${to.app.url} --all-tables`);
137
+ }
138
+ };
139
+
140
+ export { volumes_clone };
@@ -1,4 +1,5 @@
1
1
  import { volumes_backups, volumes_backup } from './backups.js';
2
+ import { volumes_clone } from './clone.js';
2
3
  import { volumes_get, volumes_export } from './export.js';
3
4
  import { volumes_import, volumes_put } from './import.js';
4
5
  import { volumes_list } from './list.js';
@@ -22,10 +23,11 @@ const volumes = {
22
23
  .command(volumes_backups)
23
24
  .command(volumes_backup)
24
25
  .command(volumes_restore)
26
+ .command(volumes_clone)
25
27
  .command(volumes_export)
26
28
  .command(volumes_import)
27
29
  .command(volumes_put)
28
- .demandCommand(1, 'Specify a volumes command: list, ls, get, rm, backups, backup, restore, export, import or put'),
30
+ .demandCommand(1, 'Specify a volumes command: list, ls, get, rm, backups, backup, restore, clone, export, import or put'),
29
31
  handler: () => {
30
32
  // Unreachable: demandCommand(1) either routes to a subcommand or fails
31
33
  // through the global .fail() in src/index.ts.
@@ -12,7 +12,7 @@ const volumes_restore = {
12
12
  .positional('backup_id', {
13
13
  type: 'string',
14
14
  demandOption: true,
15
- description: 'The backup (see `faable deploy volumes backups`)'
15
+ description: 'The backup (see `faable deploy volumes backups`). It may be one of another app of the project: a look at it without touching that app'
16
16
  })
17
17
  .option('yes', {
18
18
  alias: 'y',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faable/faable",
3
- "version": "4.29.0",
3
+ "version": "4.30.0",
4
4
  "main": "dist/index.js",
5
5
  "license": "MIT",
6
6
  "author": "Marc Pomar <marc@faable.com>",