From c2b8f54fb7a748a76731c89a745d22adfcf64d0a Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 11 Jun 2026 18:34:58 +0200 Subject: [PATCH 1/3] added ETag caching --- service/src/main/inse/main.py | 7 +++ .../src/main/inse/middleware/etag_cache.py | 52 ++++++++++++++++ webapp/src/app/app.config.ts | 3 +- .../interceptors/caching.interceptor.ts | 62 +++++++++++++++++++ 4 files changed, 123 insertions(+), 1 deletion(-) create mode 100644 service/src/main/inse/middleware/etag_cache.py create mode 100644 webapp/src/app/shared/interceptors/caching.interceptor.ts diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index a1e4614e..c7be626f 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -17,6 +17,8 @@ from inse.works.service import router as works_service_router from inse.persons.service import router as persons_service_router from inse.funders.service import router as funders_service_router +#caching +from inse.middleware.etag_cache import ETagCacheMiddleware from . import config from .service import router as service_router from .account.service import router as account_router @@ -43,12 +45,17 @@ app.include_router(funders_service_router) app.include_router(service_router) app.include_router(account_router) +app.add_middleware( + ETagCacheMiddleware, + ttl=600 # 10 minutes expiration time +) app.add_middleware( CORSMiddleware, allow_origins=settings.allowed_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], + expose_headers=["ETag"] ) diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py new file mode 100644 index 00000000..547aecb4 --- /dev/null +++ b/service/src/main/inse/middleware/etag_cache.py @@ -0,0 +1,52 @@ +# middleware/etag_cache.py +import hashlib, json, time +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import Response + +class ETagCacheMiddleware(BaseHTTPMiddleware): + def __init__(self, app, ttl: int = 60): + super().__init__(app) + self.ttl = ttl # timeout in seconds + self.cache: dict[str, dict] = {} # key → {body, etag, expires} + + def _cache_key(self, request: Request) -> str: + # Include query params and relevant headers in the key + return f"{request.url.path}?{request.url.query}" + + async def dispatch(self, request: Request, call_next): + if request.method != "GET": + return await call_next(request) + + key = self._cache_key(request) + entry = self.cache.get(key) + client_etag = request.headers.get("if-none-match") + + # Cache hit + not expired + if entry and time.time() < entry["expires"]: + if client_etag == entry["etag"]: + return Response(status_code=304, headers={"ETag": entry["etag"]}) + + # Client has stale ETag - return fresh cached body + return Response( + content=entry["body"], + media_type="application/json", + headers={"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"} + ) + + # Cache miss or expired → hit the actual route + response = await call_next(request) + body = b"".join([chunk async for chunk in response.body_iterator]) + etag = f'"{hashlib.md5(body).hexdigest()}"' + + self.cache[key] = { + "body": body, + "etag": etag, + "expires": time.time() + self.ttl + } + return Response( + content=body, + status_code=response.status_code, + media_type="application/json", + headers={"ETag": etag, "Cache-Control": f"max-age={self.ttl}"} + ) \ No newline at end of file diff --git a/webapp/src/app/app.config.ts b/webapp/src/app/app.config.ts index 7aaeef9e..596122e4 100644 --- a/webapp/src/app/app.config.ts +++ b/webapp/src/app/app.config.ts @@ -11,6 +11,7 @@ import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field'; import { MatPaginatorIntl } from '@angular/material/paginator'; import { PaginatorIntl } from './shared/utils/paginatorIntl'; import { provideEchartsCore } from 'ngx-echarts'; +import { cachingInterceptor } from './shared/interceptors/caching.interceptor'; registerLocaleData(locale); @@ -23,7 +24,7 @@ export const appConfig: ApplicationConfig = { }, { provide: MatPaginatorIntl, useClass: PaginatorIntl }, provideRouter(routes), - provideHttpClient(withInterceptors([authenticationInterceptor])), + provideHttpClient(withInterceptors([authenticationInterceptor,cachingInterceptor])), // provideApi('/inse-service'), provideAnimationsAsync(), provideEchartsCore({ echarts: () => import('echarts') }), diff --git a/webapp/src/app/shared/interceptors/caching.interceptor.ts b/webapp/src/app/shared/interceptors/caching.interceptor.ts new file mode 100644 index 00000000..4b60ec94 --- /dev/null +++ b/webapp/src/app/shared/interceptors/caching.interceptor.ts @@ -0,0 +1,62 @@ +import { + HttpInterceptorFn, + HttpResponse, + HttpErrorResponse +} from '@angular/common/http'; +import { catchError, of, tap, throwError } from 'rxjs'; +// here we do store our etags and responses from server. +const etagStore = new Map(); +const responseCache = new Map(); + +export const cachingInterceptor: HttpInterceptorFn = (req, next) => { + if (req.method !== 'GET') { + return next(req); + } + // Do we have an ETag for the corresponding request? + + const cacheKey = req.urlWithParams; + const etag = etagStore.get(cacheKey); + // If yes, set header to "If-None-Match" to let the server know we've got already an ETag. + const modifiedReq = etag + ? req.clone({ + setHeaders: { + 'If-None-Match': etag + } + }) + : req; + + // On server response: + return next(modifiedReq).pipe( + tap(event => { + if (event instanceof HttpResponse) { + const responseEtag = event.headers.get('ETag'); + // update the ETag and response body for our request + console.log("FROM NEW BACKEND CALL , UPDATING ETAG",responseEtag) + if (event.status === 200 && responseEtag) { + etagStore.set(cacheKey, responseEtag); + responseCache.set(cacheKey, event.body); + } + } + }), + // handle 304 separately (no data changes) + catchError(err => { + if ( // Server responded with 304 -> ETag hasnt changed -> use cached response body + err instanceof HttpErrorResponse && + err.status === 304 && + responseCache.has(cacheKey) + ) { + console.log("FROM CACHE!",cacheKey) + return of( + new HttpResponse({ + body: responseCache.get(cacheKey), + status: 200, + statusText: 'OK (cached)', + url: req.urlWithParams + }) + ); + } + + return throwError(() => err); + }) + ); +}; \ No newline at end of file -- 2.56.1 From 0d16159a23aa01054f9c1a46a3029a824caf58b0 Mon Sep 17 00:00:00 2001 From: genja Date: Fri, 12 Jun 2026 18:31:00 +0200 Subject: [PATCH 2/3] 5 minutes expiration time set for ETags --- service/src/main/inse/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index c7be626f..0cadf3e2 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -47,7 +47,7 @@ app.include_router(account_router) app.add_middleware( ETagCacheMiddleware, - ttl=600 # 10 minutes expiration time + ttl=300 # 5 minutes expiration time ) app.add_middleware( CORSMiddleware, -- 2.56.1 From 2b6f6bfc51fb341ea5c4366637aafdbdc6482a28 Mon Sep 17 00:00:00 2001 From: genja Date: Fri, 12 Jun 2026 18:31:29 +0200 Subject: [PATCH 3/3] removed interceptor logic, enabling browser caching only --- webapp/src/app/app.config.ts | 3 +- .../interceptors/caching.interceptor.ts | 62 ------------------- 2 files changed, 1 insertion(+), 64 deletions(-) delete mode 100644 webapp/src/app/shared/interceptors/caching.interceptor.ts diff --git a/webapp/src/app/app.config.ts b/webapp/src/app/app.config.ts index 596122e4..7aaeef9e 100644 --- a/webapp/src/app/app.config.ts +++ b/webapp/src/app/app.config.ts @@ -11,7 +11,6 @@ import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field'; import { MatPaginatorIntl } from '@angular/material/paginator'; import { PaginatorIntl } from './shared/utils/paginatorIntl'; import { provideEchartsCore } from 'ngx-echarts'; -import { cachingInterceptor } from './shared/interceptors/caching.interceptor'; registerLocaleData(locale); @@ -24,7 +23,7 @@ export const appConfig: ApplicationConfig = { }, { provide: MatPaginatorIntl, useClass: PaginatorIntl }, provideRouter(routes), - provideHttpClient(withInterceptors([authenticationInterceptor,cachingInterceptor])), + provideHttpClient(withInterceptors([authenticationInterceptor])), // provideApi('/inse-service'), provideAnimationsAsync(), provideEchartsCore({ echarts: () => import('echarts') }), diff --git a/webapp/src/app/shared/interceptors/caching.interceptor.ts b/webapp/src/app/shared/interceptors/caching.interceptor.ts deleted file mode 100644 index 4b60ec94..00000000 --- a/webapp/src/app/shared/interceptors/caching.interceptor.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { - HttpInterceptorFn, - HttpResponse, - HttpErrorResponse -} from '@angular/common/http'; -import { catchError, of, tap, throwError } from 'rxjs'; -// here we do store our etags and responses from server. -const etagStore = new Map(); -const responseCache = new Map(); - -export const cachingInterceptor: HttpInterceptorFn = (req, next) => { - if (req.method !== 'GET') { - return next(req); - } - // Do we have an ETag for the corresponding request? - - const cacheKey = req.urlWithParams; - const etag = etagStore.get(cacheKey); - // If yes, set header to "If-None-Match" to let the server know we've got already an ETag. - const modifiedReq = etag - ? req.clone({ - setHeaders: { - 'If-None-Match': etag - } - }) - : req; - - // On server response: - return next(modifiedReq).pipe( - tap(event => { - if (event instanceof HttpResponse) { - const responseEtag = event.headers.get('ETag'); - // update the ETag and response body for our request - console.log("FROM NEW BACKEND CALL , UPDATING ETAG",responseEtag) - if (event.status === 200 && responseEtag) { - etagStore.set(cacheKey, responseEtag); - responseCache.set(cacheKey, event.body); - } - } - }), - // handle 304 separately (no data changes) - catchError(err => { - if ( // Server responded with 304 -> ETag hasnt changed -> use cached response body - err instanceof HttpErrorResponse && - err.status === 304 && - responseCache.has(cacheKey) - ) { - console.log("FROM CACHE!",cacheKey) - return of( - new HttpResponse({ - body: responseCache.get(cacheKey), - status: 200, - statusText: 'OK (cached)', - url: req.urlWithParams - }) - ); - } - - return throwError(() => err); - }) - ); -}; \ No newline at end of file -- 2.56.1