// GENERATED by tools/gen — DO NOT EDIT.
///|
/// Transport-independent client. Sharing a runtime Client also shares its retry budget.
pub struct CloudflareDns {
priv client : @client.Client
priv auth : Auth
priv base_url : String
priv server_urls : Map[String, String]
}
///|
pub extend CloudflareDns with @debug.Debug::{to_repr}
///|
pub impl @debug.Debug for CloudflareDns with fn to_repr(_) {
@debug.Repr::literal("")
}
///|
/// Constructs a client using the caller's backend and clock. Retries are conservative
/// unless configured in the ledger. The default per-attempt timeout is 60000 ms. No total timeout is set by default.
/// Backend SendOptions enforce attempts; a supplied timer also bounds runtime waits.
/// Credentials are redacted from Debug output.
/// server_urls maps spec server URLs to replacement URLs, independently of base_url.
pub fn CloudflareDns::new(
backend : &@http.Backend,
clock : &@rt.Clock,
auth~ : Auth,
base_url~ : String = "https://api.cloudflare.com/client/v4",
server_urls~ : Map[String, String] = {},
retry~ : @client.RetryPolicy = default_retry(),
timer? : &@rt.Timer,
timeout_ms~ : Int32 = 60000,
total_timeout_ms? : Int32,
max_body_bytes? : Int32,
) -> CloudflareDns {
let default = @client.RedirectConfig::default()
let credential_headers = default.credential_headers.copy()
credential_headers.push("x-auth-email")
credential_headers.push("x-auth-key")
credential_headers.push("x-auth-user-service-key")
let client = @client.Client::new(
backend,
clock,
retry~,
timer?,
timeout_ms~,
total_ms?=total_timeout_ms,
max_body_bytes?,
redirect={ ..default, credential_headers, },
)
CloudflareDns::from_client(client, auth~, base_url~, server_urls~)
}
///|
/// Wraps the caller's Client; its policies and retry budget apply.
/// From mttp_core 0.3.0, SDK credential headers are marked on each request.
/// They are stripped when the host, port or scheme changes, except on a
/// same-host HTTP port 80 to HTTPS port 443 upgrade. HTTPS to HTTP is refused
/// by default.
/// Credentials are redacted from Debug output.
pub fn CloudflareDns::from_client(
client : @client.Client,
auth~ : Auth,
base_url~ : String = "https://api.cloudflare.com/client/v4",
server_urls~ : Map[String, String] = {},
) -> CloudflareDns {
{ client, auth, base_url, server_urls: server_urls.copy(), }
}
///|
fn route_matches(url : String, template : String, base_url : String) -> Bool {
let path = try {
let parsed = @http.Url::parse(url)
if parsed.is_absolute() {
let base = @http.Url::parse(base_url)
if !parsed.same_origin(base) {
return false
}
let prefix = base.path.trim_end(chars="/").to_owned()
if parsed.path == prefix {
"/"
} else if parsed.path.has_prefix(prefix + "/") {
parsed.path[prefix.length():].to_owned()
} else {
return false
}
} else {
parsed.path
}
} catch {
_ => return false
}
let actual = path.split("/").collect()
let expected = template.split("/").collect()
if actual.length() != expected.length() {
return false
}
for i, part in expected {
if !(part.has_prefix("{") && part.has_suffix("}")) && part != actual[i] {
return false
}
}
true
}
///|
fn CloudflareDns::operation_base(
self : CloudflareDns,
server : String,
) -> String {
let selected = if server == "" {
self.base_url
} else {
self.server_urls.get(server).unwrap_or(server)
}
@http.Url::parse(self.base_url)
.resolve(@http.Url::parse(selected))
.to_string() catch {
_ => selected
}
}
///|
fn CloudflareDns::prepare(
self : CloudflareDns,
original : @http.Request,
operation : String,
) -> Result[@http.Request, Failure] {
let (use_auth, server) = self.operation_config(operation)
let base = self.operation_base(server)
let mut request = { ..original, url: @http.join_url(base, original.url), }
// Do not attach credentials to a next-page URL outside the operation's origin.
let trusted = @http.Url::parse(base).same_origin(
@http.Url::parse(request.url),
) catch {
_ => false
}
let headers = request.headers
.remove("authorization")
.remove("x-auth-email")
.remove("x-auth-key")
.remove("x-auth-user-service-key")
request = { ..request, headers, }
try {
if use_auth && trusted {
request = self.authenticate(request)
}
request.headers.validate()
} catch {
@http.TransportError::TransportError(detail~, ..) =>
return Result::Err(
Failure::Validation(operation~, parameter="headers", message=detail),
)
}
// Client defaults merge after preparation, even with anonymous SDK auth.
let credential_headers = request.attributes
.get(@http.credential_headers)
.unwrap_or([])
.copy()
for
name in [
"authorization", "x-auth-email", "x-auth-key", "x-auth-user-service-key",
] {
if !credential_headers.iter().any(existing => existing.to_lower() == name) {
credential_headers.push(name)
}
}
Result::Ok(
request
.attribute(@http.credential_headers, credential_headers)
.attribute(@client.rate_limit_bucket, "cloudflare" + ":" + operation)
.attribute(@client.operation_id, operation),
)
}
///|
fn response_failure(
operation : String,
error : @client.ResponseFailure,
) -> Failure {
match error {
@client.ResponseFailure::UnexpectedStatus(head, body~) =>
Failure::Http(
envelope_failure(operation, head, body, envelope_json(body)),
)
_ => Failure::Decode(error)
}
}
///|
/// Buffers and consumes a response; HTTP failures retain status, headers and body.
async fn CloudflareDns::send_buffered(
self : CloudflareDns,
request : @http.Request,
operation~ : String = self.infer_operation(request),
) -> Result[@client.Reply[Bytes], Failure] {
let request = match self.prepare(request, operation) {
Result::Ok(request) => request
Result::Err(error) => return Result::Err(error)
}
try {
let reply = self.client.send(
@client.request(request).response(@client.as_bytes()),
decide_retry=guard_response_retry,
)
match reply.body {
Result::Ok(body) =>
Result::Ok({
status: reply.status,
headers: reply.headers,
body,
request: reply.request,
attributes: reply.attributes,
})
Result::Err(error) => Result::Err(response_failure(operation, error))
}
} catch {
@http.TransportError::TransportError(..) as error =>
Result::Err(Failure::Transport(error))
error => raise error
}
}
///|
/// Sends the request and applies the matching generated decoder to a consumed body.
pub async fn[T] CloudflareDns::call(
self : CloudflareDns,
request : @http.Request,
decode : (@http.ResponseHead, Bytes) -> Result[T, @client.ResponseFailure],
operation~ : String = self.infer_operation(request),
) -> Result[T, Failure] {
match self.send(request, operation~) {
Result::Err(error) => Result::Err(error)
Result::Ok(reply) =>
match
decode({ status: reply.status, headers: reply.headers, }, reply.body) {
Result::Ok(value) => Result::Ok(value)
Result::Err(error) => Result::Err(Failure::Decode(error))
}
}
}
///|
// The raw reply is kept for generic send and for bounded diagnostic excerpts.
// Typed operations and paginators consume the same parse used to inspect success.
async fn CloudflareDns::read_envelope(
self : CloudflareDns,
request : @http.Request,
operation~ : String,
) -> Result[(@client.Reply[Bytes], Result[Json, String]), Failure] {
match self.send_buffered(request, operation~) {
Result::Err(error) => Result::Err(error)
Result::Ok(reply) => {
let parsed = envelope_json(reply.body)
if parsed is Result::Ok({ "success": False, .. }) {
let head : @http.ResponseHead = {
status: reply.status,
headers: reply.headers,
}
Result::Err(
Failure::Http(envelope_failure(operation, head, reply.body, parsed)),
)
} else {
Result::Ok((reply, parsed))
}
}
}
}
///|
/// Returns buffered bytes and metadata, classifying HTTP and false success envelopes.
pub async fn CloudflareDns::send(
self : CloudflareDns,
request : @http.Request,
operation~ : String = self.infer_operation(request),
) -> Result[@client.Reply[Bytes], Failure] {
self.read_envelope(request, operation~).map(value => value.0)
}
///|
fn envelope_decode_failure(
reply : @client.Reply[Bytes],
message : String,
) -> Failure {
let head : @http.ResponseHead = {
status: reply.status,
headers: reply.headers,
}
Failure::Decode(
@client.ResponseFailure::Deserialization(
head,
message~,
body=reply.body[:reply.body.length().min(@client.max_error_body)].to_owned(),
),
)
}
///|
async fn[T] CloudflareDns::call_envelope(
self : CloudflareDns,
request : @http.Request,
decode : (Json) -> T raise @json.JsonDecodeError,
operation~ : String,
) -> Result[T, Failure] {
match self.read_envelope(request, operation~) {
Result::Err(error) => Result::Err(error)
Result::Ok((reply, Result::Err(message))) =>
Result::Err(envelope_decode_failure(reply, message))
Result::Ok((reply, Result::Ok(value))) =>
Result::Ok(decode(value)) catch {
error => Result::Err(envelope_decode_failure(reply, error.to_string()))
}
}
}
///|
// The server may veto any retry. An affirmative override cannot authorize
// replay outside the protected methods' explicitly allowed response statuses.
fn[T] guard_response_retry(
event : @client.AttemptResult[T],
context : @client.RetryContext,
) -> @retry.Decision {
if event.http_outcome() is @retry.AttemptOutcome::Response(status~, ..) {
if (
context.request.meth == @http.Method::parse("POST") ||
context.request.meth == @http.Method::parse("PATCH")
) &&
!(status == 429) {
return @retry.Decision::Stop(@retry.StopReason::MethodNotAllowed)
}
}
context.default_decision
}
///|
/// Credentials selected at construction; Debug deliberately redacts values.
pub(all) enum Auth {
ApiToken(String)
GlobalApiKey(email~ : String, key~ : String)
}
///|
pub extend Auth with @debug.Debug::{to_repr}
///|
pub impl @debug.Debug for Auth with fn to_repr(_) {
@debug.Repr::literal("")
}
///|
fn CloudflareDns::authenticate(
self : CloudflareDns,
request : @http.Request,
) -> @http.Request raise @http.TransportError {
match self.auth {
Auth::ApiToken(value) => {
@http.Headers::of([("authorization", value)]).validate()
request.credential("authorization", "Bearer " + value)
}
Auth::GlobalApiKey(email~, key~) => {
let fields = [("x-auth-email", email), ("x-auth-key", key)]
@http.Headers::of(fields).validate()
for (header, value) in fields; result = request {
continue result.credential(header, value)
} nobreak {
result
}
}
}
}
///|
fn CloudflareDns::operation_config(
self : CloudflareDns,
operation : String,
) -> (Bool, String) {
ignore(self)
match operation {
"zones-get" => (true, "")
"zones-post" => (true, "")
"zones-0-delete" => (true, "")
"zones-0-get" => (true, "")
"zones-0-patch" => (true, "")
"put-zones-zone_id-activation_check" => (true, "")
"dns-records-for-a-zone-list-dns-records" => (true, "")
"dns-records-for-a-zone-create-dns-record" => (true, "")
"dns-records-for-a-zone-batch-dns-records" => (true, "")
"dns-records-for-a-zone-export-dns-records" => (true, "")
"dns-records-for-a-zone-import-dns-records" => (true, "")
"dns-records-for-a-zone-review-dns-scan" => (true, "")
"dns-records-for-a-zone-apply-dns-scan-results" => (true, "")
"dns-records-for-a-zone-trigger-dns-scan" => (true, "")
"dns-records-for-a-zone-delete-dns-record" => (true, "")
"dns-records-for-a-zone-dns-record-details" => (true, "")
"dns-records-for-a-zone-patch-dns-record" => (true, "")
"dns-records-for-a-zone-update-dns-record" => (true, "")
"dns-settings-for-a-zone-list-dns-settings" => (true, "")
"dns-settings-for-a-zone-update-dns-settings" => (true, "")
"dnssec-delete-dnssec-records" => (true, "")
"dnssec-dnssec-details" => (true, "")
"dnssec-edit-dnssec-status" => (true, "")
_ => (true, "")
}
}
///|
fn CloudflareDns::infer_operation(
self : CloudflareDns,
request : @http.Request,
) -> String {
if request.meth == @http.Method::parse("GET") &&
route_matches(request.url, "/zones", self.operation_base("")) {
return "zones-get"
}
if request.meth == @http.Method::parse("POST") &&
route_matches(request.url, "/zones", self.operation_base("")) {
return "zones-post"
}
if request.meth == @http.Method::parse("DELETE") &&
route_matches(request.url, "/zones/{zone_id}", self.operation_base("")) {
return "zones-0-delete"
}
if request.meth == @http.Method::parse("GET") &&
route_matches(request.url, "/zones/{zone_id}", self.operation_base("")) {
return "zones-0-get"
}
if request.meth == @http.Method::parse("PATCH") &&
route_matches(request.url, "/zones/{zone_id}", self.operation_base("")) {
return "zones-0-patch"
}
if request.meth == @http.Method::parse("PUT") &&
route_matches(
request.url,
"/zones/{zone_id}/activation_check",
self.operation_base(""),
) {
return "put-zones-zone_id-activation_check"
}
if request.meth == @http.Method::parse("GET") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records",
self.operation_base(""),
) {
return "dns-records-for-a-zone-list-dns-records"
}
if request.meth == @http.Method::parse("POST") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records",
self.operation_base(""),
) {
return "dns-records-for-a-zone-create-dns-record"
}
if request.meth == @http.Method::parse("POST") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/batch",
self.operation_base(""),
) {
return "dns-records-for-a-zone-batch-dns-records"
}
if request.meth == @http.Method::parse("GET") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/export",
self.operation_base(""),
) {
return "dns-records-for-a-zone-export-dns-records"
}
if request.meth == @http.Method::parse("POST") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/import",
self.operation_base(""),
) {
return "dns-records-for-a-zone-import-dns-records"
}
if request.meth == @http.Method::parse("GET") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/scan/review",
self.operation_base(""),
) {
return "dns-records-for-a-zone-review-dns-scan"
}
if request.meth == @http.Method::parse("POST") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/scan/review",
self.operation_base(""),
) {
return "dns-records-for-a-zone-apply-dns-scan-results"
}
if request.meth == @http.Method::parse("POST") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/scan/trigger",
self.operation_base(""),
) {
return "dns-records-for-a-zone-trigger-dns-scan"
}
if request.meth == @http.Method::parse("DELETE") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/{dns_record_id}",
self.operation_base(""),
) {
return "dns-records-for-a-zone-delete-dns-record"
}
if request.meth == @http.Method::parse("GET") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/{dns_record_id}",
self.operation_base(""),
) {
return "dns-records-for-a-zone-dns-record-details"
}
if request.meth == @http.Method::parse("PATCH") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/{dns_record_id}",
self.operation_base(""),
) {
return "dns-records-for-a-zone-patch-dns-record"
}
if request.meth == @http.Method::parse("PUT") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_records/{dns_record_id}",
self.operation_base(""),
) {
return "dns-records-for-a-zone-update-dns-record"
}
if request.meth == @http.Method::parse("GET") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_settings",
self.operation_base(""),
) {
return "dns-settings-for-a-zone-list-dns-settings"
}
if request.meth == @http.Method::parse("PATCH") &&
route_matches(
request.url,
"/zones/{zone_id}/dns_settings",
self.operation_base(""),
) {
return "dns-settings-for-a-zone-update-dns-settings"
}
if request.meth == @http.Method::parse("DELETE") &&
route_matches(
request.url,
"/zones/{zone_id}/dnssec",
self.operation_base(""),
) {
return "dnssec-delete-dnssec-records"
}
if request.meth == @http.Method::parse("GET") &&
route_matches(
request.url,
"/zones/{zone_id}/dnssec",
self.operation_base(""),
) {
return "dnssec-dnssec-details"
}
if request.meth == @http.Method::parse("PATCH") &&
route_matches(
request.url,
"/zones/{zone_id}/dnssec",
self.operation_base(""),
) {
return "dnssec-edit-dnssec-status"
}
""
}