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
109 changes: 103 additions & 6 deletions src/app/core/browse/search-manager.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
import { Injectable } from '@angular/core';
import {
Inject,
Injectable,
} from '@angular/core';
import {
APP_CONFIG,
AppConfig,
} from '@dspace/config/app-config.interface';
import { AuthorizationFeaturesConfig } from '@dspace/config/discovery-authorization-features-config.interface';
import { FollowAuthorityMetadata } from '@dspace/config/search-follow-metadata.interface';
import {
hasValue,
isNotEmpty,
} from '@dspace/shared/utils/empty.util';
import isArray from 'lodash/isArray';
import {
combineLatest,
Observable,
of,
} from 'rxjs';
import {
catchError,
map,
switchMap,
take,
} from 'rxjs/operators';
import { SearchService } from 'src/app/shared/search/search.service';

import { environment } from '../../../environments/environment';
import { AuthorizationDataService } from '../data/feature-authorization/authorization-data.service';
import { FeatureID } from '../data/feature-authorization/feature-id';
import { ItemDataService } from '../data/item-data.service';
import { PaginatedList } from '../data/paginated-list.model';
import { RemoteData } from '../data/remote-data';
Expand All @@ -42,6 +55,8 @@ export class SearchManager {
protected itemService: ItemDataService,
protected browseService: BrowseService,
protected searchService: SearchService,
protected authorizationService: AuthorizationDataService,
@Inject(APP_CONFIG) protected appConfig: AppConfig,
) {
}

Expand All @@ -63,7 +78,7 @@ export class SearchManager {
reRequestOnStale = true,
...linksToFollow: FollowLinkConfig<T>[]): Observable<RemoteData<SearchObjects<T>>> {
return this.searchService.search(searchOptions, responseMsToLive, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)
.pipe(this.completeSearchObjectsWithExtraData());
.pipe(this.completeSearchObjectsWithExtraData(searchOptions?.configuration));
}


Expand All @@ -78,19 +93,101 @@ export class SearchManager {
});
}

