Skip to content

Commit

Permalink
refactor: cache core details in the database
Browse files Browse the repository at this point in the history
  • Loading branch information
IgnisDa committed Dec 15, 2024
1 parent ead24c6 commit 5230642
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 31 deletions.
15 changes: 6 additions & 9 deletions apps/frontend/app/lib/utilities.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,13 +174,10 @@ export const getDecodedJwt = (request: Request) => {
}>(token);
};

export const getCachedCoreDetails = async () => {
return await queryClient.ensureQueryData({
queryKey: queryFactory.miscellaneous.coreDetails().queryKey,
staleTime: dayjsLib.duration({ minutes: 5 }).asMilliseconds(),
queryFn: () =>
serverGqlService.request(CoreDetailsDocument).then((d) => d.coreDetails),
});
export const getCoreDetails = async () => {
return await serverGqlService
.request(CoreDetailsDocument)
.then((d) => d.coreDetails);
};

const getCachedUserDetails = async (request: Request) => {
Expand Down Expand Up @@ -353,7 +350,7 @@ export const getCookiesForApplication = async (
token: string,
tokenValidForDays?: number,
) => {
const [coreDetails] = await Promise.all([getCachedCoreDetails()]);
const [coreDetails] = await Promise.all([getCoreDetails()]);
const maxAge =
(tokenValidForDays || coreDetails.tokenValidForDays) * 24 * 60 * 60;
const options = { maxAge, path: "/" } satisfies SerializeOptions;
Expand Down Expand Up @@ -400,7 +397,7 @@ export const redirectToFirstPageIfOnInvalidPage = async (
totalResults: number,
currentPage: number,
) => {
const coreDetails = await getCachedCoreDetails();
const coreDetails = await getCoreDetails();
const { searchParams } = new URL(request.url);
const totalPages = Math.ceil(totalResults / coreDetails.pageSize);
if (currentPage > totalPages && currentPage !== 1) {
Expand Down
4 changes: 2 additions & 2 deletions apps/frontend/app/routes/_dashboard.media.$action.$lot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ import {
useMetadataProgressUpdate,
} from "~/lib/state/media";
import {
getCachedCoreDetails,
getCoreDetails,
getEnhancedCookieName,
redirectToFirstPageIfOnInvalidPage,
redirectUsingEnhancedCookieSearchParams,
Expand Down Expand Up @@ -153,7 +153,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
] as const;
})
.with(Action.Search, async () => {
const coreDetails = await getCachedCoreDetails();
const coreDetails = await getCoreDetails();
const metadataSourcesForLot = coreDetails.metadataLotSourceMappings.find(
(m) => m.lot === lot,
);
Expand Down
4 changes: 2 additions & 2 deletions apps/frontend/app/routes/_dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,10 @@ import {
useReviewEntity,
} from "~/lib/state/media";
import {
getCachedCoreDetails,
getCachedUserCollectionsList,
getCachedUserPreferences,
getCookieValue,
getCoreDetails,
getDecodedJwt,
redirectIfNotAuthenticatedOrUpdated,
} from "~/lib/utilities.server";
Expand All @@ -164,7 +164,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
const [userPreferences, userCollections, coreDetails] = await Promise.all([
getCachedUserPreferences(request),
getCachedUserCollectionsList(request),
getCachedCoreDetails(),
getCoreDetails(),
]);
const desktopSidebarCollapsed = getCookieValue(
request,
Expand Down
4 changes: 2 additions & 2 deletions apps/frontend/app/routes/api.auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import { $path } from "remix-routes";
import { z } from "zod";
import { zx } from "zodix";
import {
getCachedCoreDetails,
getCookiesForApplication,
getCoreDetails,
redirectWithToast,
serverGqlService,
} from "~/lib/utilities.server";
Expand Down Expand Up @@ -49,7 +49,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
type: "error",
});
}
await getCachedCoreDetails();
await getCoreDetails();
const { loginUser } = await serverGqlService.request(LoginUserDocument, {
input: { oidc: oidcInput },
});
Expand Down
4 changes: 2 additions & 2 deletions apps/frontend/app/routes/auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ import { dayjsLib, redirectToQueryParam } from "~/lib/generals";
import {
createToastHeaders,
getAuthorizationCookie,
getCachedCoreDetails,
getCookiesForApplication,
getCoreDetails,
redirectWithToast,
serverGqlService,
} from "~/lib/utilities.server";
Expand Down Expand Up @@ -68,7 +68,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
},
);
}
const [coreDetails] = await Promise.all([getCachedCoreDetails()]);
const [coreDetails] = await Promise.all([getCoreDetails()]);
return {
intent: query.intent || "login",
oidcEnabled: coreDetails.oidcEnabled,
Expand Down
6 changes: 3 additions & 3 deletions crates/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,16 +279,16 @@ impl IsFeatureEnabled for FileStorageConfig {

/// The configuration related to Umami analytics. More information
/// [here](https://umami.is/docs/tracker-configuration).
#[derive(Debug, Serialize, Deserialize, Clone, Config, SimpleObject)]
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone, Config, SimpleObject)]
#[config(rename_all = "snake_case", env_prefix = "FRONTEND_UMAMI_")]
pub struct FrontendUmamiConfig {
pub domains: String,
/// For example: https://umami.is/script.js.
pub script_url: String,
pub website_id: String,
pub domains: String,
}

