use super::{context, flow, Work};
use crate::cli::{Cli, Command};
use crate::commands;
use crate::config::vault::FileVault;
use crate::config::Config;
use crate::conn::profile::{Profile, SecretRef};
use crate::conn::{options, session::Session, store::ProfileStore, ConnectionSettings};
use crate::error::Result;
use crate::output::Envelope;
use crate::runtime::timeout::{self, Phase};
use crate::runtime::Backoff;
pub(super) fn destination(
cli: &Cli,
config: &Config,
store: &ProfileStore,
vault: &FileVault,
) -> Result<(Profile, ConnectionSettings)> {
let (profile, secret) = context::destination(config, cli, store, vault)?;
let profile = targeted(profile, cli);
let settings = context::connection(config, cli, Some(&profile), secret)?;
Ok((profile, settings))
}
pub(super) fn targeted(mut profile: Profile, cli: &Cli) -> Profile {
if profile.pin_database {
return profile;
}
if let Some(database) = cli.globals.destination.database.clone() {
profile.database = Some(database);
}
profile
}
pub(super) fn declared_target(profile: &Profile, cli: &Cli) -> crate::output::envelope::Target {
crate::output::envelope::Target {
profile: (cli.globals.destination.dsn.is_none()).then(|| profile.name.clone()),
host: profile.host.clone(),
port: profile.port,
socket: profile
.socket
.as_ref()
.map(|path| path.to_string_lossy().into_owned()),
database: cli
.globals
.destination
.database
.clone()
.or_else(|| profile.database.clone()),
}
}
pub(super) async fn profiles(
cli: &Cli,
config: &Config,
command: &crate::cli::conn::ConnCommand,
store: &mut ProfileStore,
vault: &mut FileVault,
) -> Result<Option<Envelope>> {
let under_test = match command {
crate::cli::conn::ConnCommand::Test(args) => store
.resolve(
args.name
.as_deref()
.or(cli.globals.destination.profile.as_deref()),
context::stored_default(config)?.as_deref(),
)
.ok()
.cloned(),
_ => None,
};
let secret = match &under_test {
Some(profile) => {
crate::conn::profile::SecretVault::load(vault, &SecretRef::for_profile(&profile.name))?
}
None => None,
};
let settings = context::connection(config, cli, under_test.as_ref(), secret)?;
commands::conn::execute(command, config, cli, store, vault, &settings)
.await
.map(Some)
}
pub(super) async fn open(
profile: &Profile,
settings: &ConnectionSettings,
cli: &Cli,
config: &Config,
token: &tokio_util::sync::CancellationToken,
) -> Result<Session> {
profile.ensure_accepts_a_named_database(cli.globals.destination.database.as_deref())?;
let options = options::build(profile, settings)?;
let budget = crate::settings::connect_timeout(config, &cli.globals)?;
let policy: Backoff = crate::settings::retry_policy(config, &cli.globals)?;
crate::i18n::report::channel_opening(&profile.name);
let reaching = std::time::Instant::now();
let opened = crate::runtime::retry(&policy, token, move |_attempt| {
let options = options.clone();
async move { timeout::within(Phase::Connect, budget, Session::open(options)).await }
})
.await;
let cost = reaching.elapsed().as_millis();
match &opened {
Ok(session) => crate::i18n::report::channel_opened(&session.facts().version, cost),
Err(_) => crate::i18n::report::channel_open_failed(cost),
}
opened
}
pub(super) async fn bounded<W: std::io::Write>(
work: &Work<'_>,
mut session: Session,
profile: &Profile,
settings: &ConnectionSettings,
out: &mut W,
) -> Result<Option<Envelope>> {
let budget = crate::settings::operation_timeout(work.config, &work.cli.globals)?;
let aborter = crate::conn::SecondConnection::prepare(profile, settings)?;
let named = u64::from(session.connection().id());
let running = std::time::Instant::now();
let stopping = work.shutdown.token();
let outcome = timeout::within_aborting_or_stopped(
Phase::Query,
budget,
named,
&aborter,
&stopping,
on_session(work, session, profile, out),
)
.await;
crate::i18n::report::channel_closing(running.elapsed().as_millis());
outcome
}
fn closed_by_the_reader<T>(outcome: &Result<T>) -> bool {
matches!(outcome, Err(failure)
if failure.category() == crate::error::Category::ChannelClosed)
}
async fn on_session<W: std::io::Write>(
work: &Work<'_>,
mut session: Session,
profile: &Profile,
out: &mut W,
) -> Result<Option<Envelope>> {
let (cli, config) = (work.cli, work.config);
if flow::applies(cli, config) && !work.many {
let mut context = context::query_context(config, cli, work.shutdown.token())?;
let target = declared_target(profile, cli);
let flowed = flow::run(cli, config, &mut session, &mut context, out, &target).await;
if closed_by_the_reader(&flowed) {
return flowed.map(|_| None);
}
return session.close_after(flowed).await.map(|_| None);
}
let outcome = match &cli.command {
Command::Schema(command) => {
let target = context::schema_target(config, cli, work.scope.clone())?;
commands::schema::execute(command, &mut session, &target).await
}
Command::Query(command) => {
let mut ctx = context::query_context(config, cli, work.shutdown.token())?;
commands::query::execute(command, &mut session, &mut ctx).await
}
Command::Server(command) => {
let settings = context::server_settings(config, cli)?;
commands::server::execute(command, &mut session, &settings, &work.shutdown.token())
.await
}
Command::History(command) => {
commands::history::execute(
command,
&mut session,
cli.globals.destination.database.as_deref(),
)
.await
}
Command::Data(command) => {
let settings = context::data_settings(config, cli)?;
commands::data::execute(command, &mut session, &settings, &work.shutdown.token()).await
}
Command::Conn(_) | Command::Config(_) | Command::Meta(_) => {
Err(commands::not_yet_served(&cli.command))
}
};
session.close_after(outcome).await.map(Some)
}