protected completeSearchObjectsWithExtraData<T extends DSpaceObject>() {
/**
* Complete successful search results with the referenced items (see {@link fetchExtraData}) and the
* authorizations configured for the discovery configuration (see {@link fetchConfiguredAuthorizations}),
* before emitting them.
*
* @param configuration the discovery configuration of the search, 'default' if not provided
*/
protected completeSearchObjectsWithExtraData<T extends DSpaceObject>(configuration?: string) {
return switchMap((searchObjectsRD: RemoteData<SearchObjects<T>>) => {
if (searchObjectsRD.isSuccess) {
const items: Item[] = searchObjectsRD.payload.page
.map((searchResult) => isNotEmpty(searchResult?._embedded?.indexableObject) ? searchResult._embedded.indexableObject : searchResult.indexableObject) as any;
return this.fetchExtraData(items).pipe(map(() => {
return searchObjectsRD;
}));
return this.fetchExtraData(items).pipe(
switchMap(() => this.fetchConfiguredAuthorizations(items, configuration ?? 'default')),
map(() => searchObjectsRD),
);
}
return of(searchObjectsRD);
});
}

/**
* Prefetch the authorization features configured in `searchResult.discoveryAuthorizationFeaturesConfig` for the given
* discovery configuration, with one batched request per group of objects requiring the same features.
* Following checks of those features on these objects need no further request.
* A failed prefetch is ignored: the features are then checked individually, as usual.
*
* @param objects the search result objects
* @param configuration the discovery configuration of the search
*/
protected fetchConfiguredAuthorizations<T extends DSpaceObject>(objects: T[], configuration: string): Observable<unknown> {
const featuresByType = this.getConfiguredAuthorizationsMap(objects, configuration);
if (featuresByType.size === 0) {
return of(null);
}

const uuidListsByFeatures = this.groupItemsUuidsByAuthorizations(objects, featuresByType);
const requests = [...uuidListsByFeatures.entries()].map(([features, uuidList]: [string[], string[]]) => {
const groupObjects = objects.filter((dso: T) => uuidList.includes(dso.id));
const type = groupObjects[0].uniqueType;
const hrefs = groupObjects.map((dso: T) => dso.self);
return this.authorizationService.getAuthorizationForObjects(uuidList, type, features as FeatureID[], undefined, hrefs).pipe(
take(1),
catchError(() => of(null)),
);
});

return combineLatest(requests).pipe(take(1));
}

/**
* Group the IDs of the objects by the list of features configured for their unique type
*
* @param objects the search result objects
* @param featuresByType the features configured for each unique type
*/
private groupItemsUuidsByAuthorizations<T extends DSpaceObject>(objects: T[], featuresByType: Map<string, string[]>): Map<string[], string[]> {
const uuidListsByFeatures = new Map<string[], string[]>();

objects.forEach((object: T) => {
const features = featuresByType.get(object.uniqueType);
if (hasValue(features)) {
uuidListsByFeatures.set(features, [...(uuidListsByFeatures.get(features) ?? []), object.id]);
}
});

return uuidListsByFeatures;
}

/**
* The features configured for the unique types of the given objects, for the given discovery configuration
* (or the 'default' one if it has none)
*
* @param objects the search result objects
* @param configuration the discovery configuration of the search
*/
private getConfiguredAuthorizationsMap<T extends DSpaceObject>(objects: T[], configuration: string): Map<string, string[]> {
const featuresByType = new Map<string, string[]>();
const config = this.appConfig.searchResult?.discoveryAuthorizationFeaturesConfig;
const configuredForDiscovery: AuthorizationFeaturesConfig = config?.[configuration] ?? config?.default;

if (!hasValue(configuredForDiscovery)) {
return featuresByType;
}

new Set(objects.map((dso: T) => dso?.uniqueType)).forEach((uniqueType: string) => {
const features = configuredForDiscovery[uniqueType];
if (isNotEmpty(features)) {
featuresByType.set(uniqueType, features);
}
});

return featuresByType;
}

protected fetchExtraData<T extends DSpaceObject>(objects: T[]): Observable<any> {

const items: Item[] = objects
Expand Down
99 changes: 97 additions & 2 deletions src/app/core/browse/search.manager.spec.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import { AppConfig } from '@dspace/config/app-config.interface';
import { getTestScheduler } from 'jasmine-marbles';
import { of } from 'rxjs';
import {
of,
throwError,
} from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
import { v4 as uuidv4 } from 'uuid';

import { toRemoteData } from '../../browse-by/browse-by-metadata/browse-by-metadata.component.spec';
import { AuthorizationDataService } from '../data/feature-authorization/authorization-data.service';
import { FeatureID } from '../data/feature-authorization/feature-id';
import { FindListOptions } from '../data/find-list-options.model';
import { FollowLinkConfig } from '../shared/follow-link-config.model';
import { Item } from '../shared/item.model';
import { ITEM } from '../shared/item.resource-type';
import { MetadataValue } from '../shared/metadata.models';
import { AUTHORITY_REFERENCE } from '../shared/metadata.utils';
import { PaginatedSearchOptions } from '../shared/search/models/paginated-search-options.model';
import { createPaginatedList } from '../testing/utils.test';
import {
createSuccessfulRemoteDataObject,
Expand Down Expand Up @@ -114,8 +121,31 @@ describe('SearchManager', () => {
of(createSuccessfulRemoteDataObject(createPaginatedList([]))),
};

let mockAuthorizationService: jasmine.SpyObj<AuthorizationDataService>;

const appConfig: Partial<AppConfig> = {
searchResult: {
authorMetadata: [],
followAuthorityMetadata: [],
followAuthorityMaxItemLimit: 100,
followAuthorityMetadataValuesLimit: 5,
discoveryAuthorizationFeaturesConfig: {
default: {
'core.item': [FeatureID.CanEditItem],
},
workspace: {
'core.item': [FeatureID.CanEditItem, FeatureID.CanDownload],
'submission.workspaceitem': [FeatureID.CanEditItem],
},
},
},
};

function initTestService() {
return new SearchManager(mockItemService, mockBrowseService, mockSearchService);
mockAuthorizationService = jasmine.createSpyObj('authorizationService', {
getAuthorizationForObjects: of({}),
});
return new SearchManager(mockItemService, mockBrowseService, mockSearchService, mockAuthorizationService, appConfig as AppConfig);
}

beforeEach(() => {
Expand Down Expand Up @@ -163,4 +193,69 @@ describe('SearchManager', () => {
});
});

describe('search', () => {
const resultObject = (id: string, uniqueType: string) => Object.assign(new Item(), {
id,
uniqueType,
type: ITEM.value,
metadata: {},
_links: { self: { href: `${id}-href` } },
});
const item1 = resultObject('item-1', 'core.item');
const item2 = resultObject('item-2', 'core.item');
const workspaceItem = resultObject('1', 'submission.workspaceitem');
const community = resultObject('community-1', 'core.community');

function searchWith(objects: Item[], configuration?: string) {
spyOn(mockSearchService, 'search').and.returnValue(createSuccessfulRemoteDataObject$(
createPaginatedList(objects.map((indexableObject) => ({ indexableObject }))),
));
const result = jasmine.createSpy('result');
service.search(Object.assign(new PaginatedSearchOptions({}), { configuration })).subscribe(result);
return result;
}

beforeEach(() => {
service = initTestService();
});

it('should prefetch the features configured for the default configuration', () => {
const result = searchWith([item1, item2, community]);
expect(mockAuthorizationService.getAuthorizationForObjects).toHaveBeenCalledOnceWith(
['item-1', 'item-2'], 'core.item', [FeatureID.CanEditItem], undefined, ['item-1-href', 'item-2-href'],
);
expect(result).toHaveBeenCalledTimes(1);
});

it('should send one request per unique type for the search configuration', () => {
searchWith([item1, workspaceItem], 'workspace');
expect(mockAuthorizationService.getAuthorizationForObjects).toHaveBeenCalledTimes(2);
expect(mockAuthorizationService.getAuthorizationForObjects).toHaveBeenCalledWith(
['item-1'], 'core.item', [FeatureID.CanEditItem, FeatureID.CanDownload], undefined, ['item-1-href'],
);
expect(mockAuthorizationService.getAuthorizationForObjects).toHaveBeenCalledWith(
['1'], 'submission.workspaceitem', [FeatureID.CanEditItem], undefined, ['1-href'],
);
});

it('should fall back to the default configuration', () => {
searchWith([item1], 'unconfigured');
expect(mockAuthorizationService.getAuthorizationForObjects).toHaveBeenCalledOnceWith(
['item-1'], 'core.item', [FeatureID.CanEditItem], undefined, ['item-1-href'],
);
});

it('should not prefetch anything for objects without configured features', () => {
const result = searchWith([community]);
expect(mockAuthorizationService.getAuthorizationForObjects).not.toHaveBeenCalled();
expect(result).toHaveBeenCalledTimes(1);
});

it('should still emit the results when the prefetch fails', () => {
mockAuthorizationService.getAuthorizationForObjects.and.returnValue(throwError(() => new Error('Prefetch failed')));
const result = searchWith([item1]);
expect(result).toHaveBeenCalledTimes(1);
});
});

});
Loading
Loading