cloudflare_dns

    Thin Cloudflare v4 DNS API client for MoonBit built on gaato/mttp_core: zones, DNS records, DNSSEC and zone DNS settings.

    Download zip
    Author
    Version
    0.1.2
    License
    Apache-2.0
    Last updated
    13 days ago
    Downloads
    49

    #gaato/cloudflare_dns

    Manage Cloudflare DNS from MoonBit through the v4 REST API: list, create, change and delete zones; read, create and change DNS records; batch changes in one transaction; import and export BIND zone files; and read and change DNSSEC and zone DNS settings. Use it for a deploy tool, a dynamic-DNS updater or certificate automation. It runs on native, JavaScript and Wasm GC.

    This module manages DNS from outside Cloudflare. For code that runs inside Cloudflare Workers and needs runtime bindings, see mizchi/cloudflare.

    Unofficial, and not affiliated with Cloudflare. A minor release can change the API; the changelog lists each change.

    #Install

    moon add gaato/cloudflare_dns moon add gaato/mttp

    Import gaato/cloudflare_dns and gaato/cloudflare_dns/gen (record types and low-level builders). gaato/mttp supplies the network and the clock. Also add gaato/mttp_core if you pass an existing gaato/mttp_core/client.Client to CloudflareDns::from_client, or if you write a library that takes the backend from its caller.

    Create a Cloudflare API token with Zone Read and DNS Read on the zones you need, plus DNS Write to change records. Pass it as auth=ApiToken(token). Older global keys use GlobalApiKey(email~, key~).

    #Find a zone's records

    ///|
    pub async fn count_records(
    dns : @cloudflare_dns.CloudflareDns,
    zone_name : String,
    ) -> Unit {
    match dns.list_zones(name=zone_name) {
    Ok([zone, ..]) =>
    match
    dns.list_dns_records(zone_id=zone.id, name_endswith="." + zone_name) {
    Ok(records) => println(records.length())
    Err(error) => println(@debug.to_string(error))
    }
    Ok(_) => println("Zone not found")
    Err(error) => println(@debug.to_string(error))
    }
    }

    A command-line program builds the client from mttp's backend and clock, and closes the backend when it is done. Import gaato/mttp, moonbitlang/core/env and moonbitlang/core/debug in its moon.pkg:

    ///|
    fn main {
    @mttp.run(async fn() {
    guard @env.get_env_var("CLOUDFLARE_API_TOKEN") is Some(token) else {
    println("Set CLOUDFLARE_API_TOKEN")
    return
    }
    let backend = @mttp.backend()
    defer backend.close()
    let dns = @cloudflare_dns.CloudflareDns::new(
    backend,
    @mttp.clock(),
    auth=ApiToken(token),
    timer=@mttp.timer(),
    total_timeout_ms=300_000,
    )
    count_records(dns, "example.com")
    })
    }

    list_zones and list_dns_records return one page. list_zones_pages and list_dns_records_pages take the same filters and return a paginator. Call next_page() until it returns Ok(None).

    #Add or change records

    The record constructor sets the wire type. batch_dns_records applies deletes, patches, puts and posts in one transaction.

    ///|
    pub async fn add_records(
    dns : @cloudflare_dns.CloudflareDns,
    zone_id : String,
    ) -> Result[@gen.DnsBatchResult, @cloudflare_dns.Failure] {
    let web = @gen.ARecord::new(
    name="www.example.com",
    content="192.0.2.1",
    ttl=300,
    )
    let mail = @gen.MXRecord::new(
    name="example.com",
    content="mx.example.com",
    priority=10,
    )
    let note = @gen.TXTRecord::new(
    name="_verify.example.com",
    content="\"verification\"",
    )
    match dns.create_dns_record(zone_id~, A(web)) {
    Err(error) => Err(error)
    Ok(_) =>
    dns.batch_dns_records(
    zone_id~,
    @gen.DnsBatch::new(posts=[MX(mail), TXT(note)]),
    )
    }
    }

    edit_dns_record patches selected fields (PATCH), and update_dns_record replaces a record (PUT). A record type this SDK does not know comes back as Unknown(type, json). Cloudflare limits a batch to 200 records per action on the Free plan and 3,500 on paid plans. Batch record changes

    #Import and export BIND zone files

    ///|
    pub async fn transfer_bind(
    dns : @cloudflare_dns.CloudflareDns,
    zone_id : String,
    zone_file : String,
    ) -> Result[String, @cloudflare_dns.Failure] {
    match dns.import_dns_records(zone_id~, zone_file~, proxied=false) {
    Ok(_) => dns.export_dns_records(zone_id~)
    Err(error) => Err(error)
    }
    }

    Import accepts up to 256 KiB, and export returns UTF-8 text. Cloudflare allows three of these requests per minute per user.

    #Errors, retries and deadlines

    Check the Result even when the status is 200. Cloudflare can answer success: false with a 2xx status, and that becomes Failure::Http too.

    • Http(...): the status and headers, Cloudflare's error and message arrays (codes, descriptions, documentation links), and up to 1 MiB of the body.
    • Decode(...): a successful response that does not match the model.
    • Transport(...): the network failed or a deadline expired.
    • Validation(...): invalid input, caught before sending.

    SettingDefault with CloudflareDns::newNotes
    Retries2. GET, PUT, DELETE and HEAD on 408, 409, 5xx and network failures; every method, POST and PATCH included, on 429 and when the request was never sentA 429 honours Retry-After however long, which can be minutes.
    timeout_ms60 s per attempt
    total_timeout_msnoneSet it, with timer=, to bound the waits.

    from_client keeps the supplied client's policies instead. Cloudflare also applies per-token and per-IP limits across operations. Cloudflare API limits

    #License

    Apache-2.0

    Auth

    pub(all) enum Auth {
    ApiToken(String)
    GlobalApiKey(email~ : String, key~ : String)
    }

    Credentials selected at construction; Debug deliberately redacts values.

    Auth::to_repr

    CloudflareDns

    pub struct CloudflareDns {
    // private fields
    }

    Transport-independent client. Sharing a runtime Client also shares its retry budget.

    CloudflareDns::batch_dns_records

    async fn CloudflareDns::batch_dns_records(self : CloudflareDns, zone_id~ : String, body :
    DnsBatch
    , include_shadow_metadata? : Bool) -> Result[
    DnsBatchResult
    , Failure]

    Calls dns-records-for-a-zone-batch-dns-records.

    CloudflareDns::call

    Sends the request and applies the matching generated decoder to a consumed body.

    CloudflareDns::create_dns_record

    async fn CloudflareDns::create_dns_record(self : CloudflareDns, zone_id~ : String, body :
    DnsRecord
    , include_shadow_metadata? : Bool) -> Result[
    DnsRecordResponse
    , Failure]

    Calls dns-records-for-a-zone-create-dns-record.

    CloudflareDns::create_zone

    Calls zones-post.

    CloudflareDns::delete_dns_record

    async fn CloudflareDns::delete_dns_record(self : CloudflareDns, dns_record_id~ : String, zone_id~ : String) -> Result[
    DnsRecordDeletion
    , Failure]

    Calls dns-records-for-a-zone-delete-dns-record.

    CloudflareDns::delete_dnssec

    async fn CloudflareDns::delete_dnssec(self : CloudflareDns, zone_id~ : String) -> Result[String, Failure]

    Calls dnssec-delete-dnssec-records.

    CloudflareDns::delete_zone

    Calls zones-0-delete.

    CloudflareDns::edit_dns_record

    async fn CloudflareDns::edit_dns_record(self : CloudflareDns, dns_record_id~ : String, zone_id~ : String, body :
    DnsRecordPatch
    , include_shadow_metadata? : Bool) -> Result[
    DnsRecordResponse
    , Failure]

    Calls dns-records-for-a-zone-patch-dns-record.

    CloudflareDns::edit_dns_settings

    Calls dns-settings-for-a-zone-update-dns-settings.

    CloudflareDns::edit_dnssec

    Calls dnssec-edit-dnssec-status.

    CloudflareDns::edit_zone

    Calls zones-0-patch.

    CloudflareDns::export_dns_records

    async fn CloudflareDns::export_dns_records(self : CloudflareDns, zone_id~ : String) -> Result[String, Failure]

    Calls dns-records-for-a-zone-export-dns-records.

    CloudflareDns::from_client

    fn CloudflareDns::from_client(client :
    Client
    , auth~ : Auth, base_url? : String, server_urls? : Map[String, String]) -> CloudflareDns

    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.

    CloudflareDns::get_dns_record

    async fn CloudflareDns::get_dns_record(self : CloudflareDns, dns_record_id~ : String, zone_id~ : String, include_shadow_metadata? : Bool) -> Result[
    DnsRecordResponse
    , Failure]

    Calls dns-records-for-a-zone-dns-record-details.

    CloudflareDns::get_dns_settings

    Calls dns-settings-for-a-zone-list-dns-settings.

    CloudflareDns::get_dnssec

    async fn CloudflareDns::get_dnssec(self : CloudflareDns, zone_id~ : String) -> Result[
    Dnssec
    , Failure]

    Calls dnssec-dnssec-details.

    CloudflareDns::get_zone

    async fn CloudflareDns::get_zone(self : CloudflareDns, zone_id~ : String) -> Result[
    Zone
    , Failure]

    Calls zones-0-get.

    CloudflareDns::import_dns_records

    async fn CloudflareDns::import_dns_records(self : CloudflareDns, zone_id~ : String, zone_file~ : String, proxied? : Bool) -> Result[
    DnsImportResult
    , Failure]

    Calls dns-records-for-a-zone-import-dns-records.

    CloudflareDns::list_dns_record_scan

    Calls dns-records-for-a-zone-review-dns-scan.

    CloudflareDns::list_dns_records

    async fn CloudflareDns::list_dns_records(self : CloudflareDns, zone_id~ : String, name? : String, name_exact? : String, name_contains? : String, name_startswith? : String, name_endswith? : String, type_? :
    DnsRecordType
    , content? : String, content_exact? : String, content_contains? : String, content_startswith? : String, content_endswith? : String, proxied? : Bool, match_? :
    DnsRecordMatch
    , comment? : String, comment_present? : String, comment_absent? : String, comment_exact? : String, comment_contains? : String, comment_startswith? : String, comment_endswith? : String, tag? : String, tag_present? : String, tag_absent? : String, tag_exact? : String, tag_contains? : String, tag_startswith? : String, tag_endswith? : String, search? : String, tag_match? :
    DnsRecordTagMatch
    , page? : Int, per_page? : Int, order? :
    DnsRecordOrder
    , direction? :
    DnsRecordDirection
    , include_shadow_metadata? : Bool, shadowed_by_name? : String, shadowing_name? : String) -> Result[Array[
    DnsRecordResponse
    ], Failure]

    Calls dns-records-for-a-zone-list-dns-records.

    CloudflareDns::list_dns_records_pages

    fn CloudflareDns::list_dns_records_pages(self : CloudflareDns, zone_id~ : String, name? : String, name_exact? : String, name_contains? : String, name_startswith? : String, name_endswith? : String, type_? :
    DnsRecordType
    , content? : String, content_exact? : String, content_contains? : String, content_startswith? : String, content_endswith? : String, proxied? : Bool, match_? :
    DnsRecordMatch
    , comment? : String, comment_present? : String, comment_absent? : String, comment_exact? : String, comment_contains? : String, comment_startswith? : String, comment_endswith? : String, tag? : String, tag_present? : String, tag_absent? : String, tag_exact? : String, tag_contains? : String, tag_startswith? : String, tag_endswith? : String, search? : String, tag_match? :
    DnsRecordTagMatch
    , page? : Int, per_page? : Int, order? :
    DnsRecordOrder
    , direction? :
    DnsRecordDirection
    , include_shadow_metadata? : Bool, shadowed_by_name? : String, shadowing_name? : String) ->
    Paginator
    [
    DnsRecordResponse
    , Failure]

    Pages dns-records-for-a-zone-list-dns-records, building the first request from the operation parameters.

    CloudflareDns::list_zones

    Calls zones-get.

    CloudflareDns::list_zones_pages

    Pages zones-get, building the first request from the operation parameters.

    CloudflareDns::new

    fn CloudflareDns::new(backend : &
    Backend
    , clock : &
    Clock
    , auth~ : Auth, base_url? : String, server_urls? : Map[String, String], retry? :
    RetryPolicy
    , timer? : &
    Timer
    , timeout_ms? : Int, total_timeout_ms? : Int, max_body_bytes? : Int) -> CloudflareDns

    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.

    CloudflareDns::paginate

    fn[T :
    FromJson
    ] CloudflareDns::paginate(self : CloudflareDns, first :
    Request
    , kind~ : PageKind, items~ : String, next~ : String, operation? : String) ->
    Paginator
    [T, Failure]

    Paginates JSON arrays by cursor, next URL or numeric page. A page advances only after successful decoding.

    CloudflareDns::review_dns_record_scan

    Calls dns-records-for-a-zone-apply-dns-scan-results.

    CloudflareDns::send

    async fn CloudflareDns::send(self : CloudflareDns, request :
    Request
    , operation? : String) -> Result[
    Reply
    [Bytes], Failure]

    Returns buffered bytes and metadata, classifying HTTP and false success envelopes.

    CloudflareDns::to_repr

    CloudflareDns::trigger_dns_record_scan

    async fn CloudflareDns::trigger_dns_record_scan(self : CloudflareDns, zone_id~ : String) -> Result[Unit, Failure]

    Calls dns-records-for-a-zone-trigger-dns-scan.

    CloudflareDns::trigger_zone_activation_check

    async fn CloudflareDns::trigger_zone_activation_check(self : CloudflareDns, zone_id~ : String) -> Result[
    ZoneActivation
    , Failure]

    Calls put-zones-zone_id-activation_check.

    CloudflareDns::update_dns_record

    async fn CloudflareDns::update_dns_record(self : CloudflareDns, dns_record_id~ : String, zone_id~ : String, body :
    DnsRecord
    , include_shadow_metadata? : Bool) -> Result[
    DnsRecordResponse
    , Failure]

    Calls dns-records-for-a-zone-update-dns-record.

    EnvelopeMessage

    pub(all) struct EnvelopeMessage {
    code : Int
    message : String
    documentation_url : String?
    source_pointer : String?
    } derive(
    Debug
    )

    A message reported by a structured API error envelope.

    EnvelopeMessage::to_repr

    automatically derived

    Failure

    pub(all) enum Failure {
    Http(HttpFailure)
    Transport(
    TransportError
    )
    Decode(
    ResponseFailure
    )
    Validation(operation~ : String, parameter~ : String, message~ : String)
    } derive(
    Debug
    )

    Transport failures retain their kind and phase. Cancellation propagates.

    Failure::to_repr

    automatically derived

    HttpFailure

    pub(all) struct HttpFailure {
    operation : String
    head :
    ResponseHead

    body : Bytes
    errors : Array[EnvelopeMessage]
    messages : Array[EnvelopeMessage]
    } derive(
    Debug
    )

    Response failure with the original head, bounded body and any decoded messages.

    HttpFailure::to_repr

    automatically derived

    PageKind

    pub(all) enum PageKind {
    Cursor(String)
    NextUrl
    Page(String)
    }

    How the following page is addressed; cursor names come from the API contract.

    default_retry

    SDK retry default; a Refused failure means not processed.