#[derive(Debug, Serialize, Deserialize, Clone, Config, SimpleObject)]
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone, Config, SimpleObject)]
#[config(rename_all = "snake_case", env_prefix = "FRONTEND_")]
pub struct FrontendConfig {
/// Used as the base URL when generating item links for the frontend.
Expand Down
1 change: 1 addition & 0 deletions crates/models/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@ pub struct ProgressUpdateCacheInput {
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, FromJsonQueryResult, Eq, Serialize, Deserialize)]
pub enum ApplicationCacheKey {
CoreDetails,
IgdbSettings,
TmdbSettings,
ServerKeyValidated,
Expand Down
17 changes: 9 additions & 8 deletions crates/models/dependent/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,46 +159,46 @@ pub struct MetadataBaseData {
pub creators: Vec<MetadataCreatorGroupedByRole>,
}

#[derive(Debug, Serialize, Deserialize, SimpleObject, Clone)]
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, SimpleObject, Clone)]
pub struct ExerciseParametersLotMapping {
pub lot: ExerciseLot,
pub bests: Vec<WorkoutSetPersonalBest>,
}

#[derive(Debug, Serialize, Deserialize, SimpleObject, Clone)]
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, SimpleObject, Clone)]
pub struct ExerciseFilters {
#[graphql(name = "type")]
pub lot: Vec<ExerciseLot>,
pub level: Vec<ExerciseLevel>,
pub force: Vec<ExerciseForce>,
pub muscle: Vec<ExerciseMuscle>,
pub mechanic: Vec<ExerciseMechanic>,
pub equipment: Vec<ExerciseEquipment>,
pub muscle: Vec<ExerciseMuscle>,
}

#[derive(Debug, Serialize, Deserialize, SimpleObject, Clone)]
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, SimpleObject, Clone)]
pub struct ExerciseParameters {
pub download_required: bool,
/// All filters applicable to an exercises query.
pub filters: ExerciseFilters,
pub download_required: bool,
/// Exercise type mapped to the personal bests possible.
pub lot_mapping: Vec<ExerciseParametersLotMapping>,
}

#[derive(Debug, SimpleObject, Serialize, Deserialize)]
#[derive(PartialEq, Eq, Debug, SimpleObject, Serialize, Deserialize, Clone)]
pub struct ProviderLanguageInformation {
pub source: MediaSource,
pub supported: Vec<String>,
pub default: String,
}

#[derive(Debug, SimpleObject, Serialize, Deserialize)]
#[derive(PartialEq, Eq, Debug, SimpleObject, Serialize, Deserialize, Clone)]
pub struct MetadataLotSourceMappings {
pub lot: MediaLot,
pub sources: Vec<MediaSource>,
}

#[derive(Debug, SimpleObject, Serialize, Deserialize)]
#[derive(PartialEq, Eq, Clone, Debug, SimpleObject, Serialize, Deserialize)]
pub struct CoreDetails {
pub page_size: i32,
pub version: String,
Expand Down Expand Up @@ -430,6 +430,7 @@ pub type MetadataGroupSearchResponse = SearchResults<MetadataGroupSearchItem>;
#[derive(Clone, Debug, PartialEq, FromJsonQueryResult, Serialize, Deserialize, Eq)]
pub enum ApplicationCacheValue {
Empty(EmptyCacheValue),
CoreDetails(CoreDetails),
TmdbSettings(TmdbSettings),
IgdbSettings(IgdbSettings),
UserAnalytics(UserAnalytics),
Expand Down
3 changes: 2 additions & 1 deletion crates/services/cache/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ impl CacheService {
| ApplicationCacheKey::ServerKeyValidated
| ApplicationCacheKey::TmdbSettings => None,

ApplicationCacheKey::MetadataRecentlyConsumed { .. }
ApplicationCacheKey::CoreDetails
| ApplicationCacheKey::MetadataRecentlyConsumed { .. }
| ApplicationCacheKey::MetadataSearch { .. }
| ApplicationCacheKey::PeopleSearch { .. }
| ApplicationCacheKey::MetadataGroupSearch { .. } => Some(1),
Expand Down
20 changes: 18 additions & 2 deletions crates/services/miscellaneous/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,12 +252,20 @@ ORDER BY RANDOM() LIMIT 10;
}

pub async fn core_details(&self) -> Result<CoreDetails> {
if let Some(cached) = self
.0
.cache_service
.get_value(ApplicationCacheKey::CoreDetails)
.await?
{
return Ok(cached);
}
let mut files_enabled = self.0.config.file_storage.is_enabled();
if files_enabled && !self.0.file_storage_service.is_enabled().await {
files_enabled = false;
}
let download_required = Exercise::find().count(&self.0.db).await? == 0;
Ok(CoreDetails {
let core_details = CoreDetails {
page_size: PAGE_SIZE,
version: APP_VERSION.to_owned(),
file_storage_enabled: files_enabled,
Expand Down Expand Up @@ -357,7 +365,15 @@ ORDER BY RANDOM() LIMIT 10;
}
})
.collect(),
})
};
self.0
.cache_service
.set_key(
ApplicationCacheKey::CoreDetails,
ApplicationCacheValue::CoreDetails(core_details.clone()),
)
.await?;
Ok(core_details)
}

async fn metadata_assets(&self, meta: &metadata::Model) -> Result<GraphqlMediaAssets> {
Expand Down

0 comments on commit 5230642

Please sign in to comment.