use crate::cache::Cache;
use crate::cached::{Cached, Keyed};
use crate::channels::{GatherReferencedByRequested, GatherRequested, GatherResourceRequested};
use crate::client::Links;
use crate::errors::SemiontError;
use crate::running::Running;
use crate::state_unit::StateUnit;
use crate::types::{AnnotationId, ResourceId};
use crate::types::{
GatherAnnotationComplete, GatherAnnotationOptions, GatherAnnotationRequest,
GatherReferencedByRequest, GatherResourceRequest, GatherResourceRequestOptions,
GatheredContext, GetReferencedByResponseReferencedByItem,
};
pub(super) type ReferencedBy = GetReferencedByResponseReferencedByItem;
const CONTEXT_WINDOW: u16 = 2000;
impl Default for GatherResourceRequestOptions {
fn default() -> GatherResourceRequestOptions {
GatherResourceRequestOptions {
depth: 2,
max_resources: 10,
include_content: true,
include_summary: false,
exclude_entity_types: None,
}
}
}
impl Default for GatherAnnotationOptions {
fn default() -> GatherAnnotationOptions {
GatherAnnotationOptions {
include_source_context: None,
include_target_context: None,
context_window: None,
}
}
}
pub struct GatherNamespace {
links: Links,
pub(super) referenced_by: Cache<ResourceId, Vec<ReferencedBy>>,
}
impl GatherNamespace {
pub(crate) fn new(links: Links) -> GatherNamespace {
let referenced_by = Cache::new({
let links = links.clone();
move |resource_id: ResourceId| {
let links = links.clone();
async move {
let answer = links
.request::<GatherReferencedByRequested>(&GatherReferencedByRequest {
resource_id,
motivation: None,
})
.await?;
Ok(answer.response.referenced_by)
}
}
});
GatherNamespace {
links,
referenced_by,
}
}
pub(crate) fn dispose(&self) {
self.referenced_by.dispose();
}
pub fn referenced_by(
&self,
resource_id: &ResourceId,
) -> Cached<Vec<GetReferencedByResponseReferencedByItem>> {
Cached::of(Keyed {
cache: self.referenced_by.clone(),
key: resource_id.clone(),
view: |value| value,
scope: Some((self.links.transport.clone(), resource_id.clone())),
})
}
pub fn annotation(
&self,
resource_id: &ResourceId,
annotation_id: &AnnotationId,
options: GatherAnnotationOptions,
) -> Running<GatherAnnotationComplete> {
let links = self.links.clone();
let request = GatherAnnotationRequest {
annotation_id: annotation_id.clone(),
resource_id: resource_id.clone(),
options: Some(GatherAnnotationOptions {
context_window: Some(options.context_window.unwrap_or(CONTEXT_WINDOW)),
..options
}),
};
Running::new(|_| async move { links.request::<GatherRequested>(&request).await })
}
pub async fn resource(
&self,
resource_id: &ResourceId,
mut options: GatherResourceRequestOptions,
) -> Result<GatheredContext, SemiontError> {
if options
.exclude_entity_types
.as_ref()
.is_some_and(Vec::is_empty)
{
options.exclude_entity_types = None;
}
let gathered = self
.links
.request::<GatherResourceRequested>(&GatherResourceRequest {
resource_id: resource_id.clone(),
options,
})
.await?;
Ok(gathered.response)
}
}
impl Drop for GatherNamespace {
fn drop(&mut self) {
self.dispose();
}
}