Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ web-sys = "=0.3.103"
shlex = "2.0.1"
vt100 = "0.16.2"

heck = "0.5.0"
proptest = "1.6.0"
prettyplease = "0.2.37"
progenitor = { version = "0.11.0", default-features = false }
Expand Down
3 changes: 2 additions & 1 deletion apps/piqueld-ui/src/browser/management/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use leptos_router::NavigateOptions;
use leptos_router::components::A;
use leptos_router::hooks::use_navigate;
use piqueld_client::access::AppPermission;
use piqueld_client::paths;

/// The application page: shared configuration, its environments, and history
/// across all of them.
Expand Down Expand Up @@ -50,7 +51,7 @@ pub(super) fn ApplicationSections() -> impl IntoView {
<div class="page-actions">
<a
class="btn btn-ghost"
href={format!("/api/v1/applications/{id}/manifest")}
href={paths::download_application_manifest(&id)}
download
title="Download the saved manifest as TOML"
>
Expand Down
11 changes: 3 additions & 8 deletions apps/piqueld-ui/src/browser/management/timeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ use leptos::task::spawn_local;
use leptos_router::components::A;
use piqueld_client::observability::Elapsed;
use piqueld_client::timeline::{Progress, Step, StepKey, StepState, Timeline};
use piqueld_client::{
API_PREFIX, BuildRecord, Client, Event, Operation, Phase, access::AppPermission,
};
use piqueld_client::{BuildRecord, Client, Event, Operation, Phase, access::AppPermission, paths};
use std::collections::VecDeque;
use std::time::Duration;

Expand Down Expand Up @@ -130,10 +128,7 @@ impl LiveTimeline {
/// Opens the stream, which sends the whole timeline at once, then again
/// on every change.
fn connect(self) {
let url = format!(
"{API_PREFIX}/operations/{}/timeline/stream",
self.operation.get_value()
);
let url = paths::stream_operation_timeline(&self.operation.get_value());
let stream = EventStream::open(
&url,
&["timeline", "access_ended"],
Expand Down Expand Up @@ -1228,7 +1223,7 @@ fn EventFeed(operation: String, live: Memo<bool>, attempt: Memo<u64>) -> impl In
let _ = settled.try_set_value(true);
});
};
let url = format!("{API_PREFIX}/events/stream?operation_id={operation}");
let url = format!("{}?operation_id={operation}", paths::stream_events());
let history = operation_events(&operation);
// The newest event received, which a reopened stream resumes after.
let last = StoredValue::new(0_i64);
Expand Down
2 changes: 2 additions & 0 deletions apps/piqueld/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ piqueld-store = { workspace = true, features = ["testing"] }
tokio-tungstenite.workspace = true
# The `generate_openapi` example, which `just generate` runs.
piqueld-generated.workspace = true
# Names paths like Progenitor names methods.
heck.workspace = true
prettyplease.workspace = true
progenitor.workspace = true
syn.workspace = true
Expand Down
107 changes: 98 additions & 9 deletions apps/piqueld/examples/generate_openapi/main.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
//! Generates or checks the `OpenAPI` specification, its Rust client bindings,
//! the standalone application manifest and daemon configuration JSON
//! Schemas, and the documentation's settings references rendered from those
//! schemas. `piquelctl`'s `cli_reference` example renders the command
//! reference; it depends on the client this generates, so it runs as a
//! separate step.
//! Generates or checks the `OpenAPI` specification, its Rust client bindings
//! and operation paths, the standalone application manifest and daemon
//! configuration JSON Schemas, and the documentation's settings references
//! rendered from those schemas. `piquelctl`'s `cli_reference` example renders
//! the command reference; it depends on the client this generates, so it runs
//! as a separate step.

mod settings_reference;

use anyhow::{Context, Result, anyhow, ensure};
use anyhow::{Context, Result, anyhow, bail, ensure};
use heck::ToSnakeCase;
use piqueld::api::http::openapi_document;
use piqueld_config::DaemonConfig;
use piqueld_core::manifest::ApplicationManifest;
use piqueld_generated::Artifacts;
use serde::Deserialize;
use serde_json::Value;
use serde_json::{Map, Value};
use settings_reference::SettingsPage;
use std::{
collections::BTreeSet,
collections::{BTreeMap, BTreeSet},
fmt::Write as _,
fs,
io::Write,
process::{Command, Stdio},
Expand Down Expand Up @@ -76,6 +78,7 @@ impl Generator {
.context("read Progenitor configuration")?,
)
.context("parse Progenitor configuration")?;
let operation_paths = Self::generate_paths(paths)?;
let client = self.generate_client(document.clone(), &config)?;
let document = format!("{}\n", serde_json::to_string_pretty(&document)?);
let manifest_schema = ApplicationManifest::json_schema();
Expand All @@ -90,6 +93,10 @@ impl Generator {
("docs/application-manifest.schema.json", manifest_schema),
("docs/piqueld-config.schema.json", config_schema),
("crates/piqueld-client/src/generated.rs", client),
(
"crates/piqueld-client/src/paths.rs",
self.rustfmt(&operation_paths)?,
),
(SettingsPage::MANIFEST.path, manifest_settings),
(SettingsPage::CONFIG.path, config_settings),
])?;
Expand Down Expand Up @@ -158,6 +165,88 @@ impl Generator {
))
}

