pib-client-cached 0.28.0

API client for pib-service - caching data storage
Documentation
// SPDX-FileCopyrightText: Politik im Blick developers
// SPDX-FileCopyrightText: Wolfgang Silbermayr <wolfgang@silbermayr.at>
//
// SPDX-License-Identifier: AGPL-3.0-or-later OR EUPL-1.2

use cachekit::prelude::{CacheBuilder, DynCache};
use pib_client::PibClient;
use pib_service_api_types::{Pagination, Search};
use pib_service_core_types::{DataItem, DataPage, DataPagePagination, Entity};
use std::{hash::Hash, marker::PhantomData};

use crate::{CACHE_POLICY, CACHE_SIZE, ClearableCache, ItemCache, PageableItem, item::GetableItem};

type PageKey<T> = (T, Pagination);
type Page<ID> = (DataPagePagination, Vec<ID>);

#[derive(Debug)]
pub(super) struct PageIndexCache<
    PARENTID: Copy + Ord + Hash,
    ID: std::fmt::Debug + Copy + Ord + Hash,
    T: Entity<PARENTID, ID> + std::fmt::Debug + Clone,
> {
    pages: DynCache<PageKey<PARENTID>, Page<ID>>,
    _phantom_id: PhantomData<ID>,
    _phantom_t: PhantomData<T>,
}

impl<
    PARENTID: Copy + Ord + Hash,
    ID: std::fmt::Debug + Copy + Ord + Hash,
    T: Entity<PARENTID, ID> + std::fmt::Debug + Clone,
> PageIndexCache<PARENTID, ID, T>
{
    pub fn new() -> Self {
        let pages = CacheBuilder::new(CACHE_SIZE).build(CACHE_POLICY);

        Self {
            pages,
            _phantom_id: PhantomData,
            _phantom_t: PhantomData,
        }
    }

    pub fn clear(&mut self) {
        self.pages.clear()
    }
}

impl<
    PARENTID: std::fmt::Debug + Copy + Ord + Hash,
    ID: std::fmt::Debug + Copy + Ord + Hash,
    T: PageableItem<PARENTID, ID, T>
        + GetableItem<PARENTID, ID, T>
        + Entity<PARENTID, ID>
        + std::fmt::Debug
        + Clone,
> PageIndexCache<PARENTID, ID, T>
{
    pub async fn get_page<C: PibClient, ITEMCACHEPARENTID>(
        &mut self,
        client: &C,
        item_cache: &mut ItemCache<ITEMCACHEPARENTID, ID, T>,
        parent_id: PARENTID,
        mut pagination: Pagination,
        search: Search,
    ) -> Result<DataPage<PARENTID, ID, T>, C::ClientError>
    where
        ITEMCACHEPARENTID: From<PARENTID> + std::fmt::Debug + Copy + Ord + Hash,
        T: Entity<ITEMCACHEPARENTID, ID>
            + PageableItem<ITEMCACHEPARENTID, ID, T>
            + GetableItem<ITEMCACHEPARENTID, ID, T>,
    {
        let use_cache = search.is_default();
        if pagination.page.is_none() {
            pagination.page = Some(0usize.into());
        }
        if use_cache
            && let Some((pagination, ids)) = self.pages.get(&(parent_id, pagination)).cloned()
        {
            let mut data = Vec::new();
            for id in ids {
                let item = item_cache
                    .get(client, ITEMCACHEPARENTID::from(parent_id), id)
                    .await?;
                data.push(DataItem {
                    id: item.id,
                    parent_id,
                    metadata: item.metadata,
                    value: item.value,
                });
            }
            return Ok(DataPage { data, pagination });
        }

        let page = T::get_page(client, parent_id, pagination, search).await?;

        let ids = page
            .data
            .iter()
            .map(|item| {
                let cache_item = DataItem {
                    id: item.id,
                    parent_id: ITEMCACHEPARENTID::from(item.parent_id),
                    metadata: item.metadata.clone(),
                    value: item.value.clone(),
                };
                item_cache.insert(cache_item);
                item.id
            })
            .collect();
        if use_cache {
            self.pages
                .insert((parent_id, pagination), (page.pagination.clone(), ids));
        }
        Ok(page)
    }
}

impl<
    PARENTID: std::fmt::Debug + Copy + Ord + std::hash::Hash,
    ID: std::fmt::Debug + Copy + Ord + std::hash::Hash,
    T: Entity<PARENTID, ID> + std::fmt::Debug + Clone,
> ClearableCache for PageIndexCache<PARENTID, ID, T>
{
    fn clear_cache(&mut self) {
        self.clear();
    }
}