1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![forbid(unsafe_code)]
//! # z_osmf
//!
//! The VERY work in progress Rust z/OSMF<sup>TM</sup> [^1] Client.
//!
//! ---
//!
//! [^1]: z/OSMF<sup>TM</sup>, z/OS<sup>TM</sup>, and the lowercase letter z<sup>TM</sup> (probably) are trademarks owned by International Business Machines Corporation ("IBM").
//! This crate is not approved, endorsed, acknowledged, or even tolerated by IBM.
//! (Please don't sue me, Big Blue)
pub use bytes::Bytes;
pub mod error;
#[cfg(feature = "datasets")]
pub mod datasets;
#[cfg(feature = "files")]
pub mod files;
#[cfg(feature = "jobs")]
pub mod jobs;
mod convert;
mod utils;
use std::sync::{Arc, RwLock};
use reqwest::header::HeaderValue;
use z_osmf_macros::Getters;
use self::convert::TryFromResponse;
use self::error::{CheckStatus, Error};
use self::utils::get_transaction_id;
#[cfg(feature = "datasets")]
use self::datasets::DatasetsClient;
#[cfg(feature = "files")]
use self::files::FilesClient;
#[cfg(feature = "jobs")]
use self::jobs::JobsClient;
/// # ZOsmf
///
/// Client for interacting with z/OSMF.
///
/// ```
/// # async fn example() -> anyhow::Result<()> {
/// # use z_osmf::ZOsmf;
/// let client = reqwest::Client::new();
/// let base_url = "https://zosmf.mainframe.my-company.com";
/// let username = "USERNAME";
///
/// let zosmf = ZOsmf::new(client, base_url)?;
/// zosmf.login(username, "PASSWORD").await?;
///
/// let my_datasets = zosmf.datasets().list(username).build().await?;
///
/// for dataset in my_datasets.items().iter() {
/// println!("{:#?}", dataset);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct ZOsmf {
core: Arc<ClientCore>,
}
impl ZOsmf {
/// Create a new z/OSMF client.
///
/// # Example
/// ```
/// # async fn example() -> anyhow::Result<()> {
/// # use z_osmf::ZOsmf;
/// let client = reqwest::Client::new();
/// let base_url = "https://zosmf.mainframe.my-company.com";
///
/// let zosmf = ZOsmf::new(client, base_url)?;
/// # Ok(())
/// # }
/// ```
pub fn new<B>(client: reqwest::Client, base_url: B) -> Result<Self, Error>
where
B: std::fmt::Display,
{
let base_url = format!("{}", base_url).trim_end_matches('/').into();
let core = Arc::new(ClientCore {
base_url,
client,
cookie: RwLock::new(None),
});
Ok(ZOsmf { core })
}
/// Authenticate with z/OSMF.
///
/// # Example
/// ```
/// # async fn example(zosmf: z_osmf::ZOsmf) -> anyhow::Result<()> {
/// zosmf.login("USERNAME", "PASSWORD").await?;
/// # Ok(())
/// # }
/// ```
pub async fn login<U, P>(&self, username: U, password: P) -> Result<(), Error>
where
U: std::fmt::Display,
P: std::fmt::Display,
{
let response = self
.core
.client
.post(format!(
"{}/zosmf/services/authenticate",
self.core.base_url
))
.basic_auth(username, Some(password))
.send()
.await?
.check_status()
.await?;
match self.core.cookie.write() {
Ok(mut cookie) => {
*cookie = Some(
response
.headers()
.get("Set-Cookie")
.ok_or(Error::Custom("failed to get authentication token".into()))?
.clone(),
);
}
Err(_) => {
return Err(Error::Custom(
"failed to retrieve authentication header".into(),
))
}
}
Ok(())
}
/// Logout of z/OSMF.
///
/// <p style="background:rgba(255,181,77,0.16);padding:0.75em;">
/// <strong>Warning:</strong> Logging out before an action has completed,
/// like immediately after submitting a job, can cause the action to fail.
/// </p>
///
/// # Example
/// ```
/// # async fn example(zosmf: z_osmf::ZOsmf) -> anyhow::Result<()> {
/// zosmf.logout().await?;
/// # Ok(())
/// # }
/// ```
pub async fn logout(&self) -> Result<(), Error> {
self.core
.client
.delete(format!(
"{}/zosmf/services/authenticate",
self.core.base_url
))
.send()
.await?
.check_status()
.await?;
match self.core.cookie.write() {
Ok(mut cookie) => {
*cookie = None;
}
Err(_) => {
return Err(Error::Custom(
"failed to retrieve authentication header".into(),
))
}
}
Ok(())
}
/// Create a sub-client for interacting with datasets.
///
/// # Example
/// ```
/// # async fn example(zosmf: z_osmf::ZOsmf) -> anyhow::Result<()> {
/// let datasets_client = zosmf.datasets();
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "datasets")]
pub fn datasets(&self) -> DatasetsClient {
DatasetsClient::new(&self.core)
}
/// Create a sub-client for interacting with files.
///
/// # Example
/// ```
/// # async fn example(zosmf: z_osmf::ZOsmf) -> anyhow::Result<()> {
/// let files_client = zosmf.files();
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "files")]
pub fn files(&self) -> FilesClient {
FilesClient::new(&self.core)
}
/// Create a sub-client for interacting with jobs.
///
/// # Example
/// ```
/// # async fn example(zosmf: z_osmf::ZOsmf) -> anyhow::Result<()> {
/// let jobs_client = zosmf.jobs();
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "jobs")]
pub fn jobs(&self) -> JobsClient {
JobsClient::new(&self.core)
}
}
#[derive(Clone, Debug, Getters)]
pub struct TransactionId {
transaction_id: Box<str>,
}
impl TryFromResponse for TransactionId {
async fn try_from_response(value: reqwest::Response) -> Result<Self, Error> {
let transaction_id = get_transaction_id(&value)?;
Ok(TransactionId { transaction_id })
}
}
#[derive(Debug)]
struct ClientCore {
base_url: Box<str>,
client: reqwest::Client,
cookie: RwLock<Option<HeaderValue>>,
}
#[cfg(test)]
mod tests {
use super::*;
pub(crate) fn get_zosmf() -> ZOsmf {
ZOsmf::new(reqwest::Client::new(), "https://test.com").unwrap()
}
pub(crate) trait GetJson {
fn json(&self) -> Option<serde_json::Value>;
}
impl GetJson for reqwest::Request {
fn json(&self) -> Option<serde_json::Value> {
Some(
serde_json::from_slice(self.body()?.as_bytes()?)
.expect("failed to deserialize JSON"),
)
}
}
}