@solidactions/cli 3.6.0 → 3.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -0
- package/dist/command-manifest.json +612 -1
- package/dist/commands/crew-env-list.js +15 -5
- package/dist/commands/crew-env-map-database.js +58 -0
- package/dist/commands/database.js +1317 -0
- package/dist/commands/device-login.js +1 -1
- package/dist/commands/env-list.js +21 -1
- package/dist/commands/login.js +1 -1
- package/dist/commands/skill-run.js +5 -1
- package/dist/commands/workspaces.js +23 -36
- package/dist/index.js +106 -0
- package/dist/utils/api.js +26 -4
- package/dist/utils/database-client-support.js +68 -0
- package/dist/utils/database-data-plane.js +237 -0
- package/dist/utils/database-sql-import-runner.js +466 -0
- package/dist/utils/database-sql-import.js +381 -0
- package/dist/utils/examples-ref.js +7 -4
- package/dist/utils/skills.js +1 -1
- package/dist/utils/workspace-lookup.js +65 -6
- package/package.json +3 -2
|
@@ -0,0 +1,1317 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.parseDatabaseImportSql = void 0;
|
|
40
|
+
exports.databaseListWithConfig = databaseListWithConfig;
|
|
41
|
+
exports.databaseCreateWithConfig = databaseCreateWithConfig;
|
|
42
|
+
exports.databaseImportWithConfig = databaseImportWithConfig;
|
|
43
|
+
exports.databaseDeleteWithConfig = databaseDeleteWithConfig;
|
|
44
|
+
exports.databaseUndeleteWithConfig = databaseUndeleteWithConfig;
|
|
45
|
+
exports.databaseSchemaWithConfig = databaseSchemaWithConfig;
|
|
46
|
+
exports.databaseQueryWithConfig = databaseQueryWithConfig;
|
|
47
|
+
exports.databaseExecWithConfig = databaseExecWithConfig;
|
|
48
|
+
exports.databaseDumpWithConfig = databaseDumpWithConfig;
|
|
49
|
+
exports.databasePullWithConfig = databasePullWithConfig;
|
|
50
|
+
exports.databaseList = databaseList;
|
|
51
|
+
exports.databaseCreate = databaseCreate;
|
|
52
|
+
exports.databaseDelete = databaseDelete;
|
|
53
|
+
exports.databaseUndelete = databaseUndelete;
|
|
54
|
+
exports.databaseSchema = databaseSchema;
|
|
55
|
+
exports.databaseQuery = databaseQuery;
|
|
56
|
+
exports.databaseExec = databaseExec;
|
|
57
|
+
exports.databaseDump = databaseDump;
|
|
58
|
+
exports.databasePull = databasePull;
|
|
59
|
+
exports.databaseImport = databaseImport;
|
|
60
|
+
const fs_1 = __importDefault(require("fs"));
|
|
61
|
+
const path_1 = __importDefault(require("path"));
|
|
62
|
+
const readline = __importStar(require("readline"));
|
|
63
|
+
const crypto_1 = require("crypto");
|
|
64
|
+
const url_1 = require("url");
|
|
65
|
+
const api_1 = require("../utils/api");
|
|
66
|
+
const database_data_plane_1 = require("../utils/database-data-plane");
|
|
67
|
+
const database_client_support_1 = require("../utils/database-client-support");
|
|
68
|
+
const database_sql_import_1 = require("../utils/database-sql-import");
|
|
69
|
+
var database_sql_import_2 = require("../utils/database-sql-import");
|
|
70
|
+
Object.defineProperty(exports, "parseDatabaseImportSql", { enumerable: true, get: function () { return database_sql_import_2.parseDatabaseImportSql; } });
|
|
71
|
+
const database_sql_import_runner_1 = require("../utils/database-sql-import-runner");
|
|
72
|
+
const table_1 = require("../utils/table");
|
|
73
|
+
function defaultConfirmation(message) {
|
|
74
|
+
const input = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
75
|
+
return new Promise((resolve) => {
|
|
76
|
+
let settled = false;
|
|
77
|
+
const finish = (confirmed) => {
|
|
78
|
+
if (settled)
|
|
79
|
+
return;
|
|
80
|
+
settled = true;
|
|
81
|
+
resolve(confirmed);
|
|
82
|
+
};
|
|
83
|
+
input.once('close', () => finish(false));
|
|
84
|
+
input.question(`${message} [y/N] `, (answer) => {
|
|
85
|
+
finish(/^y(?:es)?$/i.test(answer.trim()));
|
|
86
|
+
input.close();
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function resolveDependencies(dependencies) {
|
|
91
|
+
return {
|
|
92
|
+
stdout: dependencies.stdout ?? ((line) => console.log(line)),
|
|
93
|
+
stderr: dependencies.stderr ?? ((line) => console.error(line)),
|
|
94
|
+
confirm: async (message) => (await (dependencies.confirm ?? defaultConfirmation)(message)) === true,
|
|
95
|
+
isTTY: dependencies.isTTY ?? process.stdin.isTTY === true,
|
|
96
|
+
importDatabase: dependencies.importDatabase,
|
|
97
|
+
post: dependencies.post,
|
|
98
|
+
loadClient: dependencies.loadClient,
|
|
99
|
+
cwd: dependencies.cwd ?? process.cwd(),
|
|
100
|
+
tempPath: dependencies.tempPath ?? ((target) => path_1.default.join(path_1.default.dirname(target), `.${path_1.default.basename(target)}.solidactions-${(0, crypto_1.randomUUID)()}.tmp`)),
|
|
101
|
+
filesystem: dependencies.filesystem ?? fs_1.default.promises,
|
|
102
|
+
input: dependencies.input,
|
|
103
|
+
now: dependencies.now ?? Date.now,
|
|
104
|
+
abortSignal: dependencies.abortSignal,
|
|
105
|
+
controlPlaneTimeoutMs: dependencies.controlPlaneTimeoutMs,
|
|
106
|
+
dataPlaneTimeoutMs: dependencies.dataPlaneTimeoutMs ?? database_data_plane_1.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS,
|
|
107
|
+
sleep: dependencies.sleep ?? ((milliseconds) => new Promise((resolve) => {
|
|
108
|
+
setTimeout(resolve, milliseconds);
|
|
109
|
+
})),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function requestDependencies(dependencies) {
|
|
113
|
+
return {
|
|
114
|
+
post: dependencies.post,
|
|
115
|
+
controlPlaneTimeoutMs: dependencies.controlPlaneTimeoutMs,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function clientDependencies(dependencies) {
|
|
119
|
+
return {
|
|
120
|
+
post: dependencies.post,
|
|
121
|
+
loadClient: dependencies.loadClient,
|
|
122
|
+
controlPlaneTimeoutMs: dependencies.controlPlaneTimeoutMs,
|
|
123
|
+
dataPlaneTimeoutMs: dependencies.dataPlaneTimeoutMs,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function stableDatabaseRecord(database) {
|
|
127
|
+
if (!database
|
|
128
|
+
|| (database.id !== undefined && typeof database.id !== 'string')
|
|
129
|
+
|| typeof database.name !== 'string'
|
|
130
|
+
|| typeof database.status !== 'string'
|
|
131
|
+
|| typeof database.size_bytes !== 'number'
|
|
132
|
+
|| (database.deleted_at !== null && typeof database.deleted_at !== 'string')
|
|
133
|
+
|| (database.purge_at !== null && typeof database.purge_at !== 'string')) {
|
|
134
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'The database response was invalid.');
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
...(database.id === undefined ? {} : { id: database.id }),
|
|
138
|
+
name: database.name,
|
|
139
|
+
status: database.status,
|
|
140
|
+
deleted_at: database.deleted_at,
|
|
141
|
+
purge_at: database.purge_at,
|
|
142
|
+
size_bytes: database.size_bytes,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function stableDatabaseResponse(data) {
|
|
146
|
+
return { database: stableDatabaseRecord(data?.database) };
|
|
147
|
+
}
|
|
148
|
+
function stableListResponse(data) {
|
|
149
|
+
if (!data
|
|
150
|
+
|| !Array.isArray(data.databases)
|
|
151
|
+
|| typeof data.quota?.used !== 'number'
|
|
152
|
+
|| typeof data.quota?.limit !== 'number') {
|
|
153
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'The database response was invalid.');
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
databases: data.databases.map(stableDatabaseRecord),
|
|
157
|
+
quota: {
|
|
158
|
+
used: data.quota.used,
|
|
159
|
+
limit: data.quota.limit,
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function databaseRows(databases) {
|
|
164
|
+
return databases.map((database) => [
|
|
165
|
+
database.name,
|
|
166
|
+
database.status,
|
|
167
|
+
String(database.size_bytes),
|
|
168
|
+
database.deleted_at ?? '-',
|
|
169
|
+
database.purge_at ?? '-',
|
|
170
|
+
]);
|
|
171
|
+
}
|
|
172
|
+
function renderDatabaseTable(databases) {
|
|
173
|
+
return (0, table_1.renderTable)(['NAME', 'STATUS', 'SIZE (BYTES)', 'DELETED AT', 'PURGE AT'], databaseRows(databases)).join('\n');
|
|
174
|
+
}
|
|
175
|
+
function renderMutation(operation, database) {
|
|
176
|
+
const verb = operation === 'create'
|
|
177
|
+
? 'created'
|
|
178
|
+
: operation === 'delete'
|
|
179
|
+
? 'deleted'
|
|
180
|
+
: 'restored';
|
|
181
|
+
return `Database "${database.name}" ${verb}.\n${renderDatabaseTable([database])}`;
|
|
182
|
+
}
|
|
183
|
+
function writeJson(stdout, data) {
|
|
184
|
+
stdout(JSON.stringify(data, null, 2));
|
|
185
|
+
}
|
|
186
|
+
const TABLE_CATALOG_SQL = "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND sql IS NOT NULL ORDER BY name";
|
|
187
|
+
const INDEX_CATALOG_SQL = "SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%' ORDER BY name";
|
|
188
|
+
function isDirectValue(value) {
|
|
189
|
+
return value === null
|
|
190
|
+
|| typeof value === 'string'
|
|
191
|
+
|| (typeof value === 'number' && Number.isFinite(value))
|
|
192
|
+
|| typeof value === 'bigint'
|
|
193
|
+
|| value instanceof ArrayBuffer
|
|
194
|
+
|| ArrayBuffer.isView(value);
|
|
195
|
+
}
|
|
196
|
+
function stableLastInsertRowid(value) {
|
|
197
|
+
if (value === undefined || value === null) {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
if (typeof value === 'bigint') {
|
|
201
|
+
return value;
|
|
202
|
+
}
|
|
203
|
+
if (typeof value === 'number' && Number.isSafeInteger(value)) {
|
|
204
|
+
return value;
|
|
205
|
+
}
|
|
206
|
+
if (typeof value === 'string' && /^-?\d+$/.test(value)) {
|
|
207
|
+
return value;
|
|
208
|
+
}
|
|
209
|
+
throw new Error('Invalid last insert row ID.');
|
|
210
|
+
}
|
|
211
|
+
function stableDirectResult(result) {
|
|
212
|
+
if (!result || !Array.isArray(result.columns) || !Array.isArray(result.rows)) {
|
|
213
|
+
throw new Error('Invalid database result.');
|
|
214
|
+
}
|
|
215
|
+
if (!result.columns.every((column) => typeof column === 'string')) {
|
|
216
|
+
throw new Error('Invalid database result columns.');
|
|
217
|
+
}
|
|
218
|
+
const rows = result.rows.map((row) => {
|
|
219
|
+
if (row === null
|
|
220
|
+
|| typeof row !== 'object'
|
|
221
|
+
|| !Number.isSafeInteger(row.length)
|
|
222
|
+
|| row.length !== result.columns.length) {
|
|
223
|
+
throw new Error('Invalid database result row.');
|
|
224
|
+
}
|
|
225
|
+
const positional = Array.from({ length: row.length }, (_, index) => row[index]);
|
|
226
|
+
if (!positional.every(isDirectValue)) {
|
|
227
|
+
throw new Error('Invalid database result value.');
|
|
228
|
+
}
|
|
229
|
+
return positional;
|
|
230
|
+
});
|
|
231
|
+
if (result.rowsAffected !== undefined
|
|
232
|
+
&& (!Number.isSafeInteger(result.rowsAffected) || result.rowsAffected < 0)) {
|
|
233
|
+
throw new Error('Invalid affected row count.');
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
columns: [...result.columns],
|
|
237
|
+
rows,
|
|
238
|
+
rowsAffected: result.rowsAffected ?? 0,
|
|
239
|
+
lastInsertRowid: stableLastInsertRowid(result.lastInsertRowid),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
function sqliteInteger(value) {
|
|
243
|
+
if ((typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'bigint')
|
|
244
|
+
|| String(value).trim() === '') {
|
|
245
|
+
throw new Error('Invalid SQLite integer.');
|
|
246
|
+
}
|
|
247
|
+
const parsed = Number(value);
|
|
248
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0) {
|
|
249
|
+
throw new Error('Invalid SQLite integer.');
|
|
250
|
+
}
|
|
251
|
+
return parsed;
|
|
252
|
+
}
|
|
253
|
+
function sqliteBoolean(value) {
|
|
254
|
+
const parsed = sqliteInteger(value);
|
|
255
|
+
if (parsed !== 0 && parsed !== 1) {
|
|
256
|
+
throw new Error('Invalid SQLite boolean.');
|
|
257
|
+
}
|
|
258
|
+
return parsed === 1;
|
|
259
|
+
}
|
|
260
|
+
function requiredString(value) {
|
|
261
|
+
if (typeof value !== 'string') {
|
|
262
|
+
throw new Error('Invalid database metadata.');
|
|
263
|
+
}
|
|
264
|
+
return value;
|
|
265
|
+
}
|
|
266
|
+
function nullableString(value) {
|
|
267
|
+
if (value === null || typeof value === 'string') {
|
|
268
|
+
return value;
|
|
269
|
+
}
|
|
270
|
+
throw new Error('Invalid database metadata.');
|
|
271
|
+
}
|
|
272
|
+
function quotePragmaIdentifier(identifier) {
|
|
273
|
+
return `"${identifier.replace(/"/g, '""')}"`;
|
|
274
|
+
}
|
|
275
|
+
function normalizedRows(result) {
|
|
276
|
+
return result.rows.map((row) => row.map(database_data_plane_1.normalizeDatabaseValue));
|
|
277
|
+
}
|
|
278
|
+
function renderDirectTable(result) {
|
|
279
|
+
return (0, table_1.renderTable)(result.columns, result.rows.map((row) => row.map(database_data_plane_1.formatDatabaseTableValue))).join('\n');
|
|
280
|
+
}
|
|
281
|
+
async function readDatabaseSchema(client, database) {
|
|
282
|
+
const tablesResult = stableDirectResult(await client.execute(TABLE_CATALOG_SQL));
|
|
283
|
+
const indexesResult = stableDirectResult(await client.execute(INDEX_CATALOG_SQL));
|
|
284
|
+
const indexesByTable = new Map();
|
|
285
|
+
for (const row of indexesResult.rows) {
|
|
286
|
+
const index = {
|
|
287
|
+
name: requiredString(row[0]),
|
|
288
|
+
sql: nullableString(row[2]),
|
|
289
|
+
};
|
|
290
|
+
const tableName = requiredString(row[1]);
|
|
291
|
+
indexesByTable.set(tableName, [...(indexesByTable.get(tableName) ?? []), index]);
|
|
292
|
+
}
|
|
293
|
+
const tables = [];
|
|
294
|
+
for (const row of tablesResult.rows) {
|
|
295
|
+
const name = requiredString(row[0]);
|
|
296
|
+
const pragma = `PRAGMA table_info(${quotePragmaIdentifier(name)})`;
|
|
297
|
+
const columnsResult = stableDirectResult(await client.execute(pragma));
|
|
298
|
+
const columns = columnsResult.rows.map((column) => ({
|
|
299
|
+
name: requiredString(column[1]),
|
|
300
|
+
type: requiredString(column[2]),
|
|
301
|
+
notnull: sqliteBoolean(column[3]),
|
|
302
|
+
default: (0, database_data_plane_1.normalizeDatabaseValue)(column[4]),
|
|
303
|
+
pk: sqliteInteger(column[5]),
|
|
304
|
+
}));
|
|
305
|
+
tables.push({
|
|
306
|
+
name,
|
|
307
|
+
sql: requiredString(row[1]),
|
|
308
|
+
columns,
|
|
309
|
+
indexes: indexesByTable.get(name) ?? [],
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
return { database, tables };
|
|
313
|
+
}
|
|
314
|
+
function renderSchema(schema) {
|
|
315
|
+
if (schema.tables.length === 0) {
|
|
316
|
+
return `Database: ${schema.database}\nNo tables.`;
|
|
317
|
+
}
|
|
318
|
+
const sections = [`Database: ${schema.database}`];
|
|
319
|
+
for (const table of schema.tables) {
|
|
320
|
+
sections.push(`Table: ${table.name}`, (0, table_1.renderTable)(['NAME', 'TYPE', 'NOT NULL', 'DEFAULT', 'PK ORDER'], table.columns.map((column) => [
|
|
321
|
+
column.name,
|
|
322
|
+
column.type,
|
|
323
|
+
column.notnull ? 'yes' : 'no',
|
|
324
|
+
(0, database_data_plane_1.formatDatabaseTableValue)(column.default),
|
|
325
|
+
String(column.pk),
|
|
326
|
+
])).join('\n'));
|
|
327
|
+
if (table.indexes.length > 0) {
|
|
328
|
+
sections.push('Indexes:', (0, table_1.renderTable)(['NAME', 'SQL'], table.indexes.map((index) => [index.name, index.sql ?? 'NULL'])).join('\n'));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return sections.join('\n\n');
|
|
332
|
+
}
|
|
333
|
+
const INCOMPLETE_DUMP_MARKER = '-- DOWNLOAD INCOMPLETE';
|
|
334
|
+
const DUMP_TAIL_BYTES = 4096;
|
|
335
|
+
const PULL_ATTEMPTS = 3;
|
|
336
|
+
const PULL_RETRY_BACKOFF_MS = [250, 500];
|
|
337
|
+
function safeDatabaseStem(name) {
|
|
338
|
+
return name
|
|
339
|
+
.toLowerCase()
|
|
340
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
341
|
+
.replace(/^-+|-+$/g, '') || 'database';
|
|
342
|
+
}
|
|
343
|
+
function errorCode(error) {
|
|
344
|
+
return error && typeof error === 'object' && typeof error.code === 'string'
|
|
345
|
+
? error.code
|
|
346
|
+
: undefined;
|
|
347
|
+
}
|
|
348
|
+
function freshSafeFileError(error) {
|
|
349
|
+
if (error instanceof database_data_plane_1.DatabaseOperationError) {
|
|
350
|
+
return new database_data_plane_1.DatabaseOperationError(error.code, error.message, error.status);
|
|
351
|
+
}
|
|
352
|
+
if (errorCode(error) === 'database_client_unsupported') {
|
|
353
|
+
return new database_data_plane_1.DatabaseOperationError('database_client_unsupported', 'Database commands are not supported on this platform.');
|
|
354
|
+
}
|
|
355
|
+
return new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
356
|
+
}
|
|
357
|
+
function isMissingPath(error) {
|
|
358
|
+
return errorCode(error) === 'ENOENT';
|
|
359
|
+
}
|
|
360
|
+
async function lstatIfPresent(filesystem, candidate) {
|
|
361
|
+
try {
|
|
362
|
+
return await filesystem.lstat(candidate);
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
if (isMissingPath(error))
|
|
366
|
+
return null;
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
async function assertNoSymlinkComponents(filesystem, destination) {
|
|
371
|
+
const absolute = path_1.default.resolve(destination);
|
|
372
|
+
const root = path_1.default.parse(absolute).root;
|
|
373
|
+
const relative = absolute.slice(root.length);
|
|
374
|
+
const components = relative.split(path_1.default.sep).filter(Boolean);
|
|
375
|
+
let current = root;
|
|
376
|
+
for (const component of components) {
|
|
377
|
+
current = path_1.default.join(current, component);
|
|
378
|
+
const stat = await lstatIfPresent(filesystem, current);
|
|
379
|
+
if (stat?.isSymbolicLink()) {
|
|
380
|
+
throw new database_data_plane_1.DatabaseOperationError('unsafe_destination', 'Destination paths cannot contain symbolic links.');
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
async function confirmFileOverwrite(target, options, io) {
|
|
385
|
+
await assertNoSymlinkComponents(io.filesystem, target);
|
|
386
|
+
const targetStat = await lstatIfPresent(io.filesystem, target);
|
|
387
|
+
if (!targetStat)
|
|
388
|
+
return true;
|
|
389
|
+
if (!targetStat.isFile()) {
|
|
390
|
+
throw new database_data_plane_1.DatabaseOperationError('unsafe_destination', 'Destination must be a regular file.');
|
|
391
|
+
}
|
|
392
|
+
if (options.yes)
|
|
393
|
+
return true;
|
|
394
|
+
if (!io.isTTY) {
|
|
395
|
+
throw new database_data_plane_1.DatabaseOperationError('confirmation_required', 'Overwriting an existing database file requires --yes in non-interactive mode.');
|
|
396
|
+
}
|
|
397
|
+
if (!await io.confirm(`Overwrite "${target}"?`)) {
|
|
398
|
+
io.stdout('Cancelled.');
|
|
399
|
+
return false;
|
|
400
|
+
}
|
|
401
|
+
return true;
|
|
402
|
+
}
|
|
403
|
+
function resolveDatabaseDestination(io, requested, fallback) {
|
|
404
|
+
return path_1.default.resolve(io.cwd, requested ?? fallback);
|
|
405
|
+
}
|
|
406
|
+
function validatedTempPath(io, target) {
|
|
407
|
+
const temp = path_1.default.resolve(io.tempPath(target));
|
|
408
|
+
if (temp === target || path_1.default.dirname(temp) !== path_1.default.dirname(target)) {
|
|
409
|
+
throw new database_data_plane_1.DatabaseOperationError('unsafe_destination', 'The temporary database file must be a sibling of its destination.');
|
|
410
|
+
}
|
|
411
|
+
return temp;
|
|
412
|
+
}
|
|
413
|
+
async function reserveDestinationTemp(io, target) {
|
|
414
|
+
const parent = path_1.default.dirname(target);
|
|
415
|
+
await assertNoSymlinkComponents(io.filesystem, target);
|
|
416
|
+
await io.filesystem.mkdir(parent, { recursive: true });
|
|
417
|
+
await assertNoSymlinkComponents(io.filesystem, target);
|
|
418
|
+
const temp = validatedTempPath(io, target);
|
|
419
|
+
await assertNoSymlinkComponents(io.filesystem, temp);
|
|
420
|
+
const handle = await io.filesystem.open(temp, 'wx', 0o600);
|
|
421
|
+
return { temp, handle };
|
|
422
|
+
}
|
|
423
|
+
async function removeOwnedFiles(filesystem, paths) {
|
|
424
|
+
for (const candidate of paths) {
|
|
425
|
+
try {
|
|
426
|
+
await filesystem.unlink(candidate);
|
|
427
|
+
}
|
|
428
|
+
catch {
|
|
429
|
+
// Cleanup is best effort and may target only paths owned by this invocation.
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
function pullSidecars(temp) {
|
|
434
|
+
return [`${temp}-wal`, `${temp}-shm`, `${temp}-journal`, `${temp}-client_wal_index`];
|
|
435
|
+
}
|
|
436
|
+
async function anyPathExists(filesystem, candidates) {
|
|
437
|
+
for (const candidate of candidates) {
|
|
438
|
+
if (await lstatIfPresent(filesystem, candidate))
|
|
439
|
+
return true;
|
|
440
|
+
}
|
|
441
|
+
return false;
|
|
442
|
+
}
|
|
443
|
+
function streamChunk(value) {
|
|
444
|
+
if (typeof value === 'string')
|
|
445
|
+
return Buffer.from(value);
|
|
446
|
+
if (Buffer.isBuffer(value))
|
|
447
|
+
return value;
|
|
448
|
+
if (value instanceof ArrayBuffer)
|
|
449
|
+
return Buffer.from(value);
|
|
450
|
+
if (ArrayBuffer.isView(value)) {
|
|
451
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
452
|
+
}
|
|
453
|
+
throw new Error('Invalid database dump stream chunk.');
|
|
454
|
+
}
|
|
455
|
+
async function writeDumpStream(stream, handle) {
|
|
456
|
+
if (!stream || typeof stream[Symbol.asyncIterator] !== 'function') {
|
|
457
|
+
throw new Error('Invalid database dump stream.');
|
|
458
|
+
}
|
|
459
|
+
let tail = Buffer.alloc(0);
|
|
460
|
+
for await (const value of stream) {
|
|
461
|
+
const chunk = streamChunk(value);
|
|
462
|
+
let offset = 0;
|
|
463
|
+
while (offset < chunk.byteLength) {
|
|
464
|
+
const { bytesWritten } = await handle.write(chunk, offset, chunk.byteLength - offset, null);
|
|
465
|
+
if (bytesWritten <= 0)
|
|
466
|
+
throw new Error('Database dump write failed.');
|
|
467
|
+
offset += bytesWritten;
|
|
468
|
+
}
|
|
469
|
+
tail = Buffer.concat([tail, chunk]);
|
|
470
|
+
if (tail.byteLength > DUMP_TAIL_BYTES) {
|
|
471
|
+
tail = tail.subarray(tail.byteLength - DUMP_TAIL_BYTES);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return tail;
|
|
475
|
+
}
|
|
476
|
+
function displayDestination(io, target) {
|
|
477
|
+
return path_1.default.relative(io.cwd, target) || path_1.default.basename(target);
|
|
478
|
+
}
|
|
479
|
+
function checkpointInteger(value) {
|
|
480
|
+
if (typeof value === 'bigint' && value >= 0n)
|
|
481
|
+
return value;
|
|
482
|
+
if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)
|
|
483
|
+
return BigInt(value);
|
|
484
|
+
if (typeof value === 'string' && /^\d+$/.test(value))
|
|
485
|
+
return BigInt(value);
|
|
486
|
+
throw new Error('Invalid database checkpoint result.');
|
|
487
|
+
}
|
|
488
|
+
function validateCheckpointResult(result) {
|
|
489
|
+
if (!result || !Array.isArray(result.rows) || result.rows.length !== 1) {
|
|
490
|
+
throw new Error('Invalid database checkpoint result.');
|
|
491
|
+
}
|
|
492
|
+
const row = result.rows[0];
|
|
493
|
+
if (!row || !Number.isSafeInteger(row.length) || row.length < 3) {
|
|
494
|
+
throw new Error('Invalid database checkpoint result.');
|
|
495
|
+
}
|
|
496
|
+
const busy = checkpointInteger(row[0]);
|
|
497
|
+
const log = checkpointInteger(row[1]);
|
|
498
|
+
const checkpointed = checkpointInteger(row[2]);
|
|
499
|
+
if (busy !== 0n || checkpointed < log) {
|
|
500
|
+
throw new Error('Database checkpoint did not complete.');
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
const WRITABLE_RENEWAL_WINDOW_MS = 30_000;
|
|
504
|
+
const WRITABLE_WARNING = 'Writable live session: writes go to the live workspace database.';
|
|
505
|
+
const WRITABLE_PROMPT = 'solidactions-db> ';
|
|
506
|
+
const WRITABLE_CONTINUATION_PROMPT = '...> ';
|
|
507
|
+
function createWritableInput(io) {
|
|
508
|
+
if (io.input) {
|
|
509
|
+
const iterator = io.input[Symbol.asyncIterator]();
|
|
510
|
+
return {
|
|
511
|
+
iterator,
|
|
512
|
+
prompt: () => undefined,
|
|
513
|
+
interrupted: () => false,
|
|
514
|
+
close: async () => {
|
|
515
|
+
await iterator.return?.();
|
|
516
|
+
},
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
const input = readline.createInterface({
|
|
520
|
+
input: process.stdin,
|
|
521
|
+
output: process.stdout,
|
|
522
|
+
terminal: io.isTTY,
|
|
523
|
+
});
|
|
524
|
+
let interrupted = false;
|
|
525
|
+
const onSigint = () => {
|
|
526
|
+
interrupted = true;
|
|
527
|
+
input.close();
|
|
528
|
+
};
|
|
529
|
+
input.on('SIGINT', onSigint);
|
|
530
|
+
const iterator = input[Symbol.asyncIterator]();
|
|
531
|
+
return {
|
|
532
|
+
iterator,
|
|
533
|
+
prompt: (pending) => {
|
|
534
|
+
if (!io.isTTY)
|
|
535
|
+
return;
|
|
536
|
+
input.setPrompt(pending ? WRITABLE_CONTINUATION_PROMPT : WRITABLE_PROMPT);
|
|
537
|
+
input.prompt();
|
|
538
|
+
},
|
|
539
|
+
interrupted: () => interrupted,
|
|
540
|
+
close: async () => {
|
|
541
|
+
input.off('SIGINT', onSigint);
|
|
542
|
+
input.close();
|
|
543
|
+
},
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
async function nextWritableInput(iterator, signal) {
|
|
547
|
+
if (!signal)
|
|
548
|
+
return iterator.next();
|
|
549
|
+
if (signal.aborted)
|
|
550
|
+
return { done: true, value: undefined };
|
|
551
|
+
return new Promise((resolve, reject) => {
|
|
552
|
+
let settled = false;
|
|
553
|
+
const finish = (result) => {
|
|
554
|
+
if (settled)
|
|
555
|
+
return;
|
|
556
|
+
settled = true;
|
|
557
|
+
signal.removeEventListener('abort', onAbort);
|
|
558
|
+
resolve(result);
|
|
559
|
+
};
|
|
560
|
+
const onAbort = () => finish({ done: true, value: undefined });
|
|
561
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
562
|
+
iterator.next().then(finish, (error) => {
|
|
563
|
+
if (settled)
|
|
564
|
+
return;
|
|
565
|
+
settled = true;
|
|
566
|
+
signal.removeEventListener('abort', onAbort);
|
|
567
|
+
reject(error);
|
|
568
|
+
});
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
function validateWritableAccess(access, now) {
|
|
572
|
+
const value = access;
|
|
573
|
+
const url = typeof value?.url === 'string' ? value.url.trim() : '';
|
|
574
|
+
const token = typeof value?.token === 'string' ? value.token.trim() : '';
|
|
575
|
+
const expiresAt = typeof value?.expires_at === 'string' ? Date.parse(value.expires_at) : Number.NaN;
|
|
576
|
+
if (value?.mode !== 'write'
|
|
577
|
+
|| url === ''
|
|
578
|
+
|| token === ''
|
|
579
|
+
|| !Number.isFinite(now)
|
|
580
|
+
|| !Number.isFinite(expiresAt)
|
|
581
|
+
|| expiresAt <= now + WRITABLE_RENEWAL_WINDOW_MS) {
|
|
582
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'The database access response was invalid.');
|
|
583
|
+
}
|
|
584
|
+
return { url, token, expiresAt };
|
|
585
|
+
}
|
|
586
|
+
class WritableRenewalAttemptError extends Error {
|
|
587
|
+
publicError;
|
|
588
|
+
publishLastValid;
|
|
589
|
+
constructor(error, publishLastValid) {
|
|
590
|
+
super(error.message);
|
|
591
|
+
this.publicError = error;
|
|
592
|
+
this.publishLastValid = publishLastValid;
|
|
593
|
+
delete this.stack;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
function isAuthenticationExpired(error) {
|
|
597
|
+
const value = error;
|
|
598
|
+
const code = typeof value?.code === 'string' ? value.code.toUpperCase() : '';
|
|
599
|
+
const message = typeof value?.message === 'string' ? value.message : '';
|
|
600
|
+
if (['AUTH_TOKEN_EXPIRED', 'AUTH_EXPIRED', 'TOKEN_EXPIRED'].includes(code))
|
|
601
|
+
return true;
|
|
602
|
+
return code === 'SQLITE_AUTH' && /expired|expiration|\bjwt\b/i.test(message);
|
|
603
|
+
}
|
|
604
|
+
function classifyPullFailure(error) {
|
|
605
|
+
if (isAuthenticationExpired(error))
|
|
606
|
+
return 'credential_expiry';
|
|
607
|
+
const value = error;
|
|
608
|
+
const code = typeof value?.code === 'string' ? value.code.toUpperCase() : '';
|
|
609
|
+
const name = typeof value?.name === 'string' ? value.name : '';
|
|
610
|
+
const message = typeof value?.message === 'string' ? value.message : '';
|
|
611
|
+
const transientCodes = new Set([
|
|
612
|
+
'ECONNABORTED',
|
|
613
|
+
'ECONNREFUSED',
|
|
614
|
+
'ECONNRESET',
|
|
615
|
+
'EHOSTUNREACH',
|
|
616
|
+
'ENETDOWN',
|
|
617
|
+
'ENETUNREACH',
|
|
618
|
+
'ENOTFOUND',
|
|
619
|
+
'ETIMEDOUT',
|
|
620
|
+
'UND_ERR_CONNECT_TIMEOUT',
|
|
621
|
+
'UND_ERR_HEADERS_TIMEOUT',
|
|
622
|
+
'UND_ERR_SOCKET',
|
|
623
|
+
]);
|
|
624
|
+
if (transientCodes.has(code)
|
|
625
|
+
|| name === 'AbortError'
|
|
626
|
+
|| /\b(?:connection reset|network unavailable|temporary transport|transport failure|timed? ?out)\b/i.test(message)) {
|
|
627
|
+
return 'transient_transport';
|
|
628
|
+
}
|
|
629
|
+
return 'deterministic';
|
|
630
|
+
}
|
|
631
|
+
async function handoffReplicaReservation(io, temp, handle) {
|
|
632
|
+
await assertNoSymlinkComponents(io.filesystem, temp);
|
|
633
|
+
const reservedStat = await handle.stat();
|
|
634
|
+
const pathStat = await lstatIfPresent(io.filesystem, temp);
|
|
635
|
+
if (!pathStat
|
|
636
|
+
|| !pathStat.isFile()
|
|
637
|
+
|| pathStat.dev !== reservedStat.dev
|
|
638
|
+
|| pathStat.ino !== reservedStat.ino) {
|
|
639
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
640
|
+
}
|
|
641
|
+
await handle.close();
|
|
642
|
+
await io.filesystem.unlink(temp);
|
|
643
|
+
}
|
|
644
|
+
async function finalizeReplica(io, temp, target, createClient) {
|
|
645
|
+
const assertOwnedMainFile = async () => {
|
|
646
|
+
await assertNoSymlinkComponents(io.filesystem, temp);
|
|
647
|
+
const stat = await lstatIfPresent(io.filesystem, temp);
|
|
648
|
+
if (!stat || stat.isSymbolicLink() || !stat.isFile()) {
|
|
649
|
+
throw new database_data_plane_1.DatabaseOperationError('unsafe_destination', 'The database replica temporary path is unsafe.');
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
await assertOwnedMainFile();
|
|
653
|
+
let finalizer;
|
|
654
|
+
let finalizerClosePromise;
|
|
655
|
+
const closeFinalizer = () => {
|
|
656
|
+
finalizerClosePromise ??= (0, database_data_plane_1.runDatabaseClientOperationWithDeadline)(async () => { await finalizer?.close(); }, undefined, io.dataPlaneTimeoutMs);
|
|
657
|
+
return finalizerClosePromise;
|
|
658
|
+
};
|
|
659
|
+
let checkpointResult;
|
|
660
|
+
let finalizationFailed = false;
|
|
661
|
+
try {
|
|
662
|
+
finalizer = createClient({
|
|
663
|
+
url: (0, url_1.pathToFileURL)(temp).href,
|
|
664
|
+
intMode: 'string',
|
|
665
|
+
});
|
|
666
|
+
checkpointResult = await (0, database_data_plane_1.runDatabaseClientOperationWithDeadline)(() => finalizer.execute('PRAGMA wal_checkpoint(TRUNCATE)'), closeFinalizer, io.dataPlaneTimeoutMs);
|
|
667
|
+
}
|
|
668
|
+
catch {
|
|
669
|
+
finalizationFailed = true;
|
|
670
|
+
}
|
|
671
|
+
finally {
|
|
672
|
+
if (finalizer) {
|
|
673
|
+
try {
|
|
674
|
+
await closeFinalizer();
|
|
675
|
+
}
|
|
676
|
+
catch {
|
|
677
|
+
finalizationFailed = true;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if (finalizationFailed || !checkpointResult) {
|
|
682
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
683
|
+
}
|
|
684
|
+
validateCheckpointResult(checkpointResult);
|
|
685
|
+
await assertOwnedMainFile();
|
|
686
|
+
await removeOwnedFiles(io.filesystem, pullSidecars(temp));
|
|
687
|
+
if (await anyPathExists(io.filesystem, pullSidecars(temp))) {
|
|
688
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
689
|
+
}
|
|
690
|
+
await io.filesystem.chmod(temp, 0o444);
|
|
691
|
+
await assertNoSymlinkComponents(io.filesystem, target);
|
|
692
|
+
await io.filesystem.rename(temp, target);
|
|
693
|
+
}
|
|
694
|
+
async function databaseListWithConfig(options, config, dependencies = {}) {
|
|
695
|
+
const io = resolveDependencies(dependencies);
|
|
696
|
+
const data = stableListResponse(await (0, database_data_plane_1.requestDatabaseOperation)(config, { operation: 'list' }, requestDependencies(io)));
|
|
697
|
+
if (options.json) {
|
|
698
|
+
writeJson(io.stdout, data);
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
io.stdout(`${renderDatabaseTable(data.databases)}\nQuota: ${data.quota.used} / ${data.quota.limit}`);
|
|
702
|
+
}
|
|
703
|
+
async function databaseCreateWithConfig(name, options, config, dependencies = {}) {
|
|
704
|
+
const io = resolveDependencies(dependencies);
|
|
705
|
+
const preparedSource = options.from && !io.importDatabase
|
|
706
|
+
? await (0, database_sql_import_runner_1.prepareDatabaseImportSource)(options.from, io.cwd, io.filesystem)
|
|
707
|
+
: undefined;
|
|
708
|
+
const data = stableDatabaseResponse(await (0, database_data_plane_1.requestDatabaseOperation)(config, { operation: 'create', name }, requestDependencies(io)));
|
|
709
|
+
if (options.from) {
|
|
710
|
+
try {
|
|
711
|
+
if (io.importDatabase) {
|
|
712
|
+
await io.importDatabase(data.database.name, options.from);
|
|
713
|
+
}
|
|
714
|
+
else if (preparedSource) {
|
|
715
|
+
const prepared = await (0, database_sql_import_runner_1.bindPreparedDatabaseImport)(preparedSource, data.database.name, undefined, io.cwd, io.filesystem);
|
|
716
|
+
await (0, database_sql_import_runner_1.runPreparedDatabaseImport)(prepared, config, {
|
|
717
|
+
cwd: io.cwd,
|
|
718
|
+
filesystem: io.filesystem,
|
|
719
|
+
stdout: options.json ? () => undefined : io.stdout,
|
|
720
|
+
now: io.now,
|
|
721
|
+
post: io.post,
|
|
722
|
+
loadClient: io.loadClient,
|
|
723
|
+
controlPlaneTimeoutMs: io.controlPlaneTimeoutMs,
|
|
724
|
+
dataPlaneTimeoutMs: io.dataPlaneTimeoutMs,
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
catch (error) {
|
|
729
|
+
const safeGuidance = error instanceof database_data_plane_1.DatabaseOperationError
|
|
730
|
+
&& error.code === 'import_failed'
|
|
731
|
+
&& error.message.includes('Resume with:')
|
|
732
|
+
? `\n${error.message}`
|
|
733
|
+
: '';
|
|
734
|
+
throw new database_data_plane_1.DatabaseOperationError('import_failed', `Database "${data.database.name}" was created, but its SQL import failed. The database remains in place.${safeGuidance}`);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
if (options.json) {
|
|
738
|
+
writeJson(io.stdout, data);
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
io.stdout(renderMutation('create', data.database));
|
|
742
|
+
}
|
|
743
|
+
async function databaseImportWithConfig(name, file, options, config, dependencies = {}) {
|
|
744
|
+
const io = resolveDependencies(dependencies);
|
|
745
|
+
const prepared = await (0, database_sql_import_runner_1.prepareDatabaseImport)(name, file, options.resume, io.cwd, io.filesystem);
|
|
746
|
+
if (!options.yes) {
|
|
747
|
+
if (!io.isTTY) {
|
|
748
|
+
throw new database_data_plane_1.DatabaseOperationError('confirmation_required', 'Database import requires --yes in non-interactive mode.');
|
|
749
|
+
}
|
|
750
|
+
if (!await io.confirm(`Import SQL into database "${name}"?`)) {
|
|
751
|
+
io.stdout('Cancelled.');
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
await (0, database_sql_import_runner_1.runPreparedDatabaseImport)(prepared, config, {
|
|
756
|
+
cwd: io.cwd,
|
|
757
|
+
filesystem: io.filesystem,
|
|
758
|
+
stdout: io.stdout,
|
|
759
|
+
now: io.now,
|
|
760
|
+
post: io.post,
|
|
761
|
+
loadClient: io.loadClient,
|
|
762
|
+
controlPlaneTimeoutMs: io.controlPlaneTimeoutMs,
|
|
763
|
+
dataPlaneTimeoutMs: io.dataPlaneTimeoutMs,
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
async function databaseDeleteWithConfig(name, options, config, dependencies = {}) {
|
|
767
|
+
const io = resolveDependencies(dependencies);
|
|
768
|
+
if (!options.yes) {
|
|
769
|
+
if (options.json || !io.isTTY) {
|
|
770
|
+
throw new database_data_plane_1.DatabaseOperationError('confirmation_required', 'Database deletion requires --yes in JSON or non-interactive mode.');
|
|
771
|
+
}
|
|
772
|
+
if (!await io.confirm(`Delete database "${name}"?`)) {
|
|
773
|
+
io.stdout('Cancelled.');
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
const data = stableDatabaseResponse(await (0, database_data_plane_1.requestDatabaseOperation)(config, { operation: 'delete', name }, requestDependencies(io)));
|
|
778
|
+
if (options.json) {
|
|
779
|
+
writeJson(io.stdout, data);
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
io.stdout(renderMutation('delete', data.database));
|
|
783
|
+
}
|
|
784
|
+
async function databaseUndeleteWithConfig(name, options, config, dependencies = {}) {
|
|
785
|
+
const io = resolveDependencies(dependencies);
|
|
786
|
+
const data = stableDatabaseResponse(await (0, database_data_plane_1.requestDatabaseOperation)(config, { operation: 'undelete', name }, requestDependencies(io)));
|
|
787
|
+
if (options.json) {
|
|
788
|
+
writeJson(io.stdout, data);
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
io.stdout(renderMutation('undelete', data.database));
|
|
792
|
+
}
|
|
793
|
+
async function databaseSchemaWithConfig(name, options, config, dependencies = {}) {
|
|
794
|
+
const io = resolveDependencies(dependencies);
|
|
795
|
+
const schema = await (0, database_data_plane_1.withDatabaseClient)(config, name, 'read', (client) => readDatabaseSchema(client, name), clientDependencies(io));
|
|
796
|
+
if (options.json) {
|
|
797
|
+
writeJson(io.stdout, schema);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
io.stdout(renderSchema(schema));
|
|
801
|
+
}
|
|
802
|
+
async function databaseQueryWithConfig(name, sql, options, config, dependencies = {}) {
|
|
803
|
+
const io = resolveDependencies(dependencies);
|
|
804
|
+
const result = await (0, database_data_plane_1.withDatabaseClient)(config, name, 'read', async (client) => stableDirectResult(await client.execute(sql)), clientDependencies(io));
|
|
805
|
+
if (options.json) {
|
|
806
|
+
writeJson(io.stdout, {
|
|
807
|
+
columns: result.columns,
|
|
808
|
+
rows: normalizedRows(result),
|
|
809
|
+
row_count: result.rows.length,
|
|
810
|
+
});
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
io.stdout(result.columns.length > 0 ? renderDirectTable(result) : 'No rows returned.');
|
|
814
|
+
}
|
|
815
|
+
async function databaseExecWithConfig(name, sql, options, config, dependencies = {}) {
|
|
816
|
+
const io = resolveDependencies(dependencies);
|
|
817
|
+
if (!options.yes) {
|
|
818
|
+
if (options.json || !io.isTTY) {
|
|
819
|
+
throw new database_data_plane_1.DatabaseOperationError('confirmation_required', 'Database execution requires --yes in JSON or non-interactive mode.');
|
|
820
|
+
}
|
|
821
|
+
if (!await io.confirm(`Execute SQL against database "${name}"?`)) {
|
|
822
|
+
io.stdout('Cancelled.');
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
const result = await (0, database_data_plane_1.withDatabaseClient)(config, name, 'write', async (client) => stableDirectResult(await client.execute(sql)), clientDependencies(io));
|
|
827
|
+
if (options.json) {
|
|
828
|
+
writeJson(io.stdout, {
|
|
829
|
+
columns: result.columns,
|
|
830
|
+
rows: normalizedRows(result),
|
|
831
|
+
row_count: result.rows.length,
|
|
832
|
+
rows_affected: result.rowsAffected,
|
|
833
|
+
last_insert_rowid: (0, database_data_plane_1.normalizeDatabaseValue)(result.lastInsertRowid),
|
|
834
|
+
});
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
const output = [`Rows affected: ${result.rowsAffected}`];
|
|
838
|
+
if (result.rows.length > 0 && result.columns.length > 0) {
|
|
839
|
+
output.push(renderDirectTable(result));
|
|
840
|
+
}
|
|
841
|
+
io.stdout(output.join('\n'));
|
|
842
|
+
}
|
|
843
|
+
async function databaseDumpWithConfig(name, file, options, config, dependencies = {}) {
|
|
844
|
+
const io = resolveDependencies(dependencies);
|
|
845
|
+
const target = resolveDatabaseDestination(io, file, `${safeDatabaseStem(name)}.sql`);
|
|
846
|
+
let temp;
|
|
847
|
+
let handle;
|
|
848
|
+
let ownsTemp = false;
|
|
849
|
+
try {
|
|
850
|
+
if (!await confirmFileOverwrite(target, options, io))
|
|
851
|
+
return;
|
|
852
|
+
const reservation = await reserveDestinationTemp(io, target);
|
|
853
|
+
temp = reservation.temp;
|
|
854
|
+
handle = reservation.handle;
|
|
855
|
+
ownsTemp = true;
|
|
856
|
+
const stream = await (0, database_data_plane_1.requestDatabaseDumpStream)(config, name, requestDependencies(io));
|
|
857
|
+
const tail = await writeDumpStream(stream, handle);
|
|
858
|
+
await handle.close();
|
|
859
|
+
handle = undefined;
|
|
860
|
+
if (tail.includes(Buffer.from(INCOMPLETE_DUMP_MARKER))) {
|
|
861
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'The downloaded database dump is incomplete.');
|
|
862
|
+
}
|
|
863
|
+
await assertNoSymlinkComponents(io.filesystem, target);
|
|
864
|
+
await io.filesystem.rename(temp, target);
|
|
865
|
+
ownsTemp = false;
|
|
866
|
+
await io.filesystem.chmod(target, 0o444);
|
|
867
|
+
io.stdout(`Database dump saved to ${displayDestination(io, target)}.`);
|
|
868
|
+
}
|
|
869
|
+
catch (error) {
|
|
870
|
+
if (handle) {
|
|
871
|
+
try {
|
|
872
|
+
await handle.close();
|
|
873
|
+
}
|
|
874
|
+
catch {
|
|
875
|
+
// The public error remains stable; cleanup below owns the path.
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
if (ownsTemp && temp)
|
|
879
|
+
await removeOwnedFiles(io.filesystem, [temp]);
|
|
880
|
+
throw freshSafeFileError(error);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
async function databaseWritablePullWithConfig(name, destination, options, config, io) {
|
|
884
|
+
const target = resolveDatabaseDestination(io, destination, path_1.default.join('.solidactions', 'databases', `${safeDatabaseStem(name)}.db`));
|
|
885
|
+
let temp;
|
|
886
|
+
let reservationHandle;
|
|
887
|
+
let ownsTemp = false;
|
|
888
|
+
let ownsSidecars = false;
|
|
889
|
+
let client;
|
|
890
|
+
let localCreateClient;
|
|
891
|
+
let expiresAt = 0;
|
|
892
|
+
let inputSession;
|
|
893
|
+
let attachedClosePromise;
|
|
894
|
+
const closeAttachedClient = async () => {
|
|
895
|
+
if (client) {
|
|
896
|
+
const closing = client;
|
|
897
|
+
client = undefined;
|
|
898
|
+
attachedClosePromise ??= (0, database_data_plane_1.runDatabaseClientOperationWithDeadline)(async () => { await closing.close(); }, undefined, io.dataPlaneTimeoutMs);
|
|
899
|
+
}
|
|
900
|
+
if (!attachedClosePromise)
|
|
901
|
+
return;
|
|
902
|
+
try {
|
|
903
|
+
await attachedClosePromise;
|
|
904
|
+
}
|
|
905
|
+
catch {
|
|
906
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
const openAttachedClient = async (initial) => {
|
|
910
|
+
if (!initial) {
|
|
911
|
+
await assertNoSymlinkComponents(io.filesystem, temp);
|
|
912
|
+
const beforeMint = await lstatIfPresent(io.filesystem, temp);
|
|
913
|
+
if (!beforeMint || beforeMint.isSymbolicLink() || !beforeMint.isFile()) {
|
|
914
|
+
throw new database_data_plane_1.DatabaseOperationError('unsafe_destination', 'The database replica temporary path is unsafe.');
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
let loaded;
|
|
918
|
+
try {
|
|
919
|
+
loaded = await (0, database_client_support_1.loadDatabaseClientBeforeMint)(() => (0, database_data_plane_1.requestDatabaseAccess)(config, name, 'write', requestDependencies(io)), { loadClient: io.loadClient });
|
|
920
|
+
}
|
|
921
|
+
catch (error) {
|
|
922
|
+
const safeError = freshSafeFileError(error);
|
|
923
|
+
if (!initial && error instanceof database_data_plane_1.DatabaseOperationError) {
|
|
924
|
+
throw new WritableRenewalAttemptError(safeError, true);
|
|
925
|
+
}
|
|
926
|
+
throw safeError;
|
|
927
|
+
}
|
|
928
|
+
const access = validateWritableAccess(loaded.access, io.now());
|
|
929
|
+
const createClient = loaded.createClient;
|
|
930
|
+
if (initial) {
|
|
931
|
+
await handoffReplicaReservation(io, temp, reservationHandle);
|
|
932
|
+
reservationHandle = undefined;
|
|
933
|
+
ownsTemp = false;
|
|
934
|
+
}
|
|
935
|
+
await assertNoSymlinkComponents(io.filesystem, temp);
|
|
936
|
+
const beforeCreate = await lstatIfPresent(io.filesystem, temp);
|
|
937
|
+
if ((initial && beforeCreate !== null)
|
|
938
|
+
|| (!initial && (!beforeCreate || beforeCreate.isSymbolicLink() || !beforeCreate.isFile()))) {
|
|
939
|
+
throw new database_data_plane_1.DatabaseOperationError('unsafe_destination', 'The database replica temporary path is unsafe.');
|
|
940
|
+
}
|
|
941
|
+
let opened;
|
|
942
|
+
try {
|
|
943
|
+
opened = createClient({
|
|
944
|
+
url: (0, url_1.pathToFileURL)(temp).href,
|
|
945
|
+
syncUrl: access.url,
|
|
946
|
+
authToken: access.token,
|
|
947
|
+
intMode: 'string',
|
|
948
|
+
readYourWrites: true,
|
|
949
|
+
offline: false,
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
catch {
|
|
953
|
+
const createdStat = await lstatIfPresent(io.filesystem, temp);
|
|
954
|
+
if (createdStat?.isFile() && !createdStat.isSymbolicLink())
|
|
955
|
+
ownsTemp = true;
|
|
956
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
957
|
+
}
|
|
958
|
+
let openedClosePromise;
|
|
959
|
+
const closeOpened = () => {
|
|
960
|
+
openedClosePromise ??= (0, database_data_plane_1.runDatabaseClientOperationWithDeadline)(async () => { await opened.close(); }, undefined, io.dataPlaneTimeoutMs);
|
|
961
|
+
return openedClosePromise;
|
|
962
|
+
};
|
|
963
|
+
let syncFailed = false;
|
|
964
|
+
try {
|
|
965
|
+
if (typeof opened.sync !== 'function')
|
|
966
|
+
throw new Error('Database sync is unavailable.');
|
|
967
|
+
await (0, database_data_plane_1.runDatabaseClientOperationWithDeadline)(() => opened.sync(), closeOpened, io.dataPlaneTimeoutMs);
|
|
968
|
+
}
|
|
969
|
+
catch {
|
|
970
|
+
syncFailed = true;
|
|
971
|
+
}
|
|
972
|
+
const replicaStat = await lstatIfPresent(io.filesystem, temp);
|
|
973
|
+
if (replicaStat?.isFile() && !replicaStat.isSymbolicLink())
|
|
974
|
+
ownsTemp = true;
|
|
975
|
+
if (syncFailed
|
|
976
|
+
|| !replicaStat
|
|
977
|
+
|| replicaStat.isSymbolicLink()
|
|
978
|
+
|| !replicaStat.isFile()) {
|
|
979
|
+
try {
|
|
980
|
+
await closeOpened();
|
|
981
|
+
}
|
|
982
|
+
catch {
|
|
983
|
+
// The stable setup error below takes precedence.
|
|
984
|
+
}
|
|
985
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
986
|
+
}
|
|
987
|
+
attachedClosePromise = undefined;
|
|
988
|
+
client = opened;
|
|
989
|
+
localCreateClient = createClient;
|
|
990
|
+
expiresAt = access.expiresAt;
|
|
991
|
+
};
|
|
992
|
+
try {
|
|
993
|
+
if (!await confirmFileOverwrite(target, options, io))
|
|
994
|
+
return;
|
|
995
|
+
const reservation = await reserveDestinationTemp(io, target);
|
|
996
|
+
temp = reservation.temp;
|
|
997
|
+
reservationHandle = reservation.handle;
|
|
998
|
+
ownsTemp = true;
|
|
999
|
+
if (await anyPathExists(io.filesystem, pullSidecars(temp))) {
|
|
1000
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database replica temporary files already exist.');
|
|
1001
|
+
}
|
|
1002
|
+
ownsSidecars = true;
|
|
1003
|
+
await openAttachedClient(true);
|
|
1004
|
+
io.stdout(WRITABLE_WARNING);
|
|
1005
|
+
inputSession = createWritableInput(io);
|
|
1006
|
+
const accumulator = new database_sql_import_1.DatabaseSqlStatementAccumulator();
|
|
1007
|
+
let sessionFailure;
|
|
1008
|
+
let publishAfterFailure = false;
|
|
1009
|
+
try {
|
|
1010
|
+
while (true) {
|
|
1011
|
+
if (io.abortSignal?.aborted || inputSession.interrupted())
|
|
1012
|
+
break;
|
|
1013
|
+
if (io.now() >= expiresAt - WRITABLE_RENEWAL_WINDOW_MS) {
|
|
1014
|
+
try {
|
|
1015
|
+
await closeAttachedClient();
|
|
1016
|
+
await openAttachedClient(false);
|
|
1017
|
+
}
|
|
1018
|
+
catch (error) {
|
|
1019
|
+
sessionFailure = error instanceof WritableRenewalAttemptError
|
|
1020
|
+
? error.publicError
|
|
1021
|
+
: error;
|
|
1022
|
+
publishAfterFailure = error instanceof WritableRenewalAttemptError
|
|
1023
|
+
&& error.publishLastValid;
|
|
1024
|
+
break;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
inputSession.prompt(accumulator.pending);
|
|
1028
|
+
const next = await nextWritableInput(inputSession.iterator, io.abortSignal);
|
|
1029
|
+
if (io.abortSignal?.aborted || inputSession.interrupted())
|
|
1030
|
+
break;
|
|
1031
|
+
if (next.done) {
|
|
1032
|
+
if (accumulator.pending) {
|
|
1033
|
+
sessionFailure = new database_data_plane_1.DatabaseOperationError('incomplete_sql', 'The SQL input is incomplete.');
|
|
1034
|
+
}
|
|
1035
|
+
break;
|
|
1036
|
+
}
|
|
1037
|
+
if (next.value.trim() === '.exit') {
|
|
1038
|
+
if (accumulator.pending) {
|
|
1039
|
+
sessionFailure = new database_data_plane_1.DatabaseOperationError('incomplete_sql', 'The SQL input is incomplete.');
|
|
1040
|
+
}
|
|
1041
|
+
break;
|
|
1042
|
+
}
|
|
1043
|
+
const statement = accumulator.push(next.value);
|
|
1044
|
+
if (!statement)
|
|
1045
|
+
continue;
|
|
1046
|
+
try {
|
|
1047
|
+
if (statement.multiple) {
|
|
1048
|
+
if (typeof client?.executeMultiple !== 'function') {
|
|
1049
|
+
throw new Error('Multiple SQL execution is unavailable.');
|
|
1050
|
+
}
|
|
1051
|
+
await (0, database_data_plane_1.runDatabaseClientOperationWithDeadline)(() => client.executeMultiple(statement.sql), closeAttachedClient, io.dataPlaneTimeoutMs);
|
|
1052
|
+
io.stdout('Transaction group executed successfully.');
|
|
1053
|
+
}
|
|
1054
|
+
else {
|
|
1055
|
+
const result = stableDirectResult(await (0, database_data_plane_1.runDatabaseClientOperationWithDeadline)(() => client.execute(statement.sql), closeAttachedClient, io.dataPlaneTimeoutMs));
|
|
1056
|
+
io.stdout(result.columns.length > 0
|
|
1057
|
+
? renderDirectTable(result)
|
|
1058
|
+
: `Rows affected: ${result.rowsAffected}`);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
catch (error) {
|
|
1062
|
+
if (error instanceof database_data_plane_1.DatabaseOperationError
|
|
1063
|
+
&& error.message === 'Database operation timed out.') {
|
|
1064
|
+
sessionFailure = error;
|
|
1065
|
+
break;
|
|
1066
|
+
}
|
|
1067
|
+
if (!isAuthenticationExpired(error)) {
|
|
1068
|
+
io.stderr('Database statement failed.');
|
|
1069
|
+
continue;
|
|
1070
|
+
}
|
|
1071
|
+
io.stderr('Database statement has an unknown outcome because authorization expired.');
|
|
1072
|
+
try {
|
|
1073
|
+
await closeAttachedClient();
|
|
1074
|
+
await openAttachedClient(false);
|
|
1075
|
+
}
|
|
1076
|
+
catch (renewalError) {
|
|
1077
|
+
sessionFailure = renewalError instanceof WritableRenewalAttemptError
|
|
1078
|
+
? renewalError.publicError
|
|
1079
|
+
: renewalError;
|
|
1080
|
+
publishAfterFailure = renewalError instanceof WritableRenewalAttemptError
|
|
1081
|
+
&& renewalError.publishLastValid;
|
|
1082
|
+
break;
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
catch (error) {
|
|
1088
|
+
sessionFailure = error;
|
|
1089
|
+
}
|
|
1090
|
+
finally {
|
|
1091
|
+
if (inputSession) {
|
|
1092
|
+
try {
|
|
1093
|
+
await inputSession.close();
|
|
1094
|
+
}
|
|
1095
|
+
catch {
|
|
1096
|
+
if (!sessionFailure) {
|
|
1097
|
+
sessionFailure = new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
inputSession = undefined;
|
|
1101
|
+
}
|
|
1102
|
+
try {
|
|
1103
|
+
await closeAttachedClient();
|
|
1104
|
+
}
|
|
1105
|
+
catch (error) {
|
|
1106
|
+
if (!sessionFailure)
|
|
1107
|
+
sessionFailure = error;
|
|
1108
|
+
publishAfterFailure = false;
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
if (sessionFailure && !publishAfterFailure)
|
|
1112
|
+
throw sessionFailure;
|
|
1113
|
+
await finalizeReplica(io, temp, target, localCreateClient);
|
|
1114
|
+
ownsTemp = false;
|
|
1115
|
+
ownsSidecars = false;
|
|
1116
|
+
if (sessionFailure)
|
|
1117
|
+
throw sessionFailure;
|
|
1118
|
+
io.stdout(`Database replica saved to ${displayDestination(io, target)}.`);
|
|
1119
|
+
}
|
|
1120
|
+
catch (error) {
|
|
1121
|
+
if (inputSession) {
|
|
1122
|
+
try {
|
|
1123
|
+
await inputSession.close();
|
|
1124
|
+
}
|
|
1125
|
+
catch {
|
|
1126
|
+
// Cleanup remains scoped to this invocation's input session.
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
if (client) {
|
|
1130
|
+
try {
|
|
1131
|
+
await client.close();
|
|
1132
|
+
}
|
|
1133
|
+
catch {
|
|
1134
|
+
// Cleanup below remains scoped to this invocation's replica.
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
if (reservationHandle) {
|
|
1138
|
+
try {
|
|
1139
|
+
await reservationHandle.close();
|
|
1140
|
+
}
|
|
1141
|
+
catch {
|
|
1142
|
+
// Cleanup below remains scoped to the exclusively reserved path.
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
if (temp) {
|
|
1146
|
+
await removeOwnedFiles(io.filesystem, [
|
|
1147
|
+
...(ownsTemp ? [temp] : []),
|
|
1148
|
+
...(ownsSidecars ? pullSidecars(temp) : []),
|
|
1149
|
+
]);
|
|
1150
|
+
}
|
|
1151
|
+
throw freshSafeFileError(error);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
async function databasePullWithConfig(name, destination, options, config, dependencies = {}) {
|
|
1155
|
+
const io = resolveDependencies(dependencies);
|
|
1156
|
+
if (options.writable) {
|
|
1157
|
+
return databaseWritablePullWithConfig(name, destination, options, config, io);
|
|
1158
|
+
}
|
|
1159
|
+
const target = resolveDatabaseDestination(io, destination, path_1.default.join('.solidactions', 'databases', `${safeDatabaseStem(name)}.db`));
|
|
1160
|
+
let temp;
|
|
1161
|
+
let reservationHandle;
|
|
1162
|
+
let ownsTemp = false;
|
|
1163
|
+
let ownsSidecars = false;
|
|
1164
|
+
try {
|
|
1165
|
+
if (!await confirmFileOverwrite(target, options, io))
|
|
1166
|
+
return;
|
|
1167
|
+
const reservation = await reserveDestinationTemp(io, target);
|
|
1168
|
+
temp = reservation.temp;
|
|
1169
|
+
reservationHandle = reservation.handle;
|
|
1170
|
+
ownsTemp = true;
|
|
1171
|
+
const sidecars = pullSidecars(temp);
|
|
1172
|
+
if (await anyPathExists(io.filesystem, sidecars)) {
|
|
1173
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database replica temporary files already exist.');
|
|
1174
|
+
}
|
|
1175
|
+
ownsSidecars = true;
|
|
1176
|
+
let synced = false;
|
|
1177
|
+
let localCreateClient;
|
|
1178
|
+
let credentialRemintUsed = false;
|
|
1179
|
+
for (let attempt = 0; attempt < PULL_ATTEMPTS; attempt += 1) {
|
|
1180
|
+
const { createClient, access } = await (0, database_client_support_1.loadDatabaseClientBeforeMint)(() => (0, database_data_plane_1.requestDatabaseAccess)(config, name, 'read', requestDependencies(io)), { loadClient: io.loadClient });
|
|
1181
|
+
localCreateClient = createClient;
|
|
1182
|
+
if (attempt === 0) {
|
|
1183
|
+
await assertNoSymlinkComponents(io.filesystem, temp);
|
|
1184
|
+
const reservedStat = await reservationHandle.stat();
|
|
1185
|
+
const pathStat = await lstatIfPresent(io.filesystem, temp);
|
|
1186
|
+
if (!pathStat
|
|
1187
|
+
|| !pathStat.isFile()
|
|
1188
|
+
|| pathStat.dev !== reservedStat.dev
|
|
1189
|
+
|| pathStat.ino !== reservedStat.ino) {
|
|
1190
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
1191
|
+
}
|
|
1192
|
+
await reservationHandle.close();
|
|
1193
|
+
reservationHandle = undefined;
|
|
1194
|
+
await io.filesystem.unlink(temp);
|
|
1195
|
+
ownsTemp = false;
|
|
1196
|
+
}
|
|
1197
|
+
let client;
|
|
1198
|
+
try {
|
|
1199
|
+
client = createClient({
|
|
1200
|
+
url: (0, url_1.pathToFileURL)(temp).href,
|
|
1201
|
+
syncUrl: access.url,
|
|
1202
|
+
authToken: access.token,
|
|
1203
|
+
intMode: 'string',
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
catch {
|
|
1207
|
+
const createdStat = await lstatIfPresent(io.filesystem, temp);
|
|
1208
|
+
if (createdStat?.isFile() && !createdStat.isSymbolicLink())
|
|
1209
|
+
ownsTemp = true;
|
|
1210
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
1211
|
+
}
|
|
1212
|
+
let attemptFailure;
|
|
1213
|
+
let closePromise;
|
|
1214
|
+
const closeClient = () => {
|
|
1215
|
+
closePromise ??= (0, database_data_plane_1.runDatabaseClientOperationWithDeadline)(async () => { await client.close(); }, undefined, io.dataPlaneTimeoutMs);
|
|
1216
|
+
return closePromise;
|
|
1217
|
+
};
|
|
1218
|
+
try {
|
|
1219
|
+
if (typeof client.sync !== 'function')
|
|
1220
|
+
throw new Error('Database sync is unavailable.');
|
|
1221
|
+
await (0, database_data_plane_1.runDatabaseClientOperationWithDeadline)(() => client.sync(), closeClient, io.dataPlaneTimeoutMs);
|
|
1222
|
+
}
|
|
1223
|
+
catch (error) {
|
|
1224
|
+
attemptFailure = error;
|
|
1225
|
+
}
|
|
1226
|
+
finally {
|
|
1227
|
+
try {
|
|
1228
|
+
await closeClient();
|
|
1229
|
+
}
|
|
1230
|
+
catch (error) {
|
|
1231
|
+
if (!attemptFailure)
|
|
1232
|
+
attemptFailure = error;
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
if (!attemptFailure) {
|
|
1236
|
+
const replicaStat = await lstatIfPresent(io.filesystem, temp);
|
|
1237
|
+
if (!replicaStat || replicaStat.isSymbolicLink() || !replicaStat.isFile()) {
|
|
1238
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
1239
|
+
}
|
|
1240
|
+
ownsTemp = true;
|
|
1241
|
+
synced = true;
|
|
1242
|
+
break;
|
|
1243
|
+
}
|
|
1244
|
+
const replicaStat = await lstatIfPresent(io.filesystem, temp);
|
|
1245
|
+
if (replicaStat?.isSymbolicLink() || (replicaStat && !replicaStat.isFile())) {
|
|
1246
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
1247
|
+
}
|
|
1248
|
+
if (replicaStat?.isFile())
|
|
1249
|
+
ownsTemp = true;
|
|
1250
|
+
const failureClass = classifyPullFailure(attemptFailure);
|
|
1251
|
+
const hasAnotherAttempt = attempt + 1 < PULL_ATTEMPTS;
|
|
1252
|
+
if (failureClass === 'credential_expiry' && !credentialRemintUsed && hasAnotherAttempt) {
|
|
1253
|
+
credentialRemintUsed = true;
|
|
1254
|
+
continue;
|
|
1255
|
+
}
|
|
1256
|
+
if (failureClass === 'transient_transport' && hasAnotherAttempt) {
|
|
1257
|
+
await io.sleep(PULL_RETRY_BACKOFF_MS[attempt] ?? PULL_RETRY_BACKOFF_MS.at(-1));
|
|
1258
|
+
continue;
|
|
1259
|
+
}
|
|
1260
|
+
break;
|
|
1261
|
+
}
|
|
1262
|
+
if (!synced) {
|
|
1263
|
+
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'Database file operation failed.');
|
|
1264
|
+
}
|
|
1265
|
+
await finalizeReplica(io, temp, target, localCreateClient);
|
|
1266
|
+
ownsTemp = false;
|
|
1267
|
+
ownsSidecars = false;
|
|
1268
|
+
io.stdout(`Database replica saved to ${displayDestination(io, target)}.`);
|
|
1269
|
+
}
|
|
1270
|
+
catch (error) {
|
|
1271
|
+
if (reservationHandle) {
|
|
1272
|
+
try {
|
|
1273
|
+
await reservationHandle.close();
|
|
1274
|
+
}
|
|
1275
|
+
catch {
|
|
1276
|
+
// Cleanup below remains scoped to the exclusively reserved path.
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
if (temp) {
|
|
1280
|
+
await removeOwnedFiles(io.filesystem, [
|
|
1281
|
+
...(ownsTemp ? [temp] : []),
|
|
1282
|
+
...(ownsSidecars ? pullSidecars(temp) : []),
|
|
1283
|
+
]);
|
|
1284
|
+
}
|
|
1285
|
+
throw freshSafeFileError(error);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
async function databaseList(options, dependencies = {}) {
|
|
1289
|
+
await databaseListWithConfig(options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1290
|
+
}
|
|
1291
|
+
async function databaseCreate(name, options, dependencies = {}) {
|
|
1292
|
+
await databaseCreateWithConfig(name, options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1293
|
+
}
|
|
1294
|
+
async function databaseDelete(name, options, dependencies = {}) {
|
|
1295
|
+
await databaseDeleteWithConfig(name, options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1296
|
+
}
|
|
1297
|
+
async function databaseUndelete(name, options, dependencies = {}) {
|
|
1298
|
+
await databaseUndeleteWithConfig(name, options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1299
|
+
}
|
|
1300
|
+
async function databaseSchema(name, options, dependencies = {}) {
|
|
1301
|
+
await databaseSchemaWithConfig(name, options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1302
|
+
}
|
|
1303
|
+
async function databaseQuery(name, sql, options, dependencies = {}) {
|
|
1304
|
+
await databaseQueryWithConfig(name, sql, options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1305
|
+
}
|
|
1306
|
+
async function databaseExec(name, sql, options, dependencies = {}) {
|
|
1307
|
+
await databaseExecWithConfig(name, sql, options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1308
|
+
}
|
|
1309
|
+
async function databaseDump(name, file, options, dependencies = {}) {
|
|
1310
|
+
await databaseDumpWithConfig(name, file, options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1311
|
+
}
|
|
1312
|
+
async function databasePull(name, destination, options, dependencies = {}) {
|
|
1313
|
+
await databasePullWithConfig(name, destination, options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1314
|
+
}
|
|
1315
|
+
async function databaseImport(name, file, options, dependencies = {}) {
|
|
1316
|
+
await databaseImportWithConfig(name, file, options, await (0, api_1.requireConfigWithWorkspace)(), dependencies);
|
|
1317
|
+
}
|