GithubHelp home page GithubHelp logo

silverlyra / flytrap Goto Github PK

View Code? Open in Web Editor NEW
0.0 2.0 1.0 100 KB

Rust crate for reading the Fly.io runtime environment

Home Page: https://flytrap.fly.dev

License: MIT License

Dockerfile 0.64% TypeScript 5.08% Rust 94.28%
flyio rust service-discovery

flytrap's Introduction

flytrap

Crates.io CI docs.rs MIT license

Flytrap is a Rust crate for reading the Fly.io runtime environment.

A demo app is available at flytrap.fly.dev which shows this crate’s capabilities.

Usage

Flytrap can be added to your project with cargo:

cargo add flytrap

Most of the crate’s features are enabled by default, but at your option, you can enable only what you need by setting default-features = false.

cargo add flytrap --no-default-features --features 'dns environment http serde'

Placement

The Placement type gives access to Fly.io runtime environment variables like $FLY_PUBLIC_IP and $FLY_REGION.

use flytrap::{Placement, Machine}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let runtime = Placement::current()?;

    println!("Fly.io app: {}", runtime.app);
    println!("    region: {}", runtime.location);

    if let Some(Machine{ id, memory: Some(memory), image: Some(image), .. }) = runtime.machine {
        println!("   machine: {id} ({memory} MB) running {image}");
    }

    if let Some(public_ip) = runtime.public_ip {
        println!(" public IP: {}", public_ip);
    }
    println!("private IP: {}", runtime.private_ip);

    Ok(())
}

Regions

Flytrap models Fly.io regions as an enum:

use flytrap::{City, Placement, Region};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let runtime = Placement::current()?;
    let region = runtime.region().unwrap_or(Region::Guadalajara);

    show(region);
    Ok(())
}

fn show(region: Region) {
    let City { name, country, geo } = region.city;
    println!("Running in {name} ({country}) @ {}, {}", geo.x(), geo.y());
}

Regions implement Ord, and sort geographically:

#[test]
fn longitude_latitude() {
    use flytrap::Region::*;

    let mut regions = [Bucharest, Chicago, HongKong, Johannesburg,
                       LosAngeles, Madrid, Santiago, Tokyo];
    regions.sort();

    assert_eq!(regions, [LosAngeles, Chicago, Santiago, Madrid,
                         Bucharest, Johannesburg, HongKong, Tokyo]);
}

If Flytrap receives a region code it doesn’t recognize (i.e., a region which didn’t exist when your version of Flytrap was built), the raw code like ord will be stored as a RegionCode.

(If you build Flytrap without the regions feature, flytrap::Region simply becomes an alias for String.)

DNS queries

Create a Resolver in order to query the Fly.io .internal DNS zone.

use flytrap::Resolver;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resolver = Resolver::new()?;

    // Discover all instances of the currently-running app
    let peers = resolver.current()?.peers().await?;

    for peer in peers {
        println!("peer {} in {} @ {}", peer.id, peer.location, peer.private_ip);
    }
}

Machines API requests

Create an api::Client to send requests to the machines API.

Note

The api module is not built by default; the api feature must be enabled first.

use std::env;
use flytrap::api::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let token = env::var("FLY_API_TOKEN")?;
    let client = Client::new(token);

    // Discover other instances of the currently-running app
    let peers = client.peers().await?;

    for peer in peers {
        println!("peer {} in {} is {:?}", peer.name, peer.location, peer.state);
    }

    Ok(())
}

HTTP headers

The http module contains typed Header implementations of the HTTP request headers added by Fly.io edge proxies, like Fly-Client-IP.

use axum::response::Html;
use axum_extra::TypedHeader;
use flytrap::http::{FlyClientIp, FlyRegion};

async fn ip(
    TypedHeader(ip): TypedHeader<FlyClientIp>,
    TypedHeader(edge): TypedHeader<FlyRegion>,
) -> Html<String> {
    Html(format!("Your IP: <code>{ip}</code> (via {edge})"))
}

Features

Flytrap’s compilation can be controlled through a number of Cargo features.

  • api: Enable the api::Client for the Fly.io machines API
  • dns: Enable Resolver for querying Fly.io internal DNS, via hickory-dns
  • detect: Enable automatic Resolver setup for Wireguard VPN clients, via if-addrs ⭐️
  • environment: Enable code which reads Fly.io environment variables like $FLY_PUBLIC_IP ⭐️
  • http: Enable types for HTTP headers like Fly-Client-IP ⭐️
  • nightly: Enable code which is only accepted by nightly Rust toolchains
  • regions: Enable the Region type and RegionDetails structures ⭐️
  • serde: Enable Serde #[derive(Deserialize, Serialize)] on this crate’s types
  • system-resolver: Enable the Resolver::system() constructor, which reads /etc/resolv.conf

(Features marked with a ⭐️ are enabled by default.)

flytrap's People

Contributors

silverlyra avatar protochron avatar

Watchers

 avatar  avatar

Forkers

protochron

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.