Something went wrong. Try again.
Rust Framework for building Bluesky Bots
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229use crate::Result;use std::{ collections::{BTreeMap, HashMap}, fs::OpenOptions, io::Write, marker::PhantomData, ops::Deref, path::Path, time::Duration,};
use chrono::TimeZone;use jetstream_oxide::{ JetstreamConnector, events::{ EventInfo, commit::{CommitData, CommitEvent}, },};use serde::{Deserialize, Serialize};
use crate::AmselBotCronTaskRegistrar;use crate::{Agent, BskySession};
pub struct SessionWithState<'de, B, S, P>where B: AmselBotCronTaskRegistrar + Deref<Target = S>, S: Serialize + Deserialize<'de> + PartialEq + Clone, P: AsRef<Path>,{ pub(crate) session: BskySession, pub bot: B, pub(crate) initial_cursor_for_jetstream_connection: u64, pub(crate) current_saved_state: S, pub(crate) current_saved_cursor: u64, pub(crate) agent: Agent, pub(crate) path: P, pub(crate) _remove_me: &'de PhantomData<B>, pub(crate) next_hook: (u64, &'static str), pub(crate) hooks: BTreeMap<u64, &'static str>, pub(crate) cron_jobs: HashMap<&'static str, croner::Cron>,}
impl< 'de, B: AmselBotCronTaskRegistrar + Deref<Target = S>, S: Serialize + Deserialize<'de> + PartialEq + Clone, P: AsRef<Path>,> std::ops::Deref for SessionWithState<'de, B, S, P>{ type Target = B;
fn deref(&self) -> &Self::Target { &self.bot }}impl< 'de, B: AmselBotCronTaskRegistrar + Deref<Target = S>, S: Serialize + Deserialize<'de> + PartialEq + Clone, P: AsRef<Path>,> std::ops::DerefMut for SessionWithState<'de, B, S, P>{ fn deref_mut(&mut self) -> &mut Self::Target { &mut self.bot }}
impl< 'de, B: AmselBotCronTaskRegistrar + Deref<Target = S>, S: Serialize + Deserialize<'de> + PartialEq + Clone, P: AsRef<Path>,> SessionWithState<'de, B, S, P>{ pub async fn run(mut self) -> Result<()> { let jobs = self.bot.__get_cron_jobs();
self.cron_jobs = HashMap::new(); for (name, schedule) in &jobs { let cron_all = croner::Cron::new(schedule) .with_seconds_optional() .parse() .expect("Couldn't parse cron string"); self.cron_jobs.insert(name, cron_all); } let mut config = self.session.default_jetstream_config();
config.cursor = Some( chrono::DateTime::from_timestamp_micros( self.initial_cursor_for_jetstream_connection .try_into() .unwrap(), ) .unwrap(), );
self.hooks = BTreeMap::new(); for (name, schedule) in &self.cron_jobs { let next = schedule .find_next_occurrence( &config.cursor.unwrap(), /* unwrap_or(chrono::Utc::now()) */ false, ) .unwrap(); self.hooks.insert(next.timestamp_micros() as u64, name); }
let jetstream = JetstreamConnector::new(config).map_err(anyhow::Error::from)?; let receiver = jetstream.connect().await.map_err(anyhow::Error::from)?;
self.hooks.insert(u64::MAX, ""); self.next_hook = self.hooks.pop_first().unwrap();
let mut current_seen_time_us: u64 = 0; let mut events: Vec<(EventInfo, CommitData)> = Vec::new();
while let Ok(event) = receiver.recv_async().await { // TODO implement handling all other event and record types match event { jetstream_oxide::events::JetstreamEvent::Commit(commit_event) => match commit_event { CommitEvent::Create { info, commit } => { let time_us = info.time_us; if current_seen_time_us != time_us && !events.is_empty() { if time_us < current_seen_time_us { panic!("OUT OF ORDER {} < {}", time_us, current_seen_time_us); }
self.process_create_events_batch(current_seen_time_us, events) .await?; events = Vec::new(); } events.push((info, commit)); current_seen_time_us = time_us; } CommitEvent::Update { info: _, commit: _ } => {} CommitEvent::Delete { info: _, commit: _ } => {} }, jetstream_oxide::events::JetstreamEvent::Identity(_identity_event) => {} jetstream_oxide::events::JetstreamEvent::Account(_account_event) => {} } }
Ok(()) }
async fn process_create_events_batch( &mut self, time_us: u64, events: Vec<(EventInfo, CommitData)>, ) -> Result<()> { loop { if self.next_hook.0 > time_us { break; } let name = self.next_hook.1;
self.agent.clock.set_time(self.next_hook.0);
let _ = self .bot .__dispatch_cron( name, chrono::Utc .timestamp_micros(self.next_hook.0.try_into().unwrap()) .unwrap(), ) .await;
let signed_value: i64 = self.next_hook.0.try_into().unwrap(); let current_cursor = chrono::DateTime::from_timestamp_micros(signed_value + 1).unwrap();
let next = self .cron_jobs .get(name) .unwrap() .find_next_occurrence(¤t_cursor, false) .unwrap(); self.hooks.insert(next.timestamp_micros() as u64, name); self.next_hook = self.hooks.pop_first().unwrap(); }
self.agent.clock.set_time(time_us);
for event in events { self.session .handle_commit_create_record(&mut self.bot, event.0, event.1) .await; }
let path = self.path.as_ref();
if &self.current_saved_state != self.bot.deref() { let mut buf = Vec::new(); self.current_saved_cursor = time_us; buf.write_all(&time_us.to_le_bytes()).unwrap(); self.current_saved_state = self.bot.deref().clone(); self.current_saved_state .serialize(&mut minicbor_serde::Serializer::new(&mut buf)) .unwrap();
let tmp_path = path.with_extension("tmp"); let mut tmp = OpenOptions::new() .write(true) // TODO use create_new and ensure it's deleted if exists on startup .create(true) .open(&tmp_path)?; tmp.write_all(&buf)?; tmp.sync_all()?; std::fs::rename(&tmp_path, path)?; } else { if self.current_saved_cursor.abs_diff(time_us) as u128 > Duration::from_secs(10).as_micros() { self.current_saved_cursor = time_us; let cursor_path = path.with_extension("cursor"); let mut tmp = OpenOptions::new() .write(true) .create(true) .open(&cursor_path)?; tmp.write_all(&time_us.to_le_bytes())?; tmp.sync_all()?; } } Ok(()) }}