Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
perf(initiatives): check project task access once per request (#8595)
teof3e27385e659
diff --git a/crates/graphql_initiative/AGENTS.md b/crates/graphql_initiative/AGENTS.mdindex 233d75a589..7d29c9ed24 100644--- a/crates/graphql_initiative/AGENTS.md+++ b/crates/graphql_initiative/AGENTS.md@@ -11,8 +11,9 @@ inbound adapter exposing initiative queries, mutations, and loaders.how resolvers reach the `initiative` domain service.- `src/query.rs` / `src/mutation.rs`: `resolve_initiative`,`InitiativeMutationRoot`.-- `src/loaders.rs`: `InitiativeSummaryLoader` / `InitiativeDetailLoader` —- batched initiative fetches for Soup and detail views.+- `src/loaders.rs`: `InitiativeLoader` — one batched initiative read per+ request for Soup and detail views. Detail and progress fields share its+ task-access walk; progress is summarized lazily from that read.- `src/lib.rs` `graphql_error`: maps `InitiativeError` to GraphQL error codes(`NOT_FOUND`, `FORBIDDEN`, `BAD_USER_INPUT`, `CONFLICT`) — follow thispattern rather than returning a bare `async_graphql::Error`.diff --git a/crates/graphql_initiative/src/context.rs b/crates/graphql_initiative/src/context.rsindex 7ffb9475c8..d8063db915 100644--- a/crates/graphql_initiative/src/context.rs+++ b/crates/graphql_initiative/src/context.rs@@ -12,7 +12,7 @@ use entity_access::domain::{use initiative::domain::{models::{CreateInitiativeRequest, InitiativeDetail, InitiativeError, UpdateInitiativeRequest},ports::InitiativeService,- reads::{InitiativePageRow, InitiativeTasksPage, InitiativeTasksRequest},+ reads::{InitiativePageRow, InitiativeRead, InitiativeTasksPage, InitiativeTasksRequest},};use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;@@ -23,8 +23,8 @@ pub(crate) type ApiFuture<'a, T> =/// Transport-facing service bundle; implementations mint receipts and delegate policy.pub(crate) trait InitiativeApi: Send + Sync {- fn summary(&self, user: MacroUserIdStr<'static>, id: Uuid) -> ApiFuture<'_, InitiativePageRow>;- fn get(&self, user: MacroUserIdStr<'static>, id: Uuid) -> ApiFuture<'_, InitiativeDetail>;+ fn read(&self, user: MacroUserIdStr<'static>, id: Uuid) -> ApiFuture<'_, InitiativeRead>;+ fn summarize<'a>(&'a self, read: &'a InitiativeRead) -> ApiFuture<'a, InitiativePageRow>;fn ensure_description_surface(&self,user: MacroUserIdStr<'static>,@@ -96,24 +96,18 @@ struct InitiativeApiAdapter<S, A> {}impl<S: InitiativeService, A: InitiativeAuthorizer> InitiativeApi for InitiativeApiAdapter<S, A> {- fn summary(&self, user: MacroUserIdStr<'static>, id: Uuid) -> ApiFuture<'_, InitiativePageRow> {+ fn read(&self, user: MacroUserIdStr<'static>, id: Uuid) -> ApiFuture<'_, InitiativeRead> {Box::pin(async move {let receipt = self.access.authorize::<ViewAccessLevel>(&user, &id.to_string(), EntityType::Initiative).await?;- self.service.summary(receipt).await+ self.service.read(receipt).await})}- fn get(&self, user: MacroUserIdStr<'static>, id: Uuid) -> ApiFuture<'_, InitiativeDetail> {- Box::pin(async move {- let receipt = self- .access- .authorize::<ViewAccessLevel>(&user, &id.to_string(), EntityType::Initiative)- .await?;- self.service.get(receipt).await- })+ fn summarize<'a>(&'a self, read: &'a InitiativeRead) -> ApiFuture<'a, InitiativePageRow> {+ Box::pin(self.service.summarize(read))}fn ensure_description_surface(diff --git a/crates/graphql_initiative/src/lib.rs b/crates/graphql_initiative/src/lib.rsindex f8ccbf2658..1e1f14490b 100644--- a/crates/graphql_initiative/src/lib.rs+++ b/crates/graphql_initiative/src/lib.rs@@ -14,8 +14,8 @@ mod test;pub use context::{InitiativeAuthorizer, InitiativeGraphqlContext};pub use inputs::InitiativeTasksInput;pub use loaders::{- InitiativeDetailLoader, InitiativeSummaryLoader, initiative_detail_loader,- initiative_summary_loader, load_initiative_detail, load_initiative_summary,+ InitiativeLoader, LoadedInitiative, initiative_loader, load_initiative_detail,+ load_initiative_summary,};pub use mutation::{InitiativeEntityLoader, InitiativeMutationRoot};pub use objects::{GraphqlInitiativeSharePermission, GraphqlInitiativeTasksPage};diff --git a/crates/graphql_initiative/src/loaders.rs b/crates/graphql_initiative/src/loaders.rsindex 35a9f4ce61..a3221b0e8e 100644--- a/crates/graphql_initiative/src/loaders.rs+++ b/crates/graphql_initiative/src/loaders.rs@@ -7,8 +7,12 @@ use async_graphql::{dataloader::{DataLoader, Loader},};use futures::{StreamExt, stream};-use initiative::domain::{models::InitiativeDetail, reads::InitiativePageRow};+use initiative::domain::{+ models::InitiativeDetail,+ reads::{InitiativePageRow, InitiativeRead},+};use macro_user_id::user_id::MacroUserIdStr;+use tokio::sync::OnceCell;use uuid::Uuid;use crate::{InitiativeGraphqlContext, graphql_error};@@ -16,41 +20,21 @@ use crate::{InitiativeGraphqlContext, graphql_error};/// Bound concurrent domain reads until the domain exposes bulk detail/summary reads.const MAX_CONCURRENT_READS: usize = 16;-/// Viewer-scoped detail reader; authorization remains in the capability bridge.-pub struct InitiativeDetailLoader {- context: InitiativeGraphqlContext,- user: MacroUserIdStr<'static>,+/// One viewer-scoped read shared by detail and progress fields, so task access is checked once.+pub struct LoadedInitiative {+ read: InitiativeRead,+ pub(crate) detail: Arc<InitiativeDetail>,+ summary: OnceCell<Arc<InitiativePageRow>>,}-impl Loader<Uuid> for InitiativeDetailLoader {- type Value = async_graphql::Result<Arc<InitiativeDetail>>;- type Error = Infallible;-- async fn load(&self, keys: &[Uuid]) -> Result<HashMap<Uuid, Self::Value>, Self::Error> {- Ok(stream::iter(keys.iter().copied().map(|id| async move {- let result = self- .context- .0- .get(self.user.clone(), id)- .await- .map(Arc::new)- .map_err(graphql_error);- (id, result)- }))- .buffer_unordered(MAX_CONCURRENT_READS)- .collect()- .await)- }-}--/// Viewer-scoped task progress reader, selected independently of project details.-pub struct InitiativeSummaryLoader {+/// Viewer-scoped initiative reader; authorization remains in the capability bridge.+pub struct InitiativeLoader {context: InitiativeGraphqlContext,user: MacroUserIdStr<'static>,}-impl Loader<Uuid> for InitiativeSummaryLoader {- type Value = async_graphql::Result<Arc<InitiativePageRow>>;+impl Loader<Uuid> for InitiativeLoader {+ type Value = async_graphql::Result<Arc<LoadedInitiative>>;type Error = Infallible;async fn load(&self, keys: &[Uuid]) -> Result<HashMap<Uuid, Self::Value>, Self::Error> {@@ -58,9 +42,15 @@ impl Loader<Uuid> for InitiativeSummaryLoader {let result = self.context.0- .summary(self.user.clone(), id)+ .read(self.user.clone(), id).await- .map(Arc::new)+ .map(|read| {+ Arc::new(LoadedInitiative {+ detail: Arc::new(read.detail().clone()),+ read,+ summary: OnceCell::new(),+ })+ }).map_err(graphql_error);(id, result)}))@@ -70,20 +60,23 @@ impl Loader<Uuid> for InitiativeSummaryLoader {}}-/// Coalesce concurrent detail fields without retaining data across mutations or subscription events.-pub fn initiative_detail_loader(+/// Coalesce concurrent initiative fields without retaining data across mutations or subscription events.+pub fn initiative_loader(context: InitiativeGraphqlContext,user: MacroUserIdStr<'static>,-) -> DataLoader<InitiativeDetailLoader> {- DataLoader::new(InitiativeDetailLoader { context, user }, tokio::spawn)+) -> DataLoader<InitiativeLoader> {+ DataLoader::new(InitiativeLoader { context, user }, tokio::spawn)}-/// Coalesce progress fields without retaining data across mutations or subscription events.-pub fn initiative_summary_loader(- context: InitiativeGraphqlContext,- user: MacroUserIdStr<'static>,-) -> DataLoader<InitiativeSummaryLoader> {- DataLoader::new(InitiativeSummaryLoader { context, user }, tokio::spawn)+async fn load_initiative(+ loader: &DataLoader<InitiativeLoader>,+ id: Uuid,+) -> async_graphql::Result<Arc<LoadedInitiative>> {+ match loader.load_one(id).await {+ Ok(Some(result)) => result,+ Ok(None) => Err(async_graphql::Error::new("initiative is unavailable")),+ Err(impossible) => match impossible {},+ }}/// Load authorized initiative details only when a detail field is requested.@@ -91,33 +84,29 @@ pub async fn load_initiative_detail(ctx: &Context<'_>,id: Uuid,) -> async_graphql::Result<Arc<InitiativeDetail>> {- match ctx- .data::<DataLoader<InitiativeDetailLoader>>()?- .load_one(id)- .await- {- Ok(Some(result)) => result,- Ok(None) => Err(async_graphql::Error::new(- "initiative detail is unavailable",- )),- Err(impossible) => match impossible {},- }+ let loader = ctx.data::<DataLoader<InitiativeLoader>>()?;+ Ok(load_initiative(loader, id).await?.detail.clone())}-/// Load permission-filtered task progress only when a count field is requested.+/// Load task progress only when a count field is requested, from the same visible tasks as detail.pub async fn load_initiative_summary(ctx: &Context<'_>,id: Uuid,) -> async_graphql::Result<Arc<InitiativePageRow>> {- match ctx- .data::<DataLoader<InitiativeSummaryLoader>>()?- .load_one(id)+ let loader = ctx.data::<DataLoader<InitiativeLoader>>()?;+ let loaded = load_initiative(loader, id).await?;+ loaded+ .summary+ .get_or_try_init(|| async {+ loader+ .loader()+ .context+ .0+ .summarize(&loaded.read)+ .await+ .map(Arc::new)+ .map_err(graphql_error)+ }).await- {- Ok(Some(result)) => result,- Ok(None) => Err(async_graphql::Error::new(- "initiative progress is unavailable",- )),- Err(impossible) => match impossible {},- }+ .cloned()}diff --git a/crates/graphql_initiative/src/test.rs b/crates/graphql_initiative/src/test.rsindex 18f3068d91..94806ed820 100644--- a/crates/graphql_initiative/src/test.rs+++ b/crates/graphql_initiative/src/test.rs@@ -1,6 +1,7 @@use crate::context::{ApiFuture, InitiativeApi};use crate::*;use async_graphql::{Context, EmptySubscription, ID, Object, Request, Schema, SimpleObject};+use entity_access::domain::models::{EntityAccessReceipt, EntityType};use graphql_common::require_authenticated_user;use graphql_soup::{GraphqlSoupInitiative, SoupEntityEdges};use initiative::domain::{models::*, reads::*};@@ -256,15 +257,22 @@ impl RecordingApi {}impl InitiativeApi for RecordingApi {- fn get(&self, user: MacroUserIdStr<'static>, id: Uuid) -> ApiFuture<'_, InitiativeDetail> {+ fn read(&self, user: MacroUserIdStr<'static>, id: Uuid) -> ApiFuture<'_, InitiativeRead> {Box::pin(async move {- self.record(&user, "get")?;+ self.record(&user, "read")?;if self.denied_ids.lock().unwrap().contains(&id) {return Err(InitiativeError::Unauthorized);}let mut detail = self.current_detail();detail.id = InitiativeId::from_uuid(id);- Ok(detail)+ Ok(InitiativeRead::new(+ EntityAccessReceipt::dangerously_assert_internal_user(+ &id.to_string(),+ EntityType::Initiative,+ ),+ detail,+ Vec::new(),+ ))})}fn ensure_description_surface(@@ -277,12 +285,9 @@ impl InitiativeApi for RecordingApi {Ok(())})}- fn summary(&self, user: MacroUserIdStr<'static>, id: Uuid) -> ApiFuture<'_, InitiativePageRow> {+ fn summarize<'a>(&'a self, _read: &'a InitiativeRead) -> ApiFuture<'a, InitiativePageRow> {Box::pin(async move {- self.record(&user, "summary")?;- if self.denied_ids.lock().unwrap().contains(&id) {- return Err(InitiativeError::Unauthorized);- }+ self.calls.lock().unwrap().push("summarize".to_string());let mut summary = row();if let Some(count) = *self.task_count.lock().unwrap() {summary.task_count = count;@@ -367,8 +372,7 @@ fn schema_with_readers(.data(context.clone()).data(replica.loader()).data(InitiativeEntityLoader(primary.loader()))- .data(initiative_detail_loader(context.clone(), user()))- .data(initiative_summary_loader(context, user()))+ .data(initiative_loader(context, user())).finish()}@@ -511,9 +515,37 @@ async fn detail_fields_load_only_when_selected_and_share_one_domain_read() {let data = response.data.into_json().unwrap();assert_eq!(data["user"]["initiative"]["taskCount"], 3);assert_eq!(data["user"]["initiative"]["completedTaskCount"], 2);- let mut calls = api.calls.lock().unwrap().clone();- calls.sort();- assert_eq!(calls, ["get", "summary"]);+ assert_eq!(*api.calls.lock().unwrap(), ["read", "summarize"]);+}++#[tokio::test]+async fn detail_only_selection_skips_progress_summary() {+ let api = Arc::new(RecordingApi::default());+ let response = schema(api.clone())+ .execute(+ Request::new(format!(+ "{{ user {{ initiative(initiativeId: \"{PROJECT_ID}\") {{ memberIds taskIds sharePermission {{ owner }} }} }} }}"+ ))+ .data(user()),+ )+ .await;+ assert!(response.errors.is_empty(), "{:?}", response.errors);+ assert_eq!(*api.calls.lock().unwrap(), ["read"]);+}++#[tokio::test]+async fn progress_only_selection_reads_once_and_summarizes_once() {+ let api = Arc::new(RecordingApi::default());+ let response = schema(api.clone())+ .execute(+ Request::new(format!(+ "{{ user {{ initiative(initiativeId: \"{PROJECT_ID}\") {{ taskCount completedTaskCount }} }} }}"+ ))+ .data(user()),+ )+ .await;+ assert!(response.errors.is_empty(), "{:?}", response.errors);+ assert_eq!(*api.calls.lock().unwrap(), ["read", "summarize"]);}#[tokio::test]@@ -539,7 +571,7 @@ async fn mutation_replies_use_primary_state_and_preserve_viewed_metadata() {assert!(replica.calls.lock().unwrap().is_empty());assert_eq!(*api.calls.lock().unwrap(),- ["update", "get", "update", "get"]+ ["update", "read", "update", "read"]);let response = schema.execute(Request::new(format!("{{ user {{ initiative(initiativeId: \"{PROJECT_ID}\") {{ displayName memberIds }} }} }}"@@ -616,15 +648,11 @@ async fn detail_loaders_isolate_viewers_failures_and_subsequent_reads() {api.denied_ids.lock().unwrap().push(hidden);let other = MacroUserIdStr::try_from_email("[email protected]").unwrap();let context = InitiativeGraphqlContext(api.clone());- let viewer_loader = initiative_detail_loader(context.clone(), user());- let other_loader = initiative_detail_loader(context.clone(), other);- let summary_loader = initiative_summary_loader(context, user());+ let viewer_loader = initiative_loader(context.clone(), user());+ let other_loader = initiative_loader(context, other);let results = viewer_loader.load_many([project, hidden]).await.unwrap();assert!(results[&project].is_ok());assert!(results[&hidden].is_err());- let summaries = summary_loader.load_many([project, hidden]).await.unwrap();- assert_eq!(summaries[&project].as_ref().unwrap().task_count, 3);- assert!(summaries[&hidden].is_err());other_loader.load_one(project).await@@ -646,13 +674,20 @@ async fn detail_loaders_isolate_viewers_failures_and_subsequent_reads() {.unwrap().unwrap().unwrap();- assert_eq!(refreshed.name, "Updated after first read");+ assert_eq!(refreshed.detail.name, "Updated after first read");++ let schema = schema(api.clone());+ let progress =+ format!("{{ user {{ initiative(initiativeId: \"{PROJECT_ID}\") {{ taskCount }} }} }}");+ let response = schema.execute(Request::new(&progress).data(user())).await;+ assert_eq!(+ response.data.into_json().unwrap()["user"]["initiative"]["taskCount"],+ 3+ );*api.task_count.lock().unwrap() = Some(4);- let refreshed_summary = summary_loader- .load_one(project)- .await- .unwrap()- .unwrap()- .unwrap();- assert_eq!(refreshed_summary.task_count, 4);+ let response = schema.execute(Request::new(&progress).data(user())).await;+ assert_eq!(+ response.data.into_json().unwrap()["user"]["initiative"]["taskCount"],+ 4+ );}diff --git a/crates/initiative/src/domain/ports.rs b/crates/initiative/src/domain/ports.rsindex f71d6d550c..152baccc9b 100644--- a/crates/initiative/src/domain/ports.rs+++ b/crates/initiative/src/domain/ports.rs@@ -1,7 +1,7 @@//! Ports (trait contracts) for the initiative domain.use super::reads::{- InitiativePage, InitiativePageRequest, InitiativePageRow, InitiativeTasksPage,+ InitiativePage, InitiativePageRequest, InitiativePageRow, InitiativeRead, InitiativeTasksPage,InitiativeTasksRequest,};use entity_access::domain::models::{@@ -117,6 +117,18 @@ pub trait InitiativeService: Send + Sync + 'static {receipt: EntityAccessReceipt<ViewAccessLevel>,) -> impl Future<Output = Result<InitiativePageRow, InitiativeError>> + Send;+ /// Load an authorized initiative, checking each associated task's access once.+ fn read(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> impl Future<Output = Result<InitiativeRead, InitiativeError>> + Send;++ /// Canonical properties and progress of an earlier read, without re-checking task access.+ fn summarize(+ &self,+ read: &InitiativeRead,+ ) -> impl Future<Output = Result<InitiativePageRow, InitiativeError>> + Send;+/// Filter, order and page the caller's discoverable initiatives.fn page(&self,diff --git a/crates/initiative/src/domain/reads.rs b/crates/initiative/src/domain/reads.rsindex 9c60ea619c..065dc71ed1 100644--- a/crates/initiative/src/domain/reads.rs+++ b/crates/initiative/src/domain/reads.rs@@ -1,6 +1,8 @@//! Project collection and task read contracts.use chrono::{DateTime, Utc};+#[cfg(feature = "ports")]+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};use models_permissions::share_permission::access_level::AccessLevel;use serde::{Deserialize, Serialize};use uuid::Uuid;@@ -98,6 +100,57 @@ pub struct InitiativePageRow {pub completed_task_count: u32,}+/// An authorized project with the tasks its viewer may see, checked once.+///+/// Progress is summarized from the retained task receipts, so detail and+/// counts share one task-access walk.+#[cfg(feature = "ports")]+#[derive(Debug, Clone)]+pub struct InitiativeRead {+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ detail: InitiativeDetail,+ task_receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,+}++#[cfg(feature = "ports")]+impl InitiativeRead {+ /// Pair a project receipt with its detail and the viewer's task receipts.+ /// The detail's `task_ids` are replaced by the receipts' entity ids.+ pub fn new(+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ mut detail: InitiativeDetail,+ task_receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,+ ) -> Self {+ detail.task_ids = task_receipts+ .iter()+ .map(|task| task.entity().entity_id.clone())+ .collect();+ Self {+ receipt,+ detail,+ task_receipts,+ }+ }++ /// Project detail with only the viewer's visible task ids.+ pub fn detail(&self) -> &InitiativeDetail {+ &self.detail+ }++ /// Take the project detail.+ pub fn into_detail(self) -> InitiativeDetail {+ self.detail+ }++ pub(crate) fn receipt(&self) -> &EntityAccessReceipt<ViewAccessLevel> {+ &self.receipt+ }++ pub(crate) fn task_receipts(&self) -> &[EntityAccessReceipt<ViewAccessLevel>] {+ &self.task_receipts+ }+}+/// One authorized project collection page.#[derive(Debug, Clone, Serialize, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/crates/initiative/src/domain/service.rs b/crates/initiative/src/domain/service.rsindex dfcfbda35a..5826998d2a 100644--- a/crates/initiative/src/domain/service.rs+++ b/crates/initiative/src/domain/service.rs@@ -33,6 +33,7 @@ use crate::domain::models::{MAX_INITIATIVE_NAME_GRAPHEMES, UpdateInitiativeRepoArgs, UpdateInitiativeRequest,};use crate::domain::ports::{InitiativeDescriptionSurfaces, InitiativeRepo, InitiativeService};+use crate::domain::reads::InitiativeRead;use crate::domain::resources::InitiativeResources;/// Concrete initiative service backed by an [`InitiativeRepo`] and the description surface@@ -133,7 +134,34 @@ where&self,receipt: EntityAccessReceipt<ViewAccessLevel>,) -> Result<crate::domain::reads::InitiativePageRow, InitiativeError> {- self.read_summary(receipt).await+ let read = self.read(receipt).await?;+ self.summarize(&read).await+ }++ #[tracing::instrument(err, skip_all)]+ async fn read(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<InitiativeRead, InitiativeError> {+ let id = initiative_id_from_receipt(&receipt)?;+ let mut detail = self+ .repo+ .get_detail(id)+ .await+ .map_err(Into::into)?+ .ok_or(InitiativeError::NotFound)?;+ detail.user_access_level = receipt_access_level(&receipt)?;+ let tasks = self+ .visible_tasks(receipt.auth(), self.resources.project_tasks(id).await?)+ .await?;+ Ok(InitiativeRead::new(receipt, detail, tasks))+ }++ async fn summarize(+ &self,+ read: &InitiativeRead,+ ) -> Result<crate::domain::reads::InitiativePageRow, InitiativeError> {+ self.read_summary(read).await}async fn page(@@ -289,18 +317,7 @@ where&self,receipt: EntityAccessReceipt<ViewAccessLevel>,) -> Result<InitiativeDetail, InitiativeError> {- let id = initiative_id_from_receipt(&receipt)?;- let mut detail = self- .repo- .get_detail(id)- .await- .map_err(Into::into)?- .ok_or(InitiativeError::NotFound)?;- detail.user_access_level = receipt_access_level(&receipt)?;- detail.task_ids = self- .visible_tasks(receipt.auth(), self.resources.project_tasks(id).await?)- .await?;- Ok(detail)+ Ok(self.read(receipt).await?.into_detail())}#[tracing::instrument(err, skip_all)]@@ -396,7 +413,10 @@ wheredetail.user_access_level = receipt_access_level(&receipt)?;detail.task_ids = self.visible_tasks(receipt.auth(), self.resources.project_tasks(id).await?)- .await?;+ .await?+ .into_iter()+ .map(|task| task.entity().entity_id.clone())+ .collect();Ok(detail)}diff --git a/crates/initiative/src/domain/service/reads.rs b/crates/initiative/src/domain/service/reads.rsindex 73c9ad1892..ff8eebcc4e 100644--- a/crates/initiative/src/domain/service/reads.rs+++ b/crates/initiative/src/domain/service/reads.rs@@ -14,7 +14,7 @@ use crate::domain::{models::{InitiativeError, InitiativeId},ports::{InitiativeDescriptionSurfaces, InitiativeRepo, InitiativeService},reads::{- InitiativePage, InitiativePageRequest, InitiativePageRow, InitiativeSort,+ InitiativePage, InitiativePageRequest, InitiativePageRow, InitiativeRead, InitiativeSort,InitiativeTasksPage, InitiativeTasksRequest, MAX_CURSOR_LENGTH, page_size as limit,},};@@ -138,30 +138,21 @@ fn order(left: &Position, right: &Position, sort: InitiativeSort, descending: boimpl<R: InitiativeRepo, S: InitiativeDescriptionSurfaces> InitiativeServiceImpl<R, S> {pub(super) async fn read_summary(&self,- receipt: EntityAccessReceipt<ViewAccessLevel>,+ read: &InitiativeRead,) -> Result<InitiativePageRow, InitiativeError> {- let detail = self.get(receipt.clone()).await?;- let mut receipts = vec![receipt.clone()];- for task_id in &detail.task_ids {- if let Some(task_receipt) = self- .resources- .view(- receipt.auth().clone(),- Entity {- entity_id: task_id.clone(),- entity_type: EntityType::Document,- },- )- .await?- {- receipts.push(task_receipt);- }- }- let mut properties = self.resources.properties(receipts.clone()).await?;- let task_count = receipts.len().saturating_sub(1);- let completed_task_count = receipts+ let detail = read.detail();+ let tasks = read.task_receipts();+ let mut properties = self+ .resources+ .properties(+ std::iter::once(read.receipt())+ .chain(tasks)+ .cloned()+ .collect(),+ )+ .await?;+ let completed_task_count = tasks.iter()- .skip(1).filter(|task| {properties.get(&task.entity().entity_id)@@ -171,14 +162,14 @@ impl<R: InitiativeRepo, S: InitiativeDescriptionSurfaces> InitiativeServiceImpl<Ok(InitiativePageRow {initiative: crate::domain::models::InitiativeSummary {id: detail.id,- name: detail.name,+ name: detail.name.clone(),updated_at: detail.updated_at,},user_access_level: detail.user_access_level,properties: properties.remove(&detail.id.to_string()).unwrap_or_default(),- task_count: u32::try_from(task_count).unwrap_or(u32::MAX),+ task_count: u32::try_from(tasks.len()).unwrap_or(u32::MAX),completed_task_count: u32::try_from(completed_task_count).unwrap_or(u32::MAX),})}@@ -187,22 +178,21 @@ impl<R: InitiativeRepo, S: InitiativeDescriptionSurfaces> InitiativeServiceImpl<&self,auth: &EntityAccessAuth,ids: Vec<String>,- ) -> Result<Vec<String>, InitiativeError> {+ ) -> Result<Vec<EntityAccessReceipt<ViewAccessLevel>>, InitiativeError> {let mut visible = Vec::new();for id in ids {- if self+ if let Some(receipt) = self.resources.view(auth.clone(),Entity {- entity_id: id.clone(),+ entity_id: id,entity_type: EntityType::Document,},).await?- .is_some(){- visible.push(id);+ visible.push(receipt);}}Ok(visible)diff --git a/crates/initiative/src/domain/service/test/reads.rs b/crates/initiative/src/domain/service/test/reads.rsindex 67ab0d464c..4611f6f000 100644--- a/crates/initiative/src/domain/service/test/reads.rs+++ b/crates/initiative/src/domain/service/test/reads.rs@@ -6,7 +6,7 @@ use crate::domain::{use entity_access::domain::models::{Entity, EntityAccessAuth};use std::{collections::{HashMap, HashSet},- sync::Arc,+ sync::{Arc, Mutex},};#[derive(Debug, Default)]@@ -16,6 +16,10 @@ pub(super) struct FakeResources {tasks: Vec<String>,values: HashMap<String, InitiativePropertySnapshot>,fail_initialization: bool,+ /// Every entity id passed to `view`, in call order.+ checked: Arc<Mutex<Vec<String>>>,+ /// Every entity id whose receipt reached `properties`, in call order.+ read_properties: Arc<Mutex<Vec<String>>>,}impl InitiativeResources for FakeResources {@@ -50,6 +54,7 @@ impl InitiativeResources for FakeResources {entity: Entity,) -> ResourceFuture<'_, Option<EntityAccessReceipt<ViewAccessLevel>>> {Box::pin(async move {+ self.checked.lock().unwrap().push(entity.entity_id.clone());if self.denied.contains(&entity.entity_id) {return Ok(None);}@@ -67,8 +72,13 @@ impl InitiativeResources for FakeResources {}fn properties(&self,- _receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,+ receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,) -> ResourceFuture<'_, HashMap<String, InitiativePropertySnapshot>> {+ self.read_properties.lock().unwrap().extend(+ receipts+ .into_iter()+ .map(|receipt| receipt.entity().entity_id.clone()),+ );Box::pin(async { Ok(self.values.clone()) })}}@@ -97,6 +107,7 @@ async fn single_summary_counts_only_visible_tasks_and_uses_canonical_properties(.return_once(|_| Box::pin(async { Ok(Some(detail(Vec::new()))) }));let status = uuid::Uuid::from_u128(50);let project_id = detail(Vec::new()).id.to_string();+ let checked = Arc::<Mutex<Vec<String>>>::default();let svc = service_with_resources(repo,FakeResources {@@ -125,6 +136,7 @@ async fn single_summary_counts_only_visible_tasks_and_uses_canonical_properties(},),]),+ checked: checked.clone(),..Default::default()},);@@ -132,6 +144,81 @@ async fn single_summary_counts_only_visible_tasks_and_uses_canonical_properties(assert_eq!(summary.task_count, 2);assert_eq!(summary.completed_task_count, 1);assert_eq!(summary.properties.status, Some(status));+ assert_eq!(*checked.lock().unwrap(), ["open", "done", "hidden"]);+}++fn mixed_permission_tasks() -> FakeResources {+ let completed = InitiativePropertySnapshot {+ completed: true,+ ..Default::default()+ };+ FakeResources {+ denied: HashSet::from(["hidden-done".into(), "hidden-open".into()]),+ tasks: vec![+ "hidden-done".into(),+ "open".into(),+ "done".into(),+ "hidden-open".into(),+ "done-too".into(),+ ],+ values: HashMap::from([+ ("hidden-done".into(), completed.clone()),+ ("done".into(), completed.clone()),+ ("done-too".into(), completed),+ ]),+ ..Default::default()+ }+}++#[tokio::test]+async fn summarized_read_counts_exactly_the_visible_task_set_after_one_access_check_each() {+ let mut repo = MockInitiativeRepo::new();+ repo.expect_get_detail()+ .times(1)+ .return_once(|_| Box::pin(async { Ok(Some(detail(Vec::new()))) }));+ let resources = mixed_permission_tasks();+ let checked = resources.checked.clone();+ let read_properties = resources.read_properties.clone();+ let svc = service_with_resources(repo, resources);++ let read = svc.read(view_receipt()).await.unwrap();+ let summary = svc.summarize(&read).await.unwrap();++ let visible = &read.detail().task_ids;+ assert_eq!(visible, &["open", "done", "done-too"]);+ assert_eq!(summary.task_count as usize, visible.len());+ assert_eq!(summary.completed_task_count, 2);+ assert_eq!(+ *checked.lock().unwrap(),+ ["hidden-done", "open", "done", "hidden-open", "done-too"],+ "each associated task is checked exactly once"+ );+ let project_id = detail(Vec::new()).id.to_string();+ assert_eq!(+ *read_properties.lock().unwrap(),+ [project_id.as_str(), "open", "done", "done-too"],+ "properties are read only through the project and visible task receipts"+ );+}++#[tokio::test]+async fn summarized_read_with_no_visible_tasks_reports_zero_progress() {+ let mut repo = MockInitiativeRepo::new();+ repo.expect_get_detail()+ .times(1)+ .return_once(|_| Box::pin(async { Ok(Some(detail(Vec::new()))) }));+ let mut resources = mixed_permission_tasks();+ resources+ .denied+ .extend(["open".into(), "done".into(), "done-too".into()]);+ let svc = service_with_resources(repo, resources);++ let read = svc.read(view_receipt()).await.unwrap();+ let summary = svc.summarize(&read).await.unwrap();++ assert!(read.detail().task_ids.is_empty());+ assert_eq!(summary.task_count, 0);+ assert_eq!(summary.completed_task_count, 0);}#[tokio::test]diff --git a/crates/initiative/src/inbound/axum_router/test.rs b/crates/initiative/src/inbound/axum_router/test.rsindex 57c9d199f0..71d9e0ee92 100644--- a/crates/initiative/src/inbound/axum_router/test.rs+++ b/crates/initiative/src/inbound/axum_router/test.rs@@ -299,6 +299,20 @@ impl InitiativeService for FakeInitiativeService {Err(InitiativeError::NotFound)}+ async fn read(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<crate::domain::reads::InitiativeRead, InitiativeError> {+ Err(InitiativeError::NotFound)+ }++ async fn summarize(+ &self,+ _read: &crate::domain::reads::InitiativeRead,+ ) -> Result<crate::domain::reads::InitiativePageRow, InitiativeError> {+ Err(InitiativeError::NotFound)+ }+async fn create_attributed(&self,user_id: &MacroUserIdStr<'_>,diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rsindex 4d67b35464..98596fb088 100644--- a/services/document_storage_service/src/api/graphql_soup.rs+++ b/services/document_storage_service/src/api/graphql_soup.rs@@ -167,11 +167,7 @@ fn insert_graphql_context_data(data.insert(state.graphql_initiative_entity_loader.clone());data.insert(state.graphql_agent_session_entity_loader.clone());data.insert(state.graphql_primary_soup_item_loader.clone());- data.insert(graphql_initiative::initiative_detail_loader(- state.graphql_initiative_context.clone(),- macro_user_id.clone(),- ));- data.insert(graphql_initiative::initiative_summary_loader(+ data.insert(graphql_initiative::initiative_loader(state.graphql_initiative_context.clone(),macro_user_id.clone(),));