@appsys-sas/devtool 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/index.js +1458 -224
- package/dist/schema/config.schema.json +46 -7
- package/dist/ui/assets/{Checkbox-BZC5uXYP.js → Checkbox-B3IShHMs.js} +1 -1
- package/dist/ui/assets/{ConfigFileChoice-BU_T17Ks.js → ConfigFileChoice-DjlFN2hl.js} +1 -1
- package/dist/ui/assets/{ConfirmDialog-DZVlVwHs.js → ConfirmDialog-D0zdleOV.js} +1 -1
- package/dist/ui/assets/{DashboardView-CBpYvj1m.js → DashboardView-DWGIXOVl.js} +1 -1
- package/dist/ui/assets/{DialogClose-Dc6t_dfj.js → DialogClose-Dvi6msFB.js} +1 -1
- package/dist/ui/assets/{DirectoryFilesView-BmJBlbEV.js → DirectoryFilesView-Dq3pl7Lw.js} +1 -1
- package/dist/ui/assets/{DirectoryHomeView-DKIMUmcP.js → DirectoryHomeView-DjzQkjrd.js} +1 -1
- package/dist/ui/assets/DirectoryIndexView-DIe1X2Tm.js +1 -0
- package/dist/ui/assets/{DirectoryStreamView-iZqkG32T.js → DirectoryStreamView-B8MPeFDD.js} +1 -1
- package/dist/ui/assets/EnvironmentView-BFY6h7Zs.js +2 -0
- package/dist/ui/assets/{FieldRoot-BCn_CEPy.js → FieldRoot-DHNFUtPO.js} +1 -1
- package/dist/ui/assets/{FileSpaceView-Dnep-waJ.js → FileSpaceView-B_ECpJg_.js} +1 -1
- package/dist/ui/assets/{Input-Jqi22uMD.js → Input-CaKoAfUy.js} +1 -1
- package/dist/ui/assets/{IntegrationLink-BZNDXs-y.js → IntegrationLink-ANNDVOLk.js} +1 -1
- package/dist/ui/assets/{IntegrationView-ryvgBU8q.js → IntegrationView-VOeGFGP8.js} +1 -1
- package/dist/ui/assets/{MarkdownPreview-CDKfQc0T.js → MarkdownPreview-zdekVx8q.js} +3 -3
- package/dist/ui/assets/{McpDiff-D9sG8HjJ.js → McpDiff-dCRbSnn8.js} +1 -1
- package/dist/ui/assets/{McpView-DxazZIlq.js → McpView-CeXJd1BQ.js} +1 -1
- package/dist/ui/assets/{PopperContent-DsvFaOQk.js → PopperContent-C5LXxxJI.js} +1 -1
- package/dist/ui/assets/{ProjectHomeView-k5_-oZT-.js → ProjectHomeView-J411cMfr.js} +1 -1
- package/dist/ui/assets/{ProjectStreamView-CBXlt7xA.js → ProjectStreamView-BPYM_tbP.js} +1 -1
- package/dist/ui/assets/{RovingFocusItem-dPnfoQa1.js → RovingFocusItem-H18FCI46.js} +1 -1
- package/dist/ui/assets/{SidebarToggle-CJFlcnp3.js → SidebarToggle-DsOXmeZL.js} +1 -1
- package/dist/ui/assets/{StreamView-uZaVldvb.js → StreamView-C43FUvQv.js} +1 -1
- package/dist/ui/assets/{TabsTrigger-DfRyl3uN.js → TabsTrigger-1dWW4P1K.js} +1 -1
- package/dist/ui/assets/{Teleport-egLCtQOz.js → Teleport-BNK8W8yM.js} +1 -1
- package/dist/ui/assets/{badge-C9kn1dEa.js → badge-DyRtCG2g.js} +1 -1
- package/dist/ui/assets/chevron-right-D51MQRmO.js +1 -0
- package/dist/ui/assets/{file-text-BOr7q2v9.js → file-text-0uXA8m7c.js} +1 -1
- package/dist/ui/assets/{format-Ca9t39lx.js → format-Bgl22CzV.js} +1 -1
- package/dist/ui/assets/{index-BE6-bwUr.js → index-CtIt_yky.js} +3 -3
- package/dist/ui/assets/{jsonMode-BbCtae_p.js → jsonMode-T37UiqHb.js} +1 -1
- package/dist/ui/assets/{message-square-BNGIegWS.js → message-square-C0EtVtJD.js} +1 -1
- package/dist/ui/assets/{monaco-DkplEayZ.js → monaco-DQpneLK2.js} +3 -3
- package/dist/ui/assets/{play-DP2DFgX4.js → play-kel-fsD8.js} +1 -1
- package/dist/ui/assets/search-BIK5qdQy.js +1 -0
- package/dist/ui/assets/{select-cgep2tvN.js → select-BrEgKBYd.js} +1 -1
- package/dist/ui/assets/{sparkles-Dvu8icaA.js → sparkles-CzP3bvbX.js} +1 -1
- package/dist/ui/assets/{triangle-alert-BOC3BCFR.js → triangle-alert-Dx_bLHha.js} +1 -1
- package/dist/ui/assets/{useNonce-CrRZqJr-.js → useNonce-DxRnkBwr.js} +1 -1
- package/dist/ui/assets/{ws-BmpqVuYF.js → ws-Bd-Fz9iE.js} +2 -2
- package/dist/ui/index.html +13 -13
- package/package.json +11 -10
- package/dist/ui/assets/DirectoryIndexView-DKPwCoD2.js +0 -1
- package/dist/ui/assets/EnvironmentView-B3DYpN58.js +0 -2
- package/dist/ui/assets/chevron-right-BwCe3xUX.js +0 -1
- package/dist/ui/assets/search-O6vemR6e.js +0 -1
package/dist/lib/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createReadStream, createWriteStream, existsSync, mkdirSync, watch } from "node:fs";
|
|
3
|
-
import fs from "node:fs/promises";
|
|
3
|
+
import fs, { stat } from "node:fs/promises";
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { pipeline } from "node:stream/promises";
|
|
@@ -22,6 +22,8 @@ import { CreateBucketCommand, DeleteObjectCommand, DeleteObjectsCommand, GetObje
|
|
|
22
22
|
import SftpClient from "ssh2-sftp-client";
|
|
23
23
|
import { EventEmitter, once } from "node:events";
|
|
24
24
|
import { createGunzip, createGzip } from "node:zlib";
|
|
25
|
+
import mime from "mime-types";
|
|
26
|
+
import { extract, pack } from "tar-stream";
|
|
25
27
|
import { Redis } from "ioredis";
|
|
26
28
|
import { parse as parse$1, patch } from "@decimalturn/toml-patch";
|
|
27
29
|
import { isMap as isMap$2, isScalar, isSeq, parse as parse$2, parseDocument } from "yaml";
|
|
@@ -38,7 +40,6 @@ import https from "node:https";
|
|
|
38
40
|
import xtermHeadless from "@xterm/headless";
|
|
39
41
|
import treeKill from "tree-kill";
|
|
40
42
|
import { Cron } from "croner";
|
|
41
|
-
import mime from "mime-types";
|
|
42
43
|
import { WebSocketServer } from "ws";
|
|
43
44
|
import { createRequire } from "node:module";
|
|
44
45
|
import { getIcons } from "@iconify/utils";
|
|
@@ -116,7 +117,7 @@ const DEFAULT_SCOPES = [
|
|
|
116
117
|
"profile"
|
|
117
118
|
];
|
|
118
119
|
const DEFAULT_CALLBACK_PORT = 6732;
|
|
119
|
-
const MAX_PORT = 65535;
|
|
120
|
+
const MAX_PORT$1 = 65535;
|
|
120
121
|
/**
|
|
121
122
|
* Reads a setting that must hold a non-blank text.
|
|
122
123
|
* @param value The raw setting.
|
|
@@ -132,7 +133,7 @@ function readText$2(value) {
|
|
|
132
133
|
*/
|
|
133
134
|
function readPort(value) {
|
|
134
135
|
const port = typeof value === "number" ? value : typeof value === "string" && /^\s*\d+\s*$/.test(value) ? Number(value) : NaN;
|
|
135
|
-
return Number.isInteger(port) && port >= 1 && port <= MAX_PORT ? port : null;
|
|
136
|
+
return Number.isInteger(port) && port >= 1 && port <= MAX_PORT$1 ? port : null;
|
|
136
137
|
}
|
|
137
138
|
/**
|
|
138
139
|
* Reads the scopes to ask, a list of non-blank texts holding `openid`.
|
|
@@ -207,7 +208,7 @@ const openid = {
|
|
|
207
208
|
});
|
|
208
209
|
if (callbackPort === null) problems.push({
|
|
209
210
|
setting: "auth.callbackPort",
|
|
210
|
-
message: `must be a port between 1 and ${MAX_PORT}, ${DEFAULT_CALLBACK_PORT} is used`
|
|
211
|
+
message: `must be a port between 1 and ${MAX_PORT$1}, ${DEFAULT_CALLBACK_PORT} is used`
|
|
211
212
|
});
|
|
212
213
|
if (scopes === null) problems.push({
|
|
213
214
|
setting: "auth.scopes",
|
|
@@ -764,6 +765,96 @@ async function authValue(options, value) {
|
|
|
764
765
|
if (text === void 0 || text === null) throw new Error(`auth://${value}: ${options.name ?? "the identity provider"} gives no ${value}`);
|
|
765
766
|
return text;
|
|
766
767
|
}
|
|
768
|
+
// ../../packages/environment/lib/access.js
|
|
769
|
+
/** Access letting everyone pull and push. */
|
|
770
|
+
const OPEN_ACCESS = {
|
|
771
|
+
pull: null,
|
|
772
|
+
push: null
|
|
773
|
+
};
|
|
774
|
+
const DIRECTIONS = ["pull", "push"];
|
|
775
|
+
/**
|
|
776
|
+
* Reads `groups: { pull, push }`, each a non-empty list of groups of the identity provider or false.
|
|
777
|
+
*
|
|
778
|
+
* @param value - The raw `groups` setting.
|
|
779
|
+
* @returns The groups by direction, null for a direction left out, and the problems of the setting.
|
|
780
|
+
*/
|
|
781
|
+
function readTransferGroups(value) {
|
|
782
|
+
const groups = { ...OPEN_ACCESS };
|
|
783
|
+
if (value === void 0) return {
|
|
784
|
+
groups,
|
|
785
|
+
problems: []
|
|
786
|
+
};
|
|
787
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return {
|
|
788
|
+
groups,
|
|
789
|
+
problems: ["must be a map of pull and push groups"]
|
|
790
|
+
};
|
|
791
|
+
const problems = [];
|
|
792
|
+
const record = value;
|
|
793
|
+
for (const key of Object.keys(record).filter((key) => !DIRECTIONS.includes(key))) problems.push(`${key} is unknown: only pull and push`);
|
|
794
|
+
for (const direction of DIRECTIONS) {
|
|
795
|
+
const entry = record[direction];
|
|
796
|
+
if (entry === void 0) continue;
|
|
797
|
+
if (entry === false || Array.isArray(entry) && entry.length > 0 && entry.every((group) => typeof group === "string" && group !== "")) groups[direction] = entry;
|
|
798
|
+
else problems.push(`${direction} must be a non-empty list of groups, or false`);
|
|
799
|
+
}
|
|
800
|
+
return {
|
|
801
|
+
groups,
|
|
802
|
+
problems
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Gives the groups of each direction, those of an item replacing those of its backend, except where
|
|
807
|
+
* the backend refuses everyone.
|
|
808
|
+
*
|
|
809
|
+
* @param item - The groups of the item.
|
|
810
|
+
* @param backend - The groups of its backend.
|
|
811
|
+
* @returns The groups by direction.
|
|
812
|
+
*/
|
|
813
|
+
function mergeTransferGroups(item, backend) {
|
|
814
|
+
return {
|
|
815
|
+
pull: backend.pull === false ? false : item.pull ?? backend.pull,
|
|
816
|
+
push: backend.push === false ? false : item.push ?? backend.push
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Tells the signed-in developer the groups of a direction let transfer, reading the saved session once.
|
|
821
|
+
*/
|
|
822
|
+
var TransferGate = class {
|
|
823
|
+
_auth;
|
|
824
|
+
_groups = null;
|
|
825
|
+
/**
|
|
826
|
+
* @param _auth - The identity provider signing the developers in, null when the configuration declares none.
|
|
827
|
+
*/
|
|
828
|
+
constructor(_auth) {
|
|
829
|
+
this._auth = _auth;
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* Explains why the developer may not transfer.
|
|
833
|
+
*
|
|
834
|
+
* @param groups - The groups allowed to transfer in that direction.
|
|
835
|
+
* @param direction - The direction.
|
|
836
|
+
* @returns Why the transfer is refused, null when it is allowed.
|
|
837
|
+
*/
|
|
838
|
+
async refusal(groups, direction) {
|
|
839
|
+
if (groups === null) return null;
|
|
840
|
+
if (groups === false) return `${direction} is disabled`;
|
|
841
|
+
const needed = `${direction} needs one of the groups ${groups.join(", ")}`;
|
|
842
|
+
if (this._auth === null) return `${needed}, and the configuration declares no auth section`;
|
|
843
|
+
const userGroups = await this.userGroups();
|
|
844
|
+
if (userGroups === null) return `${needed}: sign in with \`devtool login\``;
|
|
845
|
+
return groups.some((group) => userGroups.includes(group)) ? null : needed;
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Reads the groups of the signed-in developer.
|
|
849
|
+
*
|
|
850
|
+
* @returns The groups, null when no developer is signed in.
|
|
851
|
+
*/
|
|
852
|
+
async userGroups() {
|
|
853
|
+
const auth = this._auth;
|
|
854
|
+
this._groups ??= auth === null ? Promise.resolve(null) : sessionStatus(auth).then((status) => status.signedIn ? status.user?.groups ?? [] : null);
|
|
855
|
+
return this._groups;
|
|
856
|
+
}
|
|
857
|
+
};
|
|
767
858
|
// ../../packages/environment/lib/backends/backend.js
|
|
768
859
|
/**
|
|
769
860
|
* Reads a setting that must hold a non-blank text.
|
|
@@ -1818,7 +1909,9 @@ var ScriptsBackend = class {
|
|
|
1818
1909
|
* @returns What the command printed and its exit code.
|
|
1819
1910
|
*/
|
|
1820
1911
|
async run(operation, filePath, localFile, allowAbsent = false) {
|
|
1821
|
-
const
|
|
1912
|
+
const command = this._settings[operation];
|
|
1913
|
+
if (command === null) throw new Error(`${this._settings.slug} declares no ${operation} command`);
|
|
1914
|
+
const args = await Promise.all(command.map(async (arg) => (await this._context.resolve(arg)).replaceAll("%{ADT:PATH}", filePath).replaceAll("%{ADT:FILE}", localFile)));
|
|
1822
1915
|
const env = { ...process.env };
|
|
1823
1916
|
for (const [key, value] of Object.entries(this._settings.env)) env[key] = await this._context.resolve(value);
|
|
1824
1917
|
const cwd = path.resolve(this._context.configFolder, this._settings.cwd);
|
|
@@ -1857,7 +1950,8 @@ const scripts = {
|
|
|
1857
1950
|
readOptions(section, shared, setting) {
|
|
1858
1951
|
const problems = [];
|
|
1859
1952
|
const commands = Object.fromEntries(OPERATIONS.map((operation) => [operation, readCommand(section[operation])]));
|
|
1860
|
-
|
|
1953
|
+
const optional = new Set(shared.groups.push === false ? ["upload", "remove"] : []);
|
|
1954
|
+
for (const operation of OPERATIONS) if (commands[operation] === null && !(optional.has(operation) && section[operation] === void 0)) problems.push({
|
|
1861
1955
|
setting: `${setting}.${operation}`,
|
|
1862
1956
|
message: "must be a command: a list of texts"
|
|
1863
1957
|
});
|
|
@@ -2081,7 +2175,7 @@ const BACKEND_TYPES = {
|
|
|
2081
2175
|
/** Kinds of backend `environment.backends` accepts. */
|
|
2082
2176
|
const BACKEND_KINDS = Object.keys(BACKEND_TYPES);
|
|
2083
2177
|
/**
|
|
2084
|
-
* Reads `environment.backends`, a map of backends by name, each with its `type`, `default` and `
|
|
2178
|
+
* Reads `environment.backends`, a map of backends by name, each with its `type`, `default`, `encryption` and `groups`.
|
|
2085
2179
|
* @param section The raw `environment.backends` section.
|
|
2086
2180
|
* @returns The backends in their declaration order, the name of the default one, and the problems of the section.
|
|
2087
2181
|
*/
|
|
@@ -2124,11 +2218,17 @@ function readBackends(section) {
|
|
|
2124
2218
|
});
|
|
2125
2219
|
const { encryption, problems: encryptionProblems } = readEncryption(record.encryption, `${setting}.encryption`);
|
|
2126
2220
|
problems.push(...encryptionProblems);
|
|
2221
|
+
const { groups, problems: groupProblems } = readTransferGroups(record.groups);
|
|
2222
|
+
problems.push(...groupProblems.map((message) => ({
|
|
2223
|
+
setting: `${setting}.groups`,
|
|
2224
|
+
message
|
|
2225
|
+
})));
|
|
2127
2226
|
const shared = {
|
|
2128
2227
|
type: record.type,
|
|
2129
2228
|
slug,
|
|
2130
2229
|
default: record.default === true,
|
|
2131
|
-
encryption
|
|
2230
|
+
encryption,
|
|
2231
|
+
groups
|
|
2132
2232
|
};
|
|
2133
2233
|
const read = BACKEND_TYPES[record.type].readOptions(record, shared, setting);
|
|
2134
2234
|
problems.push(...read.problems);
|
|
@@ -2183,21 +2283,60 @@ function defaultEnvironmentFolder() {
|
|
|
2183
2283
|
function localPathOf(folder, filePath) {
|
|
2184
2284
|
return path.join(folder, filePath);
|
|
2185
2285
|
}
|
|
2286
|
+
const heldLocks = /* @__PURE__ */ new Set();
|
|
2287
|
+
/**
|
|
2288
|
+
* Runs a task while holding a lock file, created exclusively and holding the identifier of the
|
|
2289
|
+
* holding process: the task is refused while this process or another one holds the lock. A lock
|
|
2290
|
+
* left by a process stopped abruptly stays until it is removed, as the refusal says.
|
|
2291
|
+
*
|
|
2292
|
+
* @param lockPath - The lock file.
|
|
2293
|
+
* @param name - What the lock protects, for the error message.
|
|
2294
|
+
* @param task - The task.
|
|
2295
|
+
* @returns What the task returns.
|
|
2296
|
+
*/
|
|
2297
|
+
async function withFileLock(lockPath, name, task) {
|
|
2298
|
+
if (heldLocks.has(lockPath)) throw new Error(`${name} is being transferred: try again once it ends`);
|
|
2299
|
+
heldLocks.add(lockPath);
|
|
2300
|
+
try {
|
|
2301
|
+
await fs.mkdir(path.dirname(lockPath), {
|
|
2302
|
+
recursive: true,
|
|
2303
|
+
mode: 448
|
|
2304
|
+
});
|
|
2305
|
+
await fs.writeFile(lockPath, String(process.pid), {
|
|
2306
|
+
flag: "wx",
|
|
2307
|
+
mode: 384
|
|
2308
|
+
});
|
|
2309
|
+
} catch (error) {
|
|
2310
|
+
heldLocks.delete(lockPath);
|
|
2311
|
+
if (error.code !== "EEXIST") throw error;
|
|
2312
|
+
const holder = (await fs.readFile(lockPath, "utf-8").catch(() => "")).trim();
|
|
2313
|
+
throw new Error(`${name} is in use by another process${holder === "" ? "" : ` (${holder})`}: try again once it ends, or remove ${lockPath} if none runs`, { cause: error });
|
|
2314
|
+
}
|
|
2315
|
+
try {
|
|
2316
|
+
return await task();
|
|
2317
|
+
} finally {
|
|
2318
|
+
await fs.rm(lockPath, { force: true }).finally(() => heldLocks.delete(lockPath));
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2186
2321
|
/**
|
|
2187
|
-
* Writes a local file readable by the current user only, replaced only once fully written
|
|
2322
|
+
* Writes a local file readable by the current user only, replaced only once fully written; a
|
|
2323
|
+
* stream content is closed when the file cannot be written.
|
|
2188
2324
|
*
|
|
2189
2325
|
* @param localPath - The file.
|
|
2190
2326
|
* @param content - Its content, as text, bytes or a stream.
|
|
2191
2327
|
*/
|
|
2192
2328
|
async function writeLocalFile(localPath, content) {
|
|
2193
|
-
await fs.mkdir(path.dirname(localPath), {
|
|
2194
|
-
recursive: true,
|
|
2195
|
-
mode: 448
|
|
2196
|
-
});
|
|
2197
2329
|
const partialPath = `${localPath}.part`;
|
|
2198
2330
|
try {
|
|
2331
|
+
await fs.mkdir(path.dirname(localPath), {
|
|
2332
|
+
recursive: true,
|
|
2333
|
+
mode: 448
|
|
2334
|
+
});
|
|
2199
2335
|
await fs.writeFile(partialPath, content, { mode: 384 });
|
|
2200
2336
|
await fs.rename(partialPath, localPath);
|
|
2337
|
+
} catch (error) {
|
|
2338
|
+
if (content instanceof Readable) content.destroy();
|
|
2339
|
+
throw error;
|
|
2201
2340
|
} finally {
|
|
2202
2341
|
await fs.rm(partialPath, { force: true });
|
|
2203
2342
|
}
|
|
@@ -2258,6 +2397,16 @@ var ArchiveWriter = class {
|
|
|
2258
2397
|
}
|
|
2259
2398
|
};
|
|
2260
2399
|
/**
|
|
2400
|
+
* Passes a stream through a transform, an error of either side failing the result.
|
|
2401
|
+
*
|
|
2402
|
+
* @param source - The stream.
|
|
2403
|
+
* @param transform - The transform, such as a compression.
|
|
2404
|
+
* @returns The transformed stream.
|
|
2405
|
+
*/
|
|
2406
|
+
function transformed(source, transform) {
|
|
2407
|
+
return pipeline$1(Readable.from(source), transform, () => void 0);
|
|
2408
|
+
}
|
|
2409
|
+
/**
|
|
2261
2410
|
* Reads lines and exact byte counts from a stream of chunks.
|
|
2262
2411
|
*/
|
|
2263
2412
|
var BufferedReader = class {
|
|
@@ -2379,6 +2528,138 @@ async function* readArchive(filePath) {
|
|
|
2379
2528
|
source.destroy();
|
|
2380
2529
|
}
|
|
2381
2530
|
}
|
|
2531
|
+
// ../../packages/environment/lib/tar.js
|
|
2532
|
+
const REGULAR_TYPES = /* @__PURE__ */ new Set(["file", "contiguous-file"]);
|
|
2533
|
+
const BLOCK_BYTES = 512;
|
|
2534
|
+
const END_BYTES = 2 * BLOCK_BYTES;
|
|
2535
|
+
/**
|
|
2536
|
+
* Strips the `./` the tar command writes before each path of an archive of a folder.
|
|
2537
|
+
*
|
|
2538
|
+
* @param name - The path in the archive.
|
|
2539
|
+
* @returns The path relative to the archived folder.
|
|
2540
|
+
*/
|
|
2541
|
+
function relativeName(name) {
|
|
2542
|
+
return name.startsWith("./") ? name.slice(2) : name;
|
|
2543
|
+
}
|
|
2544
|
+
/**
|
|
2545
|
+
* Tells why the devtool cannot read an entry of an archive.
|
|
2546
|
+
*
|
|
2547
|
+
* @param header - The header of the entry.
|
|
2548
|
+
* @returns Why the entry is refused, null when it is read or skipped.
|
|
2549
|
+
*/
|
|
2550
|
+
function unsupported(header) {
|
|
2551
|
+
if (!header.type) return "an entry of an unknown type";
|
|
2552
|
+
if (!REGULAR_TYPES.has(header.type) && header.type !== "directory") return `a ${header.type}`;
|
|
2553
|
+
const pax = typeof header.pax === "object" && header.pax !== null ? header.pax : {};
|
|
2554
|
+
if (pax.size !== void 0 && !(typeof pax.size === "string" && /^\d+$/.test(pax.size))) return `an entry of an invalid size ${typeof pax.size === "string" ? pax.size : JSON.stringify(pax.size)}`;
|
|
2555
|
+
if (!Number.isSafeInteger(header.size) || header.size < 0) return `an entry of an invalid size ${String(header.size)}`;
|
|
2556
|
+
return Object.keys(pax).some((key) => key.startsWith("GNU.sparse.")) ? "a sparse file" : null;
|
|
2557
|
+
}
|
|
2558
|
+
/**
|
|
2559
|
+
* Gives the offset in an archive just after the padded body of an entry.
|
|
2560
|
+
*
|
|
2561
|
+
* @param header - The header of the entry, with the offset of its body.
|
|
2562
|
+
* @returns The offset.
|
|
2563
|
+
*/
|
|
2564
|
+
function entryEnd(header) {
|
|
2565
|
+
const { byteOffset } = header;
|
|
2566
|
+
if (typeof byteOffset !== "number" || !Number.isSafeInteger(byteOffset)) throw new Error("the tar reader gives no offset of the entries");
|
|
2567
|
+
const size = header.type === "directory" ? 0 : header.size;
|
|
2568
|
+
return byteOffset + Math.ceil(size / BLOCK_BYTES) * BLOCK_BYTES;
|
|
2569
|
+
}
|
|
2570
|
+
/**
|
|
2571
|
+
* Reads the regular files of a tar archive, folders being skipped and any other entry refused. After
|
|
2572
|
+
* the body of its last entry, the archive must hold its two empty blocks and nothing but zero bytes:
|
|
2573
|
+
* one that stops before, or ends with a header of no entry, is refused once its last entry is read.
|
|
2574
|
+
*
|
|
2575
|
+
* @param source - The uncompressed archive.
|
|
2576
|
+
* @returns The files, in their order in the archive.
|
|
2577
|
+
*/
|
|
2578
|
+
async function* readTar(source) {
|
|
2579
|
+
let received = 0;
|
|
2580
|
+
let lastNonZero = -1;
|
|
2581
|
+
let lastEnd = 0;
|
|
2582
|
+
const watched = async function* () {
|
|
2583
|
+
for await (const chunk of source) {
|
|
2584
|
+
for (let index = chunk.length - 1; index >= 0; index -= 1) if (chunk[index] !== 0) {
|
|
2585
|
+
lastNonZero = received + index;
|
|
2586
|
+
break;
|
|
2587
|
+
}
|
|
2588
|
+
received += chunk.length;
|
|
2589
|
+
yield chunk;
|
|
2590
|
+
}
|
|
2591
|
+
};
|
|
2592
|
+
const input = Readable.from(watched());
|
|
2593
|
+
const extractor = extract();
|
|
2594
|
+
input.on("error", (error) => extractor.destroy(error));
|
|
2595
|
+
input.pipe(extractor);
|
|
2596
|
+
try {
|
|
2597
|
+
for await (const entry of extractor) {
|
|
2598
|
+
const name = relativeName(entry.header.name);
|
|
2599
|
+
const refusal = unsupported(entry.header);
|
|
2600
|
+
if (refusal !== null) throw new Error(`${name} is ${refusal}, which the devtool does not read`);
|
|
2601
|
+
lastEnd = entryEnd(entry.header);
|
|
2602
|
+
if (REGULAR_TYPES.has(entry.header.type) && name !== "") yield {
|
|
2603
|
+
name,
|
|
2604
|
+
size: entry.header.size,
|
|
2605
|
+
body: entry
|
|
2606
|
+
};
|
|
2607
|
+
entry.resume();
|
|
2608
|
+
}
|
|
2609
|
+
if (received - lastEnd < END_BYTES || lastNonZero >= lastEnd) throw new Error("not a complete tar archive: it does not end with its two empty blocks");
|
|
2610
|
+
} finally {
|
|
2611
|
+
input.destroy();
|
|
2612
|
+
extractor.destroy();
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
/**
|
|
2616
|
+
* Adds a file to an archive being written, its body closed when the archive fails or closes first.
|
|
2617
|
+
*
|
|
2618
|
+
* @param packer - The archive.
|
|
2619
|
+
* @param entry - The file; its body must hold exactly `size` bytes.
|
|
2620
|
+
*/
|
|
2621
|
+
async function addEntry(packer, { name, size, mtime, body }) {
|
|
2622
|
+
const input = Readable.from(body);
|
|
2623
|
+
await new Promise((resolve, reject) => {
|
|
2624
|
+
const settle = (error) => {
|
|
2625
|
+
packer.off("close", closed);
|
|
2626
|
+
if (error) {
|
|
2627
|
+
input.destroy();
|
|
2628
|
+
reject(error);
|
|
2629
|
+
} else resolve();
|
|
2630
|
+
};
|
|
2631
|
+
const closed = () => settle(/* @__PURE__ */ new Error("the archive was closed while it was written"));
|
|
2632
|
+
packer.once("close", closed);
|
|
2633
|
+
const sink = packer.entry({
|
|
2634
|
+
name: `./${name}`,
|
|
2635
|
+
size,
|
|
2636
|
+
mtime
|
|
2637
|
+
}, settle);
|
|
2638
|
+
sink.on("error", settle);
|
|
2639
|
+
input.on("error", settle);
|
|
2640
|
+
input.pipe(sink);
|
|
2641
|
+
});
|
|
2642
|
+
}
|
|
2643
|
+
/**
|
|
2644
|
+
* Writes a tar archive of files, each path behind `./` as the tar command writes those of a folder;
|
|
2645
|
+
* nothing is read before the archive is.
|
|
2646
|
+
*
|
|
2647
|
+
* @param entries - The files; each body must hold exactly `size` bytes.
|
|
2648
|
+
* @returns The uncompressed archive.
|
|
2649
|
+
*/
|
|
2650
|
+
async function* writeTar(entries) {
|
|
2651
|
+
const packer = pack();
|
|
2652
|
+
const fill = async () => {
|
|
2653
|
+
for await (const entry of entries) await addEntry(packer, entry);
|
|
2654
|
+
packer.finalize();
|
|
2655
|
+
};
|
|
2656
|
+
fill().catch((error) => packer.destroy(error instanceof Error ? error : new Error(String(error))));
|
|
2657
|
+
try {
|
|
2658
|
+
yield* packer;
|
|
2659
|
+
} finally {
|
|
2660
|
+
packer.destroy();
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2382
2663
|
// ../../packages/environment/lib/buckets.js
|
|
2383
2664
|
/**
|
|
2384
2665
|
* Creates a client of the local S3 server.
|
|
@@ -2419,80 +2700,217 @@ async function* listObjects(client, bucket) {
|
|
|
2419
2700
|
} while (token !== void 0);
|
|
2420
2701
|
}
|
|
2421
2702
|
/**
|
|
2422
|
-
*
|
|
2703
|
+
* Reads every object of a bucket, one at a time, failing on a key a snapshot could not be restored
|
|
2704
|
+
* under.
|
|
2423
2705
|
*
|
|
2424
2706
|
* @param client - The S3 client.
|
|
2425
2707
|
* @param bucket - The bucket.
|
|
2426
|
-
* @
|
|
2427
|
-
* @returns The number of objects.
|
|
2708
|
+
* @returns The objects; each body must be read before the next object is.
|
|
2428
2709
|
*/
|
|
2429
|
-
async function
|
|
2430
|
-
let count = 0;
|
|
2710
|
+
async function* readObjects(client, bucket) {
|
|
2431
2711
|
for await (const { key } of listObjects(client, bucket)) {
|
|
2712
|
+
storableKey(key);
|
|
2432
2713
|
const object = await client.send(new GetObjectCommand({
|
|
2433
2714
|
Bucket: bucket,
|
|
2434
2715
|
Key: key
|
|
2435
2716
|
}));
|
|
2717
|
+
yield {
|
|
2718
|
+
key,
|
|
2719
|
+
size: object.ContentLength ?? 0,
|
|
2720
|
+
contentType: object.ContentType,
|
|
2721
|
+
lastModified: object.LastModified,
|
|
2722
|
+
body: object.Body
|
|
2723
|
+
};
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
/**
|
|
2727
|
+
* Writes every object of a bucket to an archive, one record per object with its media type.
|
|
2728
|
+
*
|
|
2729
|
+
* @param client - The S3 client.
|
|
2730
|
+
* @param bucket - The bucket.
|
|
2731
|
+
* @param archive - The archive being written.
|
|
2732
|
+
* @returns The number of objects.
|
|
2733
|
+
*/
|
|
2734
|
+
async function snapshotBucket(client, bucket, archive) {
|
|
2735
|
+
let count = 0;
|
|
2736
|
+
for await (const { key, size, contentType, body } of readObjects(client, bucket)) {
|
|
2436
2737
|
await archive.add({
|
|
2437
2738
|
type: "object",
|
|
2438
2739
|
key,
|
|
2439
|
-
contentType:
|
|
2440
|
-
size
|
|
2441
|
-
},
|
|
2740
|
+
contentType: contentType ?? "application/octet-stream",
|
|
2741
|
+
size
|
|
2742
|
+
}, body);
|
|
2442
2743
|
count += 1;
|
|
2443
2744
|
}
|
|
2444
2745
|
return count;
|
|
2445
2746
|
}
|
|
2446
2747
|
/**
|
|
2447
|
-
*
|
|
2748
|
+
* Writes every object of a bucket to a gzip-compressed tar file, the key of each object being its
|
|
2749
|
+
* path in the archive.
|
|
2750
|
+
*
|
|
2751
|
+
* @param client - The S3 client.
|
|
2752
|
+
* @param bucket - The bucket.
|
|
2753
|
+
* @param filePath - The local file, replaced once fully written.
|
|
2754
|
+
* @returns The number of objects.
|
|
2755
|
+
*/
|
|
2756
|
+
async function snapshotBucketTar(client, bucket, filePath) {
|
|
2757
|
+
let count = 0;
|
|
2758
|
+
const entries = async function* () {
|
|
2759
|
+
for await (const { key, size, lastModified, body } of readObjects(client, bucket)) {
|
|
2760
|
+
count += 1;
|
|
2761
|
+
yield {
|
|
2762
|
+
name: key,
|
|
2763
|
+
size,
|
|
2764
|
+
mtime: lastModified,
|
|
2765
|
+
body
|
|
2766
|
+
};
|
|
2767
|
+
}
|
|
2768
|
+
};
|
|
2769
|
+
await writeLocalFile(filePath, transformed(writeTar(entries()), createGzip()));
|
|
2770
|
+
return count;
|
|
2771
|
+
}
|
|
2772
|
+
/**
|
|
2773
|
+
* Checks that an S3 server stores an object under the key it is given: an empty key, or a key with
|
|
2774
|
+
* an empty segment other than a final slash, or a `.` or `..` segment, spaces around it or not, may
|
|
2775
|
+
* be stored under another key or refused.
|
|
2776
|
+
*
|
|
2777
|
+
* @param key - The key.
|
|
2778
|
+
* @returns The key.
|
|
2779
|
+
*/
|
|
2780
|
+
function storableKey(key) {
|
|
2781
|
+
const segments = key.split("/");
|
|
2782
|
+
const rewritten = segments.some((segment, index) => [".", ".."].includes(segment.trim()) || segment === "" && index < segments.length - 1);
|
|
2783
|
+
if (key === "" || rewritten) throw new Error(`the object key "${key}" could be stored under another key: write keys without empty, . or .. segments`);
|
|
2784
|
+
return key;
|
|
2785
|
+
}
|
|
2786
|
+
/**
|
|
2787
|
+
* Reads the objects of the records of a bucket snapshot.
|
|
2788
|
+
*
|
|
2789
|
+
* @param records - The records.
|
|
2790
|
+
* @returns The objects.
|
|
2791
|
+
*/
|
|
2792
|
+
async function* objectsOfArchive(records) {
|
|
2793
|
+
for await (const { header, body } of records) {
|
|
2794
|
+
if (header.type !== "object" || typeof header.key !== "string" || typeof header.size !== "number") throw new Error("not a bucket snapshot");
|
|
2795
|
+
yield {
|
|
2796
|
+
key: storableKey(header.key),
|
|
2797
|
+
size: header.size,
|
|
2798
|
+
contentType: typeof header.contentType === "string" ? header.contentType : void 0,
|
|
2799
|
+
body
|
|
2800
|
+
};
|
|
2801
|
+
}
|
|
2802
|
+
}
|
|
2803
|
+
/**
|
|
2804
|
+
* Reads the files of a gzip-compressed tar archive as objects, their media type guessed from their name.
|
|
2805
|
+
*
|
|
2806
|
+
* @param archive - The archive.
|
|
2807
|
+
* @returns The objects, keyed by their path in the archive.
|
|
2808
|
+
*/
|
|
2809
|
+
async function* objectsOfTar(archive) {
|
|
2810
|
+
for await (const { name, size, body } of readTar(transformed(archive, createGunzip()))) yield {
|
|
2811
|
+
key: storableKey(name),
|
|
2812
|
+
size,
|
|
2813
|
+
contentType: mime.lookup(name) || "application/octet-stream",
|
|
2814
|
+
body
|
|
2815
|
+
};
|
|
2816
|
+
}
|
|
2817
|
+
/**
|
|
2818
|
+
* Reads a whole gzip-compressed tar archive of objects, failing when it is truncated or corrupted.
|
|
2819
|
+
*
|
|
2820
|
+
* @param archive - The archive.
|
|
2821
|
+
*/
|
|
2822
|
+
async function checkTar(archive) {
|
|
2823
|
+
for await (const { body } of objectsOfTar(archive)) for await (const chunk of body);
|
|
2824
|
+
}
|
|
2825
|
+
/**
|
|
2826
|
+
* Replaces the content of a bucket, created when missing, by some objects: every object is stored
|
|
2827
|
+
* first, then the objects the bucket held before and that are not among them are deleted, so a
|
|
2828
|
+
* failure deletes nothing, though objects already stored hold their new content.
|
|
2448
2829
|
*
|
|
2449
2830
|
* @param client - The S3 client.
|
|
2450
2831
|
* @param bucket - The bucket.
|
|
2451
|
-
* @param
|
|
2452
|
-
* @returns The number of objects restored.
|
|
2832
|
+
* @param objects - The objects.
|
|
2833
|
+
* @returns The number of objects the bucket holds once restored.
|
|
2453
2834
|
*/
|
|
2454
|
-
async function restoreBucket(client, bucket,
|
|
2835
|
+
async function restoreBucket(client, bucket, objects) {
|
|
2455
2836
|
try {
|
|
2456
2837
|
await client.send(new HeadBucketCommand({ Bucket: bucket }));
|
|
2457
2838
|
} catch {
|
|
2458
2839
|
await client.send(new CreateBucketCommand({ Bucket: bucket }));
|
|
2459
2840
|
}
|
|
2460
|
-
const
|
|
2461
|
-
for await (const { key } of listObjects(client, bucket))
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
await client.send(new
|
|
2841
|
+
const held = [];
|
|
2842
|
+
for await (const { key } of listObjects(client, bucket)) held.push(key);
|
|
2843
|
+
const restored = /* @__PURE__ */ new Set();
|
|
2844
|
+
for await (const { key, size, contentType, body } of objects) {
|
|
2845
|
+
await client.send(new PutObjectCommand({
|
|
2846
|
+
Bucket: bucket,
|
|
2847
|
+
Key: key,
|
|
2848
|
+
Body: Readable.from(body, { objectMode: false }),
|
|
2849
|
+
ContentLength: size,
|
|
2850
|
+
ContentType: contentType
|
|
2851
|
+
}));
|
|
2852
|
+
restored.add(key);
|
|
2853
|
+
}
|
|
2854
|
+
const stale = held.filter((key) => !restored.has(key));
|
|
2855
|
+
for (let start = 0; start < stale.length; start += 1e3) {
|
|
2856
|
+
const batch = stale.slice(start, start + 1e3).map((Key) => ({ Key }));
|
|
2857
|
+
const { Errors: errors = [] } = await client.send(new DeleteObjectsCommand({
|
|
2465
2858
|
Bucket: bucket,
|
|
2466
2859
|
Delete: {
|
|
2467
2860
|
Objects: batch,
|
|
2468
2861
|
Quiet: true
|
|
2469
2862
|
}
|
|
2470
2863
|
}));
|
|
2864
|
+
if (errors.length > 0) throw new Error(`objects the snapshot does not hold could not be deleted: ${errors.map((error) => `${error.Key} (${error.Message ?? error.Code})`).join(", ")}`);
|
|
2471
2865
|
}
|
|
2472
|
-
|
|
2473
|
-
for await (const { header, body } of records) {
|
|
2474
|
-
if (header.type !== "object" || typeof header.key !== "string" || typeof header.size !== "number") throw new Error("not a bucket snapshot");
|
|
2475
|
-
await client.send(new PutObjectCommand({
|
|
2476
|
-
Bucket: bucket,
|
|
2477
|
-
Key: header.key,
|
|
2478
|
-
Body: Readable.from(body, { objectMode: false }),
|
|
2479
|
-
ContentLength: header.size,
|
|
2480
|
-
ContentType: typeof header.contentType === "string" ? header.contentType : void 0
|
|
2481
|
-
}));
|
|
2482
|
-
count += 1;
|
|
2483
|
-
}
|
|
2484
|
-
return count;
|
|
2866
|
+
return restored.size;
|
|
2485
2867
|
}
|
|
2486
2868
|
// ../../packages/environment/lib/engines.js
|
|
2869
|
+
const MONGODUMP_MAGIC = Buffer.from([
|
|
2870
|
+
109,
|
|
2871
|
+
226,
|
|
2872
|
+
153,
|
|
2873
|
+
129
|
|
2874
|
+
]);
|
|
2875
|
+
const MONGODUMP_TERMINATOR = -1;
|
|
2876
|
+
const BSON_MIN_DOCUMENT_BYTES = 5;
|
|
2877
|
+
const BSON_MAX_DOCUMENT_BYTES = 16793600;
|
|
2878
|
+
const SQL_LINE_HEAD_BYTES = 64;
|
|
2879
|
+
const SQL_DATABASE_STATEMENT = /^\s*(?:\/\*M?!\d+\s+)?(?:USE[\s`]|(?:CREATE(?:\s+OR\s+REPLACE)?|DROP)\s+(?:DATABASE|SCHEMA)\b)/i;
|
|
2880
|
+
const SQL_DELIMITER_LINE = /^DELIMITER\s+(\S+)/i;
|
|
2881
|
+
/**
|
|
2882
|
+
* Beginning of the scripts restoring an archive, after the setup of their engine: the archive is
|
|
2883
|
+
* read on the standard input into the file `$ARCHIVE`, removed at exit by `cleanup`, and the script
|
|
2884
|
+
* stops before changing anything unless the file holds the number of bytes given as first argument.
|
|
2885
|
+
* `leftover` reports what could not be cleaned up on both outputs, the standard output being read
|
|
2886
|
+
* when the script succeeds and the error output when it fails.
|
|
2887
|
+
*/
|
|
2888
|
+
const RECEIVE_ARCHIVE = `ARCHIVE=$(mktemp)
|
|
2889
|
+
leftover() {
|
|
2890
|
+
echo "$1"
|
|
2891
|
+
echo "$1" >&2
|
|
2892
|
+
}
|
|
2893
|
+
cleanup() { rm -f "$ARCHIVE"; }
|
|
2894
|
+
trap cleanup EXIT
|
|
2895
|
+
cat > "$ARCHIVE"
|
|
2896
|
+
[ "$(wc -c < "$ARCHIVE")" -eq "$1" ] || { echo "the archive was not received whole: nothing was changed" >&2; exit 1; }
|
|
2897
|
+
shift
|
|
2898
|
+
`;
|
|
2899
|
+
/**
|
|
2900
|
+
* Script line setting `$SUFFIX` to 16 random hexadecimal digits, naming the databases a script
|
|
2901
|
+
* creates for itself.
|
|
2902
|
+
*/
|
|
2903
|
+
const UNIQUE_SUFFIX = `SUFFIX=$(od -An -N8 -tx1 /dev/urandom | tr -d ' \\n')
|
|
2904
|
+
`;
|
|
2487
2905
|
/**
|
|
2488
|
-
* Keeps the end of
|
|
2906
|
+
* Keeps the end of an output of a process.
|
|
2489
2907
|
*
|
|
2490
|
-
* @param
|
|
2908
|
+
* @param output - The output.
|
|
2491
2909
|
* @returns A function giving the collected text.
|
|
2492
2910
|
*/
|
|
2493
|
-
function
|
|
2911
|
+
function collectTail(output) {
|
|
2494
2912
|
let tail = "";
|
|
2495
|
-
|
|
2913
|
+
output?.on("data", (chunk) => {
|
|
2496
2914
|
tail = (tail + chunk.toString("utf-8")).slice(-4096);
|
|
2497
2915
|
});
|
|
2498
2916
|
return () => tail.trim();
|
|
@@ -2509,28 +2927,43 @@ async function assertExit(child, errors, label) {
|
|
|
2509
2927
|
if (code !== 0) throw new Error(`${label} failed (exit ${code}): ${errors()}`);
|
|
2510
2928
|
}
|
|
2511
2929
|
/**
|
|
2512
|
-
*
|
|
2930
|
+
* Builds the arguments of `docker exec` running a shell script in the container of a database,
|
|
2931
|
+
* the script reading the name of the database, when given, as `$ADT_DATABASE`.
|
|
2513
2932
|
*
|
|
2514
|
-
* @param
|
|
2933
|
+
* @param target - The database.
|
|
2934
|
+
* @param interactive - Whether the script reads its standard input.
|
|
2515
2935
|
* @param script - The script, reading its arguments as `$1`, `$2`...
|
|
2516
2936
|
* @param args - The arguments of the script.
|
|
2517
|
-
* @returns The
|
|
2937
|
+
* @returns The arguments of `docker`.
|
|
2518
2938
|
*/
|
|
2519
|
-
|
|
2520
|
-
|
|
2939
|
+
function dockerExec(target, interactive, script, args) {
|
|
2940
|
+
return [
|
|
2521
2941
|
"exec",
|
|
2522
|
-
|
|
2942
|
+
...interactive ? ["-i"] : [],
|
|
2943
|
+
...target.database === null ? [] : ["-e", `ADT_DATABASE=${target.database}`],
|
|
2944
|
+
target.container,
|
|
2523
2945
|
"sh",
|
|
2524
2946
|
"-c",
|
|
2525
2947
|
script,
|
|
2526
2948
|
"sh",
|
|
2527
2949
|
...args
|
|
2528
|
-
]
|
|
2950
|
+
];
|
|
2951
|
+
}
|
|
2952
|
+
/**
|
|
2953
|
+
* Runs a shell script in a container, streaming its output.
|
|
2954
|
+
*
|
|
2955
|
+
* @param target - The database whose container runs the script.
|
|
2956
|
+
* @param script - The script, reading its arguments as `$1`, `$2`...
|
|
2957
|
+
* @param args - The arguments of the script.
|
|
2958
|
+
* @returns The output, failing at its end when the script failed.
|
|
2959
|
+
*/
|
|
2960
|
+
async function* scriptOutput(target, script, args = []) {
|
|
2961
|
+
const child = spawn("docker", dockerExec(target, false, script, args), { stdio: [
|
|
2529
2962
|
"ignore",
|
|
2530
2963
|
"pipe",
|
|
2531
2964
|
"pipe"
|
|
2532
2965
|
] });
|
|
2533
|
-
const exited = assertExit(child,
|
|
2966
|
+
const exited = assertExit(child, collectTail(child.stderr), `docker exec ${target.container}`);
|
|
2534
2967
|
exited.catch(() => void 0);
|
|
2535
2968
|
try {
|
|
2536
2969
|
for await (const chunk of child.stdout) yield chunk;
|
|
@@ -2542,43 +2975,61 @@ async function* scriptOutput(container, script, args = []) {
|
|
|
2542
2975
|
/**
|
|
2543
2976
|
* Runs a shell script in a container and reads its whole output.
|
|
2544
2977
|
*
|
|
2545
|
-
* @param
|
|
2978
|
+
* @param target - The database whose container runs the script.
|
|
2546
2979
|
* @param script - The script.
|
|
2547
2980
|
* @returns The output text.
|
|
2548
2981
|
*/
|
|
2549
|
-
async function scriptText(
|
|
2982
|
+
async function scriptText(target, script) {
|
|
2550
2983
|
const chunks = [];
|
|
2551
|
-
for await (const chunk of scriptOutput(
|
|
2984
|
+
for await (const chunk of scriptOutput(target, script)) chunks.push(chunk);
|
|
2552
2985
|
return Buffer.concat(chunks).toString("utf-8");
|
|
2553
2986
|
}
|
|
2554
2987
|
/**
|
|
2555
2988
|
* Runs a shell script in a container with an input.
|
|
2556
2989
|
*
|
|
2557
|
-
* @param
|
|
2990
|
+
* @param target - The database whose container runs the script.
|
|
2558
2991
|
* @param script - The script, reading its arguments as `$1`, `$2`...
|
|
2559
2992
|
* @param input - The standard input of the script.
|
|
2560
2993
|
* @param args - The arguments of the script.
|
|
2994
|
+
* @returns What the script wrote on its standard output, trimmed.
|
|
2561
2995
|
*/
|
|
2562
|
-
async function scriptInput(
|
|
2563
|
-
const child = spawn("docker", [
|
|
2564
|
-
"
|
|
2565
|
-
"-i",
|
|
2566
|
-
container,
|
|
2567
|
-
"sh",
|
|
2568
|
-
"-c",
|
|
2569
|
-
script,
|
|
2570
|
-
"sh",
|
|
2571
|
-
...args
|
|
2572
|
-
], { stdio: [
|
|
2996
|
+
async function scriptInput(target, script, input, args = []) {
|
|
2997
|
+
const child = spawn("docker", dockerExec(target, true, script, args), { stdio: [
|
|
2998
|
+
"pipe",
|
|
2573
2999
|
"pipe",
|
|
2574
|
-
"ignore",
|
|
2575
3000
|
"pipe"
|
|
2576
3001
|
] });
|
|
2577
|
-
const errors =
|
|
3002
|
+
const errors = collectTail(child.stderr);
|
|
3003
|
+
const report = collectTail(child.stdout);
|
|
2578
3004
|
const piped = pipeline(Readable.from(input), child.stdin).then(() => null, (error) => error instanceof Error ? error : new Error(String(error)));
|
|
2579
|
-
await assertExit(child, errors, `docker exec ${container}`);
|
|
3005
|
+
await assertExit(child, errors, `docker exec ${target.container}`);
|
|
2580
3006
|
const pipeError = await piped;
|
|
2581
3007
|
if (pipeError) throw pipeError;
|
|
3008
|
+
return report();
|
|
3009
|
+
}
|
|
3010
|
+
/**
|
|
3011
|
+
* Fails on an empty list of tables, which would select every table of an archive: a whole restore
|
|
3012
|
+
* is asked for with null.
|
|
3013
|
+
*
|
|
3014
|
+
* @param tables - The tables to restore, or null for the whole database.
|
|
3015
|
+
*/
|
|
3016
|
+
function assertTablesChosen(tables) {
|
|
3017
|
+
if (tables?.length === 0) throw new Error("no table chosen: restore the whole database, or name some tables");
|
|
3018
|
+
}
|
|
3019
|
+
/**
|
|
3020
|
+
* Uncompresses a gzip-compressed archive, failing with a message naming the expected format when
|
|
3021
|
+
* the archive is not one, or is cut.
|
|
3022
|
+
*
|
|
3023
|
+
* @param archive - The archive.
|
|
3024
|
+
* @returns Its uncompressed bytes.
|
|
3025
|
+
*/
|
|
3026
|
+
async function* gunzipped(archive) {
|
|
3027
|
+
try {
|
|
3028
|
+
yield* transformed(archive, createGunzip());
|
|
3029
|
+
} catch (error) {
|
|
3030
|
+
if (error instanceof Error && "code" in error && typeof error.code === "string" && error.code.startsWith("Z_")) throw new Error(`not a complete gzip-compressed archive (${error.message})`, { cause: error });
|
|
3031
|
+
throw error;
|
|
3032
|
+
}
|
|
2582
3033
|
}
|
|
2583
3034
|
/**
|
|
2584
3035
|
* Puts a text before a stream.
|
|
@@ -2600,49 +3051,305 @@ async function* prefixed(prefix, body) {
|
|
|
2600
3051
|
function textStream(text) {
|
|
2601
3052
|
return Readable.from([Buffer.from(text)]);
|
|
2602
3053
|
}
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
3054
|
+
/**
|
|
3055
|
+
* Reads a whole SQL dump of one database, failing when a line of the dump starts by selecting,
|
|
3056
|
+
* creating or dropping a database, as a dump made with `--databases` does, so such a dump is refused
|
|
3057
|
+
* before the database changes. The bodies of routines, triggers and events, written between
|
|
3058
|
+
* `DELIMITER` lines, are not read, their lines being no statements of the dump. It catches that
|
|
3059
|
+
* mistake of the one dumping; a dump is trusted SQL, run with the rights of the server's root.
|
|
3060
|
+
*
|
|
3061
|
+
* @param sql - The dump, each statement starting a line.
|
|
3062
|
+
* @returns The size of the dump, in bytes.
|
|
3063
|
+
*/
|
|
3064
|
+
async function assertDatabaseLessDump(sql) {
|
|
3065
|
+
let inBody = false;
|
|
3066
|
+
const judge = (lineHead) => {
|
|
3067
|
+
const delimiter = SQL_DELIMITER_LINE.exec(lineHead);
|
|
3068
|
+
if (delimiter) inBody = delimiter[1] !== ";";
|
|
3069
|
+
else if (!inBody && SQL_DATABASE_STATEMENT.test(lineHead)) throw new Error(`the dump names its own database (${lineHead.trim().slice(0, 40)}): dump one database, without --databases`);
|
|
3070
|
+
};
|
|
3071
|
+
let size = 0;
|
|
3072
|
+
let pending = Buffer.alloc(0);
|
|
3073
|
+
let midLine = false;
|
|
3074
|
+
for await (const chunk of sql) {
|
|
3075
|
+
if (chunk.length === 0) continue;
|
|
3076
|
+
size += chunk.length;
|
|
3077
|
+
let data = chunk;
|
|
3078
|
+
let lineStart = 0;
|
|
3079
|
+
if (pending.length > 0) {
|
|
3080
|
+
data = Buffer.concat([pending, chunk]);
|
|
3081
|
+
pending = Buffer.alloc(0);
|
|
3082
|
+
} else if (midLine) {
|
|
3083
|
+
const newline = data.indexOf(10);
|
|
3084
|
+
lineStart = newline < 0 ? data.length : newline + 1;
|
|
3085
|
+
}
|
|
3086
|
+
while (lineStart < data.length) {
|
|
3087
|
+
const newline = data.indexOf(10, lineStart);
|
|
3088
|
+
const end = newline < 0 ? data.length : newline;
|
|
3089
|
+
if (newline < 0 && end - lineStart < SQL_LINE_HEAD_BYTES) {
|
|
3090
|
+
pending = Buffer.from(data.subarray(lineStart));
|
|
3091
|
+
break;
|
|
3092
|
+
}
|
|
3093
|
+
judge(data.toString("latin1", lineStart, Math.min(end, lineStart + SQL_LINE_HEAD_BYTES)));
|
|
3094
|
+
lineStart = end + 1;
|
|
3095
|
+
}
|
|
3096
|
+
midLine = pending.length === 0 && data.length > 0 && data[data.length - 1] !== 10;
|
|
3097
|
+
}
|
|
3098
|
+
judge(pending.toString("latin1"));
|
|
3099
|
+
return size;
|
|
3100
|
+
}
|
|
3101
|
+
/**
|
|
3102
|
+
* Builds the line of a script setting `$DB`, the database of the target, to the one the image
|
|
3103
|
+
* creates when the target names none.
|
|
3104
|
+
*
|
|
3105
|
+
* @param variable - The environment variable of the image naming its database.
|
|
3106
|
+
* @returns The script line.
|
|
3107
|
+
*/
|
|
3108
|
+
function databaseSetup(variable) {
|
|
3109
|
+
return `DB="\${ADT_DATABASE:-$${variable}}"
|
|
3110
|
+
[ -n "$DB" ] || { echo "no database: set database on the item or ${variable} in the container" >&2; exit 1; }
|
|
3111
|
+
`;
|
|
3112
|
+
}
|
|
3113
|
+
/**
|
|
3114
|
+
* Unquotes an identifier PostgreSQL quoted with `%I`.
|
|
3115
|
+
*
|
|
3116
|
+
* @param identifier - The identifier, quoted or not.
|
|
3117
|
+
* @returns The name.
|
|
3118
|
+
*/
|
|
3119
|
+
function unquotePostgres(identifier) {
|
|
3120
|
+
return identifier.startsWith("\"") ? identifier.slice(1, -1).replaceAll("\"\"", "\"") : identifier;
|
|
3121
|
+
}
|
|
3122
|
+
/**
|
|
3123
|
+
* Splits a `schema.table` name of PostgreSQL, each part quoted with `%I`.
|
|
3124
|
+
*
|
|
3125
|
+
* @param name - The qualified name.
|
|
3126
|
+
* @returns The schema and the table, unquoted.
|
|
3127
|
+
*/
|
|
3128
|
+
function splitPostgresName(name) {
|
|
3129
|
+
const match = /^("(?:[^"]|"")*"|[^."]*)\.("(?:[^"]|"")*"|[^."]*)$/.exec(name);
|
|
3130
|
+
if (!match) throw new Error(`not a schema.table name: ${name}`);
|
|
3131
|
+
return {
|
|
3132
|
+
schema: unquotePostgres(match[1]),
|
|
3133
|
+
table: unquotePostgres(match[2])
|
|
3134
|
+
};
|
|
3135
|
+
}
|
|
3136
|
+
/**
|
|
3137
|
+
* Prefix of the PostgreSQL scripts: `$DB`, the database, and `$CONN`, the connection string naming it
|
|
3138
|
+
* literally, whatever characters it holds.
|
|
3139
|
+
*/
|
|
3140
|
+
const POSTGRES_SETUP = `: "\${POSTGRES_USER:=postgres}"
|
|
3141
|
+
: "\${POSTGRES_DB:=$POSTGRES_USER}"
|
|
3142
|
+
${databaseSetup("POSTGRES_DB")}CONN="dbname='$(printf '%s' "$DB" | sed "s/[\\\\\\\\']/\\\\\\\\&/g")'"
|
|
3143
|
+
`;
|
|
3144
|
+
const POSTGRES_CLIENT = "psql -U \"$POSTGRES_USER\" -d \"$CONN\" -X -q -v ON_ERROR_STOP=1";
|
|
3145
|
+
/**
|
|
3146
|
+
* Builds the statements setting the sequences owned by tables, or by the tables they inherit from or
|
|
3147
|
+
* are partitions of, just after their highest value; rolled back with the transaction running them.
|
|
3148
|
+
*
|
|
3149
|
+
* @param tables - The tables, as `schema.table` identifiers, or null for every table of the database.
|
|
3150
|
+
* @returns The SQL.
|
|
3151
|
+
*/
|
|
3152
|
+
function postgresSequencesSql(tables) {
|
|
3153
|
+
const names = tables?.map((table) => `'${table.replaceAll("'", "''")}'`).join(", ");
|
|
3154
|
+
return `DO $adt$
|
|
3155
|
+
DECLARE c record; next bigint;
|
|
2606
3156
|
BEGIN
|
|
2607
3157
|
FOR c IN
|
|
2608
3158
|
SELECT a.attrelid::regclass AS rel, a.attname, pg_get_serial_sequence(a.attrelid::regclass::text, a.attname) AS seq
|
|
2609
3159
|
FROM pg_attribute a
|
|
2610
3160
|
JOIN pg_class r ON r.oid = a.attrelid
|
|
2611
3161
|
JOIN pg_namespace n ON n.oid = r.relnamespace
|
|
2612
|
-
WHERE r.relkind
|
|
3162
|
+
WHERE r.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped AND n.nspname NOT IN ('pg_catalog', 'information_schema')${tables === null ? "" : ` AND a.attrelid IN (WITH RECURSIVE lineage(rel) AS (SELECT unnest(ARRAY[${names}]::regclass[])::oid UNION SELECT i.inhparent FROM pg_inherits i JOIN lineage l ON i.inhrelid = l.rel) SELECT rel FROM lineage)`}
|
|
2613
3163
|
LOOP
|
|
2614
3164
|
IF c.seq IS NOT NULL THEN
|
|
2615
|
-
EXECUTE format('SELECT
|
|
3165
|
+
EXECUTE format('SELECT coalesce(max(%I), 0) + 1 FROM %s', c.attname, c.rel) INTO next;
|
|
3166
|
+
EXECUTE format('ALTER SEQUENCE %s RESTART WITH %s', c.seq, next);
|
|
2616
3167
|
END IF;
|
|
2617
3168
|
END LOOP;
|
|
2618
|
-
END
|
|
3169
|
+
END $adt$;
|
|
3170
|
+
`;
|
|
3171
|
+
}
|
|
3172
|
+
/**
|
|
3173
|
+
* Replaces the database by the received `pg_dump -Fc` archive: the archive is restored into a new
|
|
3174
|
+
* database of a name no database has, with the encoding, locale and owner of the database it
|
|
3175
|
+
* replaces and the privileges the archive grants, those granted to roles the server lacks being
|
|
3176
|
+
* skipped, and that database takes the place of the database once wholly
|
|
3177
|
+
* restored, in one transaction; a refused archive leaves the database as it was. Once the database
|
|
3178
|
+
* is replaced, a former copy that cannot be dropped is reported on the standard output.
|
|
3179
|
+
*/
|
|
3180
|
+
const POSTGRES_WHOLE_RESTORE = `set -e
|
|
3181
|
+
export PGOPTIONS="-c client_min_messages=warning"
|
|
3182
|
+
${UNIQUE_SUFFIX}STAGING="adt_staging_$SUFFIX"
|
|
3183
|
+
REPLACED="adt_replaced_$SUFFIX"
|
|
3184
|
+
work=$(mktemp -d)
|
|
3185
|
+
created=
|
|
3186
|
+
cleanup() {
|
|
3187
|
+
rm -rf "$ARCHIVE" "$work"
|
|
3188
|
+
[ -z "$created" ] || dropdb -U "$POSTGRES_USER" --force --if-exists "$STAGING" || leftover "the temporary database $STAGING could not be dropped: drop it by hand"
|
|
3189
|
+
}
|
|
3190
|
+
psql -U "$POSTGRES_USER" -d template1 -X -q -v ON_ERROR_STOP=1 -v staging="$STAGING" -v target="$DB" <<'SQL'
|
|
3191
|
+
SELECT coalesce(
|
|
3192
|
+
(SELECT format('CREATE DATABASE %I TEMPLATE template0 ENCODING %L LC_COLLATE %L LC_CTYPE %L OWNER %I', :'staging', pg_encoding_to_char(encoding), datcollate, datctype, pg_get_userbyid(datdba))
|
|
3193
|
+
|| CASE l->>'datlocprovider'
|
|
3194
|
+
WHEN 'i' THEN format(' LOCALE_PROVIDER icu ICU_LOCALE %L', coalesce(l->>'datlocale', l->>'daticulocale')) || coalesce(' ICU_RULES ' || quote_literal(l->>'daticurules'), '')
|
|
3195
|
+
WHEN 'b' THEN format(' LOCALE_PROVIDER builtin BUILTIN_LOCALE %L', l->>'datlocale')
|
|
3196
|
+
WHEN 'c' THEN ' LOCALE_PROVIDER libc'
|
|
3197
|
+
ELSE ''
|
|
3198
|
+
END
|
|
3199
|
+
FROM pg_database d, to_jsonb(d) l WHERE datname = :'target'),
|
|
3200
|
+
format('CREATE DATABASE %I', :'staging')
|
|
3201
|
+
) \\gexec
|
|
3202
|
+
SQL
|
|
3203
|
+
created=1
|
|
3204
|
+
pg_restore -U "$POSTGRES_USER" -d "dbname='$STAGING'" --no-owner --no-privileges --exit-on-error "$ARCHIVE"
|
|
3205
|
+
pg_restore -l "$ARCHIVE" > "$work/toc"
|
|
3206
|
+
grep -E '^[0-9]+; [0-9]+ [0-9]+ (DEFAULT )?ACL ' "$work/toc" > "$work/grants" || true
|
|
3207
|
+
if [ -s "$work/grants" ]; then
|
|
3208
|
+
pg_restore -L "$work/grants" -f "$work/grants.sql" "$ARCHIVE"
|
|
3209
|
+
psql -U "$POSTGRES_USER" -d "dbname='$STAGING'" -X -q -f "$work/grants.sql" > /dev/null 2> "$work/grants.err" || {
|
|
3210
|
+
cat "$work/grants.err" >&2
|
|
3211
|
+
exit 1
|
|
3212
|
+
}
|
|
3213
|
+
if grep 'ERROR:' "$work/grants.err" | grep -qv 'ERROR: role ".*" does not exist'; then
|
|
3214
|
+
cat "$work/grants.err" >&2
|
|
3215
|
+
echo "the privileges of the archive could not be applied: nothing was changed" >&2
|
|
3216
|
+
exit 1
|
|
3217
|
+
fi
|
|
3218
|
+
fi
|
|
3219
|
+
swapped=$(psql -U "$POSTGRES_USER" -d template1 -X -q -v ON_ERROR_STOP=1 -v staging="$STAGING" -v target="$DB" -v replaced="$REPLACED" -1 <<'SQL'
|
|
3220
|
+
SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname = :'target') AS present \\gset
|
|
3221
|
+
\\if :present
|
|
3222
|
+
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = :'target' AND pid <> pg_backend_pid() \\g /dev/null
|
|
3223
|
+
ALTER DATABASE :"target" RENAME TO :"replaced";
|
|
3224
|
+
\\echo replaced
|
|
3225
|
+
\\endif
|
|
3226
|
+
ALTER DATABASE :"staging" RENAME TO :"target";
|
|
3227
|
+
SQL
|
|
3228
|
+
)
|
|
3229
|
+
created=
|
|
3230
|
+
if [ "$swapped" = replaced ]; then
|
|
3231
|
+
dropdb -U "$POSTGRES_USER" --force "$REPLACED" 2> /dev/null || leftover "its former copy $REPLACED could not be dropped: drop it by hand"
|
|
3232
|
+
fi
|
|
3233
|
+
`;
|
|
3234
|
+
/**
|
|
3235
|
+
* Replaces the rows of some tables by those of the received `pg_dump -Fc` archive, in one
|
|
3236
|
+
* transaction, foreign keys unchecked: `$1` empties the tables, `$2` runs once their rows are loaded,
|
|
3237
|
+
* then each pair of arguments names the schema and the table of an archive entry, which must exist.
|
|
3238
|
+
*/
|
|
3239
|
+
const POSTGRES_PARTIAL_RESTORE = `set -e
|
|
3240
|
+
work=$(mktemp -d)
|
|
3241
|
+
cleanup() { rm -rf "$ARCHIVE" "$work"; }
|
|
3242
|
+
pg_restore -l "$ARCHIVE" > /dev/null
|
|
3243
|
+
before="$1"; after="$2"; shift 2
|
|
3244
|
+
: > "$work/list"
|
|
3245
|
+
while [ $# -gt 0 ]; do
|
|
3246
|
+
pg_restore -l -n "$1" -t "$2" "$ARCHIVE" > "$work/entries"
|
|
3247
|
+
grep -E '^[0-9]+; [0-9]+ [0-9]+ TABLE DATA ' "$work/entries" > "$work/entry" || true
|
|
3248
|
+
[ -s "$work/entry" ] || { echo "$1.$2 is not in the archive" >&2; exit 1; }
|
|
3249
|
+
cat "$work/entry" >> "$work/list"
|
|
3250
|
+
shift 2
|
|
3251
|
+
done
|
|
3252
|
+
pg_restore --data-only -L "$work/list" -f "$work/data.sql" "$ARCHIVE"
|
|
3253
|
+
{ printf 'SET session_replication_role = replica;\\n%s\\n' "$before"; cat "$work/data.sql"; printf '\\n%s\\n' "$after"; } | ${POSTGRES_CLIENT} -1
|
|
2619
3254
|
`;
|
|
2620
3255
|
/** PostgreSQL of the official image: local socket, credentials from the container environment. */
|
|
2621
3256
|
const postgres = {
|
|
2622
|
-
async listTables(
|
|
2623
|
-
return (await scriptText(
|
|
3257
|
+
async listTables(target) {
|
|
3258
|
+
return (await scriptText(target, `${POSTGRES_SETUP}${POSTGRES_CLIENT} -At -c "SELECT format('%I.%I', n.nspname, c.relname) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname NOT IN ('pg_catalog', 'information_schema') ORDER BY 1"`)).split("\n").filter((line) => line !== "");
|
|
2624
3259
|
},
|
|
2625
|
-
dumpSchema(
|
|
2626
|
-
return scriptOutput(
|
|
3260
|
+
dumpSchema(target) {
|
|
3261
|
+
return scriptOutput(target, `${POSTGRES_SETUP}pg_dump -U "$POSTGRES_USER" --schema-only --no-owner --no-privileges -d "$CONN"`);
|
|
2627
3262
|
},
|
|
2628
|
-
dumpTable(
|
|
2629
|
-
return scriptOutput(
|
|
3263
|
+
dumpTable(target, table) {
|
|
3264
|
+
return scriptOutput(target, `${POSTGRES_SETUP}pg_dump -U "$POSTGRES_USER" --data-only --no-owner --no-privileges -t "$1" -d "$CONN"`, [table]);
|
|
2630
3265
|
},
|
|
2631
|
-
async reset(
|
|
2632
|
-
await scriptText(
|
|
3266
|
+
async reset(target) {
|
|
3267
|
+
await scriptText(target, `${POSTGRES_SETUP}dropdb -U "$POSTGRES_USER" --force --if-exists -- "$DB" && createdb -U "$POSTGRES_USER" -- "$DB"`);
|
|
2633
3268
|
},
|
|
2634
|
-
async importSchema(
|
|
2635
|
-
await scriptInput(
|
|
3269
|
+
async importSchema(target, sql) {
|
|
3270
|
+
await scriptInput(target, `${POSTGRES_SETUP}${POSTGRES_CLIENT}`, sql);
|
|
2636
3271
|
},
|
|
2637
|
-
async importTable(
|
|
2638
|
-
const preamble = `SET session_replication_role = replica;\n${replace ? `DELETE FROM ${table};\n` : ""}`;
|
|
2639
|
-
await scriptInput(
|
|
3272
|
+
async importTable(target, table, sql, replace) {
|
|
3273
|
+
const preamble = `SET session_replication_role = replica;\n${replace ? `DELETE FROM ONLY ${table};\n` : ""}`;
|
|
3274
|
+
await scriptInput(target, `${POSTGRES_SETUP}${POSTGRES_CLIENT}`, prefixed(preamble, sql));
|
|
2640
3275
|
},
|
|
2641
|
-
async finish(
|
|
2642
|
-
await scriptInput(
|
|
3276
|
+
async finish(target) {
|
|
3277
|
+
await scriptInput(target, `${POSTGRES_SETUP}${POSTGRES_CLIENT}`, textStream(postgresSequencesSql(null)));
|
|
3278
|
+
},
|
|
3279
|
+
dumpNative(target) {
|
|
3280
|
+
return scriptOutput(target, `${POSTGRES_SETUP}pg_dump -U "$POSTGRES_USER" -Fc -d "$CONN"`);
|
|
3281
|
+
},
|
|
3282
|
+
async restoreNative(target, archivePath, tables) {
|
|
3283
|
+
assertTablesChosen(tables);
|
|
3284
|
+
const { size } = await stat(archivePath);
|
|
3285
|
+
if (tables === null) return await scriptInput(target, `${POSTGRES_SETUP}${RECEIVE_ARCHIVE}${POSTGRES_WHOLE_RESTORE}`, createReadStream(archivePath), [String(size)]) || null;
|
|
3286
|
+
const empty = tables.map((table) => `DELETE FROM ONLY ${table};`).join(" ");
|
|
3287
|
+
const selection = tables.flatMap((table) => {
|
|
3288
|
+
const { schema, table: name } = splitPostgresName(table);
|
|
3289
|
+
return [schema, name];
|
|
3290
|
+
});
|
|
3291
|
+
await scriptInput(target, `${POSTGRES_SETUP}${RECEIVE_ARCHIVE}${POSTGRES_PARTIAL_RESTORE}`, createReadStream(archivePath), [
|
|
3292
|
+
String(size),
|
|
3293
|
+
empty,
|
|
3294
|
+
postgresSequencesSql(tables),
|
|
3295
|
+
...selection
|
|
3296
|
+
]);
|
|
3297
|
+
return null;
|
|
2643
3298
|
}
|
|
2644
3299
|
};
|
|
2645
|
-
|
|
3300
|
+
/**
|
|
3301
|
+
* Prefix of the MariaDB scripts: `$DB`, the database, the root password, `$GRANTED`, the database
|
|
3302
|
+
* as a privilege target matching itself only, `empty`, dropping the database and creating it again
|
|
3303
|
+
* without table, with the options of `CREATE DATABASE` given as argument, and `grant`, giving the
|
|
3304
|
+
* account of the container, when it declares one, every privilege on the database.
|
|
3305
|
+
*/
|
|
3306
|
+
const MARIADB_SETUP = `${databaseSetup("MARIADB_DATABASE")}export MYSQL_PWD="$MARIADB_ROOT_PASSWORD"
|
|
3307
|
+
QUOTED=$(printf '%s' "$DB" | sed 's/\`/\`\`/g')
|
|
3308
|
+
GRANTED=$(printf '%s' "$QUOTED" | sed 's/[_%\\\\]/\\\\&/g')
|
|
3309
|
+
empty() {
|
|
3310
|
+
mariadb -uroot -e "DROP DATABASE IF EXISTS \\\`$QUOTED\\\`; CREATE DATABASE \\\`$QUOTED\\\`$1"
|
|
3311
|
+
}
|
|
3312
|
+
grant() {
|
|
3313
|
+
[ -z "$MARIADB_USER" ] || mariadb -uroot -e "GRANT ALL PRIVILEGES ON \\\`$GRANTED\\\`.* TO '$MARIADB_USER'@'%'"
|
|
3314
|
+
}
|
|
3315
|
+
`;
|
|
3316
|
+
/**
|
|
3317
|
+
* Replaces the database by the received SQL dump, keeping its character set and collation: the
|
|
3318
|
+
* database is saved first, and put back when the server refuses a step of the restore. The dump is
|
|
3319
|
+
* loaded in the sandbox mode of the client, without local files, so it can neither run commands nor
|
|
3320
|
+
* read files of the container. Its saved dump is kept in the container when it cannot be put back.
|
|
3321
|
+
*/
|
|
3322
|
+
const MARIADB_WHOLE_RESTORE = `saved=$(mktemp)
|
|
3323
|
+
kept=
|
|
3324
|
+
cleanup() {
|
|
3325
|
+
rm -f "$ARCHIVE"
|
|
3326
|
+
[ -n "$kept" ] || rm -f "$saved"
|
|
3327
|
+
}
|
|
3328
|
+
existed=
|
|
3329
|
+
options=
|
|
3330
|
+
if found=$(mariadb -uroot -N -B -e "USE \\\`$QUOTED\\\`; SELECT @@character_set_database, @@collation_database" 2> "$saved"); then
|
|
3331
|
+
existed=1
|
|
3332
|
+
options=" CHARACTER SET $(printf '%s' "$found" | cut -f1) COLLATE $(printf '%s' "$found" | cut -f2)"
|
|
3333
|
+
mariadb-dump -uroot --single-transaction --routines --triggers --events -- "$DB" > "$saved" || {
|
|
3334
|
+
echo "the database could not be saved before its restore, so nothing was changed: repair it, or drop it to restore the archive into a new database" >&2
|
|
3335
|
+
exit 1
|
|
3336
|
+
}
|
|
3337
|
+
elif ! grep -q '^ERROR 1049 ' "$saved"; then
|
|
3338
|
+
cat "$saved" >&2
|
|
3339
|
+
echo "the server could not tell whether the database exists: nothing was changed" >&2
|
|
3340
|
+
exit 1
|
|
3341
|
+
fi
|
|
3342
|
+
empty "$options" && grant && mariadb -uroot --sandbox --local-infile=0 -- "$DB" < "$ARCHIVE" > /dev/null && exit 0
|
|
3343
|
+
if [ -z "$existed" ]; then
|
|
3344
|
+
mariadb -uroot -e "DROP DATABASE IF EXISTS \\\`$QUOTED\\\`" && echo "the restore was refused: the database, which did not exist, was removed" >&2
|
|
3345
|
+
elif empty "$options" && mariadb -uroot -- "$DB" < "$saved" > /dev/null; then
|
|
3346
|
+
echo "the restore was refused: the database was put back as it was" >&2
|
|
3347
|
+
else
|
|
3348
|
+
kept=1
|
|
3349
|
+
echo "the restore was refused and the database could not be put back: its dump is kept in the container, in $saved" >&2
|
|
3350
|
+
fi
|
|
3351
|
+
exit 1
|
|
3352
|
+
`;
|
|
2646
3353
|
/**
|
|
2647
3354
|
* Quotes a MariaDB identifier.
|
|
2648
3355
|
*
|
|
@@ -2654,35 +3361,44 @@ function quoteMariadb(name) {
|
|
|
2654
3361
|
}
|
|
2655
3362
|
/** MariaDB of the official image: root account, credentials from the container environment. */
|
|
2656
3363
|
const mariadb = {
|
|
2657
|
-
async listTables(
|
|
2658
|
-
return (await scriptText(
|
|
3364
|
+
async listTables(target) {
|
|
3365
|
+
return (await scriptText(target, `${MARIADB_SETUP}mariadb -uroot -N -B -e "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'" -- "$DB"`)).split("\n").filter((line) => line !== "").map((line) => line.split(" ")[0]);
|
|
2659
3366
|
},
|
|
2660
|
-
dumpSchema(
|
|
2661
|
-
return scriptOutput(
|
|
3367
|
+
dumpSchema(target) {
|
|
3368
|
+
return scriptOutput(target, `${MARIADB_SETUP}mariadb-dump -uroot --no-data --routines --triggers --events --skip-comments -- "$DB"`);
|
|
2662
3369
|
},
|
|
2663
|
-
dumpTable(
|
|
2664
|
-
return scriptOutput(
|
|
3370
|
+
dumpTable(target, table) {
|
|
3371
|
+
return scriptOutput(target, `${MARIADB_SETUP}mariadb-dump -uroot --no-create-info --skip-triggers --skip-comments --single-transaction -- "$DB" "$1"`, [table]);
|
|
2665
3372
|
},
|
|
2666
|
-
async reset(
|
|
2667
|
-
await scriptText(
|
|
3373
|
+
async reset(target) {
|
|
3374
|
+
await scriptText(target, `${MARIADB_SETUP}empty && grant`);
|
|
2668
3375
|
},
|
|
2669
|
-
async importSchema(
|
|
2670
|
-
await scriptInput(
|
|
3376
|
+
async importSchema(target, sql) {
|
|
3377
|
+
await scriptInput(target, `${MARIADB_SETUP}mariadb -uroot -- "$DB"`, sql);
|
|
2671
3378
|
},
|
|
2672
|
-
async importTable(
|
|
3379
|
+
async importTable(target, table, sql, replace) {
|
|
2673
3380
|
const preamble = `SET FOREIGN_KEY_CHECKS = 0;\n${replace ? `DELETE FROM ${quoteMariadb(table)};\n` : ""}`;
|
|
2674
|
-
await scriptInput(
|
|
3381
|
+
await scriptInput(target, `${MARIADB_SETUP}mariadb -uroot -- "$DB"`, prefixed(preamble, sql));
|
|
2675
3382
|
},
|
|
2676
3383
|
finish() {
|
|
2677
3384
|
return Promise.resolve();
|
|
3385
|
+
},
|
|
3386
|
+
dumpNative(target) {
|
|
3387
|
+
return transformed(scriptOutput(target, `${MARIADB_SETUP}mariadb-dump -uroot --single-transaction --routines --triggers --events -- "$DB"`), createGzip());
|
|
3388
|
+
},
|
|
3389
|
+
async restoreNative(target, archivePath, tables) {
|
|
3390
|
+
if (tables !== null) throw new Error("a native mariadb archive is a SQL script: it restores the whole database only");
|
|
3391
|
+
const dump = () => gunzipped(createReadStream(archivePath));
|
|
3392
|
+
const size = await assertDatabaseLessDump(dump());
|
|
3393
|
+
if (size === 0) throw new Error("the archive holds an empty dump: a dump of an empty database still holds its header");
|
|
3394
|
+
return await scriptInput(target, `${MARIADB_SETUP}${RECEIVE_ARCHIVE}${MARIADB_WHOLE_RESTORE}`, dump(), [String(size)]) || null;
|
|
2678
3395
|
}
|
|
2679
3396
|
};
|
|
2680
3397
|
/**
|
|
2681
|
-
* Prefix of the MongoDB scripts: `$DB`, the database
|
|
2682
|
-
* tool with the root credentials of the container when it declares some.
|
|
3398
|
+
* Prefix of the MongoDB scripts: `$DB`, the database, exported for the scripts of the MongoDB shell,
|
|
3399
|
+
* and `auth`, running a MongoDB tool with the root credentials of the container when it declares some.
|
|
2683
3400
|
*/
|
|
2684
|
-
const MONGODB_SETUP =
|
|
2685
|
-
[ -n "$DB" ] || { echo "MONGO_INITDB_DATABASE is not set in the container" >&2; exit 1; }
|
|
3401
|
+
const MONGODB_SETUP = `${databaseSetup("MONGO_INITDB_DATABASE")}export DB
|
|
2686
3402
|
auth() {
|
|
2687
3403
|
if [ -n "$MONGO_INITDB_ROOT_USERNAME" ]; then
|
|
2688
3404
|
"$@" --username "$MONGO_INITDB_ROOT_USERNAME" --password "$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin
|
|
@@ -2692,6 +3408,153 @@ auth() {
|
|
|
2692
3408
|
}
|
|
2693
3409
|
`;
|
|
2694
3410
|
/**
|
|
3411
|
+
* Escapes the wildcards of a MongoDB namespace pattern.
|
|
3412
|
+
*
|
|
3413
|
+
* @param name - A database or collection name.
|
|
3414
|
+
* @returns The name, matching itself only.
|
|
3415
|
+
*/
|
|
3416
|
+
function escapeNamespace(name) {
|
|
3417
|
+
return name.replace(/[\\*]/g, "\\$&");
|
|
3418
|
+
}
|
|
3419
|
+
/**
|
|
3420
|
+
* Reads the string fields at the top level of a BSON document.
|
|
3421
|
+
*
|
|
3422
|
+
* @param document - The document.
|
|
3423
|
+
* @returns The values of its string fields, by name.
|
|
3424
|
+
*/
|
|
3425
|
+
function bsonStrings(document) {
|
|
3426
|
+
const fixedSizes = {
|
|
3427
|
+
1: 8,
|
|
3428
|
+
7: 12,
|
|
3429
|
+
8: 1,
|
|
3430
|
+
9: 8,
|
|
3431
|
+
10: 0,
|
|
3432
|
+
16: 4,
|
|
3433
|
+
17: 8,
|
|
3434
|
+
18: 8,
|
|
3435
|
+
19: 16
|
|
3436
|
+
};
|
|
3437
|
+
const fields = /* @__PURE__ */ new Map();
|
|
3438
|
+
const lengthAt = (at, minimum, prefix) => {
|
|
3439
|
+
const length = at + 4 <= document.length ? document.readInt32LE(at) : -1;
|
|
3440
|
+
if (length < minimum || at + prefix + length > document.length) throw new Error("not a mongodump archive: one of its documents is corrupted");
|
|
3441
|
+
return length;
|
|
3442
|
+
};
|
|
3443
|
+
let offset = 4;
|
|
3444
|
+
while (offset < document.length - 1) {
|
|
3445
|
+
const type = document[offset];
|
|
3446
|
+
const nameEnd = document.indexOf(0, offset + 1);
|
|
3447
|
+
if (nameEnd < 0) break;
|
|
3448
|
+
const name = document.toString("utf-8", offset + 1, nameEnd);
|
|
3449
|
+
offset = nameEnd + 1;
|
|
3450
|
+
if (type === 2) {
|
|
3451
|
+
const length = lengthAt(offset, 1, 4);
|
|
3452
|
+
fields.set(name, document.toString("utf-8", offset + 4, offset + 4 + length - 1));
|
|
3453
|
+
offset += 4 + length;
|
|
3454
|
+
} else if (type === 3 || type === 4) offset += lengthAt(offset, BSON_MIN_DOCUMENT_BYTES, 0);
|
|
3455
|
+
else if (type === 5) offset += 5 + lengthAt(offset, 0, 5);
|
|
3456
|
+
else if (type in fixedSizes) offset += fixedSizes[type];
|
|
3457
|
+
else break;
|
|
3458
|
+
}
|
|
3459
|
+
return fields;
|
|
3460
|
+
}
|
|
3461
|
+
/**
|
|
3462
|
+
* Reads the collections listed in the prelude of an archive of `mongodump --archive --gzip`: its
|
|
3463
|
+
* magic number, a header document, then one document per collection up to a -1 terminator.
|
|
3464
|
+
*
|
|
3465
|
+
* @param archive - The archive.
|
|
3466
|
+
* @returns The collections, with the database they were dumped from.
|
|
3467
|
+
*/
|
|
3468
|
+
async function mongodumpNamespaces(archive) {
|
|
3469
|
+
const namespaces = [];
|
|
3470
|
+
let buffer = Buffer.alloc(0);
|
|
3471
|
+
let started = false;
|
|
3472
|
+
let documents = 0;
|
|
3473
|
+
for await (const chunk of gunzipped(archive)) {
|
|
3474
|
+
buffer = buffer.length > 0 ? Buffer.concat([buffer, chunk]) : chunk;
|
|
3475
|
+
if (!started) {
|
|
3476
|
+
if (buffer.length < MONGODUMP_MAGIC.length) continue;
|
|
3477
|
+
if (!buffer.subarray(0, MONGODUMP_MAGIC.length).equals(MONGODUMP_MAGIC)) throw new Error("not a mongodump archive");
|
|
3478
|
+
buffer = buffer.subarray(MONGODUMP_MAGIC.length);
|
|
3479
|
+
started = true;
|
|
3480
|
+
}
|
|
3481
|
+
while (buffer.length >= 4) {
|
|
3482
|
+
const size = buffer.readInt32LE(0);
|
|
3483
|
+
if (size === MONGODUMP_TERMINATOR) {
|
|
3484
|
+
if (documents === 0) throw new Error("not a mongodump archive: no header");
|
|
3485
|
+
return namespaces;
|
|
3486
|
+
}
|
|
3487
|
+
if (size < BSON_MIN_DOCUMENT_BYTES || size > BSON_MAX_DOCUMENT_BYTES) throw new Error("not a mongodump archive: one of its documents is corrupted");
|
|
3488
|
+
if (buffer.length < size) break;
|
|
3489
|
+
const fields = bsonStrings(buffer.subarray(0, size));
|
|
3490
|
+
const db = fields.get("db");
|
|
3491
|
+
const collection = fields.get("collection");
|
|
3492
|
+
if (documents > 0 && db !== void 0 && collection !== void 0) namespaces.push({
|
|
3493
|
+
db,
|
|
3494
|
+
collection
|
|
3495
|
+
});
|
|
3496
|
+
documents += 1;
|
|
3497
|
+
buffer = buffer.subarray(size);
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
throw new Error("not a mongodump archive: no complete list of collections");
|
|
3501
|
+
}
|
|
3502
|
+
/**
|
|
3503
|
+
* Dumps the database as an archive of `mongodump --archive --gzip`, failing for a database without
|
|
3504
|
+
* collection, which the tool would dump as an empty archive.
|
|
3505
|
+
*/
|
|
3506
|
+
const MONGODB_DUMP = `count=$(auth mongosh --quiet --eval 'print(db.getSiblingDB(process.env.DB).getCollectionNames().length)') || exit 1
|
|
3507
|
+
[ "$count" -gt 0 ] || { echo "the database $DB has no collection: there is nothing to dump" >&2; exit 1; }
|
|
3508
|
+
auth mongodump --quiet --archive --gzip --db "$DB"
|
|
3509
|
+
`;
|
|
3510
|
+
/**
|
|
3511
|
+
* Replaces the database, when `$1` is 1, or the collections the following arguments select, by the
|
|
3512
|
+
* received archive of `mongodump --archive --gzip`, whatever database it was dumped from: the archive
|
|
3513
|
+
* is first restored into a new database of a name no database has, dropped afterwards, so an archive
|
|
3514
|
+
* the engine refuses leaves the database as it was; the database is then saved, and put back when
|
|
3515
|
+
* its own restore fails. Its saved dump is kept in the container when it cannot be put back, and a
|
|
3516
|
+
* temporary database that cannot be dropped is reported on both outputs.
|
|
3517
|
+
*/
|
|
3518
|
+
const MONGODB_RESTORE = `set -e
|
|
3519
|
+
whole="$1"; shift
|
|
3520
|
+
${UNIQUE_SUFFIX}export STAGING="adt_staging_$SUFFIX"
|
|
3521
|
+
SAVED="$ARCHIVE.saved"
|
|
3522
|
+
created=
|
|
3523
|
+
kept=
|
|
3524
|
+
drop() {
|
|
3525
|
+
auth mongosh --quiet --eval "db.getSiblingDB(process.env.$1).dropDatabase()" > /dev/null
|
|
3526
|
+
}
|
|
3527
|
+
cleanup() {
|
|
3528
|
+
rm -f "$ARCHIVE"
|
|
3529
|
+
[ -n "$kept" ] || rm -f "$SAVED"
|
|
3530
|
+
[ -z "$created" ] || drop STAGING || leftover "the temporary database $STAGING could not be dropped: drop it by hand"
|
|
3531
|
+
}
|
|
3532
|
+
restore_into() {
|
|
3533
|
+
into="$1"; shift
|
|
3534
|
+
auth mongorestore --archive="$ARCHIVE" --gzip --drop --stopOnError --nsFrom '$db$.$coll$' --nsTo "$into"'.$coll$' "$@"
|
|
3535
|
+
}
|
|
3536
|
+
auth mongosh --quiet --eval 'quit(db.getMongo().getDBNames().includes(process.env.STAGING) ? 1 : 0)' || {
|
|
3537
|
+
echo "the database $STAGING already exists: nothing was changed, try again" >&2
|
|
3538
|
+
exit 1
|
|
3539
|
+
}
|
|
3540
|
+
created=1
|
|
3541
|
+
restore_into "$STAGING" "$@"
|
|
3542
|
+
auth mongodump --quiet --archive="$SAVED" --gzip --db "$DB" || {
|
|
3543
|
+
echo "the database could not be saved before its restore: nothing was changed" >&2
|
|
3544
|
+
exit 1
|
|
3545
|
+
}
|
|
3546
|
+
if { [ "$whole" = 0 ] || drop DB; } && restore_into "$DB" "$@"; then
|
|
3547
|
+
exit 0
|
|
3548
|
+
fi
|
|
3549
|
+
if drop DB && auth mongorestore --archive="$SAVED" --gzip --stopOnError; then
|
|
3550
|
+
echo "the restore was refused: the database was put back as it was" >&2
|
|
3551
|
+
else
|
|
3552
|
+
kept=1
|
|
3553
|
+
echo "the restore was refused and the database could not be put back: its dump is kept in the container, in $SAVED" >&2
|
|
3554
|
+
fi
|
|
3555
|
+
exit 1
|
|
3556
|
+
`;
|
|
3557
|
+
/**
|
|
2695
3558
|
* Gives an empty stream.
|
|
2696
3559
|
*
|
|
2697
3560
|
* @returns A stream without chunk.
|
|
@@ -2703,26 +3566,44 @@ const ENGINES = {
|
|
|
2703
3566
|
postgres,
|
|
2704
3567
|
mariadb,
|
|
2705
3568
|
mongodb: {
|
|
2706
|
-
async listTables(
|
|
2707
|
-
return (await scriptText(
|
|
3569
|
+
async listTables(target) {
|
|
3570
|
+
return (await scriptText(target, `${MONGODB_SETUP}auth mongosh --quiet --eval 'db.getSiblingDB(process.env.DB).getCollectionNames().filter((name) => !name.startsWith("system.")).sort().forEach((name) => print(name))'`)).split("\n").filter((line) => line !== "");
|
|
2708
3571
|
},
|
|
2709
3572
|
dumpSchema() {
|
|
2710
3573
|
return emptyStream();
|
|
2711
3574
|
},
|
|
2712
|
-
dumpTable(
|
|
2713
|
-
return scriptOutput(
|
|
3575
|
+
dumpTable(target, table) {
|
|
3576
|
+
return scriptOutput(target, `${MONGODB_SETUP}auth mongodump --quiet --archive --db "$DB" --collection "$1"`, [table]);
|
|
2714
3577
|
},
|
|
2715
|
-
async reset(
|
|
2716
|
-
await scriptText(
|
|
3578
|
+
async reset(target) {
|
|
3579
|
+
await scriptText(target, `${MONGODB_SETUP}auth mongosh --quiet --eval 'db.getSiblingDB(process.env.DB).dropDatabase()'`);
|
|
2717
3580
|
},
|
|
2718
|
-
async importSchema(
|
|
3581
|
+
async importSchema(_target, sql) {
|
|
2719
3582
|
for await (const chunk of sql);
|
|
2720
3583
|
},
|
|
2721
|
-
async importTable(
|
|
2722
|
-
await scriptInput(
|
|
3584
|
+
async importTable(target, table, sql, replace) {
|
|
3585
|
+
await scriptInput(target, `${MONGODB_SETUP}auth mongorestore --quiet --archive --stopOnError --nsInclude "*.$1" --nsFrom "\\$db\\$.$1" --nsTo "$DB.$1"${replace ? " --drop" : ""}`, sql, [table]);
|
|
2723
3586
|
},
|
|
2724
3587
|
finish() {
|
|
2725
3588
|
return Promise.resolve();
|
|
3589
|
+
},
|
|
3590
|
+
dumpNative(target) {
|
|
3591
|
+
return scriptOutput(target, `${MONGODB_SETUP}${MONGODB_DUMP}`);
|
|
3592
|
+
},
|
|
3593
|
+
async restoreNative(target, archivePath, tables) {
|
|
3594
|
+
assertTablesChosen(tables);
|
|
3595
|
+
const namespaces = await mongodumpNamespaces(createReadStream(archivePath));
|
|
3596
|
+
const sources = [...new Set(namespaces.map((namespace) => namespace.db))];
|
|
3597
|
+
if (sources.length !== 1) throw new Error(sources.length === 0 ? "the archive holds no collection" : `the archive holds several databases (${sources.join(", ")}): dump one, with --db`);
|
|
3598
|
+
const missing = (tables ?? []).filter((table) => !namespaces.some((namespace) => namespace.collection === table));
|
|
3599
|
+
if (missing.length > 0) throw new Error(`not in the archive: ${missing.join(", ")}`);
|
|
3600
|
+
const selection = namespaces.filter((namespace) => tables?.includes(namespace.collection) === true).flatMap((namespace) => ["--nsInclude", `${escapeNamespace(namespace.db)}.${escapeNamespace(namespace.collection)}`]);
|
|
3601
|
+
const { size } = await stat(archivePath);
|
|
3602
|
+
return await scriptInput(target, `${MONGODB_SETUP}${RECEIVE_ARCHIVE}${MONGODB_RESTORE}`, createReadStream(archivePath), [
|
|
3603
|
+
String(size),
|
|
3604
|
+
tables === null ? "1" : "0",
|
|
3605
|
+
...selection
|
|
3606
|
+
]) || null;
|
|
2726
3607
|
}
|
|
2727
3608
|
}
|
|
2728
3609
|
};
|
|
@@ -3540,6 +4421,8 @@ function countChoices(differences, choices, baseSide) {
|
|
|
3540
4421
|
// ../../packages/environment/lib/environment.js
|
|
3541
4422
|
/** Path of the shared devtool configuration, the file declaring the environment. */
|
|
3542
4423
|
const SHARED_CONFIG_PATH = "devtool/config.yml";
|
|
4424
|
+
/** Folder of the environment holding the locks of the transfers, which no item may use. */
|
|
4425
|
+
const LOCKS_FOLDER = ".devtool-locks";
|
|
3543
4426
|
const MEDIA_TYPES = {
|
|
3544
4427
|
".yml": "application/yaml",
|
|
3545
4428
|
".yaml": "application/yaml",
|
|
@@ -3547,6 +4430,7 @@ const MEDIA_TYPES = {
|
|
|
3547
4430
|
".env": "text/plain",
|
|
3548
4431
|
".gz": "application/gzip"
|
|
3549
4432
|
};
|
|
4433
|
+
const ARCHIVE_FORMATS = ["devtool", "native"];
|
|
3550
4434
|
/**
|
|
3551
4435
|
* Reads a record of the configuration.
|
|
3552
4436
|
*
|
|
@@ -3599,6 +4483,18 @@ function readIgnoredKeys(itemPath, value) {
|
|
|
3599
4483
|
return value.length > 0 ? new IgnoredKeys(value) : null;
|
|
3600
4484
|
}
|
|
3601
4485
|
/**
|
|
4486
|
+
* Reads the archive format of a database or a bucket, `format: devtool | native`.
|
|
4487
|
+
*
|
|
4488
|
+
* @param itemPath - The path of the item.
|
|
4489
|
+
* @param value - The raw `format` setting.
|
|
4490
|
+
* @returns The format, `devtool` when the setting is missing.
|
|
4491
|
+
*/
|
|
4492
|
+
function readFormat(itemPath, value) {
|
|
4493
|
+
if (value === void 0) return "devtool";
|
|
4494
|
+
if (!ARCHIVE_FORMATS.includes(value)) throw new Error(`invalid format of ${itemPath} in the environment: must be ${ARCHIVE_FORMATS.join(" or ")}`);
|
|
4495
|
+
return value;
|
|
4496
|
+
}
|
|
4497
|
+
/**
|
|
3602
4498
|
* Gives the keys an item leaves out of its synchronization.
|
|
3603
4499
|
*
|
|
3604
4500
|
* @param item - The item.
|
|
@@ -3610,8 +4506,8 @@ function ignoredKeysOf(item) {
|
|
|
3610
4506
|
/**
|
|
3611
4507
|
* Reads the `environment` section of the devtool configuration: its `backends`, its `folder` being the
|
|
3612
4508
|
* parent of the configuration folder when it names none, each of its `files` a path or
|
|
3613
|
-
* `{ path, display, local, sync, pull, backend, ignore }`, its databases, buckets and Redis databases taking a
|
|
3614
|
-
* `pull
|
|
4509
|
+
* `{ path, display, local, sync, pull, backend, ignore, groups }`, its databases, buckets and Redis databases taking a
|
|
4510
|
+
* `pull`, a `backend` and `groups` too, an item naming no backend using the default one.
|
|
3615
4511
|
*
|
|
3616
4512
|
* @param section - The raw section.
|
|
3617
4513
|
* @returns The environment, or null when the section is missing.
|
|
@@ -3648,7 +4544,26 @@ function readEnvironmentOptions(section) {
|
|
|
3648
4544
|
if (typeof value !== "string" || !backends.some((backend) => backend.slug === value)) throw new Error(`${itemPath}: backend ${JSON.stringify(value)} is not declared in environment.backends`);
|
|
3649
4545
|
return value;
|
|
3650
4546
|
};
|
|
4547
|
+
const baseOf = (itemPath, entry) => {
|
|
4548
|
+
const backend = backendOf(itemPath, entry.backend);
|
|
4549
|
+
const { groups, problems: groupProblems } = readTransferGroups(entry.groups);
|
|
4550
|
+
if (groupProblems.length > 0) throw new Error(`invalid groups of ${itemPath} in the environment: ${groupProblems[0]}`);
|
|
4551
|
+
const backendGroups = backends.find((candidate) => candidate.slug === backend)?.groups ?? OPEN_ACCESS;
|
|
4552
|
+
return {
|
|
4553
|
+
path: itemPath,
|
|
4554
|
+
backend,
|
|
4555
|
+
encryption: encryptionOf(itemPath, entry.encryption),
|
|
4556
|
+
groups: mergeTransferGroups(groups, backendGroups)
|
|
4557
|
+
};
|
|
4558
|
+
};
|
|
3651
4559
|
const addItem = (item, pull) => {
|
|
4560
|
+
const canonical = canonicalBackendPath(item.path);
|
|
4561
|
+
if (canonical !== item.path) throw new Error(`invalid path of ${item.path} in the environment: write it ${canonical}`);
|
|
4562
|
+
const folded = foldedPath(item.path);
|
|
4563
|
+
if (folded === LOCKS_FOLDER || folded.startsWith(`${LOCKS_FOLDER}/`)) throw new Error(`invalid path of ${item.path} in the environment: ${LOCKS_FOLDER} holds the locks of the transfers`);
|
|
4564
|
+
const twin = items.find((other) => foldedPath(other.path) === folded);
|
|
4565
|
+
if (twin?.path === item.path) throw new Error(`${item.path} is declared twice in the environment`);
|
|
4566
|
+
if (twin) throw new Error(`${item.path} and ${twin.path} differ only by letter case, Unicode form or path spelling, which a backend or a disk may store as one file: declare one of them`);
|
|
3652
4567
|
items.push(item);
|
|
3653
4568
|
const autoPull = readAutoPull(item.path, pull);
|
|
3654
4569
|
if (autoPull) autoPulls.push(autoPull);
|
|
@@ -3668,40 +4583,36 @@ function readEnvironmentOptions(section) {
|
|
|
3668
4583
|
});
|
|
3669
4584
|
if (entry.sync !== false) addItem({
|
|
3670
4585
|
kind: "file",
|
|
3671
|
-
|
|
3672
|
-
backend: backendOf(entry.path, entry.backend),
|
|
3673
|
-
encryption: encryptionOf(entry.path, entry.encryption),
|
|
4586
|
+
...baseOf(entry.path, entry),
|
|
3674
4587
|
ignore: readIgnoredKeys(entry.path, entry.ignore)
|
|
3675
4588
|
}, entry.pull);
|
|
3676
4589
|
}
|
|
3677
4590
|
for (const database of recordsOf(record.databases)) {
|
|
3678
|
-
|
|
4591
|
+
const name = database.database;
|
|
4592
|
+
if (typeof database.path !== "string" || !isDatabaseEngineName(database.engine) || typeof database.container !== "string" || name !== void 0 && (typeof name !== "string" || name.trim() === "")) throw new Error(`invalid database in the environment: ${JSON.stringify(database)}`);
|
|
3679
4593
|
addItem({
|
|
3680
4594
|
kind: "database",
|
|
3681
|
-
|
|
3682
|
-
backend: backendOf(database.path, database.backend),
|
|
3683
|
-
encryption: encryptionOf(database.path, database.encryption),
|
|
4595
|
+
...baseOf(database.path, database),
|
|
3684
4596
|
engine: database.engine,
|
|
3685
|
-
container: database.container
|
|
4597
|
+
container: database.container,
|
|
4598
|
+
database: typeof name === "string" ? name : null,
|
|
4599
|
+
format: readFormat(database.path, database.format)
|
|
3686
4600
|
}, database.pull);
|
|
3687
4601
|
}
|
|
3688
4602
|
for (const bucket of recordsOf(record.buckets)) {
|
|
3689
4603
|
if (typeof bucket.path !== "string" || typeof bucket.bucket !== "string") throw new Error(`invalid bucket in the environment: ${JSON.stringify(bucket)}`);
|
|
3690
4604
|
addItem({
|
|
3691
4605
|
kind: "bucket",
|
|
3692
|
-
|
|
3693
|
-
|
|
3694
|
-
|
|
3695
|
-
bucket: bucket.bucket
|
|
4606
|
+
...baseOf(bucket.path, bucket),
|
|
4607
|
+
bucket: bucket.bucket,
|
|
4608
|
+
format: readFormat(bucket.path, bucket.format)
|
|
3696
4609
|
}, bucket.pull);
|
|
3697
4610
|
}
|
|
3698
4611
|
for (const redis of recordsOf(record.redis)) {
|
|
3699
4612
|
if (typeof redis.path !== "string" || typeof redis.url !== "string") throw new Error(`invalid Redis database in the environment: ${JSON.stringify({ path: redis.path })}`);
|
|
3700
4613
|
addItem({
|
|
3701
4614
|
kind: "redis",
|
|
3702
|
-
|
|
3703
|
-
backend: backendOf(redis.path, redis.backend),
|
|
3704
|
-
encryption: encryptionOf(redis.path, redis.encryption),
|
|
4615
|
+
...baseOf(redis.path, redis),
|
|
3705
4616
|
url: redis.url
|
|
3706
4617
|
}, redis.pull);
|
|
3707
4618
|
}
|
|
@@ -3751,13 +4662,91 @@ function parseTargets(options, targets) {
|
|
|
3751
4662
|
});
|
|
3752
4663
|
}
|
|
3753
4664
|
/**
|
|
4665
|
+
* Gives the canonical form of the path of a file in a backend, the one items are declared with.
|
|
4666
|
+
*
|
|
4667
|
+
* @param filePath - The path, possibly with `./`, a leading `/`, repeated or `..` segments.
|
|
4668
|
+
* @param written - The path as written, named when it leaves the backend.
|
|
4669
|
+
* @returns The canonical path.
|
|
4670
|
+
*/
|
|
4671
|
+
function canonicalBackendPath(filePath, written = filePath) {
|
|
4672
|
+
const canonical = path.posix.normalize(filePath).replace(/^(?:\.?\/)+/, "");
|
|
4673
|
+
if (canonical === "" || canonical === "." || canonical === ".." || canonical.startsWith("../")) throw new Error(`${written} is not a path inside the backend`);
|
|
4674
|
+
return canonical;
|
|
4675
|
+
}
|
|
4676
|
+
/**
|
|
4677
|
+
* Folds a path so that spellings a case-insensitive or normalizing store, or one taking backslashes
|
|
4678
|
+
* for separators, takes for one file are equal, in their canonical form; fails on a path leaving
|
|
4679
|
+
* the backend once read that way.
|
|
4680
|
+
*
|
|
4681
|
+
* @param filePath - The path.
|
|
4682
|
+
* @returns Its folded form.
|
|
4683
|
+
*/
|
|
4684
|
+
function foldedPath(filePath) {
|
|
4685
|
+
return canonicalBackendPath(filePath.normalize("NFKD").toUpperCase().toLowerCase().replaceAll("\\", "/"), filePath);
|
|
4686
|
+
}
|
|
4687
|
+
/**
|
|
4688
|
+
* Finds the item a backend stores at a path. A path differing from the one of an item by its letter
|
|
4689
|
+
* case, Unicode form or path spelling only is refused, since a backend may store both as one file.
|
|
4690
|
+
*
|
|
4691
|
+
* @param items - The items of the environment.
|
|
4692
|
+
* @param backend - The name of the backend.
|
|
4693
|
+
* @param filePath - The path, in its canonical form.
|
|
4694
|
+
* @returns The item, null when the backend stores no item there.
|
|
4695
|
+
*/
|
|
4696
|
+
function itemStoredAt(items, backend, filePath) {
|
|
4697
|
+
const stored = items.filter((item) => item.backend === backend);
|
|
4698
|
+
const exact = stored.find((item) => item.path === filePath);
|
|
4699
|
+
const alias = exact ? void 0 : stored.find((item) => foldedPath(item.path) === foldedPath(filePath));
|
|
4700
|
+
if (alias) throw new Error(`${filePath} names the item ${alias.path} in another letter case, Unicode form or path spelling: write its path exactly`);
|
|
4701
|
+
return exact ?? null;
|
|
4702
|
+
}
|
|
4703
|
+
/**
|
|
4704
|
+
* Tells whether some tables of a database, or key groups of a Redis database, can be transferred
|
|
4705
|
+
* alone in a direction: never in a native archive pushed, nor in a native mariadb archive.
|
|
4706
|
+
*
|
|
4707
|
+
* @param item - The item.
|
|
4708
|
+
* @param direction - The direction.
|
|
4709
|
+
* @returns True when a part of the item can be chosen.
|
|
4710
|
+
*/
|
|
4711
|
+
function transfersParts(item, direction) {
|
|
4712
|
+
if (item.kind === "redis") return true;
|
|
4713
|
+
if (item.kind !== "database") return false;
|
|
4714
|
+
return item.format === "devtool" || direction === "pull" && item.engine !== "mariadb";
|
|
4715
|
+
}
|
|
4716
|
+
/**
|
|
4717
|
+
* Gives the shared devtool configuration as an item of the default backend.
|
|
4718
|
+
*
|
|
4719
|
+
* @param options - The environment.
|
|
4720
|
+
* @returns The item, null when the environment declares no backend.
|
|
4721
|
+
*/
|
|
4722
|
+
function sharedConfigItem(options) {
|
|
4723
|
+
const backend = options.backends.find((candidate) => candidate.slug === options.defaultBackend);
|
|
4724
|
+
return backend ? {
|
|
4725
|
+
kind: "file",
|
|
4726
|
+
path: SHARED_CONFIG_PATH,
|
|
4727
|
+
backend: backend.slug,
|
|
4728
|
+
encryption: null,
|
|
4729
|
+
groups: backend.groups,
|
|
4730
|
+
ignore: null
|
|
4731
|
+
} : null;
|
|
4732
|
+
}
|
|
4733
|
+
/**
|
|
3754
4734
|
* Lists the tables of the local database of an item, or the key groups of its local Redis database.
|
|
3755
4735
|
*
|
|
3756
4736
|
* @param item - The database or Redis item.
|
|
3757
4737
|
* @returns The tables or key groups.
|
|
3758
4738
|
*/
|
|
3759
4739
|
async function listTables(item) {
|
|
3760
|
-
return item.kind === "redis" ? listRedisGroups(item.url) : databaseEngine(item.engine).listTables(item
|
|
4740
|
+
return item.kind === "redis" ? listRedisGroups(item.url) : databaseEngine(item.engine).listTables(item);
|
|
4741
|
+
}
|
|
4742
|
+
/**
|
|
4743
|
+
* Names the local database of an item, for the messages.
|
|
4744
|
+
*
|
|
4745
|
+
* @param item - The database item.
|
|
4746
|
+
* @returns Its container, followed by its database when the item names one.
|
|
4747
|
+
*/
|
|
4748
|
+
function databaseNameOf(item) {
|
|
4749
|
+
return item.database === null ? item.container : `${item.container}/${item.database}`;
|
|
3761
4750
|
}
|
|
3762
4751
|
/**
|
|
3763
4752
|
* Tells whether pulling a selection overwrites local data.
|
|
@@ -3800,15 +4789,38 @@ var Environment = class {
|
|
|
3800
4789
|
_context;
|
|
3801
4790
|
_s3 = null;
|
|
3802
4791
|
_encrypted = /* @__PURE__ */ new Map();
|
|
4792
|
+
_gate;
|
|
3803
4793
|
/**
|
|
3804
4794
|
* @param _backends - The backends of the environment, by name.
|
|
3805
4795
|
* @param _options - The environment.
|
|
3806
|
-
* @param _context - Reads the value blocks
|
|
4796
|
+
* @param _context - Reads the value blocks, asks the developer for the secrets of encrypted items and names the identity provider.
|
|
3807
4797
|
*/
|
|
3808
4798
|
constructor(_backends, _options, _context) {
|
|
3809
4799
|
this._backends = _backends;
|
|
3810
4800
|
this._options = _options;
|
|
3811
4801
|
this._context = _context;
|
|
4802
|
+
this._gate = new TransferGate(_context.auth);
|
|
4803
|
+
}
|
|
4804
|
+
/**
|
|
4805
|
+
* Explains why the developer may not transfer an item, or a file of a backend, in a direction.
|
|
4806
|
+
*
|
|
4807
|
+
* @param target - The item or the settings of the backend.
|
|
4808
|
+
* @param target.groups - Who may pull and push it.
|
|
4809
|
+
* @param direction - The direction.
|
|
4810
|
+
* @returns Why the transfer is refused, null when it is allowed.
|
|
4811
|
+
*/
|
|
4812
|
+
async refusal({ groups }, direction) {
|
|
4813
|
+
return this._gate.refusal(groups[direction], direction);
|
|
4814
|
+
}
|
|
4815
|
+
/**
|
|
4816
|
+
* Fails when the developer may not transfer an item in a direction.
|
|
4817
|
+
*
|
|
4818
|
+
* @param item - The item.
|
|
4819
|
+
* @param direction - The direction.
|
|
4820
|
+
*/
|
|
4821
|
+
async assertAllowed(item, direction) {
|
|
4822
|
+
const refusal = await this.refusal(item, direction);
|
|
4823
|
+
if (refusal !== null) throw new Error(`${item.path}: ${refusal}`);
|
|
3812
4824
|
}
|
|
3813
4825
|
/**
|
|
3814
4826
|
* Describes every item with its local copy and its copy on its backend. The local copies are
|
|
@@ -3880,30 +4892,129 @@ var Environment = class {
|
|
|
3880
4892
|
return record;
|
|
3881
4893
|
}
|
|
3882
4894
|
/**
|
|
3883
|
-
* Replaces the local
|
|
4895
|
+
* Replaces the local data an item holds by the copy of its backend, then its local copy once that
|
|
4896
|
+
* data is restored: a restore that fails leaves the local copy and its synchronization record as
|
|
4897
|
+
* they were. The item is recorded as synchronized only when the copy of the backend did not change
|
|
4898
|
+
* during the pull; a record that cannot be written is reported in the result. One transfer of an
|
|
4899
|
+
* item runs at a time, across processes.
|
|
3884
4900
|
*
|
|
3885
4901
|
* @param selection - The item, the tables or key groups to restore, or the keys to take for a configuration file.
|
|
3886
4902
|
* @returns What was done.
|
|
3887
4903
|
*/
|
|
3888
4904
|
async pull(selection) {
|
|
4905
|
+
await this.assertAllowed(selection.item, "pull");
|
|
4906
|
+
return this.locked(selection.item, async () => this.pullItem(selection));
|
|
4907
|
+
}
|
|
4908
|
+
/**
|
|
4909
|
+
* Sends the local copy of an item to its backend, after dumping the local data it holds. For some
|
|
4910
|
+
* tables of a database, only their rows are replaced in the stored archive. One transfer of an
|
|
4911
|
+
* item runs at a time, across processes.
|
|
4912
|
+
*
|
|
4913
|
+
* @param selection - The item, the tables or key groups to dump, or the keys to send for a configuration file.
|
|
4914
|
+
* @returns What was done.
|
|
4915
|
+
*/
|
|
4916
|
+
async push(selection) {
|
|
4917
|
+
await this.assertAllowed(selection.item, "push");
|
|
4918
|
+
return this.locked(selection.item, async () => this.pushItem(selection));
|
|
4919
|
+
}
|
|
4920
|
+
/**
|
|
4921
|
+
* Runs a transfer of an item while no other transfer of it runs, in any process using the same
|
|
4922
|
+
* environment folder; the lock lives in that folder, named after the folded path of the item, so
|
|
4923
|
+
* spellings a store takes for one file share it.
|
|
4924
|
+
*
|
|
4925
|
+
* @param item - The item.
|
|
4926
|
+
* @param transfer - The transfer.
|
|
4927
|
+
* @returns What the transfer did.
|
|
4928
|
+
*/
|
|
4929
|
+
async locked(item, transfer) {
|
|
4930
|
+
const key = createHash("sha256").update(foldedPath(item.path)).digest("hex");
|
|
4931
|
+
return withFileLock(path.join(this._options.folder, LOCKS_FOLDER, `${key}.lock`), item.path, transfer);
|
|
4932
|
+
}
|
|
4933
|
+
/**
|
|
4934
|
+
* Pulls an item, once its transfer is locked.
|
|
4935
|
+
*
|
|
4936
|
+
* @param selection - The item, the tables or key groups to restore, or the keys to take for a configuration file.
|
|
4937
|
+
* @returns What was done.
|
|
4938
|
+
*/
|
|
4939
|
+
async pullItem(selection) {
|
|
3889
4940
|
const { item, tables } = selection;
|
|
3890
|
-
if (item.kind === "file" && (selection.keys || await this.mergesWhole(item))) return this.pullKeys(item, selection.keys ?? null);
|
|
3891
|
-
if (!await this.download(item)) return {
|
|
3892
|
-
done: false,
|
|
3893
|
-
detail: `absent from ${item.backend}`
|
|
3894
|
-
};
|
|
3895
4941
|
const localPath = localPathOf(this._options.folder, item.path);
|
|
3896
|
-
|
|
3897
|
-
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
|
|
4942
|
+
if (item.kind === "database" && tables !== null && !transfersParts(item, "pull")) throw new Error(`${item.path} is a native ${item.engine} archive: pull the whole database, its tables cannot be restored one by one`);
|
|
4943
|
+
const pulled = await this.backendFor(item).list().then((files) => files && (files.find((file) => file.path === item.path) ?? void 0), () => void 0);
|
|
4944
|
+
if (item.kind === "file") {
|
|
4945
|
+
if (selection.keys || await this.mergesWhole(item)) return this.pullKeys(item, selection.keys ?? null, pulled);
|
|
4946
|
+
if (!await this.download(item)) return {
|
|
4947
|
+
done: false,
|
|
4948
|
+
detail: `absent from ${item.backend}`
|
|
4949
|
+
};
|
|
4950
|
+
return this.recorded(item, {
|
|
4951
|
+
done: true,
|
|
4952
|
+
detail: localPath
|
|
4953
|
+
}, pulled);
|
|
4954
|
+
}
|
|
4955
|
+
const pulledPath = `${localPath}.${randomUUID()}.pull`;
|
|
4956
|
+
try {
|
|
4957
|
+
if (!await this.download(item, pulledPath)) return {
|
|
4958
|
+
done: false,
|
|
4959
|
+
detail: `absent from ${item.backend}`
|
|
4960
|
+
};
|
|
4961
|
+
const result = await this.restore(item, pulledPath, tables);
|
|
4962
|
+
await fs.rename(pulledPath, localPath);
|
|
4963
|
+
return await this.recorded(item, result, pulled);
|
|
4964
|
+
} finally {
|
|
4965
|
+
await fs.rm(pulledPath, { force: true });
|
|
4966
|
+
}
|
|
4967
|
+
}
|
|
4968
|
+
/**
|
|
4969
|
+
* Records a pulled item as synchronized when the copy of its backend listed before the pull is
|
|
4970
|
+
* known and still the same, reporting in the result of the pull why it is not recorded.
|
|
4971
|
+
*
|
|
4972
|
+
* @param item - The item.
|
|
4973
|
+
* @param result - What the pull did.
|
|
4974
|
+
* @param pulled - The copy of the backend listed before the pull, null when the backend lists
|
|
4975
|
+
* nothing, undefined when the listing failed or did not hold the item.
|
|
4976
|
+
* @returns What the pull did.
|
|
4977
|
+
*/
|
|
4978
|
+
async recorded(item, result, pulled) {
|
|
4979
|
+
if (pulled === null) return result;
|
|
4980
|
+
try {
|
|
4981
|
+
if (pulled === void 0) throw new Error(`the copy of ${item.backend} could not be listed before the pull: pull again`);
|
|
4982
|
+
await this.recordSync(item, pulled);
|
|
4983
|
+
return result;
|
|
4984
|
+
} catch (error) {
|
|
4985
|
+
return {
|
|
4986
|
+
...result,
|
|
4987
|
+
detail: `${result.detail}, not recorded as synchronized: ${error instanceof Error ? error.message : String(error)}`
|
|
4988
|
+
};
|
|
4989
|
+
}
|
|
4990
|
+
}
|
|
4991
|
+
/**
|
|
4992
|
+
* Gives the copy of an item its backend lists.
|
|
4993
|
+
*
|
|
4994
|
+
* @param item - The item.
|
|
4995
|
+
* @returns The copy, undefined when the backend lists none.
|
|
4996
|
+
*/
|
|
4997
|
+
async remoteCopy(item) {
|
|
4998
|
+
return (await this.backendFor(item).list())?.find((file) => file.path === item.path);
|
|
4999
|
+
}
|
|
5000
|
+
/**
|
|
5001
|
+
* Replaces the local data of an item by an archive of it. An archive of the devtool is read whole
|
|
5002
|
+
* first, so a truncated or corrupted one changes nothing.
|
|
5003
|
+
*
|
|
5004
|
+
* @param item - The database, bucket or Redis item.
|
|
5005
|
+
* @param archivePath - The archive, which nothing else reads or writes.
|
|
5006
|
+
* @param tables - The tables or key groups to restore, or null for the whole item.
|
|
5007
|
+
* @returns What was done.
|
|
5008
|
+
*/
|
|
5009
|
+
async restore(item, archivePath, tables) {
|
|
5010
|
+
if (item.kind === "redis" || item.format === "devtool") for await (const { body } of item.kind === "bucket" ? objectsOfArchive(readArchive(archivePath)) : readArchive(archivePath)) for await (const chunk of body);
|
|
5011
|
+
if (item.kind === "bucket" && item.format === "native") return this.restoreBucketTar(item, archivePath);
|
|
3901
5012
|
if (item.kind === "bucket") return {
|
|
3902
5013
|
done: true,
|
|
3903
|
-
detail: `${await restoreBucket(this.s3(), item.bucket, readArchive(
|
|
5014
|
+
detail: `${await restoreBucket(this.s3(), item.bucket, objectsOfArchive(readArchive(archivePath)))} objects restored in ${item.bucket}`
|
|
3904
5015
|
};
|
|
3905
5016
|
if (item.kind === "redis") {
|
|
3906
|
-
const records = readArchive(
|
|
5017
|
+
const records = readArchive(archivePath);
|
|
3907
5018
|
const first = await records.next();
|
|
3908
5019
|
if (first.done || first.value.header.type !== "redis") throw new Error(`${item.path} is not a Redis archive`);
|
|
3909
5020
|
const restored = await restoreRedis(item.url, records, tables);
|
|
@@ -3913,37 +5024,90 @@ var Environment = class {
|
|
|
3913
5024
|
detail: tables === null ? `${restored.count} keys restored in Redis ${redisDatabaseName(item.url)}` : `key groups restored: ${tables.join(", ")} (${restored.count} keys)`
|
|
3914
5025
|
};
|
|
3915
5026
|
}
|
|
5027
|
+
return item.format === "native" ? this.restoreNative(item, archivePath, tables) : this.restoreDatabase(item, archivePath, tables);
|
|
5028
|
+
}
|
|
5029
|
+
/**
|
|
5030
|
+
* Replaces the objects of a bucket by those of a tar.gz archive, read whole first so that a
|
|
5031
|
+
* truncated or corrupted archive leaves the bucket untouched.
|
|
5032
|
+
*
|
|
5033
|
+
* @param item - The bucket item.
|
|
5034
|
+
* @param archivePath - The archive.
|
|
5035
|
+
* @returns What was done.
|
|
5036
|
+
*/
|
|
5037
|
+
async restoreBucketTar(item, archivePath) {
|
|
5038
|
+
await checkTar(createReadStream(archivePath)).catch((error) => {
|
|
5039
|
+
throw new Error(`${item.path} is not a complete tar.gz archive: ${error instanceof Error ? error.message : String(error)}`);
|
|
5040
|
+
});
|
|
5041
|
+
return {
|
|
5042
|
+
done: true,
|
|
5043
|
+
detail: `${await restoreBucket(this.s3(), item.bucket, objectsOfTar(createReadStream(archivePath)))} objects restored in ${item.bucket}`
|
|
5044
|
+
};
|
|
5045
|
+
}
|
|
5046
|
+
/**
|
|
5047
|
+
* Restores a local database from an archive of the devtool.
|
|
5048
|
+
*
|
|
5049
|
+
* @param item - The database item.
|
|
5050
|
+
* @param localPath - The archive.
|
|
5051
|
+
* @param tables - The tables to restore, or null for the whole database.
|
|
5052
|
+
* @returns What was done.
|
|
5053
|
+
*/
|
|
5054
|
+
async restoreDatabase(item, localPath, tables) {
|
|
3916
5055
|
const engine = databaseEngine(item.engine);
|
|
3917
5056
|
const records = readArchive(localPath);
|
|
3918
5057
|
const first = await records.next();
|
|
3919
5058
|
if (first.done || first.value.header.type !== "database" || first.value.header.engine !== item.engine) throw new Error(`${item.path} is not a ${item.engine} archive`);
|
|
3920
|
-
if (tables === null) await engine.reset(item
|
|
3921
|
-
else assertKnownTables(tables, await engine.listTables(item
|
|
5059
|
+
if (tables === null) await engine.reset(item);
|
|
5060
|
+
else assertKnownTables(tables, await engine.listTables(item), databaseNameOf(item));
|
|
3922
5061
|
const restored = [];
|
|
3923
|
-
for await (const { header, body } of records) if (header.type === "schema" && tables === null) await engine.importSchema(item
|
|
5062
|
+
for await (const { header, body } of records) if (header.type === "schema" && tables === null) await engine.importSchema(item, body);
|
|
3924
5063
|
else if (header.type === "table" && typeof header.name === "string" && (tables === null || tables.includes(header.name))) {
|
|
3925
|
-
await engine.importTable(item
|
|
5064
|
+
await engine.importTable(item, header.name, body, tables !== null);
|
|
3926
5065
|
restored.push(header.name);
|
|
3927
5066
|
}
|
|
3928
5067
|
if (tables !== null) assertKnownTables(tables, restored, item.path);
|
|
3929
|
-
await engine.finish(item
|
|
5068
|
+
await engine.finish(item);
|
|
3930
5069
|
return {
|
|
3931
5070
|
done: true,
|
|
3932
5071
|
detail: tables === null ? `database restored (${restored.length} tables)` : `tables restored: ${restored.join(", ")}`
|
|
3933
5072
|
};
|
|
3934
5073
|
}
|
|
3935
5074
|
/**
|
|
3936
|
-
*
|
|
5075
|
+
* Restores a local database from an archive of the engine's own tools; an archive the engine
|
|
5076
|
+
* refuses, being of another engine, truncated or corrupted, leaves the database as it was. What
|
|
5077
|
+
* could not be cleaned up once the database was restored is reported with what was done.
|
|
5078
|
+
*
|
|
5079
|
+
* @param item - The database item.
|
|
5080
|
+
* @param archivePath - The archive.
|
|
5081
|
+
* @param tables - The tables to restore, or null for the whole database.
|
|
5082
|
+
* @returns What was done.
|
|
5083
|
+
*/
|
|
5084
|
+
async restoreNative(item, archivePath, tables) {
|
|
5085
|
+
const engine = databaseEngine(item.engine);
|
|
5086
|
+
if (tables !== null) assertKnownTables(tables, await engine.listTables(item), databaseNameOf(item));
|
|
5087
|
+
const leftover = await engine.restoreNative(item, archivePath, tables);
|
|
5088
|
+
const detail = tables === null ? `database restored in ${databaseNameOf(item)}` : `tables restored: ${tables.join(", ")}`;
|
|
5089
|
+
return {
|
|
5090
|
+
done: true,
|
|
5091
|
+
detail: leftover === null ? detail : `${detail}, but ${leftover}`
|
|
5092
|
+
};
|
|
5093
|
+
}
|
|
5094
|
+
/**
|
|
5095
|
+
* Pushes an item, once its transfer is locked.
|
|
3937
5096
|
*
|
|
3938
5097
|
* @param selection - The item, the tables or key groups to dump, or the keys to send for a configuration file.
|
|
3939
5098
|
* @returns What was done.
|
|
3940
5099
|
*/
|
|
3941
|
-
async
|
|
5100
|
+
async pushItem(selection) {
|
|
3942
5101
|
const { item, tables } = selection;
|
|
3943
5102
|
if (item.kind === "file" && (selection.keys || await this.mergesWhole(item))) return this.pushKeys(item, selection.keys ?? null);
|
|
3944
5103
|
const localPath = localPathOf(this._options.folder, item.path);
|
|
3945
5104
|
let detail = localPath;
|
|
3946
|
-
if (item.kind === "database"
|
|
5105
|
+
if (item.kind === "database" && item.format === "native") {
|
|
5106
|
+
if (tables !== null) throw new Error(`${item.path} is a native archive: push the whole database, its tables cannot be replaced one by one`);
|
|
5107
|
+
await writeLocalFile(localPath, databaseEngine(item.engine).dumpNative(item));
|
|
5108
|
+
detail = `database dumped from ${databaseNameOf(item)}`;
|
|
5109
|
+
} else if (item.kind === "database") detail = await this.writeLocal(localPath, (archive) => this.dumpDatabase(item, tables, archive));
|
|
5110
|
+
else if (item.kind === "bucket" && item.format === "native") detail = `${await snapshotBucketTar(this.s3(), item.bucket, localPath)} objects of ${item.bucket}`;
|
|
3947
5111
|
else if (item.kind === "bucket") detail = await this.writeLocal(localPath, async (archive) => `${await snapshotBucket(this.s3(), item.bucket, archive)} objects of ${item.bucket}`);
|
|
3948
5112
|
else if (item.kind === "redis") detail = await this.writeLocal(localPath, (archive) => this.dumpRedis(item, tables, archive));
|
|
3949
5113
|
else if (!await fs.stat(localPath).then((stat) => stat.isFile(), () => false)) return {
|
|
@@ -3984,9 +5148,11 @@ var Environment = class {
|
|
|
3984
5148
|
*
|
|
3985
5149
|
* @param item - The file item.
|
|
3986
5150
|
* @param keys - The value to keep for each differing key, null to take every value of the backend.
|
|
5151
|
+
* @param pulled - The copy of the backend listed before it was read, null when the backend lists
|
|
5152
|
+
* nothing, undefined when the listing failed or did not hold the item.
|
|
3987
5153
|
* @returns What was done.
|
|
3988
5154
|
*/
|
|
3989
|
-
async pullKeys(item, keys) {
|
|
5155
|
+
async pullKeys(item, keys, pulled) {
|
|
3990
5156
|
const { format, local, remote } = await this.readBothCopies(item);
|
|
3991
5157
|
const ignored = ignoredKeysOf(item);
|
|
3992
5158
|
const differences = diffConfig(format, local, remote, ignored);
|
|
@@ -3996,12 +5162,12 @@ var Environment = class {
|
|
|
3996
5162
|
}));
|
|
3997
5163
|
const merged = mergeConfig(format, local, "local", differences, choices, ignored);
|
|
3998
5164
|
await writeLocalFile(localPathOf(this._options.folder, item.path), merged);
|
|
3999
|
-
if (diffConfig(format, merged, remote, ignored).length === 0) await this.recordSync(item);
|
|
4000
5165
|
const counts = countChoices(differences, choices, "local");
|
|
4001
|
-
|
|
5166
|
+
const result = {
|
|
4002
5167
|
done: true,
|
|
4003
5168
|
detail: `keys merged: ${counts.remote} from ${item.backend}, ${counts.local} kept local`
|
|
4004
5169
|
};
|
|
5170
|
+
return diffConfig(format, merged, remote, ignored).length === 0 ? this.recorded(item, result, pulled) : result;
|
|
4005
5171
|
}
|
|
4006
5172
|
/**
|
|
4007
5173
|
* Sends to its backend the copy of a configuration file with the local values chosen for its
|
|
@@ -4061,12 +5227,15 @@ var Environment = class {
|
|
|
4061
5227
|
}
|
|
4062
5228
|
/**
|
|
4063
5229
|
* Records in the synchronization journal both copies of an item, now equal, so a later change on
|
|
4064
|
-
* either side shows; neither copy is touched.
|
|
5230
|
+
* either side shows; neither copy is touched. Fails, recording nothing, when the copy of the
|
|
5231
|
+
* backend is no longer the one that was pulled.
|
|
4065
5232
|
*
|
|
4066
5233
|
* @param item - The item.
|
|
5234
|
+
* @param pulled - The copy of the backend that was pulled, undefined when unknown.
|
|
4067
5235
|
*/
|
|
4068
|
-
async recordSync(item) {
|
|
4069
|
-
const remote =
|
|
5236
|
+
async recordSync(item, pulled) {
|
|
5237
|
+
const remote = await this.remoteCopy(item);
|
|
5238
|
+
if (pulled !== void 0 && remote?.version !== pulled.version) throw new Error(`the copy of ${item.backend} changed during the pull: pull again`);
|
|
4070
5239
|
const local = await fs.stat(localPathOf(this._options.folder, item.path)).catch(() => null);
|
|
4071
5240
|
if (remote && local) await writeSyncRecord(item.path, {
|
|
4072
5241
|
localUpdatedAt: local.mtime,
|
|
@@ -4086,25 +5255,25 @@ var Environment = class {
|
|
|
4086
5255
|
*/
|
|
4087
5256
|
async dumpDatabase(item, tables, archive) {
|
|
4088
5257
|
const engine = databaseEngine(item.engine);
|
|
4089
|
-
const localTables = await engine.listTables(item
|
|
5258
|
+
const localTables = await engine.listTables(item);
|
|
4090
5259
|
if (tables === null) {
|
|
4091
5260
|
await archive.add({
|
|
4092
5261
|
type: "database",
|
|
4093
5262
|
engine: item.engine
|
|
4094
5263
|
});
|
|
4095
|
-
await archive.add({ type: "schema" }, engine.dumpSchema(item
|
|
5264
|
+
await archive.add({ type: "schema" }, engine.dumpSchema(item));
|
|
4096
5265
|
for (const table of localTables) await archive.add({
|
|
4097
5266
|
type: "table",
|
|
4098
5267
|
name: table
|
|
4099
|
-
}, engine.dumpTable(item
|
|
5268
|
+
}, engine.dumpTable(item, table));
|
|
4100
5269
|
return `database dumped (${localTables.length} tables)`;
|
|
4101
5270
|
}
|
|
4102
|
-
assertKnownTables(tables, localTables, item
|
|
5271
|
+
assertKnownTables(tables, localTables, databaseNameOf(item));
|
|
4103
5272
|
await this.copyBase(item, archive, (header) => header.type !== "table" || typeof header.name !== "string" || !tables.includes(header.name));
|
|
4104
5273
|
for (const table of tables) await archive.add({
|
|
4105
5274
|
type: "table",
|
|
4106
5275
|
name: table
|
|
4107
|
-
}, engine.dumpTable(item
|
|
5276
|
+
}, engine.dumpTable(item, table));
|
|
4108
5277
|
return `tables dumped: ${tables.join(", ")}`;
|
|
4109
5278
|
}
|
|
4110
5279
|
/**
|
|
@@ -4172,13 +5341,15 @@ var Environment = class {
|
|
|
4172
5341
|
}
|
|
4173
5342
|
}
|
|
4174
5343
|
/**
|
|
4175
|
-
* Downloads the copy of an item on its backend to a local file, replaced only once the download is
|
|
5344
|
+
* Downloads the copy of an item on its backend to a local file, replaced only once the download is
|
|
5345
|
+
* complete, when the groups of the developer let them pull the item.
|
|
4176
5346
|
*
|
|
4177
5347
|
* @param item - The item.
|
|
4178
5348
|
* @param localPath - The local file, its mirror in the environment directory by default.
|
|
4179
5349
|
* @returns False when the backend has no such file.
|
|
4180
5350
|
*/
|
|
4181
5351
|
async download(item, localPath = localPathOf(this._options.folder, item.path)) {
|
|
5352
|
+
await this.assertAllowed(item, "pull");
|
|
4182
5353
|
const content = await this.backendFor(item).download(item.path);
|
|
4183
5354
|
if (!content) return false;
|
|
4184
5355
|
await writeLocalFile(localPath, content);
|
|
@@ -4710,7 +5881,7 @@ function runProxy({ adtSecurePort = 6731, proxyPort = 443 } = {}) {
|
|
|
4710
5881
|
return server;
|
|
4711
5882
|
}
|
|
4712
5883
|
// ../server/package.json
|
|
4713
|
-
var version$1 = "1.0.
|
|
5884
|
+
var version$1 = "1.0.3";
|
|
4714
5885
|
// ../../packages/certs/lib/certificate.js
|
|
4715
5886
|
const CERTIFICATE_BLOCK = /-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/;
|
|
4716
5887
|
const COMMON_NAME = /(?:^|\n| \+ )CN=((?:\\.|[^\\\n+])+?)(?= \+ |\n|$)/;
|
|
@@ -7357,14 +8528,14 @@ var DevtoolConfigure = class {
|
|
|
7357
8528
|
return folders;
|
|
7358
8529
|
}
|
|
7359
8530
|
/**
|
|
7360
|
-
* Reads where the page of a directory asks for the inputs of a command, `dialog` or `
|
|
8531
|
+
* Reads where the page of a directory asks for the inputs of a command, `dialog`, `inline` or `inlineExpanded`.
|
|
7361
8532
|
* @param slug Names the setting in warnings.
|
|
7362
8533
|
* @param value The raw setting.
|
|
7363
8534
|
* @returns The form, null when the setting is missing or invalid.
|
|
7364
8535
|
*/
|
|
7365
8536
|
readForm(slug, value) {
|
|
7366
|
-
if (value === "dialog" || value === "inline") return value;
|
|
7367
|
-
if (value !== void 0) this.addWarning(slug, "must be dialog or
|
|
8537
|
+
if (value === "dialog" || value === "inline" || value === "inlineExpanded") return value;
|
|
8538
|
+
if (value !== void 0) this.addWarning(slug, "must be dialog, inline or inlineExpanded");
|
|
7368
8539
|
return null;
|
|
7369
8540
|
}
|
|
7370
8541
|
/**
|
|
@@ -10032,8 +11203,9 @@ var DevtoolEnvironment = class {
|
|
|
10032
11203
|
}
|
|
10033
11204
|
/**
|
|
10034
11205
|
* Pulls items on their own: an item whose copy on its backend is missing or unchanged since the last
|
|
10035
|
-
* sync is left alone, one whose local copy changed since the last sync (or was never synchronized)
|
|
10036
|
-
*
|
|
11206
|
+
* sync is left alone, one whose local copy changed since the last sync (or was never synchronized), or
|
|
11207
|
+
* that the groups of the developer do not let pull, is skipped and reported, the others are pulled.
|
|
11208
|
+
* Nothing happens while another run is in progress.
|
|
10037
11209
|
*
|
|
10038
11210
|
* @param paths - The paths of the items.
|
|
10039
11211
|
*/
|
|
@@ -10052,6 +11224,14 @@ var DevtoolEnvironment = class {
|
|
|
10052
11224
|
});
|
|
10053
11225
|
continue;
|
|
10054
11226
|
}
|
|
11227
|
+
const refusal = await environment.refusal(item, "pull");
|
|
11228
|
+
if (refusal !== null) {
|
|
11229
|
+
skipped.push({
|
|
11230
|
+
path: item.path,
|
|
11231
|
+
detail: refusal
|
|
11232
|
+
});
|
|
11233
|
+
continue;
|
|
11234
|
+
}
|
|
10055
11235
|
targets.push({
|
|
10056
11236
|
path: item.path,
|
|
10057
11237
|
tables: null
|
|
@@ -10077,7 +11257,16 @@ var DevtoolEnvironment = class {
|
|
|
10077
11257
|
encrypted: item.encryption !== null,
|
|
10078
11258
|
engine: item.kind === "database" ? item.engine : null,
|
|
10079
11259
|
container: item.kind === "database" ? item.container : null,
|
|
11260
|
+
database: item.kind === "database" ? item.database : null,
|
|
10080
11261
|
bucket: item.kind === "bucket" ? item.bucket : null,
|
|
11262
|
+
parts: {
|
|
11263
|
+
pull: transfersParts(item, "pull"),
|
|
11264
|
+
push: transfersParts(item, "push")
|
|
11265
|
+
},
|
|
11266
|
+
allowed: {
|
|
11267
|
+
pull: await environment.refusal(item, "pull") === null,
|
|
11268
|
+
push: await environment.refusal(item, "push") === null
|
|
11269
|
+
},
|
|
10081
11270
|
redis: item.kind === "redis" ? redisDatabaseName(item.url) : null,
|
|
10082
11271
|
keyed,
|
|
10083
11272
|
local: local ? copyPayload(local) : null,
|
|
@@ -10100,20 +11289,14 @@ var DevtoolEnvironment = class {
|
|
|
10100
11289
|
*/
|
|
10101
11290
|
async pullSharedConfig() {
|
|
10102
11291
|
const environment = this.environment();
|
|
10103
|
-
const
|
|
10104
|
-
if (!environment ||
|
|
11292
|
+
const item = this._options && sharedConfigItem(this._options);
|
|
11293
|
+
if (!environment || !item) return false;
|
|
10105
11294
|
try {
|
|
10106
11295
|
const result = await environment.pull({
|
|
10107
|
-
item
|
|
10108
|
-
kind: "file",
|
|
10109
|
-
path: SHARED_CONFIG_PATH,
|
|
10110
|
-
backend,
|
|
10111
|
-
encryption: null,
|
|
10112
|
-
ignore: null
|
|
10113
|
-
},
|
|
11296
|
+
item,
|
|
10114
11297
|
tables: null
|
|
10115
11298
|
});
|
|
10116
|
-
this._error = result.done ? null : `${SHARED_CONFIG_PATH} is not on ${backend}`;
|
|
11299
|
+
this._error = result.done ? null : `${SHARED_CONFIG_PATH} is not on ${item.backend}`;
|
|
10117
11300
|
} catch (error) {
|
|
10118
11301
|
this._error = error instanceof Error ? error.message : String(error);
|
|
10119
11302
|
}
|
|
@@ -12155,6 +13338,9 @@ function environmentTools(host) {
|
|
|
12155
13338
|
run: async ({ direction, targets }, call) => {
|
|
12156
13339
|
if (host.environment.state().run?.finished === false) throw new McpToolError("A pull or push is already running");
|
|
12157
13340
|
const paths = targets.map((target) => target.path);
|
|
13341
|
+
const items = host.environment.state().items;
|
|
13342
|
+
const refused = paths.filter((path) => items.find((item) => item.path === path)?.allowed[direction] === false);
|
|
13343
|
+
if (refused.length > 0) throw new McpToolError(`The groups of the user do not let them ${direction} ${refused.join(", ")}`);
|
|
12158
13344
|
call.describe(`environment ${direction}`);
|
|
12159
13345
|
await call.authorize({
|
|
12160
13346
|
action: "run",
|
|
@@ -14740,7 +15926,10 @@ function createRuntimeConfig(raw, options) {
|
|
|
14740
15926
|
const base = mergeDeep({
|
|
14741
15927
|
loadBalancers: {},
|
|
14742
15928
|
adt: { notifications: true }
|
|
14743
|
-
}, raw, {
|
|
15929
|
+
}, raw, {
|
|
15930
|
+
adt: adtRuntimeOverrides,
|
|
15931
|
+
...Number.isInteger(options.dnsPort) && options.dnsPort > 0 ? { dns: { port: options.dnsPort } } : {}
|
|
15932
|
+
});
|
|
14744
15933
|
const serverConfig = toRecord(base.server);
|
|
14745
15934
|
const adtConfig = toRecord(base.adt);
|
|
14746
15935
|
delete adtConfig.uiPath;
|
|
@@ -14770,17 +15959,18 @@ function resolveConfigPaths(configPaths) {
|
|
|
14770
15959
|
}
|
|
14771
15960
|
/**
|
|
14772
15961
|
* Creates the loader of the merged configuration files, with the runtime overrides applied.
|
|
14773
|
-
* @param options Ports, SSL domain and UI path overriding the configuration files.
|
|
15962
|
+
* @param options Ports of the server, load balancer and DNS, SSL domain and UI path overriding the configuration files.
|
|
14774
15963
|
* @param configPaths Paths of the configuration files.
|
|
14775
15964
|
* @returns The configuration loader.
|
|
14776
15965
|
*/
|
|
14777
|
-
function createConfigProvider({ serverPort, loadBalancerPort, ssl, uiPath }, configPaths) {
|
|
15966
|
+
function createConfigProvider({ serverPort, loadBalancerPort, dnsPort, ssl, uiPath }, configPaths) {
|
|
14778
15967
|
return async () => {
|
|
14779
15968
|
const { config, loadedPaths, sources, localPath } = await loadMergedConfig(configPaths);
|
|
14780
15969
|
return {
|
|
14781
15970
|
raw: createRuntimeConfig(config, {
|
|
14782
15971
|
serverPort,
|
|
14783
15972
|
loadBalancerPort,
|
|
15973
|
+
dnsPort,
|
|
14784
15974
|
ssl: ssl ?? null,
|
|
14785
15975
|
uiPath: uiPath ?? null
|
|
14786
15976
|
}),
|
|
@@ -14849,7 +16039,7 @@ async function renewCertificates(names, configPaths = []) {
|
|
|
14849
16039
|
}
|
|
14850
16040
|
}
|
|
14851
16041
|
// package.json
|
|
14852
|
-
var version = "1.0.
|
|
16042
|
+
var version = "1.0.3";
|
|
14853
16043
|
// src/skills.ts
|
|
14854
16044
|
const MANIFEST = ".devtool-skills.json";
|
|
14855
16045
|
/**
|
|
@@ -15047,6 +16237,7 @@ async function exists(target) {
|
|
|
15047
16237
|
}
|
|
15048
16238
|
// src/index.ts
|
|
15049
16239
|
const UI_PATH = fileURLToPath(new URL("../ui", import.meta.url));
|
|
16240
|
+
const MAX_PORT = 65535;
|
|
15050
16241
|
/**
|
|
15051
16242
|
* Reads the identity provider of the configuration of the devtool installation.
|
|
15052
16243
|
* @returns The options.
|
|
@@ -15092,13 +16283,7 @@ async function openEnvironment(configPaths, bootstrap = true) {
|
|
|
15092
16283
|
};
|
|
15093
16284
|
try {
|
|
15094
16285
|
if (!(await environment.pull({
|
|
15095
|
-
item:
|
|
15096
|
-
kind: "file",
|
|
15097
|
-
path: "devtool/config.yml",
|
|
15098
|
-
backend: options.defaultBackend,
|
|
15099
|
-
encryption: null,
|
|
15100
|
-
ignore: null
|
|
15101
|
-
},
|
|
16286
|
+
item: sharedConfigItem(options),
|
|
15102
16287
|
tables: null
|
|
15103
16288
|
})).done) throw new Error(`${SHARED_CONFIG_PATH} is not on ${options.defaultBackend}`);
|
|
15104
16289
|
} finally {
|
|
@@ -15114,17 +16299,27 @@ async function closeBackends(backends) {
|
|
|
15114
16299
|
await Promise.all([...backends.values()].map(async (backend) => backend.close()));
|
|
15115
16300
|
}
|
|
15116
16301
|
/**
|
|
15117
|
-
* Runs a task on a backend of the environment,
|
|
16302
|
+
* Runs a task on a file of a backend of the environment, when the groups of the item stored there,
|
|
16303
|
+
* or else of the backend, let the developer transfer in the direction of the task, then closes the
|
|
16304
|
+
* backends. The task receives the path in its canonical form, the one the groups were checked for;
|
|
16305
|
+
* a path differing from the one of an item by its letter case, Unicode form or path spelling only is
|
|
16306
|
+
* refused.
|
|
15118
16307
|
* @param name The name of the backend, the default one when missing.
|
|
15119
|
-
* @param
|
|
16308
|
+
* @param filePath The path of the file in the backend.
|
|
16309
|
+
* @param direction Whether the task reads the file, or writes or deletes it.
|
|
16310
|
+
* @param task Uses the backend on the canonical path.
|
|
15120
16311
|
*/
|
|
15121
|
-
async function withBackend(name, task) {
|
|
15122
|
-
const { options, backends } = await openEnvironment(resolveDefaultConfigPaths(), false);
|
|
16312
|
+
async function withBackend(name, filePath, direction, task) {
|
|
16313
|
+
const { options, backends, environment } = await openEnvironment(resolveDefaultConfigPaths(), false);
|
|
15123
16314
|
try {
|
|
15124
16315
|
const slug = name ?? options.defaultBackend;
|
|
15125
16316
|
const backend = backends.get(slug);
|
|
15126
|
-
|
|
15127
|
-
|
|
16317
|
+
const settings = options.backends.find((candidate) => candidate.slug === slug);
|
|
16318
|
+
if (!backend || !settings) throw new Error(`no backend named ${slug} in environment.backends (${[...backends.keys()].join(", ")})`);
|
|
16319
|
+
const canonical = canonicalBackendPath(filePath);
|
|
16320
|
+
const refusal = await environment.refusal(itemStoredAt(options.items, slug, canonical) ?? settings, direction);
|
|
16321
|
+
if (refusal !== null) throw new Error(`${canonical} on ${slug}: ${refusal}`);
|
|
16322
|
+
await task(backend, canonical);
|
|
15128
16323
|
} finally {
|
|
15129
16324
|
await closeBackends(backends);
|
|
15130
16325
|
}
|
|
@@ -15147,7 +16342,7 @@ async function signIn(options) {
|
|
|
15147
16342
|
*/
|
|
15148
16343
|
function describeItem(item) {
|
|
15149
16344
|
switch (item.kind) {
|
|
15150
|
-
case "database": return `${item.path} (${item.engine} database of container ${item.container})`;
|
|
16345
|
+
case "database": return `${item.path} (${item.engine} database ${item.database === null ? "" : `${item.database} `}of container ${item.container})`;
|
|
15151
16346
|
case "bucket": return `${item.path} (bucket ${item.bucket})`;
|
|
15152
16347
|
case "redis": return `${item.path} (Redis ${redisDatabaseName(item.url)})`;
|
|
15153
16348
|
default: return `${item.path} (file)`;
|
|
@@ -15162,15 +16357,32 @@ function targetOf(selection) {
|
|
|
15162
16357
|
return selection.tables ? `${selection.item.path}:${selection.tables.join(",")}` : selection.item.path;
|
|
15163
16358
|
}
|
|
15164
16359
|
/**
|
|
15165
|
-
*
|
|
15166
|
-
* @param
|
|
15167
|
-
* @param
|
|
16360
|
+
* Keeps the items the groups of the developer let transfer in a direction, reporting the others as skipped.
|
|
16361
|
+
* @param environment The environment.
|
|
16362
|
+
* @param items The items.
|
|
16363
|
+
* @param direction The direction.
|
|
16364
|
+
* @returns The items that may be transferred.
|
|
16365
|
+
*/
|
|
16366
|
+
async function transferableItems(environment, items, direction) {
|
|
16367
|
+
const allowed = [];
|
|
16368
|
+
for (const item of items) {
|
|
16369
|
+
const refusal = await environment.refusal(item, direction);
|
|
16370
|
+
if (refusal === null) allowed.push(item);
|
|
16371
|
+
else logger.warn("CLI", "Env", `${item.path}: skipped, ${refusal}`);
|
|
16372
|
+
}
|
|
16373
|
+
return allowed;
|
|
16374
|
+
}
|
|
16375
|
+
/**
|
|
16376
|
+
* Asks which items, and which tables of the databases or key groups of the Redis databases when they
|
|
16377
|
+
* can be transferred alone, to transfer.
|
|
16378
|
+
* @param candidates The items to choose from.
|
|
16379
|
+
* @param direction The direction of the transfer.
|
|
15168
16380
|
* @returns The selections.
|
|
15169
16381
|
*/
|
|
15170
|
-
async function chooseSelections(
|
|
16382
|
+
async function chooseSelections(candidates, direction) {
|
|
15171
16383
|
const items = await checkbox({
|
|
15172
|
-
message: `Items to ${
|
|
15173
|
-
choices:
|
|
16384
|
+
message: `Items to ${direction}`,
|
|
16385
|
+
choices: candidates.map((item) => ({
|
|
15174
16386
|
name: describeItem(item),
|
|
15175
16387
|
value: item
|
|
15176
16388
|
})),
|
|
@@ -15179,7 +16391,7 @@ async function chooseSelections(options, verb) {
|
|
|
15179
16391
|
});
|
|
15180
16392
|
const selections = [];
|
|
15181
16393
|
for (const item of items) {
|
|
15182
|
-
if (item.kind !== "database" && item.kind !== "redis") {
|
|
16394
|
+
if (item.kind !== "database" && item.kind !== "redis" || !transfersParts(item, direction)) {
|
|
15183
16395
|
selections.push({
|
|
15184
16396
|
item,
|
|
15185
16397
|
tables: null
|
|
@@ -15246,7 +16458,8 @@ async function transfer(selections, run) {
|
|
|
15246
16458
|
if (failures > 0) throw new Error(`${failures} of ${selections.length} items failed`);
|
|
15247
16459
|
}
|
|
15248
16460
|
/**
|
|
15249
|
-
* Pulls or pushes items of the environment, chosen by targets or interactively
|
|
16461
|
+
* Pulls or pushes items of the environment, chosen by targets or interactively; without target, the
|
|
16462
|
+
* items the groups of the developer do not let transfer are skipped.
|
|
15250
16463
|
* @param direction Whether the copies of the backends replace the local ones, or the reverse.
|
|
15251
16464
|
* @param targets The targets, every item when empty.
|
|
15252
16465
|
* @param flags Whether to choose interactively and whether local data may be replaced without asking.
|
|
@@ -15254,7 +16467,15 @@ async function transfer(selections, run) {
|
|
|
15254
16467
|
async function syncEnvironment(direction, targets, flags) {
|
|
15255
16468
|
const { options, backends, environment } = await openEnvironment(resolveDefaultConfigPaths());
|
|
15256
16469
|
try {
|
|
15257
|
-
|
|
16470
|
+
let selections;
|
|
16471
|
+
if (targets.length > 0 && !flags.interactive) selections = parseTargets(options, targets);
|
|
16472
|
+
else {
|
|
16473
|
+
const items = await transferableItems(environment, options.items, direction);
|
|
16474
|
+
selections = flags.interactive && items.length > 0 ? await chooseSelections(items, direction) : items.map((item) => ({
|
|
16475
|
+
item,
|
|
16476
|
+
tables: null
|
|
16477
|
+
}));
|
|
16478
|
+
}
|
|
15258
16479
|
if (direction === "push") {
|
|
15259
16480
|
await transfer(selections, (selection) => environment.push(selection));
|
|
15260
16481
|
return;
|
|
@@ -15323,11 +16544,23 @@ async function syncAgentSkills(flags) {
|
|
|
15323
16544
|
if (result.skipped.length) logger.warn("CLI", "Skills", `${folder.replace(os.homedir(), "~")}: kept the skills of the same name you made: ${result.skipped.join(", ")}`);
|
|
15324
16545
|
}
|
|
15325
16546
|
}
|
|
16547
|
+
/**
|
|
16548
|
+
* Reads a port given on the command line.
|
|
16549
|
+
* @param input The value given.
|
|
16550
|
+
* @param label What the port is for, in the error message.
|
|
16551
|
+
* @returns The port, between 1 and 65535.
|
|
16552
|
+
*/
|
|
15326
16553
|
function parsePort(input, label) {
|
|
15327
16554
|
const parsed = Number(input);
|
|
15328
|
-
if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(`Invalid ${label}: ${input}`);
|
|
16555
|
+
if (!Number.isInteger(parsed) || parsed <= 0 || parsed > MAX_PORT) throw new Error(`Invalid ${label}: ${input}, must be between 1 and ${MAX_PORT}`);
|
|
15329
16556
|
return parsed;
|
|
15330
16557
|
}
|
|
16558
|
+
/**
|
|
16559
|
+
* Reads a port given on the command line, when one is.
|
|
16560
|
+
* @param input The value given, undefined when the option is left out.
|
|
16561
|
+
* @param label What the port is for, in the error message.
|
|
16562
|
+
* @returns The port, undefined when none is given.
|
|
16563
|
+
*/
|
|
15331
16564
|
function parseOptionalPort(input, label) {
|
|
15332
16565
|
if (typeof input !== "string") return;
|
|
15333
16566
|
return parsePort(input, label);
|
|
@@ -15345,7 +16578,7 @@ async function main() {
|
|
|
15345
16578
|
process.env[CONFIG_FOLDER_VARIABLE] = folder.startsWith("~") ? folder : path.resolve(invocationCwd, folder);
|
|
15346
16579
|
}
|
|
15347
16580
|
});
|
|
15348
|
-
program.command("server [configurations...]").description("Run Devtool server").option("-s, --ssl <domain>", "enable SSL for the domain given").option("-g, --server-port <port>", "server port").option("-l, --load-balancer-port <port>", "load balancer port").option("--log-level <level>", "set log level (error|warn|info|debug)", "info").action(async (configurations, options) => {
|
|
16581
|
+
program.command("server [configurations...]").description("Run Devtool server").option("-s, --ssl <domain>", "enable SSL for the domain given").option("-g, --server-port <port>", "server port").option("-l, --load-balancer-port <port>", "load balancer port").option("--dns-port <port>", "DNS port, instead of dns.port of the configuration").option("--log-level <level>", "set log level (error|warn|info|debug)", "info").action(async (configurations, options) => {
|
|
15349
16582
|
const invocationCwd = process.env.INIT_CWD?.length ? process.env.INIT_CWD : process.cwd();
|
|
15350
16583
|
const configPaths = configurations.length ? configurations.map((configuration) => path.isAbsolute(configuration) ? configuration : path.resolve(invocationCwd, configuration)) : resolveDefaultConfigPaths();
|
|
15351
16584
|
if (await relaunchUnderApp((await loadMergedConfig(configPaths)).config)) return;
|
|
@@ -15353,6 +16586,7 @@ async function main() {
|
|
|
15353
16586
|
await runServer({
|
|
15354
16587
|
serverPort: parseOptionalPort(options.serverPort, "server port"),
|
|
15355
16588
|
loadBalancerPort: parseOptionalPort(options.loadBalancerPort, "load balancer port"),
|
|
16589
|
+
dnsPort: parseOptionalPort(options.dnsPort, "DNS port"),
|
|
15356
16590
|
ssl: options.ssl ?? null,
|
|
15357
16591
|
uiPath: UI_PATH,
|
|
15358
16592
|
configPaths
|
|
@@ -15374,8 +16608,8 @@ async function main() {
|
|
|
15374
16608
|
});
|
|
15375
16609
|
const env = program.command("env").description("Development environment (environment.folder), mirrored on its backends: configurations, databases, buckets, Redis databases").addHelpText("after", "\nTargets: <path> for an item, <path>:<table>,<table> for tables of a database, <path>:<group>,<group> for key groups of a Redis database (such as account/redis.gz:session:*); every item without target.");
|
|
15376
16610
|
const file = env.command("file").description("Any file of a backend, by hand");
|
|
15377
|
-
file.command("pull <path> [destination]").description("Download a file; `-` as destination writes it to the standard output").option("-b, --backend <name>", "backend of environment.backends, the default one when omitted").action(async (
|
|
15378
|
-
await withBackend(flags.backend, async (backend) => {
|
|
16611
|
+
file.command("pull <path> [destination]").description("Download a file; `-` as destination writes it to the standard output").option("-b, --backend <name>", "backend of environment.backends, the default one when omitted").action(async (given, destination, flags) => {
|
|
16612
|
+
await withBackend(flags.backend, given, "pull", async (backend, filePath) => {
|
|
15379
16613
|
const content = await backend.download(filePath);
|
|
15380
16614
|
if (!content) throw new Error(`no such file: ${filePath}`);
|
|
15381
16615
|
if (destination === "-") {
|
|
@@ -15393,14 +16627,14 @@ async function main() {
|
|
|
15393
16627
|
logger.info("CLI", "Pull", `${filePath} -> ${target}`);
|
|
15394
16628
|
});
|
|
15395
16629
|
});
|
|
15396
|
-
file.command("push <path> <file>").description("Upload a file, replacing the stored one").option("-b, --backend <name>", "backend of environment.backends, the default one when omitted").option("-t, --type <mediaType>", "media type of the file, guessed from its name when omitted").action(async (
|
|
15397
|
-
await withBackend(flags.backend, async (backend) => {
|
|
16630
|
+
file.command("push <path> <file>").description("Upload a file, replacing the stored one").option("-b, --backend <name>", "backend of environment.backends, the default one when omitted").option("-t, --type <mediaType>", "media type of the file, guessed from its name when omitted").action(async (given, localFile, flags) => {
|
|
16631
|
+
await withBackend(flags.backend, given, "push", async (backend, filePath) => {
|
|
15398
16632
|
await backend.upload(filePath, path.resolve(localFile), flags.type ?? mediaTypeOf(filePath));
|
|
15399
16633
|
logger.info("CLI", "Push", `${localFile} -> ${filePath}`);
|
|
15400
16634
|
});
|
|
15401
16635
|
});
|
|
15402
|
-
file.command("rm <path>").description("Delete a file").option("-b, --backend <name>", "backend of environment.backends, the default one when omitted").action(async (
|
|
15403
|
-
await withBackend(flags.backend, async (backend) => {
|
|
16636
|
+
file.command("rm <path>").description("Delete a file").option("-b, --backend <name>", "backend of environment.backends, the default one when omitted").action(async (given, flags) => {
|
|
16637
|
+
await withBackend(flags.backend, given, "push", async (backend, filePath) => {
|
|
15404
16638
|
await backend.remove(filePath);
|
|
15405
16639
|
logger.info("CLI", "Remove", filePath);
|
|
15406
16640
|
});
|