Skip to content

Commit

Permalink
Move a2 clients into State
Browse files Browse the repository at this point in the history
  • Loading branch information
link2xt committed Feb 29, 2024
1 parent d7ff3b7 commit ab33fb7
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 55 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod notifier;
pub mod server;
pub mod state;
13 changes: 3 additions & 10 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use anyhow::{Context, Result};
use async_std::prelude::*;
use structopt::StructOpt;

use notifiers::{notifier, server};
use notifiers::{notifier, server, state};

#[derive(Debug, StructOpt)]
struct Opt {
Expand Down Expand Up @@ -37,22 +37,15 @@ async fn main() -> Result<()> {
let opt = Opt::from_args();
let certificate = std::fs::File::open(&opt.certificate_file).context("invalid certificate")?;

let state = server::State::new(&opt.db)?;
let state = state::State::new(&opt.db, certificate, &opt.password)?;

let state2 = state.clone();
let host = opt.host.clone();
let port = opt.port;
let server = async_std::task::spawn(async move { server::start(state2, host, port).await });

let notif = async_std::task::spawn(async move {
notifier::start(
state.db(),
certificate,
&opt.password,
opt.topic.as_deref(),
opt.interval,
)
.await
notifier::start(state, opt.topic.as_deref(), opt.interval).await
});

server.try_join(notif).await?;
Expand Down
28 changes: 11 additions & 17 deletions src/notifier.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,30 @@
use a2::{
Client, DefaultNotificationBuilder, Endpoint, Error::ResponseError, NotificationBuilder,
Client, DefaultNotificationBuilder, Error::ResponseError, NotificationBuilder,
NotificationOptions, Priority,
};
use anyhow::{Context as _, Result};
use anyhow::Result;
use async_std::prelude::*;
use log::*;
use std::io::Seek;

pub async fn start(
db: &sled::Db,
mut certificate: std::fs::File,
password: &str,
topic: Option<&str>,
interval: std::time::Duration,
) -> Result<()> {
use crate::state::State;

pub async fn start(state: State, topic: Option<&str>, interval: std::time::Duration) -> Result<()> {
let db = state.db();
let production_client = state.production_client();
let sandbox_client = state.sandbox_client();

info!(
"Waking up devices every {}",
humantime::format_duration(interval)
);
let production_client = Client::certificate(&mut certificate, password, Endpoint::Production)
.context("Failed to create production client")?;
certificate.rewind()?;
let sandbox_client = Client::certificate(&mut certificate, password, Endpoint::Sandbox)
.context("Failed to create sandbox client")?;

// first wakeup on startup
wakeup(db, &production_client, &sandbox_client, topic).await;
wakeup(db, production_client, sandbox_client, topic).await;

// create interval
let mut interval = async_std::stream::interval(interval);
while interval.next().await.is_some() {
wakeup(db, &production_client, &sandbox_client, topic).await;
wakeup(db, production_client, sandbox_client, topic).await;
}

Ok(())
Expand Down
30 changes: 2 additions & 28 deletions src/server.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use std::path::PathBuf;

use anyhow::Result;
use async_std::sync::Arc;
use log::*;
use serde::Deserialize;

use crate::state::State;

pub async fn start(state: State, server: String, port: u16) -> Result<()> {
let mut app = tide::with_state(state);
app.at("/").get(|_| async { Ok("Hello, world!") });
Expand All @@ -15,31 +14,6 @@ pub async fn start(state: State, server: String, port: u16) -> Result<()> {
Ok(())
}

#[derive(Debug, Clone)]
pub struct State {
inner: Arc<InnerState>,
}

#[derive(Debug)]
pub struct InnerState {
db: sled::Db,
}

impl State {
pub fn new(db: &PathBuf) -> Result<Self> {
let db = sled::open(db)?;
info!("{} devices registered currently", db.len());

Ok(State {
inner: Arc::new(InnerState { db }),
})
}

pub fn db(&self) -> &sled::Db {
&self.inner.db
}
}

#[derive(Debug, Clone, Deserialize)]
struct DeviceQuery {
token: String,
Expand Down
55 changes: 55 additions & 0 deletions src/state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use std::path::PathBuf;

use a2::{Client, Endpoint};
use anyhow::{Context as _, Result};
use async_std::sync::Arc;
use log::*;
use std::io::Seek;

#[derive(Debug, Clone)]
pub struct State {
inner: Arc<InnerState>,
}

#[derive(Debug)]
pub struct InnerState {
db: sled::Db,

production_client: Client,

sandbox_client: Client,
}

impl State {
pub fn new(db: &PathBuf, mut certificate: std::fs::File, password: &str) -> Result<Self> {
let db = sled::open(db)?;
let production_client =
Client::certificate(&mut certificate, password, Endpoint::Production)
.context("Failed to create production client")?;
certificate.rewind()?;
let sandbox_client = Client::certificate(&mut certificate, password, Endpoint::Sandbox)
.context("Failed to create sandbox client")?;

info!("{} devices registered currently", db.len());

Ok(State {
inner: Arc::new(InnerState {
db,
production_client,
sandbox_client,
}),
})
}

pub fn db(&self) -> &sled::Db {
&self.inner.db
}

pub fn production_client(&self) -> &Client {
&self.inner.production_client
}

pub fn sandbox_client(&self) -> &Client {
&self.inner.sandbox_client
}
}

0 comments on commit ab33fb7

Please sign in to comment.