Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ import {
EMPTY,
Observable,
of,
throwError,
} from 'rxjs';
import {
catchError,
expand,
filter,
map,
reduce,
shareReplay,
switchMap,
take,
} from 'rxjs/operators';
Expand Down Expand Up @@ -63,6 +65,14 @@ export class AuthorizationDataService extends BaseDataService<Authorization> imp

private searchData: SearchDataImpl<Authorization>;

/**
* 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<string, { expiresAt: number; featureIds$: Observable<Set<string>> }>();

constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
Expand All @@ -80,6 +90,7 @@ export class AuthorizationDataService extends BaseDataService<Authorization> imp
* Set all authorization requests to stale
*/
invalidateAuthorizationsRequestCache() {
this.anonymousFeatureIds.clear();
this.requestService.setStaleByHrefSubstring(this.linkPath);
}

Expand Down Expand Up @@ -111,27 +122,72 @@ export class AuthorizationDataService extends BaseDataService<Authorization> 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.
*/
private checkAnonymousAuthorization(featureId: FeatureID, objectUrl: string, useCachedVersionIfAvailable: boolean, reRequestOnStale: boolean): Observable<boolean> {
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<string>) => featureIds.has(featureId.valueOf())),
// Any failure along the way: ask the backend about this single feature instead
catchError(() => this.checkAuthorization(featureId, objectUrl, undefined, useCachedVersionIfAvailable, reRequestOnStale)),
);
}

/**
* 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<Set<string>> {
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<Set<string>>,
};
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.
Expand Down
Loading