|
| 1 | +use aws_sdk_firehose::{model::Record, types::Blob, Client}; |
| 2 | +use lambda_extension::{Error, Extension, LambdaLog, LambdaLogRecord, Service, SharedService}; |
| 3 | +use std::{future::Future, pin::Pin, task::Poll}; |
| 4 | + |
| 5 | +#[derive(Clone)] |
| 6 | +struct FirehoseLogsProcessor { |
| 7 | + client: Client, |
| 8 | +} |
| 9 | + |
| 10 | +impl FirehoseLogsProcessor { |
| 11 | + pub fn new(client: Client) -> Self { |
| 12 | + FirehoseLogsProcessor { client } |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +/// Implementation of the actual log processor |
| 17 | +/// |
| 18 | +/// This receives a `Vec<LambdaLog>` whenever there are new log entries available. |
| 19 | +impl Service<Vec<LambdaLog>> for FirehoseLogsProcessor { |
| 20 | + type Response = (); |
| 21 | + type Error = Error; |
| 22 | + type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; |
| 23 | + |
| 24 | + fn poll_ready(&mut self, _cx: &mut core::task::Context<'_>) -> core::task::Poll<Result<(), Self::Error>> { |
| 25 | + Poll::Ready(Ok(())) |
| 26 | + } |
| 27 | + |
| 28 | + fn call(&mut self, logs: Vec<LambdaLog>) -> Self::Future { |
| 29 | + let mut records = Vec::with_capacity(logs.len()); |
| 30 | + |
| 31 | + for log in logs { |
| 32 | + match log.record { |
| 33 | + LambdaLogRecord::Function(record) => { |
| 34 | + records.push(Record::builder().data(Blob::new(record.as_bytes())).build()) |
| 35 | + } |
| 36 | + _ => unreachable!(), |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + let fut = self |
| 41 | + .client |
| 42 | + .put_record_batch() |
| 43 | + .set_records(Some(records)) |
| 44 | + .delivery_stream_name(std::env::var("KINESIS_DELIVERY_STREAM").unwrap()) |
| 45 | + .send(); |
| 46 | + |
| 47 | + Box::pin(async move { |
| 48 | + let _ = fut.await?; |
| 49 | + Ok(()) |
| 50 | + }) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +#[tokio::main] |
| 55 | +async fn main() -> Result<(), Error> { |
| 56 | + let config = aws_config::load_from_env().await; |
| 57 | + let logs_processor = SharedService::new(FirehoseLogsProcessor::new(Client::new(&config))); |
| 58 | + |
| 59 | + Extension::new() |
| 60 | + .with_log_types(&["function"]) |
| 61 | + .with_logs_processor(logs_processor) |
| 62 | + .run() |
| 63 | + .await?; |
| 64 | + |
| 65 | + Ok(()) |
| 66 | +} |
0 commit comments