Content: Markdown
Framework: Zola
Hosting: Github Pages
Styling: SCSS
Theme: Consoler Dark
Title: parkerjones.dev

upgrade bookmark tool

0 minute read Published: 2024-01-01
// Placeholder for main Rust implementation
use chrono::Local;
use aws_sdk_lambda::{Client, Error};

// Placeholder for the module to collect Lambda functions
mod lambda_collector {
    use aws_sdk_lambda::Client;
    use aws_sdk_lambda::types::SdkError;
    use aws_sdk_lambda::operation::list_functions::ListFunctionsError;
    use serde::Deserialize;
    use std::error::Error;

    #[derive(Debug, Deserialize, Clone)]
    pub struct LambdaFunction {
        pub function_name: String,
    }

    pub async fn collect_lambda_functions(client: &Client, search_term: &str) -> Result<Vec<LambdaFunction>, Box<dyn Error>> {
        let mut functions = Vec::new();
        let resp = client.list_functions().send().await?;

        if let Some(lambda_functions) = resp.functions {
            for function in lambda_functions {
                if let Some(function_name) = function.function_name {
                    if function_name.contains(search_term) {
                        functions.push(LambdaFunction { function_name });
                    }
                }
            }
        }

        Ok(functions)
    }
}

// Placeholder for the module to handle bookmark file generation
mod bookmark_generator {
    use std::fs::File;
    use std::io::{BufWriter, Write};

    pub struct BookmarkEntry {
        pub title: String,
        pub url: String,
        pub add_date: i64,
    }

