diff --git a/services/backup/src/constants.rs b/services/backup/src/constants.rs index 050c680a7..506931d12 100644 --- a/services/backup/src/constants.rs +++ b/services/backup/src/constants.rs @@ -1,42 +1,43 @@ // Assorted constants pub const MPSC_CHANNEL_BUFFER_CAPACITY: usize = 1; pub const ID_SEPARATOR: &str = ":"; pub const ATTACHMENT_HOLDER_SEPARATOR: &str = ";"; pub const WS_FRAME_SIZE: usize = 1_048_576; // 1MiB pub const LOG_DEFAULT_PAGE_SIZE: i32 = 20; +pub const LOG_BACKUP_ID_SEPARATOR: &str = "#"; // Configuration defaults pub const DEFAULT_HTTP_PORT: u16 = 50052; pub const DEFAULT_BLOB_SERVICE_URL: &str = "http://localhost:50053"; // Environment variable names pub const LOG_LEVEL_ENV_VAR: &str = tracing_subscriber::filter::EnvFilter::DEFAULT_ENV; // DynamoDB constants pub mod backup_table { pub const TABLE_NAME: &str = "backup-service-backup"; pub const CREATED_INDEX: &str = "userID-created-index"; pub mod attr { pub const USER_ID: &str = "userID"; pub const BACKUP_ID: &str = "backupID"; pub const CREATED: &str = "created"; pub const USER_DATA: &str = "userData"; pub const USER_KEYS: &str = "userKeys"; pub const ATTACHMENTS: &str = "attachments"; } } pub mod log_table { pub const TABLE_NAME: &str = "backup-service-log"; pub mod attr { pub const BACKUP_ID: &str = "backupID"; pub const LOG_ID: &str = "logID"; pub const CONTENT_DB: &str = "content"; pub const CONTENT_BLOB_INFO: &str = "blobInfo"; pub const ATTACHMENTS: &str = "attachments"; } } diff --git a/services/backup/src/database/log_item.rs b/services/backup/src/database/log_item.rs index f5ba3a4d4..196636ac9 100644 --- a/services/backup/src/database/log_item.rs +++ b/services/backup/src/database/log_item.rs @@ -1,114 +1,142 @@ -use crate::constants::log_table::attr; +use crate::constants::{log_table::attr, LOG_BACKUP_ID_SEPARATOR}; use aws_sdk_dynamodb::types::AttributeValue; use comm_lib::{ blob::{ client::{BlobServiceClient, BlobServiceError}, types::BlobInfo, }, constants::DDB_ITEM_SIZE_LIMIT, database::{ blob::BlobOrDBContent, calculate_size_in_db, parse_int_attribute, - AttributeExtractor, AttributeTryInto, DBItemError, + AttributeExtractor, AttributeTryInto, DBItemAttributeError, DBItemError, + Value, }, }; use std::collections::HashMap; use tracing::debug; #[derive(Clone, Debug)] pub struct LogItem { + pub user_id: String, pub backup_id: String, pub log_id: usize, pub content: BlobOrDBContent, pub attachments: Vec, } impl LogItem { pub async fn ensure_size_constraints( &mut self, blob_client: &BlobServiceClient, ) -> Result<(), BlobServiceError> { if let Ok(size) = calculate_size_in_db(&self.clone().into()) { if size < DDB_ITEM_SIZE_LIMIT { return Ok(()); }; } debug!( log_id = ?self.log_id, "Log content exceeds DDB item size limit, moving to blob storage" ); self.content.move_to_blob(blob_client).await } + pub fn partition_key( + user_id: impl Into, + backup_id: impl Into, + ) -> String { + format!( + "{}{}{}", + user_id.into(), + LOG_BACKUP_ID_SEPARATOR, + backup_id.into(), + ) + } + pub fn item_key( + user_id: impl Into, backup_id: impl Into, log_id: usize, ) -> HashMap { HashMap::from([ ( attr::BACKUP_ID.to_string(), - AttributeValue::S(backup_id.into()), + AttributeValue::S(Self::partition_key(user_id, backup_id)), ), ( attr::LOG_ID.to_string(), AttributeValue::N(log_id.to_string()), ), ]) } } impl From for HashMap { fn from(value: LogItem) -> Self { - let mut attrs = LogItem::item_key(value.backup_id, value.log_id); + let mut attrs = + LogItem::item_key(value.user_id, value.backup_id, value.log_id); let (content_attr_name, content_attr) = value .content .into_attr_pair(attr::CONTENT_BLOB_INFO, attr::CONTENT_DB); attrs.insert(content_attr_name, content_attr); if !value.attachments.is_empty() { attrs.insert( attr::ATTACHMENTS.to_string(), AttributeValue::L( value .attachments .into_iter() .map(AttributeValue::from) .collect(), ), ); } attrs } } impl TryFrom> for LogItem { type Error = DBItemError; fn try_from( mut value: HashMap, ) -> Result { - let backup_id = value.take_attr(attr::BACKUP_ID)?; + let id: String = value.take_attr(attr::BACKUP_ID)?; + let (user_id, backup_id) = + match &id.split(LOG_BACKUP_ID_SEPARATOR).collect::>()[..] { + &[user_id, backup_id] => (user_id.to_string(), backup_id.to_string()), + _ => { + return Err(DBItemError::new( + attr::BACKUP_ID.to_string(), + Value::String(id), + DBItemAttributeError::InvalidValue, + )) + } + }; let log_id = parse_int_attribute(attr::LOG_ID, value.remove(attr::LOG_ID))?; let content = BlobOrDBContent::parse_from_attrs( &mut value, attr::CONTENT_BLOB_INFO, attr::CONTENT_DB, )?; let attachments = value.remove(attr::ATTACHMENTS); let attachments = if attachments.is_some() { attachments.attr_try_into(attr::ATTACHMENTS)? } else { Vec::new() }; Ok(LogItem { + user_id, backup_id, log_id, content, attachments, }) } } diff --git a/services/backup/src/database/mod.rs b/services/backup/src/database/mod.rs index 3a25b19dc..3de1dd7b3 100644 --- a/services/backup/src/database/mod.rs +++ b/services/backup/src/database/mod.rs @@ -1,325 +1,325 @@ pub mod backup_item; pub mod log_item; use self::{ backup_item::{BackupItem, OrderedBackupItem}, log_item::LogItem, }; use crate::constants::{backup_table, log_table, LOG_DEFAULT_PAGE_SIZE}; use aws_sdk_dynamodb::{ operation::get_item::GetItemOutput, types::{AttributeValue, DeleteRequest, ReturnValue, WriteRequest}, }; use comm_lib::database::{ self, batch_operations::ExponentialBackoffConfig, parse_int_attribute, Error, }; use tracing::{error, trace, warn}; #[derive(Clone)] pub struct DatabaseClient { client: aws_sdk_dynamodb::Client, } impl DatabaseClient { pub fn new(aws_config: &aws_types::SdkConfig) -> Self { DatabaseClient { client: aws_sdk_dynamodb::Client::new(aws_config), } } } /// Backup functions impl DatabaseClient { pub async fn put_backup_item( &self, backup_item: BackupItem, ) -> Result<(), Error> { let item = backup_item.into(); self .client .put_item() .table_name(backup_table::TABLE_NAME) .set_item(Some(item)) .send() .await .map_err(|e| { error!("DynamoDB client failed to put backup item"); Error::AwsSdk(e.into()) })?; Ok(()) } pub async fn find_backup_item( &self, user_id: &str, backup_id: &str, ) -> Result, Error> { let item_key = BackupItem::item_key(user_id, backup_id); let output = self .client .get_item() .table_name(backup_table::TABLE_NAME) .set_key(Some(item_key)) .send() .await .map_err(|e| { error!("DynamoDB client failed to find backup item"); Error::AwsSdk(e.into()) })?; let GetItemOutput { item: Some(item), .. } = output else { return Ok(None); }; let backup_item = item.try_into()?; Ok(Some(backup_item)) } pub async fn find_last_backup_item( &self, user_id: &str, ) -> Result, Error> { let response = self .client .query() .table_name(backup_table::TABLE_NAME) .index_name(backup_table::CREATED_INDEX) .key_condition_expression("#userID = :valueToMatch") .expression_attribute_names("#userID", backup_table::attr::USER_ID) .expression_attribute_values( ":valueToMatch", AttributeValue::S(user_id.to_string()), ) .limit(1) .scan_index_forward(false) .send() .await .map_err(|e| { error!("DynamoDB client failed to find last backup"); Error::AwsSdk(e.into()) })?; match response.items.unwrap_or_default().pop() { Some(item) => { let backup_item = item.try_into()?; Ok(Some(backup_item)) } None => Ok(None), } } pub async fn remove_backup_item( &self, user_id: &str, backup_id: &str, ) -> Result, Error> { let item_key = BackupItem::item_key(user_id, backup_id); let response = self .client .delete_item() .table_name(backup_table::TABLE_NAME) .set_key(Some(item_key)) .return_values(ReturnValue::AllOld) .send() .await .map_err(|e| { error!("DynamoDB client failed to remove backup item"); Error::AwsSdk(e.into()) })?; let result = response .attributes .map(BackupItem::try_from) .transpose() .map_err(Error::from)?; - self.remove_log_items_for_backup(backup_id).await?; + self.remove_log_items_for_backup(user_id, backup_id).await?; Ok(result) } /// For the purposes of the initial backup version this function /// removes all backups except for the latest one pub async fn remove_old_backups( &self, user_id: &str, ) -> Result, Error> { let response = self .client .query() .table_name(backup_table::TABLE_NAME) .index_name(backup_table::CREATED_INDEX) .key_condition_expression("#userID = :valueToMatch") .expression_attribute_names("#userID", backup_table::attr::USER_ID) .expression_attribute_values( ":valueToMatch", AttributeValue::S(user_id.to_string()), ) .scan_index_forward(false) .send() .await .map_err(|e| { error!("DynamoDB client failed to fetch backups"); Error::AwsSdk(e.into()) })?; if response.last_evaluated_key().is_some() { // In the intial version of the backup service this function will be run // for every new backup (each user only has one backup), so this shouldn't // happen warn!("Not all old backups have been cleaned up"); } let items = response .items .unwrap_or_default() .into_iter() .map(OrderedBackupItem::try_from) .collect::, _>>()?; let mut removed_backups = vec![]; let Some(latest) = items.iter().map(|item| item.created).max() else { return Ok(removed_backups); }; for item in items { if item.created == latest { trace!( "Skipping removal of the latest backup item: {}", item.backup_id ); continue; } trace!("Removing backup item: {item:?}"); if let Some(backup) = self.remove_backup_item(user_id, &item.backup_id).await? { removed_backups.push(backup); } else { warn!("Backup was found during query, but wasn't found when deleting") }; } Ok(removed_backups) } } /// Backup log functions impl DatabaseClient { pub async fn put_log_item(&self, log_item: LogItem) -> Result<(), Error> { let item = log_item.into(); self .client .put_item() .table_name(log_table::TABLE_NAME) .set_item(Some(item)) .send() .await .map_err(|e| { error!("DynamoDB client failed to put log item"); Error::AwsSdk(e.into()) })?; Ok(()) } pub async fn fetch_log_items( &self, + user_id: &str, backup_id: &str, from_id: Option, ) -> Result<(Vec, Option), Error> { + let id = LogItem::partition_key(user_id, backup_id); let mut query = self .client .query() .table_name(log_table::TABLE_NAME) .key_condition_expression("#backupID = :valueToMatch") .expression_attribute_names("#backupID", log_table::attr::BACKUP_ID) .expression_attribute_values( ":valueToMatch", - AttributeValue::S(backup_id.to_string()), + AttributeValue::S(id.clone()), ) .limit(LOG_DEFAULT_PAGE_SIZE); if let Some(from_id) = from_id { query = query - .exclusive_start_key( - log_table::attr::BACKUP_ID, - AttributeValue::S(backup_id.to_string()), - ) + .exclusive_start_key(log_table::attr::BACKUP_ID, AttributeValue::S(id)) .exclusive_start_key( log_table::attr::LOG_ID, AttributeValue::N(from_id.to_string()), ); } let response = query.send().await.map_err(|e| { error!("DynamoDB client failed to fetch logs"); Error::AwsSdk(e.into()) })?; let last_id = response .last_evaluated_key() .map(|key| { parse_int_attribute( log_table::attr::LOG_ID, key.get(log_table::attr::LOG_ID).cloned(), ) }) .transpose()?; let items = response .items .unwrap_or_default() .into_iter() .map(LogItem::try_from) .collect::, _>>()?; Ok((items, last_id)) } pub async fn remove_log_items_for_backup( &self, + user_id: &str, backup_id: &str, ) -> Result<(), Error> { let (mut items, mut last_id) = - self.fetch_log_items(backup_id, None).await?; + self.fetch_log_items(user_id, backup_id, None).await?; while last_id.is_some() { let (mut new_items, new_last_id) = - self.fetch_log_items(backup_id, last_id).await?; + self.fetch_log_items(user_id, backup_id, last_id).await?; items.append(&mut new_items); last_id = new_last_id; } let write_requests = items .into_iter() .map(|key| { DeleteRequest::builder() - .set_key(Some(LogItem::item_key(key.backup_id, key.log_id))) + .set_key(Some(LogItem::item_key(user_id, key.backup_id, key.log_id))) .build() }) .map(|request| WriteRequest::builder().delete_request(request).build()) .collect::>(); database::batch_operations::batch_write( &self.client, log_table::TABLE_NAME, write_requests, ExponentialBackoffConfig::default(), ) .await?; Ok(()) } } diff --git a/services/backup/src/http/handlers/log.rs b/services/backup/src/http/handlers/log.rs index ab3d3f527..2f5536c37 100644 --- a/services/backup/src/http/handlers/log.rs +++ b/services/backup/src/http/handlers/log.rs @@ -1,295 +1,306 @@ use crate::constants::WS_FRAME_SIZE; use crate::database::{log_item::LogItem, DatabaseClient}; use actix::{Actor, ActorContext, ActorFutureExt, AsyncContext, StreamHandler}; use actix_http::ws::{CloseCode, Item}; use actix_web::{ web::{self, Bytes, BytesMut}, Error, HttpRequest, HttpResponse, }; use actix_web_actors::ws::{self, WebsocketContext}; +use comm_lib::auth::UserIdentity; use comm_lib::{ backup::{ DownloadLogsRequest, LogWSRequest, LogWSResponse, UploadLogRequest, }, blob::{ client::{BlobServiceClient, BlobServiceError}, types::BlobInfo, }, database::{self, blob::BlobOrDBContent}, }; use std::time::{Duration, Instant}; use tracing::{error, info, instrument, warn}; pub async fn handle_ws( req: HttpRequest, + user: UserIdentity, stream: web::Payload, blob_client: web::Data, db_client: web::Data, ) -> Result { ws::WsResponseBuilder::new( LogWSActor { + user, blob_client: blob_client.as_ref().clone(), db_client: db_client.as_ref().clone(), last_msg_time: Instant::now(), buffer: BytesMut::new(), }, &req, stream, ) .frame_size(WS_FRAME_SIZE) .start() } #[derive( Debug, derive_more::From, derive_more::Display, derive_more::Error, )] enum LogWSError { Bincode(bincode::Error), Blob(BlobServiceError), DB(database::Error), } struct LogWSActor { + user: UserIdentity, blob_client: BlobServiceClient, db_client: DatabaseClient, last_msg_time: Instant, buffer: BytesMut, } impl LogWSActor { const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5); const CONNECTION_TIMEOUT: Duration = Duration::from_secs(10); fn handle_msg_sync( &self, ctx: &mut WebsocketContext, bytes: Bytes, ) { - let fut = - Self::handle_msg(self.blob_client.clone(), self.db_client.clone(), bytes); + let fut = Self::handle_msg( + self.user.user_id.clone(), + self.blob_client.clone(), + self.db_client.clone(), + bytes, + ); let fut = actix::fut::wrap_future(fut).map( |responses, _: &mut LogWSActor, ctx: &mut WebsocketContext| { let responses = match responses { Ok(responses) => responses, Err(err) => { error!("Error: {err:?}"); vec![LogWSResponse::ServerError] } }; for response in responses { match bincode::serialize(&response) { Ok(bytes) => ctx.binary(bytes), Err(error) => { error!( "Error serializing a response: {response:?}. Error: {error}" ); } }; } }, ); ctx.spawn(fut); } async fn handle_msg( + user_id: String, blob_client: BlobServiceClient, db_client: DatabaseClient, bytes: Bytes, ) -> Result, LogWSError> { let request = bincode::deserialize(&bytes)?; match request { LogWSRequest::UploadLog(UploadLogRequest { backup_id, log_id, content, attachments, }) => { let mut attachment_blob_infos = Vec::new(); for attachment in attachments.unwrap_or_default() { let blob_info = Self::create_attachment(&blob_client, attachment).await?; attachment_blob_infos.push(blob_info); } let mut log_item = LogItem { + user_id, backup_id: backup_id.clone(), log_id, content: BlobOrDBContent::new(content), attachments: attachment_blob_infos, }; log_item.ensure_size_constraints(&blob_client).await?; db_client.put_log_item(log_item).await?; Ok(vec![LogWSResponse::LogUploaded { backup_id, log_id }]) } LogWSRequest::DownloadLogs(DownloadLogsRequest { backup_id, from_id, }) => { - let (log_items, last_id) = - db_client.fetch_log_items(&backup_id, from_id).await?; + let (log_items, last_id) = db_client + .fetch_log_items(&user_id, &backup_id, from_id) + .await?; let mut messages = vec![]; for LogItem { log_id, content, attachments, .. } in log_items { let content = content.fetch_bytes(&blob_client).await?; let attachments: Vec = attachments.into_iter().map(|att| att.blob_hash).collect(); let attachments = if attachments.is_empty() { None } else { Some(attachments) }; messages.push(LogWSResponse::LogDownload { log_id, content, attachments, }) } messages.push(LogWSResponse::LogDownloadFinished { last_log_id: last_id, }); Ok(messages) } } } async fn create_attachment( blob_client: &BlobServiceClient, attachment: String, ) -> Result { let blob_info = BlobInfo { blob_hash: attachment, holder: uuid::Uuid::new_v4().to_string(), }; if !blob_client .assign_holder(&blob_info.blob_hash, &blob_info.holder) .await? { warn!( "Blob attachment with hash {:?} doesn't exist", blob_info.blob_hash ); } Ok(blob_info) } } impl Actor for LogWSActor { type Context = ws::WebsocketContext; #[instrument(skip_all)] fn started(&mut self, ctx: &mut Self::Context) { info!("Socket opened"); ctx.run_interval(Self::HEARTBEAT_INTERVAL, |actor, ctx| { if Instant::now().duration_since(actor.last_msg_time) > Self::CONNECTION_TIMEOUT { warn!("Socket timeout, closing connection"); ctx.stop(); return; } ctx.ping(&[]); }); } #[instrument(skip_all)] fn stopped(&mut self, _: &mut Self::Context) { info!("Socket closed"); } } impl StreamHandler> for LogWSActor { #[instrument(skip_all)] fn handle( &mut self, msg: Result, ctx: &mut Self::Context, ) { let msg = match msg { Ok(msg) => msg, Err(err) => { warn!("Error during socket message handling: {err}"); ctx.close(Some(CloseCode::Error.into())); ctx.stop(); return; } }; self.last_msg_time = Instant::now(); match msg { ws::Message::Binary(bytes) => self.handle_msg_sync(ctx, bytes), // Continuations - this is mostly boilerplate code. Some websocket // clients may split a message into these ones ws::Message::Continuation(Item::FirstBinary(bytes)) => { if !self.buffer.is_empty() { warn!("Socket received continuation before previous was completed"); ctx.close(Some(CloseCode::Error.into())); ctx.stop(); return; } self.buffer.extend_from_slice(&bytes); } ws::Message::Continuation(Item::Continue(bytes)) => { if self.buffer.is_empty() { warn!("Socket received continuation message before it was started"); ctx.close(Some(CloseCode::Error.into())); ctx.stop(); return; } self.buffer.extend_from_slice(&bytes); } ws::Message::Continuation(Item::Last(bytes)) => { if self.buffer.is_empty() { warn!( "Socket received last continuation message before it was started" ); ctx.close(Some(CloseCode::Error.into())); ctx.stop(); return; } self.buffer.extend_from_slice(&bytes); let bytes = self.buffer.split(); self.handle_msg_sync(ctx, bytes.into()); } // Heartbeat ws::Message::Ping(message) => ctx.pong(&message), ws::Message::Pong(_) => (), // Other ws::Message::Text(_) | ws::Message::Continuation(Item::FirstText(_)) => { warn!("Socket received unsupported message"); ctx.close(Some(CloseCode::Unsupported.into())); ctx.stop(); } ws::Message::Close(reason) => { info!("Socket was closed"); ctx.close(reason); ctx.stop(); } ws::Message::Nop => (), } } }