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(github): add document service to GithubSyncService (#1776)

Will Hutchinsone7454a0ed6df
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 7f58c30e4e..acfaeb8e76 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -4166,6 +4166,7 @@ dependencies = [
"axum",
"axum-extra",
"chrono",
+ "documents",
"entity_access",
"fusionauth",
"hex",
@@ -4176,6 +4177,7 @@ dependencies = [
"macro_user_id",
"macro_uuid",
"mockall",
+ "model",
"model-error-response",
"redis",
"regex",
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index f6bacefb68..252b24d0e7 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -22,6 +22,7 @@ use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use github::domain::service::GithubSyncServiceImpl;
+use github::outbound::github_sync_client::GithubSyncClientImpl;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_env_var::env_var;
use macro_sha_count_client::Redis;
@@ -126,7 +127,13 @@ pub(crate) type CommsState = CommsRouterState<CommsChannelService>;
pub(crate) type DssChannelsState =
ChannelsRouterState<ChannelMessagesServiceImpl<PgChannelMessagesRepo>, PgChannelAccessCheck>;
-pub(crate) type GithubSyncServiceType = GithubSyncServiceImpl;
+/// Type alias for the document service used by the github sync service.
+pub(crate) type GithubDocumentService =
+ DocumentServiceImpl<PgDocumentRepo, S3UploadUrlAdapter, TaskPropertiesAdapter>;
+
+/// Type alias for the github sync service.
+pub(crate) type GithubSyncServiceType =
+ GithubSyncServiceImpl<GithubDocumentService, GithubSyncClientImpl>;
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 2ffe4d14ed..c746ec96fc 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -28,6 +28,7 @@ use dynamodb_client::DynamodbClient;
use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use github::domain::service::{GithubSyncConfig, GithubSyncServiceImpl};
+use github::outbound::github_sync_client::GithubSyncClientImpl;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
@@ -309,14 +310,14 @@ async fn main() -> anyhow::Result<()> {
config.vars.document_storage_bucket.as_ref(),
config.vars.docx_document_upload_bucket.as_ref(),
);
- let document_service = DocumentServiceImpl::new(
+ let document_service = Arc::new(DocumentServiceImpl::new(
document_repo,
cloudfront_config,
sync_service_client.clone(),
s3_upload_adapter,
TaskPropertiesAdapter(system_properties_service.clone()),
db.clone(),
- );
+ ));
let github_webhook_secret = secretsmanager_client
.get_maybe_secret_value(env, GithubWebhookSecretKey::new()?)
@@ -326,12 +327,16 @@ async fn main() -> anyhow::Result<()> {
.get_maybe_secret_value(env, GithubSyncAppPemSecretKey::new()?)
.await?;
- let github_sync_service_impl = GithubSyncServiceImpl::new(GithubSyncConfig {
- webhook_secret: github_webhook_secret.as_ref().to_string(),
- github_sync_app_url: config.vars.github_sync_app_url.to_string(),
- sync_app_pem: github_sync_app_pem.as_ref().to_string(),
- sync_app_client_id: config.vars.github_sync_app_client_id.to_string(),
- });
+ let github_sync_service_impl = GithubSyncServiceImpl::new(
+ GithubSyncConfig {
+ webhook_secret: github_webhook_secret.as_ref().to_string(),
+ github_sync_app_url: config.vars.github_sync_app_url.to_string(),
+ sync_app_pem: github_sync_app_pem.as_ref().to_string(),
+ sync_app_client_id: config.vars.github_sync_app_client_id.to_string(),
+ },
+ document_service.clone(),
+ GithubSyncClientImpl::default(),
+ );
let api_context = ApiContext {
soup_router_state: SoupRouterState::new(
@@ -365,7 +370,7 @@ async fn main() -> anyhow::Result<()> {
permissions_token_secret: comms_permissions_token_secret,
entity_access_service: entity_access_service.clone(),
documents_state: DocumentRouterState {
- service: Arc::new(document_service),
+ service: document_service,
access_service: entity_access_service,
pool: db.clone(),
},
diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.toml
index 8e97e8a8e3..73b580d99c 100644
--- a/rust/cloud-storage/github/Cargo.toml
+++ b/rust/cloud-storage/github/Cargo.toml
@@ -7,7 +7,7 @@ version = "0.1.0"
[features]
default = ["ports", "sync", "link", "inbound", "outbound", "axum"]
ports = []
-sync = ["dep:reqwest", "ports"]
+sync = ["dep:reqwest", "dep:documents", "ports"]
link = ["ports"]
inbound = ["axum", "ports"]
outbound = [
@@ -38,6 +38,7 @@ reqwest = {workspace = true, optional = true }
serde_json = { workspace = true }
regex = { workspace = true }
urlencoding = { workspace = true, optional = true }
+documents = { path = "../documents", default-features = false, features = ["ports"], optional = true }
entity_access = { path = "../entity_access" }
jsonwebtoken = { workspace = true }
hmac = "0.12.1"
@@ -60,5 +61,6 @@ utoipa = { workspace = true, optional = true }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
http-body-util = { workspace = true }
+model = { path = "../model" }
tokio = { workspace = true }
tower = { workspace = true }
diff --git a/rust/cloud-storage/github/src/domain/ports/mod.rs b/rust/cloud-storage/github/src/domain/ports/mod.rs
index bf902b40d1..cabd48b15f 100644
--- a/rust/cloud-storage/github/src/domain/ports/mod.rs
+++ b/rust/cloud-storage/github/src/domain/ports/mod.rs
@@ -6,8 +6,12 @@
mod link;
#[cfg(feature = "sync")]
mod sync;
+#[cfg(feature = "sync")]
+mod sync_client;
#[cfg(feature = "link")]
pub use link::*;
#[cfg(feature = "sync")]
pub use sync::*;
+#[cfg(feature = "sync")]
+pub use sync_client::*;
diff --git a/rust/cloud-storage/github/src/domain/ports/sync_client.rs b/rust/cloud-storage/github/src/domain/ports/sync_client.rs
new file mode 100644
index 0000000000..a3658ccb6a
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/ports/sync_client.rs
@@ -0,0 +1,18 @@
+//! Port definition for the github sync API client.
+
+use std::future::Future;
+
+use crate::domain::models::{GithubError, GithubInstallationAccessToken};
+
+/// Client interface for making GitHub sync API calls.
+///
+/// Abstracts HTTP communication with GitHub's API so the service
+/// layer does not need to manage its own HTTP client.
+pub trait GithubSyncClient: Send + Sync + 'static {
+ /// Generates an installation access token for a given GitHub App installation.
+ fn generate_installation_access_token(
+ &self,
+ jwt: &str,
+ installation_id: u64,
+ ) -> impl Future<Output = Result<GithubInstallationAccessToken, GithubError>> + Send;
+}
diff --git a/rust/cloud-storage/github/src/domain/service/mod.rs b/rust/cloud-storage/github/src/domain/service/mod.rs
index 91ede3c7c3..b9fb5dc6d7 100644
--- a/rust/cloud-storage/github/src/domain/service/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/mod.rs
@@ -41,26 +41,35 @@ mod sync_impl {
GithubInstallationAccessToken, GithubWebhookEventType, MacroTaskId,
ValidatedGithubWebhookEvent,
},
- ports::GithubSyncService,
+ ports::{GithubSyncClient, GithubSyncService},
};
+ use documents::domain::ports::DocumentService;
use hmac::{Hmac, Mac};
use sha2::Sha256;
+ use std::sync::Arc;
use subtle::ConstantTimeEq;
type HmacSha256 = Hmac<Sha256>;
/// The concrete github sync service implementation.
- pub struct GithubSyncServiceImpl {
+ pub struct GithubSyncServiceImpl<D: DocumentService, C: GithubSyncClient> {
config: super::GithubSyncConfig,
+ #[allow(dead_code)]
+ document_service: Arc<D>,
+ client: C,
}
- impl GithubSyncServiceImpl {
+ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {
/// Create a new github sync service.
- pub fn new(config: super::GithubSyncConfig) -> Self {
- Self { config }
+ pub fn new(config: super::GithubSyncConfig, document_service: Arc<D>, client: C) -> Self {
+ Self {
+ config,
+ document_service,
+ client,
+ }
}
}
- impl GithubSyncService for GithubSyncServiceImpl {
+ impl<D: DocumentService, C: GithubSyncClient> GithubSyncService for GithubSyncServiceImpl<D, C> {
#[tracing::instrument(skip(self, body), err)]
async fn validate_webhook_event(
&self,
@@ -158,36 +167,9 @@ mod sync_impl {
let jwt = jsonwebtoken::encode(&header, &claims, &encoding_key)
.map_err(|e| GithubError::Internal(anyhow::anyhow!("failed to encode JWT: {e}")))?;
- let client = reqwest::Client::new();
- let response = client
- .post(format!(
- "https://api.github.com/app/installations/{installation_id}/access_tokens"
- ))
- .header("Authorization", format!("Bearer {jwt}"))
- .header("Accept", "application/vnd.github+json")
- .header("User-Agent", "Macro-Auth-Service")
- .header("X-GitHub-Api-Version", "2022-11-28")
- .send()
+ self.client
+ .generate_installation_access_token(&jwt, installation_id)
.await
- .map_err(|e| GithubError::Internal(e.into()))?;
-
- let status = response.status();
- if !status.is_success() {
- let error_body = response
- .text()
- .await
- .unwrap_or_else(|_| "unknown error".to_string());
- return Err(GithubError::Internal(anyhow::anyhow!(
- "failed to create installation access token (status {status}): {error_body}"
- )));
- }
-
- let token: GithubInstallationAccessToken = response
- .json()
- .await
- .map_err(|e| GithubError::Internal(e.into()))?;
-
- Ok(token)
}
}
}
diff --git a/rust/cloud-storage/github/src/domain/service/test.rs b/rust/cloud-storage/github/src/domain/service/test.rs
index 161e4d8b40..5e5dd51040 100644
--- a/rust/cloud-storage/github/src/domain/service/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/test.rs
@@ -1,14 +1,91 @@
-use crate::domain::{models::ValidatedGithubWebhookEvent, ports::GithubSyncService};
+use std::sync::Arc;
+
+use crate::domain::{
+ models::{GithubError, GithubInstallationAccessToken, ValidatedGithubWebhookEvent},
+ ports::{GithubSyncClient, GithubSyncService},
+};
+use documents::domain::{
+ models::{CreateDocumentRepoArgs, DocumentError, LocationQueryParams},
+ ports::DocumentService,
+};
+use entity_access::domain::models::{EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel};
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::{
+ DocumentBasic,
+ response::{CreateDocumentResponseData, GetDocumentResponseData, LocationResponseV3},
+};
use super::*;
-fn make_sync_service() -> GithubSyncServiceImpl {
- GithubSyncServiceImpl::new(GithubSyncConfig {
- webhook_secret: "test-webhook-secret".to_string(),
- github_sync_app_url: "test".to_string(),
- sync_app_pem: "test-sync-app-pem".to_string(),
- sync_app_client_id: "test-sync-app-client-id".to_string(),
- })
+struct StubDocumentService;
+
+impl DocumentService for StubDocumentService {
+ async fn internal_get_basic_document(
+ &self,
+ _document_id: &str,
+ ) -> Result<DocumentBasic, DocumentError> {
+ unimplemented!()
+ }
+ async fn get_document(
+ &self,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<GetDocumentResponseData, DocumentError> {
+ unimplemented!()
+ }
+ async fn get_document_location(
+ &self,
+ _ctx: &DocumentBasic,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ _params: LocationQueryParams,
+ ) -> Result<LocationResponseV3, DocumentError> {
+ unimplemented!()
+ }
+ async fn delete_document(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _project_id: Option<String>,
+ ) -> Result<(), DocumentError> {
+ unimplemented!()
+ }
+ async fn get_document_text(
+ &self,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<String, DocumentError> {
+ unimplemented!()
+ }
+ async fn create_document(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ _args: CreateDocumentRepoArgs,
+ _job_id: Option<String>,
+ ) -> Result<CreateDocumentResponseData, DocumentError> {
+ unimplemented!()
+ }
+}
+
+struct StubSyncClient;
+
+impl GithubSyncClient for StubSyncClient {
+ async fn generate_installation_access_token(
+ &self,
+ _jwt: &str,
+ _installation_id: u64,
+ ) -> Result<GithubInstallationAccessToken, GithubError> {
+ unimplemented!()
+ }
+}
+
+fn make_sync_service() -> GithubSyncServiceImpl<StubDocumentService, StubSyncClient> {
+ GithubSyncServiceImpl::new(
+ GithubSyncConfig {
+ webhook_secret: "test-webhook-secret".to_string(),
+ github_sync_app_url: "test".to_string(),
+ sync_app_pem: "test-sync-app-pem".to_string(),
+ sync_app_client_id: "test-sync-app-client-id".to_string(),
+ },
+ Arc::new(StubDocumentService),
+ StubSyncClient,
+ )
}
#[tokio::test]
diff --git a/rust/cloud-storage/github/src/lib.rs b/rust/cloud-storage/github/src/lib.rs
index 4265a28a91..61e630155e 100644
--- a/rust/cloud-storage/github/src/lib.rs
+++ b/rust/cloud-storage/github/src/lib.rs
@@ -11,7 +11,7 @@
#![deny(missing_docs)]
pub mod domain;
-#[cfg(feature = "outbound")]
+#[cfg(any(feature = "outbound", feature = "sync"))]
pub mod outbound;
#[cfg(feature = "inbound")]
diff --git a/rust/cloud-storage/github/src/outbound.rs b/rust/cloud-storage/github/src/outbound.rs
index 49501fa367..3450f552f6 100644
--- a/rust/cloud-storage/github/src/outbound.rs
+++ b/rust/cloud-storage/github/src/outbound.rs
@@ -4,5 +4,7 @@
pub mod github_auth_client;
#[cfg(feature = "link")]
pub mod github_oauth_client;
+#[cfg(feature = "sync")]
+pub mod github_sync_client;
#[cfg(feature = "link")]
pub mod pg_github_repo;
diff --git a/rust/cloud-storage/github/src/outbound/github_sync_client.rs b/rust/cloud-storage/github/src/outbound/github_sync_client.rs
new file mode 100644
index 0000000000..90fde1b5cb
--- /dev/null
+++ b/rust/cloud-storage/github/src/outbound/github_sync_client.rs
@@ -0,0 +1,53 @@
+//! Github Sync Client implementation of the [`GithubSyncClient`] port.
+
+use crate::domain::{
+ models::{GithubError, GithubInstallationAccessToken},
+ ports::GithubSyncClient,
+};
+
+/// Github sync client implementation backed by a reusable [`reqwest::Client`].
+#[derive(Clone, Default)]
+pub struct GithubSyncClientImpl {
+ /// The reqwest client
+ client: reqwest::Client,
+}
+
+impl GithubSyncClient for GithubSyncClientImpl {
+ #[tracing::instrument(skip(self, jwt), err)]
+ async fn generate_installation_access_token(
+ &self,
+ jwt: &str,
+ installation_id: u64,
+ ) -> Result<GithubInstallationAccessToken, GithubError> {
+ let response = self
+ .client
+ .post(format!(
+ "https://api.github.com/app/installations/{installation_id}/access_tokens"
+ ))
+ .header("Authorization", format!("Bearer {jwt}"))
+ .header("Accept", "application/vnd.github+json")
+ .header("User-Agent", "Macro-Auth-Service")
+ .header("X-GitHub-Api-Version", "2022-11-28")
+ .send()
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ let status = response.status();
+ if !status.is_success() {
+ let error_body = response
+ .text()
+ .await
+ .unwrap_or_else(|_| "unknown error".to_string());
+ return Err(GithubError::Internal(anyhow::anyhow!(
+ "failed to create installation access token (status {status}): {error_body}"
+ )));
+ }
+
+ let token: GithubInstallationAccessToken = response
+ .json()
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ Ok(token)
+ }
+}