iroh-dns-server 1.0.0

A pkarr relay and DNS server
Documentation
use axum::{
    extract::{Path, State},
    response::IntoResponse,
};
use bytes::Bytes;
use http::{StatusCode, header};
use iroh_base::PublicKey;
use iroh_dns::pkarr::SignedPacket;
use tracing::info;

use super::error::AppError;
use crate::{state::AppState, store::PacketSource, util::PublicKeyBytes};

pub(super) async fn put(
    State(state): State<AppState>,
    Path(key): Path<String>,
    body: Bytes,
) -> Result<impl IntoResponse, AppError> {
    let public_key = PublicKey::from_z32(&key)
        .map_err(|e| AppError::new(StatusCode::BAD_REQUEST, Some(format!("invalid key: {e}"))))?;
    let label = key.get(..10).unwrap_or(&key);
    let signed_packet = SignedPacket::from_relay_payload(&public_key, &body).map_err(|e| {
        AppError::new(
            StatusCode::BAD_REQUEST,
            Some(format!("invalid body payload: {e}")),
        )
    })?;

    let updated = state
        .store
        .insert(signed_packet, PacketSource::PkarrPublish)
        .await?;
    info!(key = %label, ?updated, "pkarr upsert");
    Ok(StatusCode::NO_CONTENT)
}

pub(super) async fn get(
    State(state): State<AppState>,
    Path(pubkey): Path<String>,
) -> Result<impl IntoResponse, AppError> {
    let pubkey = PublicKeyBytes::from_z32(&pubkey)
        .map_err(|e| AppError::new(StatusCode::BAD_REQUEST, Some(format!("invalid key: {e}"))))?;
    let signed_packet = state
        .store
        .get_signed_packet(&pubkey)
        .await?
        .ok_or_else(|| AppError::with_status(StatusCode::NOT_FOUND))?;
    let body = signed_packet.to_relay_payload();
    let headers = [(header::CONTENT_TYPE, "application/x-pkarr-signed-packet")];
    Ok((headers, body))
}