Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(frecency): improve db poller (#27)

Sean Aye3c80948491ba
diff --git a/rust/cloud-storage/connection_gateway/src/context.rs b/rust/cloud-storage/connection_gateway/src/context.rs
index a90d3ed6ea..dfc35cb225 100644
--- a/rust/cloud-storage/connection_gateway/src/context.rs
+++ b/rust/cloud-storage/connection_gateway/src/context.rs
@@ -1,6 +1,10 @@
use crate::config::Config;
use axum::extract::FromRef;
-use frecency::{domain::services::EventIngestorImpl, outbound::postgres::FrecencyPgStorage};
+use frecency::{
+ domain::services::EventIngestorImpl,
+ inbound::polling_aggregator::FrecencyAggregatorWorkerHandle,
+ outbound::postgres::FrecencyPgStorage,
+};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use redis::{RedisError, aio::MultiplexedConnection};
@@ -29,6 +33,7 @@ pub struct AppState {
pub config: Arc<Config>,
pub jwt_args: JwtValidationArgs,
pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,
+ pub frecency_worker: Arc<FrecencyAggregatorWorkerHandle>,
}
impl AsRef<ApiContext> for AppState {
diff --git a/rust/cloud-storage/connection_gateway/src/main.rs b/rust/cloud-storage/connection_gateway/src/main.rs
index a7b65ad241..bdf34bbadf 100644
--- a/rust/cloud-storage/connection_gateway/src/main.rs
+++ b/rust/cloud-storage/connection_gateway/src/main.rs
@@ -4,6 +4,8 @@ mod constants;
mod context;
mod model;
mod service;
+use std::{sync::Arc, time::Duration};
+
use crate::{api::router, config::EnvVars, context::AppState};
use anyhow::{Context, Result};
use axum::http::{
@@ -12,7 +14,11 @@ use axum::http::{
};
use config::Config;
use constants::ORIGINS;
-use frecency::{domain::services::EventIngestorImpl, outbound::postgres::FrecencyPgStorage};
+use frecency::{
+ domain::services::{EventIngestorImpl, PullAggregatorImpl},
+ inbound::polling_aggregator::FrecencyAggregatorWorkerHandle,
+ outbound::postgres::{FrecencyPgProcessor, FrecencyPgStorage},
+};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_env_var::env_var;
@@ -21,7 +27,6 @@ use secretsmanager_client::LocalOrRemoteSecret;
use service::dynamodb::create_dynamo_db_connection_manager;
use service::redis::poll_messages;
use sqlx::postgres::PgPoolOptions;
-use std::sync::Arc;
use tower_http::cors::CorsLayer;
env_var!(
@@ -106,6 +111,10 @@ async fn main() -> Result<()> {
config: Arc::clone(&config),
jwt_args,
internal_auth_key: LocalOrRemoteSecret::Local(InternalApiSecretKey::new()?),
+ frecency_worker: Arc::new(FrecencyAggregatorWorkerHandle::new_worker(
+ PullAggregatorImpl::new_with_default_time(FrecencyPgProcessor::new(pgpool)),
+ Duration::from_secs(60),
+ )),
})
.layer(cors);
diff --git a/rust/cloud-storage/frecency/.gitignore b/rust/cloud-storage/frecency/.gitignore
new file mode 100644
index 0000000000..4c49bd78f1
--- /dev/null
+++ b/rust/cloud-storage/frecency/.gitignore
@@ -0,0 +1 @@
+.env
diff --git a/rust/cloud-storage/frecency/.sqlx/query-89004da6bcdd66bccd56ed64402d82dc4fb489cccaf5ca647c5a9403fa760ce9.json b/rust/cloud-storage/frecency/.sqlx/query-89004da6bcdd66bccd56ed64402d82dc4fb489cccaf5ca647c5a9403fa760ce9.json
new file mode 100644
index 0000000000..a989abc850
--- /dev/null
+++ b/rust/cloud-storage/frecency/.sqlx/query-89004da6bcdd66bccd56ed64402d82dc4fb489cccaf5ca647c5a9403fa760ce9.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT pg_try_advisory_xact_lock($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pg_try_advisory_xact_lock",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "89004da6bcdd66bccd56ed64402d82dc4fb489cccaf5ca647c5a9403fa760ce9"
+}
diff --git a/rust/cloud-storage/frecency/.sqlx/query-06e932b580d1f7a6f60d847e38b6270e48e384e3e8a70f5a3cdcec1f275d0438.json b/rust/cloud-storage/frecency/.sqlx/query-d42e3270642ca0b9eff6b5807f600c24fd26d50d612a66edf0738c62d15680ba.json
similarity index 89%
rename from rust/cloud-storage/frecency/.sqlx/query-06e932b580d1f7a6f60d847e38b6270e48e384e3e8a70f5a3cdcec1f275d0438.json
rename to rust/cloud-storage/frecency/.sqlx/query-d42e3270642ca0b9eff6b5807f600c24fd26d50d612a66edf0738c62d15680ba.json
index 88c156406f..563aad9bf4 100644
--- a/rust/cloud-storage/frecency/.sqlx/query-06e932b580d1f7a6f60d847e38b6270e48e384e3e8a70f5a3cdcec1f275d0438.json
+++ b/rust/cloud-storage/frecency/.sqlx/query-d42e3270642ca0b9eff6b5807f600c24fd26d50d612a66edf0738c62d15680ba.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT *\n FROM\n frecency_events\n WHERE was_processed = false\n LIMIT $1\n FOR UPDATE\n ",
+ "query": "\n SELECT *\n FROM\n frecency_events\n WHERE was_processed = false\n LIMIT $1\n ",
"describe": {
"columns": [
{
@@ -60,5 +60,5 @@
false
]
},
- "hash": "06e932b580d1f7a6f60d847e38b6270e48e384e3e8a70f5a3cdcec1f275d0438"
+ "hash": "d42e3270642ca0b9eff6b5807f600c24fd26d50d612a66edf0738c62d15680ba"
}
diff --git a/rust/cloud-storage/frecency/src/domain/services.rs b/rust/cloud-storage/frecency/src/domain/services.rs
index a86934d8fb..b46c4abfd2 100644
--- a/rust/cloud-storage/frecency/src/domain/services.rs
+++ b/rust/cloud-storage/frecency/src/domain/services.rs
@@ -3,8 +3,8 @@
use crate::{
domain::{
models::{
- AggregateFrecency, AggregateId, EventAggregationStats, FrecencyPageRequest,
- FrecencyPageResponse,
+ AggregateFrecency, AggregateId, EventAggregationStats, EventRecordWithId,
+ FrecencyPageRequest, FrecencyPageResponse,
},
ports::{
AggregateFrecencyStorage, EventIngestorService, EventRecordStorage, FrecencyQueryErr,
@@ -13,8 +13,10 @@ use crate::{
},
outbound::time::DefaultTime,
};
+use chrono::{DateTime, Utc};
use macro_user_id::cowlike::CowLike;
-use std::collections::HashMap;
+use std::{collections::HashMap, sync::Arc};
+use tokio::task::JoinHandle;
/// concrete struct which implements [EventIngestorService]
#[derive(Clone)]
@@ -50,11 +52,107 @@ where
}
}
+/// the message that the [SyncWorker] receives which contains the data to be processed
+struct AggregationTask<T> {
+ tx: tokio::sync::oneshot::Sender<AggregationOutput<T>>,
+ events: Vec<EventRecordWithId<'static, T>>,
+ aggregates: Vec<AggregateFrecency>,
+ now: DateTime<Utc>,
+}
+
+/// completed aggregation which is sent back out of the [SyncWorker]
+struct AggregationOutput<T> {
+ events: Vec<EventRecordWithId<'static, T>>,
+ aggregates: Vec<AggregateFrecency>,
+ existing_aggregate_count: usize,
+ new_aggregate_count: usize,
+}
+
+/// worker which processes the cpu-bound task of computing the aggregate scores
+struct SyncWorker<T> {
+ #[expect(dead_code)]
+ handle: JoinHandle<()>,
+ sender: tokio::sync::mpsc::Sender<AggregationTask<T>>,
+}
+
+impl<T> SyncWorker<T>
+where
+ T: Send + 'static,
+{
+ async fn process_message(
+ &self,
+ events: Vec<EventRecordWithId<'static, T>>,
+ aggregates: Vec<AggregateFrecency>,
+ now: DateTime<Utc>,
+ ) -> Result<
+ tokio::sync::oneshot::Receiver<AggregationOutput<T>>,
+ tokio::sync::mpsc::error::SendError<AggregationTask<T>>,
+ > {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let task = AggregationTask {
+ tx,
+ events,
+ aggregates,
+ now,
+ };
+ self.sender.send(task).await?;
+ Ok(rx)
+ }
+
+ fn new() -> Self {
+ let (tx, mut rx) = tokio::sync::mpsc::channel(10);
+ let handle = tokio::task::spawn_blocking(move || {
+ while let Some(AggregationTask {
+ tx,
+ events,
+ aggregates,
+ now,
+ }) = rx.blocking_recv()
+ {
+ let mut aggregates: HashMap<_, _> = aggregates
+ .into_iter()
+ .map(|aggregate| (aggregate.id.clone(), aggregate))
+ .collect();
+
+ let existing_aggregate_count = aggregates.len();
+ let mut new_aggregate_count = 0usize;
+ for e in events.iter() {
+ let Ok(id) = AggregateId::from_event_record(e) else {
+ continue;
+ };
+ aggregates
+ .entry(id.clone())
+ .and_modify(|aggregate| aggregate.append_event_mut(&e.event_record, now))
+ .or_insert_with(|| {
+ new_aggregate_count += 1;
+ AggregateFrecency::new_from_initial_action_and_user_id(
+ id.user_id.into_owned(),
+ e.event_record.clone(),
+ now,
+ )
+ });
+ }
+
+ let aggregates = aggregates.into_values().collect();
+ let _ = tx.send(AggregationOutput {
+ events,
+ aggregates,
+ existing_aggregate_count,
+ new_aggregate_count,
+ });
+ }
+ });
+
+ SyncWorker { handle, sender: tx }
+ }
+}
+
/// a concrete struct which implements [PullEventAggregatorService]
#[derive(Clone)]
-pub struct PullAggregatorImpl<S, T> {
+pub struct PullAggregatorImpl<S: UnprocessedEventsRepo, T> {
event_storage: S,
time: T,
+ sync_worker: Arc<SyncWorker<S::EventId>>,
}
impl<S, T> PullAggregatorImpl<S, T>
@@ -68,6 +166,7 @@ where
PullAggregatorImpl {
event_storage,
time,
+ sync_worker: Arc::new(SyncWorker::new()),
}
}
}
@@ -98,39 +197,26 @@ where
let ids: Result<Vec<_>, _> = events.iter().map(AggregateId::from_event_record).collect();
let ids = ids?;
- let mut aggregates: HashMap<AggregateId, AggregateFrecency> = self
+ let aggregates = self
.event_storage
.get_aggregates_for_users_entities(ids)
- .await?
- .into_iter()
- .map(|aggregate| (aggregate.id.clone(), aggregate))
- .collect();
-
- let now = self.time.now();
-
- let existing_aggregate_count = aggregates.len();
- let mut new_aggregate_count = 0usize;
- for e in events.iter() {
- let Ok(id) = AggregateId::from_event_record(e) else {
- continue;
- };
- aggregates
- .entry(id.clone())
- .and_modify(|aggregate| aggregate.append_event_mut(&e.event_record, now))
- .or_insert_with(|| {
- new_aggregate_count += 1;
- AggregateFrecency::new_from_initial_action_and_user_id(
- id.user_id.into_owned(),
- e.event_record.clone(),
- now,
- )
- });
- }
-
- self.event_storage
- .set_aggregates(aggregates.into_values().collect())
.await?;
+ let rx = self
+ .sync_worker
+ .process_message(events, aggregates, self.time.now())
+ .await
+ .map_err(|r| anyhow::anyhow!("Tried to send message to closed worker: {r:?}"))?;
+
+ let AggregationOutput {
+ events,
+ aggregates,
+ existing_aggregate_count,
+ new_aggregate_count,
+ } = rx.await?;
+
+ self.event_storage.set_aggregates(aggregates).await?;
+
self.event_storage.mark_processed(events).await?;
Ok(EventAggregationStats {
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres.rs b/rust/cloud-storage/frecency/src/outbound/postgres.rs
index 5e3a939e81..bc4ea24b4e 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres.rs
@@ -13,7 +13,7 @@ use macro_user_id::{
};
use model_entity::{Entity, EntityType, TrackAction, TrackingData};
use sqlx::{PgPool, Postgres, QueryBuilder, Row, Transaction, prelude::FromRow};
-use std::{borrow::Cow, collections::VecDeque, str::FromStr, time::Duration};
+use std::{borrow::Cow, collections::VecDeque, str::FromStr};
use thiserror::Error;
#[cfg(test)]
@@ -388,6 +388,9 @@ pub struct FrecencyPgProcessor {
tx: tokio::sync::Mutex<Option<Transaction<'static, Postgres>>>,
}
+// Define a unique lock ID for frecency polling
+const FRECENCY_POLLER_LOCK_ID: i64 = 999_999_001;
+
impl FrecencyPgProcessor {
/// create a new instance of self from a [PgPool]
pub fn new(pool: PgPool) -> Self {
@@ -396,11 +399,58 @@ impl FrecencyPgProcessor {
tx: tokio::sync::Mutex::new(None),
}
}
+}
+
+type ExistingEventRow = EventRow<'static, i64>;
- async fn get_unprocessed_events_inner(
+/// the types of errors that can occur with the poller
+#[derive(Debug, Error)]
+pub enum PollerErr {
+ /// there was an issue accessing the db tx
+ #[error("Expected to be inside a transaction, but no transaction was present")]
+ TxErr,
+ /// failed to acquire advisory lock on db
+ #[error("another poller currently holds the frecency lock")]
+ DbLockErr,
+ /// failed to acquire mutex lock
+ #[error(transparent)]
+ MutexErr(#[from] tokio::sync::TryLockError),
+ /// sqlx database error
+ #[error(transparent)]
+ Sqlx(#[from] sqlx::Error),
+ /// error parsing macro user id
+ #[error(transparent)]
+ ParseErr(#[from] ParseErr),
+ /// some other error
+ #[error(transparent)]
+ OtherErr(#[from] anyhow::Error),
+}
+
+/// we need to bind 7 parameters per event we need to process to insert 1 [AggregateFrecency].
+/// Due to the u16 max upper bound on query parameters this is the limit for items that can be processed in one batch.
+/// Leftover entries just get processed later
+static FETCH_LIMIT: u16 = u16::MAX / 7;
+
+impl UnprocessedEventsRepo for FrecencyPgProcessor {
+ type Err = PollerErr;
+ type EventId = i64;
+
+ async fn get_unprocessed_events(
&self,
- ) -> Result<Vec<EventRecordWithId<'static, i64>>, anyhow::Error> {
+ ) -> Result<Vec<EventRecordWithId<'static, i64>>, Self::Err> {
let mut tx = self.pool.begin().await?;
+ let true = sqlx::query_scalar!(
+ r#"
+ SELECT pg_try_advisory_xact_lock($1)
+ "#,
+ FRECENCY_POLLER_LOCK_ID
+ )
+ .fetch_one(&mut *tx)
+ .await?
+ .unwrap_or(false) else {
+ return Err(PollerErr::DbLockErr);
+ };
+
let res: Vec<ExistingEventRow> = sqlx::query_as!(
ExistingEventRow,
r#"
@@ -409,7 +459,6 @@ impl FrecencyPgProcessor {
frecency_events
WHERE was_processed = false
LIMIT $1
- FOR UPDATE
"#,
FETCH_LIMIT as i64
)
@@ -420,37 +469,7 @@ impl FrecencyPgProcessor {
let mut guard = self.tx.try_lock()?;
*guard = Some(tx);
- res
- }
-}
-
-type ExistingEventRow = EventRow<'static, i64>;
-
-#[derive(Debug, Error)]
-#[error("Expected to be inside a transaction, but no transaction was present")]
-struct LockErr;
-
-/// we need to bind 7 parameters per event we need to process to insert 1 [AggregateFrecency].
-/// Due to the u16 max upper bound on query parameters this is the limit for items that can be processed in one batch.
-/// Leftover entries just get processed later
-static FETCH_LIMIT: u16 = u16::MAX / 7;
-
-impl UnprocessedEventsRepo for FrecencyPgProcessor {
- type Err = anyhow::Error;
- type EventId = i64;
-
- async fn get_unprocessed_events(
- &self,
- ) -> Result<Vec<EventRecordWithId<'static, i64>>, Self::Err> {
- const TIMEOUT_SECS: u64 = 2;
- tokio::select! {
- res = self.get_unprocessed_events_inner() => {
- res
- },
- _ = tokio::time::sleep(Duration::from_secs(TIMEOUT_SECS)) => {
- Err(anyhow::anyhow!("Failed to acquire row level lock after {TIMEOUT_SECS} seconds. Timeout reached"))
- }
- }
+ res.map_err(PollerErr::from)
}
async fn mark_processed<'a>(
@@ -459,7 +478,7 @@ impl UnprocessedEventsRepo for FrecencyPgProcessor {
) -> Result<(), Self::Err> {
let mut guard = self.tx.try_lock()?;
- let mut tx = guard.take().ok_or(LockErr)?;
+ let mut tx = guard.take().ok_or(PollerErr::TxErr)?;
if event.is_empty() {
tx.commit().await?;
@@ -493,7 +512,7 @@ impl UnprocessedEventsRepo for FrecencyPgProcessor {
aggregates: Vec<AggregateId<'_>>,
) -> Result<Vec<AggregateFrecency>, Self::Err> {
let mut guard = self.tx.try_lock()?;
- let tx = guard.as_deref_mut().ok_or(LockErr)?;
+ let tx = guard.as_deref_mut().ok_or(PollerErr::TxErr)?;
let mut query_builder = QueryBuilder::<Postgres>::new(
r#"
@@ -532,7 +551,7 @@ impl UnprocessedEventsRepo for FrecencyPgProcessor {
async fn set_aggregates(&self, aggregates: Vec<AggregateFrecency>) -> Result<(), Self::Err> {
let mut guard = self.tx.try_lock()?;
- let tx = guard.as_deref_mut().ok_or(LockErr)?;
+ let tx = guard.as_deref_mut().ok_or(PollerErr::TxErr)?;
if aggregates.is_empty() {
return Ok(());