From 17b2277d6ed606996a02030c5d291b22656988a5 Mon Sep 17 00:00:00 2001 From: bram-atmire Date: Tue, 17 Nov 2026 18:45:52 +0100 Subject: [PATCH] Share anonymous feature IDs between checks on the same object Since 6f52262129, each anonymous feature check rebuilt the unfiltered authorization search and resolved every embedded feature again, even when another check on the same object had already done so. On an item page with many bitstreams this repeated work for every feature checked on every bitstream, making server-side rendering and hydration slower than before #6257. Restore the per-object shared lookup from 3a45c31e9f in a commented form: all checks on an object reuse one observable of granted feature IDs until it expires with the underlying response or the authorization cache is invalidated. Failed lookups are dropped so the next check retries them, and expired entries are pruned. Assisted-by: Claude Code [claude-opus-5-5] --- .../authorization-data.service.spec.ts | 69 ++++++++++++++++-- .../authorization-data.service.ts | 70 +++++++++++++++++-- 2 files changed, 128 insertions(+), 11 deletions(-) diff --git a/src/app/core/data/feature-authorization/authorization-data.service.spec.ts b/src/app/core/data/feature-authorization/authorization-data.service.spec.ts index 615f2d71050..5a4b7de55a2 100644 --- a/src/app/core/data/feature-authorization/authorization-data.service.spec.ts +++ b/src/app/core/data/feature-authorization/authorization-data.service.spec.ts @@ -1,7 +1,11 @@ -import { hasValue } from '@dspace/shared/utils/empty.util'; +import { + hasNoValue, + hasValue, +} from '@dspace/shared/utils/empty.util'; import { BehaviorSubject, combineLatest as observableCombineLatest, + defer, Observable, of, throwError, @@ -259,12 +263,69 @@ describe('AuthorizationDataService', () => { service.isAuthorized(featureID, 'item-url').subscribe((value) => results.push(value)); service.isAuthorized(FeatureID.CanCreateVersion, 'item-url').subscribe((value) => results.push(value)); expect(results).toEqual([true, false]); - // Identical unfiltered searches, which the request cache serves with a single request - expect(search.calls.count()).toBe(2); - expect(search.calls.argsFor(0)).toEqual(search.calls.argsFor(1)); + expect(search.calls.count()).toBe(1); expect(search).toHaveBeenCalledWith(undefined, 'item-url', undefined, { elementsPerPage: 100 }, true, true, jasmine.anything()); }); + it('should resolve the embedded features once for all checks on the same object', () => { + let resolutions = 0; + const grant = Object.assign(new Authorization(), { + feature: defer(() => { + resolutions++; + return createSuccessfulRemoteDataObject$(Object.assign(new Feature(), { id: featureID })); + }), + }); + search.and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList([grant]))); + service.isAuthorized(FeatureID.CanDownload, 'bitstream-url').subscribe(); + service.isAuthorized(FeatureID.CanRequestACopy, 'bitstream-url').subscribe(); + service.isAuthorized(featureID, 'bitstream-url').subscribe((value) => expect(value).toBeTrue()); + expect(search.calls.count()).withContext('searches').toBe(1); + expect(resolutions).withContext('feature resolutions').toBe(1); + }); + + it('should search separately for different objects', () => { + service.isAuthorized(featureID, 'item-url').subscribe(); + service.isAuthorized(featureID, 'other-url').subscribe(); + expect(search.calls.count()).toBe(2); + }); + + it('should search again after the authorizations are invalidated', () => { + service.isAuthorized(featureID, 'item-url').subscribe(); + service.invalidateAuthorizationsRequestCache(); + service.isAuthorized(featureID, 'item-url').subscribe(); + expect(search.calls.count()).toBe(2); + }); + + it('should search again once the shared result has expired', () => { + jasmine.clock().install(); + try { + jasmine.clock().mockDate(new Date(2026, 0, 1)); + service.isAuthorized(featureID, 'item-url').subscribe(); + jasmine.clock().tick(15 * 60 * 1000 + 1); + service.isAuthorized(featureID, 'item-url').subscribe(); + expect(search.calls.count()).toBe(2); + } finally { + jasmine.clock().uninstall(); + } + }); + + it('should not reuse a shared result when the cached version must be bypassed', () => { + service.isAuthorized(featureID, 'item-url').subscribe(); + service.isAuthorized(featureID, 'item-url', undefined, false).subscribe(); + expect(search.calls.count()).toBe(2); + }); + + it('should retry a failed batch on the next check instead of replaying the error', () => { + search.and.callFake((feature) => feature + ? createSuccessfulRemoteDataObject$(createPaginatedList(validPayload)) + : createFailedRemoteDataObject$('Batch failed', 500)); + service.isAuthorized(featureID, 'item-url').subscribe((value) => expect(value).toBeTrue()); + search.and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(validPayload))); + service.isAuthorized(featureID, 'item-url').subscribe((value) => expect(value).toBeTrue()); + const unfiltered = search.calls.allArgs().filter((args) => hasNoValue(args[0])); + expect(unfiltered.length).toBe(2); + }); + it('should resolve the site URL for checks without an object', () => { service.isAuthorized(featureID).subscribe((value) => expect(value).toBeTrue()); expect(search).toHaveBeenCalledWith(undefined, site.self, undefined, { elementsPerPage: 100 }, true, true, jasmine.anything()); diff --git a/src/app/core/data/feature-authorization/authorization-data.service.ts b/src/app/core/data/feature-authorization/authorization-data.service.ts index ea23d81b275..4c86557c1de 100644 --- a/src/app/core/data/feature-authorization/authorization-data.service.ts +++ b/src/app/core/data/feature-authorization/authorization-data.service.ts @@ -10,6 +10,7 @@ import { EMPTY, Observable, of, + throwError, } from 'rxjs'; import { catchError, @@ -17,6 +18,7 @@ import { filter, map, reduce, + shareReplay, switchMap, take, } from 'rxjs/operators'; @@ -63,6 +65,14 @@ export class AuthorizationDataService extends BaseDataService imp private searchData: SearchDataImpl; + /** + * The IDs of the features granted anonymously on an object, keyed by object URL and + * re-request setting. A page checks several features on the same object (e.g. two per + * bitstream on an item page); each entry lets all of those checks share one search and one + * resolution of the embedded features, instead of repeating that work for every feature. + */ + private anonymousFeatureIds = new Map> }>(); + constructor( protected requestService: RequestService, protected rdbService: RemoteDataBuildService, @@ -80,6 +90,7 @@ export class AuthorizationDataService extends BaseDataService imp * Set all authorization requests to stale */ invalidateAuthorizationsRequestCache() { + this.anonymousFeatureIds.clear(); this.requestService.setStaleByHrefSubstring(this.linkPath); } @@ -111,9 +122,8 @@ export class AuthorizationDataService extends BaseDataService imp } /** - * Anonymous feature checks for the same object share the existing unfiltered REST search. - * The request cache deduplicates pending requests and retains its normal expiry, dependency - * invalidation and SSR transfer behavior. No permissions are cached separately here. + * Anonymous feature checks for the same object share one unfiltered REST search, and the + * feature IDs resolved from it (see {@link getAnonymousFeatureIds}). * A failed batch (including a custom feature throwing on the backend) falls back to the * original individual feature check. */ @@ -121,10 +131,8 @@ export class AuthorizationDataService extends BaseDataService imp const objectUrl$ = hasValue(objectUrl) ? of(objectUrl) : this.siteService.find().pipe(map((site) => site.self)); return objectUrl$.pipe( take(1), - // Retrieve every authorization granted on the object, without a feature filter - switchMap((url: string) => this.findAllAuthorizationsForObject(url, useCachedVersionIfAvailable, reRequestOnStale)), - // Resolve the embedded feature of each authorization to its ID - authorizationFeatureIds, + // Retrieve the IDs of all features granted on the object, shared with other checks on it + switchMap((url: string) => this.getAnonymousFeatureIds(url, useCachedVersionIfAvailable, reRequestOnStale)), // The requested feature is granted if its ID is among them map((featureIds: Set) => featureIds.has(featureId.valueOf())), // Any failure along the way: ask the backend about this single feature instead @@ -132,6 +140,54 @@ export class AuthorizationDataService extends BaseDataService imp ); } + /** + * Retrieve the IDs of all features granted anonymously on an object. + * Concurrent and later calls for the same object reuse the same observable until it expires + * with the underlying response, so the search and the feature resolution happen only once. + * The request cache still handles the HTTP request itself (deduplication, SSR transfer state). + * A failed lookup is removed, so that the next check retries it rather than replaying the error. + */ + private getAnonymousFeatureIds(url: string, useCachedVersionIfAvailable: boolean, reRequestOnStale: boolean): Observable> { + const key = `${url}|${reRequestOnStale}`; + const now = Date.now(); + const cached = this.anonymousFeatureIds.get(key); + if (useCachedVersionIfAvailable && hasValue(cached) && cached.expiresAt > now) { + return cached.featureIds$; + } + const entry = { + // BaseDataService may leave responseMsToLive unset; RequestService then uses 15 minutes too + expiresAt: now + (this.responseMsToLive ?? 15 * 60 * 1000), + featureIds$: undefined as Observable>, + }; + entry.featureIds$ = this.findAllAuthorizationsForObject(url, useCachedVersionIfAvailable, reRequestOnStale).pipe( + // Resolve the embedded feature of each authorization to its ID + authorizationFeatureIds, + // Forget a failed lookup, unless it has already been replaced + catchError((error: unknown) => { + if (this.anonymousFeatureIds.get(key) === entry) { + this.anonymousFeatureIds.delete(key); + } + return throwError(() => error); + }), + // Run the lookup once and replay its result to every check on this object + shareReplay({ bufferSize: 1, refCount: false }), + ); + this.removeExpiredAnonymousFeatureIds(now); + this.anonymousFeatureIds.set(key, entry); + return entry.featureIds$; + } + + /** + * Remove expired entries, so that browsing many objects does not grow the map indefinitely. + */ + private removeExpiredAnonymousFeatureIds(now: number): void { + this.anonymousFeatureIds.forEach((entry, key) => { + if (entry.expiresAt <= now) { + this.anonymousFeatureIds.delete(key); + } + }); + } + /** * Retrieve all {@link Authorization}s granted on an object, following every page before * completing, so that a feature is never considered absent because it is on a later page.