Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- **Gmail** — `void gmail search` and `void gmail thread` read from the local INBOX store when a usable body is already synced. `--live` forces the Gmail API (`in:sent`, drafts, and unsynced mail still go to the network).

### Fixed

- **Gmail** — Retry transient API failures (429, 5xx, and 403 `rateLimitExceeded`) with exponential backoff, honouring `Retry-After` and the retry timestamp in Google's error body.
Expand Down
9 changes: 9 additions & 0 deletions crates/void-cli/src/commands/gmail/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ pub struct SearchArgs {
/// Max results to return
#[arg(long, default_value = "20")]
pub max: u32,
/// Skip the local store and hit the Gmail API for every message.
///
/// Default reads hydrate from the INBOX mirror when a usable body is already
/// stored (`in:sent`, drafts, and unsynced mail still go to the API).
#[arg(long)]
pub live: bool,
/// Gmail connection to use
#[arg(long)]
pub connection: Option<String>,
Expand All @@ -46,6 +52,9 @@ pub struct SearchArgs {
pub struct ThreadArgs {
/// Thread ID
pub thread_id: String,
/// Skip the local store and fetch the live Gmail thread.
#[arg(long)]
pub live: bool,
/// Gmail connection to use
#[arg(long)]
pub connection: Option<String>,
Expand Down
6 changes: 4 additions & 2 deletions crates/void-cli/src/commands/gmail/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ pub(super) async fn dispatch(args: &GmailArgs) -> anyhow::Result<()> {

async fn run_search(args: &SearchArgs) -> anyhow::Result<()> {
let connector = build_gmail_connector(args.connection.as_deref())?;
let messages = connector.search_api(&args.query, args.max).await?;
let messages = connector
.search_api(&args.query, args.max, args.live)
.await?;

let items: Vec<serde_json::Value> = messages
.iter()
Expand Down Expand Up @@ -57,7 +59,7 @@ async fn run_search(args: &SearchArgs) -> anyhow::Result<()> {

async fn run_thread(args: &ThreadArgs) -> anyhow::Result<()> {
let connector = build_gmail_connector(args.connection.as_deref())?;
let thread = connector.get_thread(&args.thread_id).await?;
let thread = connector.get_thread(&args.thread_id, args.live).await?;

let msgs: Vec<serde_json::Value> = thread
.messages
Expand Down
14 changes: 14 additions & 0 deletions crates/void-cli/tests/cli_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,3 +170,17 @@ fn inbox_with_bogus_connector_fails_with_message() {
.stderr(predicate::str::contains("Unknown connector"))
.stderr(predicate::str::contains("bogus"));
}

#[test]
fn gmail_search_and_thread_help_include_live() {
void()
.args(["gmail", "search", "--help"])
.assert()
.success()
.stdout(predicate::str::contains("--live"));
void()
.args(["gmail", "thread", "--help"])
.assert()
.success()
.stdout(predicate::str::contains("--live"));
}
15 changes: 15 additions & 0 deletions crates/void-core/src/db/conversations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,21 @@ pub(super) fn find_by_name_contains(
rows.collect::<Result<_, _>>().map_err(Into::into)
}

pub(super) fn find_by_connector_external_id(
conn: &Connection,
connector: &str,
external_id: &str,
) -> Result<Option<Conversation>, DbError> {
conn.query_row(
"SELECT id, connection_id, connector, external_id, name, kind, last_message_at, unread_count, is_muted, metadata
FROM conversations WHERE connector = ?1 AND external_id = ?2 LIMIT 1",
params![connector, external_id],
row::row_to_conversation,
)
.optional()
.map_err(Into::into)
}

pub(super) fn get(conn: &Connection, id: &str) -> Result<Option<Conversation>, DbError> {
conn.query_row(
"SELECT id, connection_id, connector, external_id, name, kind, last_message_at, unread_count, is_muted, metadata
Expand Down
21 changes: 21 additions & 0 deletions crates/void-core/src/db/database_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,27 @@ impl Database {
messages::find_by_external_id(&*self.conn()?, connection_id, external_id)
}

/// Look up a message by connector + native id, across connection ids.
///
/// Gmail stores `connection_id` as the account email after the first sync,
/// while CLI commands may still key off the config id. Routing by
/// `(connector, external_id)` finds the row either way.
pub fn find_message_by_connector_external_id(
&self,
connector: &str,
external_id: &str,
) -> Result<Option<Message>, DbError> {
messages::find_by_connector_external_id(&*self.conn()?, connector, external_id)
}

pub fn find_conversation_by_connector_external_id(
&self,
connector: &str,
external_id: &str,
) -> Result<Option<Conversation>, DbError> {
conversations::find_by_connector_external_id(&*self.conn()?, connector, external_id)
}

/// Resolve a Slack permalink to a stored message.
///
/// Looks up by the Slack-native `(channel external_id, message ts)` pair,
Expand Down
15 changes: 15 additions & 0 deletions crates/void-core/src/db/messages/lookup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ use super::super::row;
use crate::error::DbError;
use crate::models::Message;

pub fn find_by_connector_external_id(
conn: &Connection,
connector: &str,
external_id: &str,
) -> Result<Option<Message>, DbError> {
conn.query_row(
"SELECT id, conversation_id, connection_id, connector, external_id, sender, sender_name, sender_avatar_url, body, timestamp, synced_at, is_archived, reply_to_id, media_type, metadata, context_id, is_saved
FROM messages WHERE connector = ?1 AND external_id = ?2 LIMIT 1",
params![connector, external_id],
row::row_to_message,
)
.optional()
.map_err(Into::into)
}

pub fn find_by_external_id(
conn: &Connection,
connection_id: &str,
Expand Down
4 changes: 2 additions & 2 deletions crates/void-core/src/db/messages/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ pub use inbox::{
senders_missing_avatar,
};
pub use lookup::{
find_by_external_id, find_by_slack_link, find_slack_conversation_by_external_id,
last_in_conversation,
find_by_connector_external_id, find_by_external_id, find_by_slack_link,
find_slack_conversation_by_external_id, last_in_conversation,
};
pub use read::{
count_for_conversation, count_recent, get, latest_timestamp, list_for_conversation, list_recent,
Expand Down
26 changes: 26 additions & 0 deletions crates/void-core/src/db/tests/crud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -679,3 +679,29 @@ fn migrations_preserve_existing_data() {
.unwrap();
assert_eq!(sync_conn, "legacy-acct");
}

#[test]
fn find_by_connector_external_id_ignores_connection_id() {
let db = test_db();
let conv = make_conversation_with_connector("c1", "me@gmail.com", "t1", "gmail");
db.upsert_conversation(&conv).unwrap();
let mut msg = make_message_with_connector("m1", "c1", "me@gmail.com", "hello", 1, "gmail");
msg.external_id = "gmail-msg-1".into();
db.upsert_message(&msg).unwrap();

let found = db
.find_message_by_connector_external_id("gmail", "gmail-msg-1")
.unwrap()
.expect("row");
assert_eq!(found.id, "m1");
assert_eq!(found.connection_id, "me@gmail.com");

assert!(db
.find_conversation_by_connector_external_id("gmail", "t1")
.unwrap()
.is_some());
assert!(db
.find_message_by_connector_external_id("gmail", "missing")
.unwrap()
.is_none());
}
2 changes: 1 addition & 1 deletion crates/void-gmail/src/api/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub struct MessageHeader {
pub value: String,
}

#[derive(Debug, Clone, serde::Serialize)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FileAttachment {
pub filename: String,
pub mime_type: Option<String>,
Expand Down
60 changes: 47 additions & 13 deletions crates/void-gmail/src/connector/api_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use tracing::warn;

use crate::api::GmailApiClient;
use crate::auth;
use void_core::db::Database;

use super::GmailConnector;

Expand Down Expand Up @@ -39,24 +40,29 @@ impl GmailConnector {
&self,
query: &str,
max_results: u32,
live: bool,
) -> anyhow::Result<Vec<crate::api::GmailMessage>> {
let api = self.get_client().await?;
let resp = api
.list_messages(max_results, None, None, Some(query))
.await?;
let mut messages = Vec::new();
if let Some(refs) = resp.messages {
for r in &refs {
match api.get_message(&r.id).await {
Ok(msg) => messages.push(msg),
Err(e) => warn!(message_id = %r.id, "failed to fetch: {e}"),
let db = if live {
None
} else {
super::store::open_store(&self.store_path)?
};
search_with_api(&api, db.as_ref(), query, max_results).await
}

pub async fn get_thread(
&self,
thread_id: &str,
live: bool,
) -> anyhow::Result<crate::api::GmailThread> {
if !live {
if let Some(db) = super::store::open_store(&self.store_path)? {
if let Some(thread) = super::store::load_stored_thread(&db, thread_id) {
return Ok(thread);
}
}
}
Ok(messages)
}

pub async fn get_thread(&self, thread_id: &str) -> anyhow::Result<crate::api::GmailThread> {
let api = self.get_client().await?;
api.get_thread(thread_id).await.map_err(Into::into)
}
Expand Down Expand Up @@ -374,3 +380,31 @@ pub(super) fn build_reply_all_recipients(

recipients.join(", ")
}

pub(super) async fn search_with_api(
api: &GmailApiClient,
db: Option<&Database>,
query: &str,
max_results: u32,
) -> anyhow::Result<Vec<crate::api::GmailMessage>> {
let resp = api
.list_messages(max_results, None, None, Some(query))
.await?;
let mut messages = Vec::new();
if let Some(refs) = resp.messages {
for r in &refs {
if let Some(db) = db {
if let Some(stored) = super::store::load_stored_message(db, &r.id) {
debug!(message_id = %r.id, "gmail: serving message from local store");
messages.push(stored);
continue;
}
}
match api.get_message(&r.id).await {
Ok(msg) => messages.push(msg),
Err(e) => warn!(message_id = %r.id, "failed to fetch: {e}"),
}
}
}
Ok(messages)
}
1 change: 1 addition & 0 deletions crates/void-gmail/src/connector/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod api_methods;
mod compose;
mod connector_trait;
mod store;
mod sync;

#[cfg(test)]
Expand Down
Loading