/// Generates the source of `piqueld_client::paths` from the document's
/// `paths`: one function per operation, named after its operation ID as
/// the generated client's methods are, that builds the operation's path
/// with its path parameters percent-encoded as the client encodes them.
/// It reads the complete document, so it also covers the operations
/// Progenitor's copy drops, such as the exec WebSocket.
fn generate_paths(paths: &Map<String, Value>) -> Result<String> {
let mut functions = BTreeMap::new();
for (path, item) in paths {
let operations = item
.as_object()
.with_context(|| format!("OpenAPI path {path} is not an object"))?;
for (method, operation) in operations {
let Some(operation) = operation.as_object() else {
continue;
};
let id = operation
.get("operationId")
.and_then(Value::as_str)
.with_context(|| format!("{method} {path} has no operation ID"))?;
// Progenitor names its methods with heck's snake case too.
let name = id.to_snake_case();
let mut template = String::new();
let mut parameters = Vec::new();
let mut arguments = String::new();
// Placeholders are the odd parts between braces.
for (index, part) in path.split(['{', '}']).enumerate() {
if index % 2 == 0 {
template.push_str(part);
continue;
}
let format = operation
.get("parameters")
.and_then(Value::as_array)
.into_iter()
.flatten()
.find(|parameter| {
parameter.get("in").and_then(Value::as_str) == Some("path")
&& parameter.get("name").and_then(Value::as_str) == Some(part)
})
.and_then(|parameter| parameter.get("schema"))
.map(|schema| {
(
schema.get("type").and_then(Value::as_str),
schema.get("format").and_then(Value::as_str),
)
});
// Strings are percent-encoded; integers need no encoding.
let kind = match format {
Some((Some("string"), _)) => {
write!(arguments, ", {part} = encode_path({part})")?;
"&str"
}
Some((Some("integer"), Some("int64"))) => "i64",
_ => bail!("{id}'s path parameter {part} has an unsupported type"),
};
write!(template, "{{{part}}}")?;
parameters.push(format!("{part}: {kind}"));
}
let body = if parameters.is_empty() {
format!("String::from({template:?})")
} else {
format!("format!({template:?}{arguments})")
};
let function = format!(
"/// `{} {path}`\n#[must_use]\npub fn {name}({}) -> String {{ {body} }}\n\n",
method.to_uppercase(),
parameters.join(", ")
);
ensure!(
functions.insert(name, function).is_none(),
"two operations are named {id}"
);
}
}
Ok(format!(
"// Generated from the OpenAPI document. Run `just generate`; do not edit.\n\n\
use progenitor_client::encode_path;\n\n{}",
functions.into_values().collect::<String>()
))
}

/// Formats Rust source through `rustfmt` over stdin and stdout.
fn rustfmt(&self, source: &str) -> Result<String> {
let mut child = Command::new("rustfmt")
Expand Down
5 changes: 3 additions & 2 deletions crates/piqueld-client/src/applications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub use piqueld_core::api::{
use crate::{
Client, ClientError, Page,
client::{EnvelopedCall, GeneratedCall, check_page_limit, collect_byte_stream},
paths,
};

#[derive(Clone, Debug, Default, Eq, PartialEq)]
Expand Down Expand Up @@ -202,7 +203,7 @@ impl Client {
headers.push(("X-Expected-Application-Id", expected_id.to_owned()));
}
self.send(
"/api/v1/applications/apply",
&paths::apply_application(),
&query,
&headers,
("application/toml", manifest.to_owned().into()),
Expand All @@ -228,7 +229,7 @@ impl Client {
let query =
environment.map_or_default(|environment| vec![("environment", environment.to_owned())]);
self.send(
"/api/v1/applications/plan",
&paths::plan_application(),
&query,
&headers,
("application/toml", manifest.to_owned().into()),
Expand Down
7 changes: 3 additions & 4 deletions crates/piqueld-client/src/exec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
//! cookie. Dropping both the reader and the writer closes the connection,
//! which stops streaming without stopping the command.

use crate::{Client, ClientError};
use piqueld_core::api::API_PREFIX;
use crate::{Client, ClientError, paths};
use piqueld_core::exec::MAX_STDIN_BYTES;
pub use piqueld_core::exec::{
ExecCommand, ExecCommandError, ExecFrame, ExecInput, ExecOutput, ExecRequest, TerminalSize,
Expand Down Expand Up @@ -37,9 +36,9 @@ impl Client {
request: &ExecRequest,
) -> Result<(ExecReader, ExecWriter), ClientError> {
let url = format!(
"{}{API_PREFIX}/environments/{}/exec",
"{}{}",
self.generated.baseurl,
progenitor_client::encode_path(id)
paths::exec_environment_command(id)
);
let request = serde_json::to_string(request).map_err(ClientError::invalid_request)?;
let (reader, writer) = socket::open(self, url, request).await?;
Expand Down
8 changes: 7 additions & 1 deletion crates/piqueld-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ pub mod observability;
pub mod openapi;
/// Operation inspection contracts, and their timelines of steps.
pub mod operations;
/// Each operation's path, for what the client does not send itself: the
/// dashboard's links and event streams, and the client's hand-written
/// requests. Functions are named after the API's operation IDs, as the
/// generated client's methods are, and percent-encode path parameters as
/// those methods do.
pub mod paths;
/// Preview lifecycle and branch state contracts.
pub mod previews;
/// Deploying on push: environment opt-out and GitHub webhooks.
Expand Down Expand Up @@ -118,7 +124,7 @@ pub use system::{
};

pub use piqueld_core::api::{
API_PREFIX, ApplicationLogs, BuildLogChunk, BuildLogPage, BuildRecord, BuildState, Envelope,
ApplicationLogs, BuildLogChunk, BuildLogPage, BuildRecord, BuildState, Envelope,
EnvironmentAccess, ErrorBody, LogRecord, LogStream, ManifestChange, MountedSecret, Page,
SecretAccess, SecretAccessChange, SecretKeyRecovery, SecretMetadata, StoredSecret,
};
Expand Down
Loading