ecs-pf
Version:
CLI for port-forwarding to RDS via AWS ECS
70 lines (69 loc) • 3.12 kB
JavaScript
import { safeParse } from "valibot";
import { startSSMSession } from "../../session.js";
import { parseClusterName, parsePort, parseRegionName, parseTaskArn, parseTaskId, } from "../../types/parsers.js";
import { HandleConnectionParamsSchema } from "../../types/schemas.js";
import { messages } from "../../utils/index.js";
import { generateReproducibleCommand } from "../command-generation.js";
import { displayDryRunResult, generateConnectDryRun } from "../dry-run.js";
export async function handleConnection(params) {
const parseResult = safeParse(HandleConnectionParamsSchema, params);
if (!parseResult.success) {
throw new Error(`Invalid parameters: ${parseResult.issues.map((issue) => `${issue.path?.map((p) => p.key).join(".")} - ${issue.message}`).join(", ")}`);
}
const { selections, selectedInference, selectedRDS, rdsPort, selectedTask, options, } = parseResult.output;
const regionResult = parseRegionName(selections.region);
if (!regionResult.success)
throw new Error(regionResult.error);
const clusterResult = parseClusterName(selections.ecsCluster || String(selectedInference.cluster.clusterName));
if (!clusterResult.success)
throw new Error(clusterResult.error);
const taskResult = parseTaskArn(selectedTask);
if (!taskResult.success)
throw new Error(taskResult.error);
const rdsPortResult = parsePort(rdsPort);
if (!rdsPortResult.success)
throw new Error(rdsPortResult.error);
const localPortStr = selections.localPort || "8888";
const localPortResult = parsePort(localPortStr);
if (!localPortResult.success)
throw new Error(localPortResult.error);
const reproducibleCommand = generateReproducibleCommand({
region: regionResult.data,
cluster: clusterResult.data,
task: taskResult.data,
rds: selectedRDS.dbInstanceIdentifier,
rdsPort: rdsPortResult.data,
localPort: localPortResult.data,
});
if (options.dryRun) {
await handleDryRun(regionResult.data, clusterResult.data, taskResult.data, selectedRDS, rdsPortResult.data, localPortResult.data);
}
else {
await handleLiveConnection(taskResult.data, selectedRDS, rdsPortResult.data, localPortResult.data, reproducibleCommand);
}
}
async function handleDryRun(region, cluster, taskArn, selectedRDS, rdsPort, localPort) {
const taskIdStr = String(taskArn).split("_")[1] || String(taskArn);
const taskIdResult = parseTaskId(taskIdStr);
if (!taskIdResult.success)
throw new Error(taskIdResult.error);
const dryRunResult = generateConnectDryRun({
region,
cluster,
task: taskIdResult.data,
rdsInstance: selectedRDS,
rdsPort,
localPort,
});
displayDryRunResult(dryRunResult);
messages.success("Dry run completed successfully.");
}
async function handleLiveConnection(taskArn, selectedRDS, rdsPort, localPort, reproducibleCommand) {
await startSSMSession({
localPort,
rdsInstance: selectedRDS,
rdsPort,
taskArn,
reproducibleCommand,
});
}