    pub fn generate_bookmark_file(bookmark_entries: Vec<BookmarkEntry>, output_file: &str) -> std::io::Result<()> {
        let file = File::create(output_file)?;
        let mut writer = BufWriter::new(file);

        // Start Netscape Bookmark File
        writeln!(writer, "<!DOCTYPE NETSCAPE-Bookmark-file-1>")?;
        writeln!(writer, "<!-- This is an automatically generated file. -->")?;
        writeln!(writer, "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">")?;
        writeln!(writer, "<TITLE>Bookmarks</TITLE>")?;
        writeln!(writer, "<H1>Bookmarks</H1>")?;
        writeln!(writer, "<DL><p>")?;

        for entry in bookmark_entries {
            writeln!(writer, "    <DT><A HREF=\"{}\" ADD_DATE=\"{}\">{}</A>", entry.url, entry.add_date, entry.title)?;
        }

        // Close Netscape Bookmark File
        writeln!(writer, "</DL><p>")
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Placeholder for AWS SDK client initialization and function invocation
    let shared_config = aws_config::load_from_env().await;
    let client = Client::new(&shared_config);
    let search_term = std::env::args().nth(1).expect("Please provide a search term");

    let lambda_functions = lambda_collector::collect_lambda_functions(&client, &search_term).await?;

    let timestamp = Local::now().format("%Y-%m-%d_%H-%M-%S").to_string();
    let output_file = format!("lambda_bookmarks_{}.html", timestamp);

    let bookmark_entries: Vec<bookmark_generator::BookmarkEntry> = lambda_functions
        .into_iter()
        .map(|function| {
            let region = std::env::var("AWS_REGION").unwrap_or_else(|_| "us-east-1".to_string());
            let log_group = format!("/aws/lambda/{}", function.function_name);
            let cloudwatch_logs_url = format!(
                "https://{}.console.aws.amazon.com/cloudwatch/home?region={}#logsV2:log-groups/log-group/{}",
                region,
                region,
                log_group.replace("/", "%2F")
            );
            let lambda_function_url = format!(
                "https://{}.console.aws.amazon.com/lambda/home?region={}#/functions/{}?tab=code",
                region,
                region,
                function.function_name
            );

            vec![
                bookmark_generator::BookmarkEntry {
                    title: format!("{} - CloudWatch Logs", function.function_name),
                    url: cloudwatch_logs_url,
                    add_date: Local::now().timestamp(),
                },
                bookmark_generator::BookmarkEntry {
                    title: format!("{} - Lambda Function", function.function_name),
                    url: lambda_function_url,
                    add_date: Local::now().timestamp(),
                },
            ]
        })
        .flatten()
        .collect();

    bookmark_generator::generate_bookmark_file(bookmark_entries, &output_file)?;
    
    println!("Bookmarks saved to {}", output_file);
    Ok(())
}


// API Module for Rust Bookmark Tool

use axum::{routing::get, Router, Json};
use aws_sdk_lambda::{Client, Error};
use serde::Serialize;
use std::net::SocketAddr;
use lambda_collector::{collect_lambda_functions, LambdaFunction};
use bookmark_generator::BookmarkEntry;
use chrono::Local;
use tokio;

mod lambda_collector {
    use aws_sdk_lambda::Client;
    use aws_sdk_lambda::types::SdkError;
    use aws_sdk_lambda::operation::list_functions::ListFunctionsError;
    use serde::Deserialize;
    use std::error::Error;

    #[derive(Debug, Deserialize, Clone)]
    pub struct LambdaFunction {
        pub function_name: String,
    }

    pub async fn collect_lambda_functions(client: &Client, search_term: &str) -> Result<Vec<LambdaFunction>, Box<dyn Error>> {
        let mut functions = Vec::new();
        let resp = client.list_functions().send().await?;

        if let Some(lambda_functions) = resp.functions {
            for function in lambda_functions {
                if let Some(function_name) = function.function_name {
                    if function_name.contains(search_term) {
                        functions.push(LambdaFunction { function_name });
                    }
                }
            }
        }

        Ok(functions)
    }
}

mod bookmark_generator {
    use serde::Serialize;
    use std::io::{Write};

    #[derive(Serialize)]
    pub struct BookmarkEntry {
        pub title: String,
        pub url: String,
        pub add_date: i64,
    }

    pub fn generate_bookmark_file(bookmark_entries: Vec<BookmarkEntry>, output: &mut dyn Write) -> std::io::Result<()> {
        // Start Netscape Bookmark File
        writeln!(output, "<!DOCTYPE NETSCAPE-Bookmark-file-1>")?;
        writeln!(output, "<!-- This is an automatically generated file. -->")?;
        writeln!(output, "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">")?;
        writeln!(output, "<TITLE>Bookmarks</TITLE>")?;
        writeln!(output, "<H1>Bookmarks</H1>")?;
        writeln!(output, "<DL><p>")?;

        for entry in bookmark_entries {
            writeln!(output, "    <DT><A HREF=\"{}\" ADD_DATE=\"{}\">{}</A>", entry.url, entry.add_date, entry.title)?;
        }

        // Close Netscape Bookmark File
        writeln!(output, "</DL><p>")
    }
}

#[derive(Serialize)]
struct ApiResponse {
    lambda_functions: Vec<LambdaFunction>,
    bookmark_entries: Vec<BookmarkEntry>,
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let app = Router::new().route("/api/lambda-bookmarks", get(get_lambda_bookmarks));

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    println!("Listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();

    Ok(())
}

async fn get_lambda_bookmarks() -> Result<Json<ApiResponse>, Error> {
    let shared_config = aws_config::load_from_env().await;
    let client = Client::new(&shared_config);
    let search_term = "example"; // placeholder search term

    let lambda_functions = collect_lambda_functions(&client, search_term).await?;

    let bookmark_entries: Vec<BookmarkEntry> = lambda_functions
        .iter()
        .flat_map(|function| {
            let region = std::env::var("AWS_REGION").unwrap_or_else(|_| "us-east-1".to_string());
            let log_group = format!("/aws/lambda/{}", function.function_name);
            let cloudwatch_logs_url = format!(
                "https://{}.console.aws.amazon.com/cloudwatch/home?region={}#logsV2:log-groups/log-group/{}",
                region,
                region,
                log_group.replace("/", "%2F")
            );
            let lambda_function_url = format!(
                "https://{}.console.aws.amazon.com/lambda/home?region={}#/functions/{}?tab=code",
                region,
                region,
                function.function_name
            );

            vec![
                BookmarkEntry {
                    title: format!("{} - CloudWatch Logs", function.function_name),
                    url: cloudwatch_logs_url,
                    add_date: Local::now().timestamp(),
                },
                BookmarkEntry {
                    title: format!("{} - Lambda Function", function.function_name),
                    url: lambda_function_url,
                    add_date: Local::now().timestamp(),
                },
            ]
        })
        .collect();

    Ok(Json(ApiResponse {
        lambda_functions,
        bookmark_entries,
    }))
}