@solidactions/cli 3.5.0 → 3.7.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 +64 -0
- package/dist/command-manifest.json +567 -1
- package/dist/commands/database.js +1315 -0
- package/dist/commands/deploy.js +29 -14
- package/dist/commands/device-login.js +1 -1
- package/dist/index.js +96 -0
- package/dist/utils/api.js +25 -1
- 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/env.js +15 -6
- package/dist/utils/examples-ref.js +6 -3
- package/dist/utils/skills.js +1 -1
- package/package.json +2 -1
package/dist/commands/deploy.js
CHANGED
|
@@ -11,6 +11,7 @@ exports.isConfirmationMatch = isConfirmationMatch;
|
|
|
11
11
|
exports.confirmDeploymentWithRetry = confirmDeploymentWithRetry;
|
|
12
12
|
exports.formatDeploymentConfirmation = formatDeploymentConfirmation;
|
|
13
13
|
exports.safeCollectSourceMetadata = safeCollectSourceMetadata;
|
|
14
|
+
exports.pushYamlDeclarations = pushYamlDeclarations;
|
|
14
15
|
exports.shouldPrintWorkspaceMismatch = shouldPrintWorkspaceMismatch;
|
|
15
16
|
exports.isPlanLimitReachedError = isPlanLimitReachedError;
|
|
16
17
|
exports.handlePlanLimitReached = handlePlanLimitReached;
|
|
@@ -214,28 +215,29 @@ function safeCollectSourceMetadata(sourceDir, options, collector = source_proven
|
|
|
214
215
|
/**
|
|
215
216
|
* Push YAML env declarations to the project.
|
|
216
217
|
* This registers all YAML-declared vars and their mappings.
|
|
218
|
+
*
|
|
219
|
+
* Always POSTs, even when `parsedVars` is empty: the endpoint prunes stale
|
|
220
|
+
* mappings on an explicit `declarations: []`, so removing the last YAML env
|
|
221
|
+
* declaration must still reach it (spec #1127 §4B).
|
|
222
|
+
*
|
|
223
|
+
* Throws the raw axios error on failure — callers decide how to handle it
|
|
224
|
+
* (PM round #1127 finding 14: a failed sync must never be reported as
|
|
225
|
+
* success by the caller).
|
|
217
226
|
*/
|
|
218
227
|
async function pushYamlDeclarations(config, projectSlug, yamlConfig) {
|
|
219
228
|
const parsedVars = (0, env_1.parseYamlEnvVars)(yamlConfig);
|
|
220
|
-
if (parsedVars.length === 0) {
|
|
221
|
-
return;
|
|
222
|
-
}
|
|
223
229
|
// Build the declarations array
|
|
224
230
|
const declarations = parsedVars.map(v => ({
|
|
225
231
|
env_name: v.key,
|
|
226
232
|
yaml_default_global_key: v.mappedTo,
|
|
227
233
|
yaml_default_oauth_name: v.oauthName,
|
|
234
|
+
yaml_default_database_name: v.databaseName,
|
|
228
235
|
source: 'yaml',
|
|
229
236
|
}));
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
console.log(chalk_1.default.gray(`Synced ${declarations.length} YAML env declarations`));
|
|
235
|
-
}
|
|
236
|
-
catch (error) {
|
|
237
|
-
console.error(chalk_1.default.yellow('Warning: Failed to sync YAML declarations:'), error.response?.data?.message || error.message);
|
|
238
|
-
}
|
|
237
|
+
await axios_1.default.post(`${config.host}/api/v1/projects/${projectSlug}/variable-mappings/sync-yaml`, { declarations }, {
|
|
238
|
+
headers: (0, api_1.getApiHeaders)(config, 'application/json'),
|
|
239
|
+
});
|
|
240
|
+
console.log(chalk_1.default.gray(`Synced ${declarations.length} YAML env declarations`));
|
|
239
241
|
}
|
|
240
242
|
/**
|
|
241
243
|
* Returns true only when a 404 on the environment-specific project lookup
|
|
@@ -492,7 +494,13 @@ async function deploy(projectName, sourcePath, options = {}) {
|
|
|
492
494
|
console.error(chalk_1.default.red('Cannot sync config: solidactions.yaml not found or invalid.'));
|
|
493
495
|
process.exit(1);
|
|
494
496
|
}
|
|
495
|
-
|
|
497
|
+
try {
|
|
498
|
+
await pushYamlDeclarations(config, projectSlug, yamlConfig);
|
|
499
|
+
}
|
|
500
|
+
catch (error) {
|
|
501
|
+
console.error(chalk_1.default.red(`Config sync FAILED: ${error.response?.data?.message || error.message}`));
|
|
502
|
+
process.exit(1);
|
|
503
|
+
}
|
|
496
504
|
console.log(chalk_1.default.green(`✓ Config synced for ${projectSlug}${envLabel}`));
|
|
497
505
|
return;
|
|
498
506
|
}
|
|
@@ -606,7 +614,14 @@ async function deploy(projectName, sourcePath, options = {}) {
|
|
|
606
614
|
}
|
|
607
615
|
// Always sync YAML declarations (registers variables and their mappings)
|
|
608
616
|
if (yamlConfig) {
|
|
609
|
-
|
|
617
|
+
try {
|
|
618
|
+
await pushYamlDeclarations(config, projectSlug, yamlConfig);
|
|
619
|
+
}
|
|
620
|
+
catch (error) {
|
|
621
|
+
console.error(chalk_1.default.red(`Config sync FAILED: ${error.response?.data?.message || error.message}`));
|
|
622
|
+
cleanupArchive();
|
|
623
|
+
process.exit(1);
|
|
624
|
+
}
|
|
610
625
|
}
|
|
611
626
|
if (yamlConfig && shouldPrintWebhookSecretNotice(yamlConfig.workflows ?? [])) {
|
|
612
627
|
const envFlag = environment !== 'dev' ? ` -e ${environment}` : '';
|
|
@@ -16,7 +16,7 @@ const login_1 = require("./login");
|
|
|
16
16
|
const CLI_OAUTH_CLIENT_ID = '9f1b6e2a-9c1e-4b6e-8f0a-6c9f2b1e7d4c';
|
|
17
17
|
// CLI capability scopes requested at device-code issuance — the server
|
|
18
18
|
// rejects any scope not pre-registered via Passport::tokensCan().
|
|
19
|
-
const CLI_SCOPES = 'env deploy runs docs';
|
|
19
|
+
const CLI_SCOPES = 'env deploy runs docs databases';
|
|
20
20
|
async function requestDeviceCode(host) {
|
|
21
21
|
const response = await axios_1.default.post(`${host}/oauth/device/code`, {
|
|
22
22
|
client_id: CLI_OAUTH_CLIENT_ID,
|
package/dist/index.js
CHANGED
|
@@ -91,6 +91,7 @@ const crew_env_delete_1 = require("./commands/crew-env-delete");
|
|
|
91
91
|
const crew_env_push_1 = require("./commands/crew-env-push");
|
|
92
92
|
const state_1 = require("./commands/state");
|
|
93
93
|
const workflow_view_1 = require("./commands/workflow-view");
|
|
94
|
+
const database_1 = require("./commands/database");
|
|
94
95
|
const config_1 = require("./utils/config");
|
|
95
96
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
96
97
|
const pkg = require('../package.json');
|
|
@@ -209,6 +210,101 @@ exports.program
|
|
|
209
210
|
(0, dev_1.dev)(file, options);
|
|
210
211
|
});
|
|
211
212
|
// =============================================================================
|
|
213
|
+
// database <subcommand>
|
|
214
|
+
// =============================================================================
|
|
215
|
+
// Register the complete public surface up front so help and the generated
|
|
216
|
+
// command manifest stay authoritative while handlers land in focused slices.
|
|
217
|
+
const database = exports.program.command('database').description('Manage workspace databases');
|
|
218
|
+
database
|
|
219
|
+
.command('list')
|
|
220
|
+
.description('List workspace databases')
|
|
221
|
+
.option('--json', 'Output as JSON')
|
|
222
|
+
.action(async (options) => {
|
|
223
|
+
await (0, database_1.databaseList)(options);
|
|
224
|
+
});
|
|
225
|
+
database
|
|
226
|
+
.command('create')
|
|
227
|
+
.description('Create a workspace database')
|
|
228
|
+
.argument('<name>', 'Database name')
|
|
229
|
+
.option('--from <file.sql>', 'Import a SQL file after creation')
|
|
230
|
+
.option('--json', 'Output as JSON')
|
|
231
|
+
.action(async (name, options) => {
|
|
232
|
+
await (0, database_1.databaseCreate)(name, options);
|
|
233
|
+
});
|
|
234
|
+
database
|
|
235
|
+
.command('delete')
|
|
236
|
+
.description('Delete a workspace database')
|
|
237
|
+
.argument('<name>', 'Database name')
|
|
238
|
+
.option('-y, --yes', 'Skip confirmation')
|
|
239
|
+
.option('--json', 'Output as JSON')
|
|
240
|
+
.action(async (name, options) => {
|
|
241
|
+
await (0, database_1.databaseDelete)(name, options);
|
|
242
|
+
});
|
|
243
|
+
database
|
|
244
|
+
.command('undelete')
|
|
245
|
+
.description('Restore a deleted workspace database')
|
|
246
|
+
.argument('<name>', 'Database name')
|
|
247
|
+
.option('--json', 'Output as JSON')
|
|
248
|
+
.action(async (name, options) => {
|
|
249
|
+
await (0, database_1.databaseUndelete)(name, options);
|
|
250
|
+
});
|
|
251
|
+
database
|
|
252
|
+
.command('schema')
|
|
253
|
+
.description('Show a database schema')
|
|
254
|
+
.argument('<name>', 'Database name')
|
|
255
|
+
.option('--json', 'Output as JSON')
|
|
256
|
+
.action(async (name, options) => {
|
|
257
|
+
await (0, database_1.databaseSchema)(name, options);
|
|
258
|
+
});
|
|
259
|
+
database
|
|
260
|
+
.command('query')
|
|
261
|
+
.description('Run a read-only SQL query')
|
|
262
|
+
.argument('<name>', 'Database name')
|
|
263
|
+
.argument('<sql>', 'SQL query')
|
|
264
|
+
.option('--json', 'Output as JSON')
|
|
265
|
+
.action(async (name, sql, options) => {
|
|
266
|
+
await (0, database_1.databaseQuery)(name, sql, options);
|
|
267
|
+
});
|
|
268
|
+
database
|
|
269
|
+
.command('exec')
|
|
270
|
+
.description('Execute a SQL statement')
|
|
271
|
+
.argument('<name>', 'Database name')
|
|
272
|
+
.argument('<sql>', 'SQL statement')
|
|
273
|
+
.option('-y, --yes', 'Skip confirmation')
|
|
274
|
+
.option('--json', 'Output as JSON')
|
|
275
|
+
.action(async (name, sql, options) => {
|
|
276
|
+
await (0, database_1.databaseExec)(name, sql, options);
|
|
277
|
+
});
|
|
278
|
+
database
|
|
279
|
+
.command('dump')
|
|
280
|
+
.description('Download a database SQL dump')
|
|
281
|
+
.argument('<name>', 'Database name')
|
|
282
|
+
.argument('[file]', 'Destination file')
|
|
283
|
+
.option('-y, --yes', 'Overwrite without confirmation')
|
|
284
|
+
.action(async (name, file, options) => {
|
|
285
|
+
await (0, database_1.databaseDump)(name, file, options);
|
|
286
|
+
});
|
|
287
|
+
database
|
|
288
|
+
.command('pull')
|
|
289
|
+
.description('Pull a database into a local file')
|
|
290
|
+
.argument('<name>', 'Database name')
|
|
291
|
+
.argument('[path]', 'Destination path')
|
|
292
|
+
.option('-y, --yes', 'Overwrite without confirmation')
|
|
293
|
+
.option('--writable', 'Open a foreground writable session')
|
|
294
|
+
.action(async (name, destination, options) => {
|
|
295
|
+
await (0, database_1.databasePull)(name, destination, options);
|
|
296
|
+
});
|
|
297
|
+
database
|
|
298
|
+
.command('import')
|
|
299
|
+
.description('Import a SQL file into a database')
|
|
300
|
+
.argument('<name>', 'Database name')
|
|
301
|
+
.argument('<file.sql>', 'SQL file')
|
|
302
|
+
.option('-y, --yes', 'Skip confirmation')
|
|
303
|
+
.option('--resume <checkpoint>', 'Resume from a validated import checkpoint')
|
|
304
|
+
.action(async (name, file, options) => {
|
|
305
|
+
await (0, database_1.databaseImport)(name, file, options);
|
|
306
|
+
});
|
|
307
|
+
// =============================================================================
|
|
212
308
|
// project <subcommand>
|
|
213
309
|
// =============================================================================
|
|
214
310
|
const project = exports.program.command('project').description('Manage projects');
|
package/dist/utils/api.js
CHANGED
|
@@ -7,6 +7,7 @@ exports.SANDBOX_EGRESS_MESSAGE = void 0;
|
|
|
7
7
|
exports.augmentSandboxEgressMessage = augmentSandboxEgressMessage;
|
|
8
8
|
exports.augmentNotFoundMessage = augmentNotFoundMessage;
|
|
9
9
|
exports.augmentWorkspaceForbiddenMessage = augmentWorkspaceForbiddenMessage;
|
|
10
|
+
exports.augmentTokenMissingAbilityMessage = augmentTokenMissingAbilityMessage;
|
|
10
11
|
exports.getApiHeaders = getApiHeaders;
|
|
11
12
|
exports.describeProjectEnvironments = describeProjectEnvironments;
|
|
12
13
|
exports.formatValidationError = formatValidationError;
|
|
@@ -134,7 +135,30 @@ function augmentWorkspaceForbiddenMessage(error) {
|
|
|
134
135
|
}
|
|
135
136
|
return error;
|
|
136
137
|
}
|
|
137
|
-
|
|
138
|
+
/**
|
|
139
|
+
* Existing device tokens predate the coarse `databases` scope. Turn the app's
|
|
140
|
+
* stable missing-ability response into a re-login instruction while preserving
|
|
141
|
+
* its original message. Other ability failures retain their existing behavior.
|
|
142
|
+
*/
|
|
143
|
+
function augmentTokenMissingAbilityMessage(error) {
|
|
144
|
+
const response = error?.response;
|
|
145
|
+
const requiredAbility = response?.data?.required_ability;
|
|
146
|
+
const isDatabaseAbility = requiredAbility === 'databases'
|
|
147
|
+
|| (typeof requiredAbility === 'string' && requiredAbility.startsWith('databases:'));
|
|
148
|
+
if (response?.status === 403
|
|
149
|
+
&& response.data?.code === 'token_missing_ability'
|
|
150
|
+
&& isDatabaseAbility) {
|
|
151
|
+
const hint = 'Run `solidactions login --device` to refresh database access.';
|
|
152
|
+
const message = typeof response.data.message === 'string' && response.data.message.length > 0
|
|
153
|
+
? response.data.message
|
|
154
|
+
: 'This session does not have database access.';
|
|
155
|
+
if (!message.includes('solidactions login --device')) {
|
|
156
|
+
response.data.message = `${message}\n\n${hint}`;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return error;
|
|
160
|
+
}
|
|
161
|
+
axios_1.default.interceptors.response.use((response) => response, (error) => Promise.reject(augmentTokenMissingAbilityMessage(augmentWorkspaceForbiddenMessage(augmentNotFoundMessage(augmentSandboxEgressMessage(error))))));
|
|
138
162
|
function getApiHeaders(config, contentType) {
|
|
139
163
|
const headers = {
|
|
140
164
|
'Authorization': `Bearer ${config.apiKey}`,
|
|
@@ -0,0 +1,68 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.DatabaseClientUnsupportedError = void 0;
|
|
37
|
+
exports.loadDatabaseClientBeforeMint = loadDatabaseClientBeforeMint;
|
|
38
|
+
class DatabaseClientUnsupportedError extends Error {
|
|
39
|
+
code = 'database_client_unsupported';
|
|
40
|
+
constructor() {
|
|
41
|
+
super('Database commands are not supported on this platform.');
|
|
42
|
+
this.name = 'DatabaseClientUnsupportedError';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
exports.DatabaseClientUnsupportedError = DatabaseClientUnsupportedError;
|
|
46
|
+
/**
|
|
47
|
+
* Load the native-capable client module before requesting a short-lived
|
|
48
|
+
* credential. Import and binding failures are deliberately collapsed to a
|
|
49
|
+
* stable product error so low-level module paths and implementation details do
|
|
50
|
+
* not reach users. Mint failures are left untouched for the API error mapper.
|
|
51
|
+
*/
|
|
52
|
+
async function loadDatabaseClientBeforeMint(mintAccess, dependencies = {}) {
|
|
53
|
+
let clientModule;
|
|
54
|
+
try {
|
|
55
|
+
clientModule = await (dependencies.loadClient ?? (() => Promise.resolve().then(() => __importStar(require('@libsql/client')))))();
|
|
56
|
+
if (typeof clientModule.createClient !== 'function') {
|
|
57
|
+
throw new Error('Database client factory is unavailable.');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
throw new DatabaseClientUnsupportedError();
|
|
62
|
+
}
|
|
63
|
+
const access = await mintAccess();
|
|
64
|
+
return {
|
|
65
|
+
createClient: clientModule.createClient,
|
|
66
|
+
access,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.DatabaseOperationError = exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS = exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS = void 0;
|
|
7
|
+
exports.safeDatabaseRequestError = safeDatabaseRequestError;
|
|
8
|
+
exports.runDatabaseClientOperationWithDeadline = runDatabaseClientOperationWithDeadline;
|
|
9
|
+
exports.requestDatabaseOperation = requestDatabaseOperation;
|
|
10
|
+
exports.requestDatabaseDumpStream = requestDatabaseDumpStream;
|
|
11
|
+
exports.requestDatabaseAccess = requestDatabaseAccess;
|
|
12
|
+
exports.withDatabaseClient = withDatabaseClient;
|
|
13
|
+
exports.normalizeDatabaseValue = normalizeDatabaseValue;
|
|
14
|
+
exports.formatDatabaseTableValue = formatDatabaseTableValue;
|
|
15
|
+
const axios_1 = __importDefault(require("axios"));
|
|
16
|
+
const api_1 = require("./api");
|
|
17
|
+
const database_client_support_1 = require("./database-client-support");
|
|
18
|
+
exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS = 30_000;
|
|
19
|
+
exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS = 120_000;
|
|
20
|
+
class DatabaseOperationError extends Error {
|
|
21
|
+
code;
|
|
22
|
+
status;
|
|
23
|
+
constructor(code, message, status) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.code = code;
|
|
26
|
+
if (status !== undefined) {
|
|
27
|
+
this.status = status;
|
|
28
|
+
}
|
|
29
|
+
// A public command error is deliberately data-only. In particular, it
|
|
30
|
+
// must never retain an upstream stack, request, response, config, or
|
|
31
|
+
// cause that could contain either control- or data-plane credentials.
|
|
32
|
+
delete this.stack;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
exports.DatabaseOperationError = DatabaseOperationError;
|
|
36
|
+
function safeDatabaseRequestError(error) {
|
|
37
|
+
const augmented = (0, api_1.augmentTokenMissingAbilityMessage)(error);
|
|
38
|
+
const response = augmented?.response;
|
|
39
|
+
const status = typeof response?.status === 'number' ? response.status : undefined;
|
|
40
|
+
const codeCandidate = typeof response?.data?.code === 'string'
|
|
41
|
+
? response.data.code.trim()
|
|
42
|
+
: '';
|
|
43
|
+
const stableCode = codeCandidate.length > 0 ? codeCandidate : null;
|
|
44
|
+
const code = stableCode ?? 'upstream_unavailable';
|
|
45
|
+
const appMessage = stableCode !== null
|
|
46
|
+
&& typeof response?.data?.message === 'string'
|
|
47
|
+
&& response.data.message.trim().length > 0
|
|
48
|
+
? response.data.message
|
|
49
|
+
: 'Database request failed.';
|
|
50
|
+
const message = code === 'unauthenticated'
|
|
51
|
+
? `${appMessage} Run solidactions login to authenticate again.`
|
|
52
|
+
: appMessage;
|
|
53
|
+
return new DatabaseOperationError(code, message, status);
|
|
54
|
+
}
|
|
55
|
+
function positiveTimeout(value, fallback) {
|
|
56
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
57
|
+
? value
|
|
58
|
+
: fallback;
|
|
59
|
+
}
|
|
60
|
+
class DatabaseDeadlineElapsed extends DatabaseOperationError {
|
|
61
|
+
constructor(message) {
|
|
62
|
+
super('upstream_unavailable', message);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async function requestWithDeadline(operation, timeoutMs) {
|
|
66
|
+
const controller = new AbortController();
|
|
67
|
+
let timer;
|
|
68
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
69
|
+
timer = setTimeout(() => {
|
|
70
|
+
controller.abort();
|
|
71
|
+
reject(new DatabaseDeadlineElapsed('Database request timed out.'));
|
|
72
|
+
}, timeoutMs);
|
|
73
|
+
});
|
|
74
|
+
try {
|
|
75
|
+
return await Promise.race([operation(controller.signal, timeoutMs), deadline]);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
if (timer)
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Bound a Hrana operation and actively invoke its cancellation/close hook when
|
|
84
|
+
* the deadline expires. Callers can inject a shorter timeout per command.
|
|
85
|
+
*/
|
|
86
|
+
async function runDatabaseClientOperationWithDeadline(operation, onTimeout, timeoutMs = exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS) {
|
|
87
|
+
const boundedTimeout = positiveTimeout(timeoutMs, exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS);
|
|
88
|
+
let timer;
|
|
89
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
90
|
+
timer = setTimeout(() => {
|
|
91
|
+
try {
|
|
92
|
+
void Promise.resolve(onTimeout?.()).catch(() => undefined);
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
reject(new DatabaseDeadlineElapsed('Database operation timed out.'));
|
|
96
|
+
}
|
|
97
|
+
}, boundedTimeout);
|
|
98
|
+
});
|
|
99
|
+
try {
|
|
100
|
+
return await Promise.race([Promise.resolve().then(operation), deadline]);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
if (timer)
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Call the single CLI database control-plane endpoint and discard all Axios
|
|
109
|
+
* transport state at the error boundary.
|
|
110
|
+
*/
|
|
111
|
+
async function requestDatabaseOperation(config, body, dependencies = {}) {
|
|
112
|
+
const post = dependencies.post ?? axios_1.default.post;
|
|
113
|
+
const timeoutMs = positiveTimeout(dependencies.controlPlaneTimeoutMs, exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS);
|
|
114
|
+
try {
|
|
115
|
+
const response = await requestWithDeadline((signal, timeout) => post(`${config.host}/api/v1/databases`, body, {
|
|
116
|
+
headers: (0, api_1.getApiHeaders)(config, 'application/json'),
|
|
117
|
+
signal,
|
|
118
|
+
timeout,
|
|
119
|
+
}), timeoutMs);
|
|
120
|
+
return response.data;
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
throw safeDatabaseRequestError(error);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** Request the existing server-side SQL dump as a stream. */
|
|
127
|
+
async function requestDatabaseDumpStream(config, name, dependencies = {}) {
|
|
128
|
+
const post = dependencies.post ?? axios_1.default.post;
|
|
129
|
+
const timeoutMs = positiveTimeout(dependencies.controlPlaneTimeoutMs, exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS);
|
|
130
|
+
try {
|
|
131
|
+
const response = await requestWithDeadline((signal, timeout) => post(`${config.host}/api/v1/databases`, { operation: 'dump', name }, {
|
|
132
|
+
headers: {
|
|
133
|
+
...(0, api_1.getApiHeaders)(config, 'application/json'),
|
|
134
|
+
Accept: 'application/sql',
|
|
135
|
+
},
|
|
136
|
+
responseType: 'stream',
|
|
137
|
+
signal,
|
|
138
|
+
timeout,
|
|
139
|
+
}), timeoutMs);
|
|
140
|
+
return response.data;
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
throw safeDatabaseRequestError(error);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function safeDirectClientError() {
|
|
147
|
+
return new DatabaseOperationError('upstream_unavailable', 'Database operation failed.');
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Request a short-lived direct database credential from the app control plane.
|
|
151
|
+
* Any Axios transport object is discarded at this boundary.
|
|
152
|
+
*/
|
|
153
|
+
async function requestDatabaseAccess(config, name, mode, dependencies = {}) {
|
|
154
|
+
return requestDatabaseOperation(config, { operation: 'access', name, mode }, dependencies);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Run one foreground operation with an ephemeral direct client. Native support
|
|
158
|
+
* is loaded before access is minted, and the client is always closed once it
|
|
159
|
+
* exists. Direct-client details are collapsed to a credential-safe error.
|
|
160
|
+
*/
|
|
161
|
+
async function withDatabaseClient(config, name, mode, operation, dependencies = {}) {
|
|
162
|
+
const { createClient, access } = await (0, database_client_support_1.loadDatabaseClientBeforeMint)(() => requestDatabaseAccess(config, name, mode, {
|
|
163
|
+
post: dependencies.post,
|
|
164
|
+
controlPlaneTimeoutMs: dependencies.controlPlaneTimeoutMs,
|
|
165
|
+
}), { loadClient: dependencies.loadClient });
|
|
166
|
+
let client;
|
|
167
|
+
try {
|
|
168
|
+
client = createClient({
|
|
169
|
+
url: access.url,
|
|
170
|
+
authToken: access.token,
|
|
171
|
+
intMode: 'string',
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
throw safeDirectClientError();
|
|
176
|
+
}
|
|
177
|
+
const dataPlaneTimeoutMs = positiveTimeout(dependencies.dataPlaneTimeoutMs, exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS);
|
|
178
|
+
let closePromise;
|
|
179
|
+
const closeClient = () => {
|
|
180
|
+
closePromise ??= runDatabaseClientOperationWithDeadline(async () => { await client.close(); }, undefined, dataPlaneTimeoutMs);
|
|
181
|
+
return closePromise;
|
|
182
|
+
};
|
|
183
|
+
let primaryFailure;
|
|
184
|
+
try {
|
|
185
|
+
return await runDatabaseClientOperationWithDeadline(() => operation(client), closeClient, dataPlaneTimeoutMs);
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
primaryFailure = error instanceof DatabaseDeadlineElapsed
|
|
189
|
+
? new DatabaseOperationError(error.code, error.message, error.status)
|
|
190
|
+
: safeDirectClientError();
|
|
191
|
+
throw primaryFailure;
|
|
192
|
+
}
|
|
193
|
+
finally {
|
|
194
|
+
try {
|
|
195
|
+
await closeClient();
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
if (!primaryFailure) {
|
|
199
|
+
throw safeDirectClientError();
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function blobBytes(value) {
|
|
205
|
+
if (ArrayBuffer.isView(value)) {
|
|
206
|
+
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
207
|
+
}
|
|
208
|
+
if (value instanceof ArrayBuffer) {
|
|
209
|
+
return new Uint8Array(value);
|
|
210
|
+
}
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
/** Normalize direct-client values into the stable JSON contract. */
|
|
214
|
+
function normalizeDatabaseValue(value) {
|
|
215
|
+
if (typeof value === 'bigint') {
|
|
216
|
+
return value.toString(10);
|
|
217
|
+
}
|
|
218
|
+
const bytes = blobBytes(value);
|
|
219
|
+
if (bytes) {
|
|
220
|
+
return { base64: Buffer.from(bytes).toString('base64') };
|
|
221
|
+
}
|
|
222
|
+
return value;
|
|
223
|
+
}
|
|
224
|
+
/** Render one direct-client value as a concise, implementation-neutral cell. */
|
|
225
|
+
function formatDatabaseTableValue(value) {
|
|
226
|
+
if (value === null) {
|
|
227
|
+
return 'NULL';
|
|
228
|
+
}
|
|
229
|
+
if (typeof value === 'bigint') {
|
|
230
|
+
return value.toString(10);
|
|
231
|
+
}
|
|
232
|
+
const bytes = blobBytes(value);
|
|
233
|
+
if (bytes) {
|
|
234
|
+
return `<blob ${bytes.byteLength} bytes>`;
|
|
235
|
+
}
|
|
236
|
+
return String(value);
|
|
237
|
+
}
|