import { ClientRepository } from "@pie-api-gcp/datastore/repositories"; import { CollectionService, PitsBuildService } from "@pie-api-gcp/datastore/services"; import { PieConfigContainer } from "@pie-api-gcp/datastore/types"; import { getLogger } from "@pie-api-gcp/shared/logging"; import { AuthInfo } from "@pie-api-gcp/shared/auth"; import graphqlFields from "graphql-fields"; import { decode, encode } from "universal-base64"; import { printDeep } from "@pie-api-gcp/shared/util"; import { SearchSchema } from "@pie-api-gcp/shared/search"; import { Sort, AggregateParameters, SearchResult, PagingParameters, EsSearchBody, SearchClient, } from "@pie-api-gcp/search/client"; import { SearchMetadataServiceSpec, SearchMetadataService } from "@pie-api-gcp/search/services"; import { NODE_NAME_MAPPING } from "@pie-api-gcp/search/mapping"; import { UnsupportedContainerType } from "@pie-api-gcp/search/errors"; import { ResultFunctionContext } from "../types"; const logger = getLogger(); export class SearchCursor { public sortValues?: any[]; } export const decodeCursor = (encodedCursor: any): SearchCursor => { if (!encodedCursor) { return {}; } const cursorAsJson = decode(encodedCursor); // log(`encoded cursor: ${cursorAsJson}`); const cursor = JSON.parse(cursorAsJson) as SearchCursor; // log(`decoded cursor: ${printDeep(cursor)}`); return cursor; }; export const encodeCursor = (previousRow: any, sortKeys: string[]) => { const cursor: SearchCursor = previousRow ? { sortValues: sortKeys.map((k) => previousRow[k]) } : {}; const cursorAsJson = JSON.stringify(cursor); // log(`cursorAsJson: ${cursorAsJson}`); const encodedCursor = encode(cursorAsJson); return encodedCursor; }; const getSort = (o: any): Sort[] => { if (o) { return Object.keys(o).map((property) => { const order = o[property] as "ASC" | "DESC"; return { property, order, }; }); } return []; }; const getAggregateParameters = (fields: any): AggregateParameters => { const p: AggregateParameters = { countProperties: [] }; if (fields.aggregate && fields.aggregate.counts) { logger.debug(printDeep(fields.aggregate)); const keys = Object.keys(fields.aggregate.counts); if (keys && keys.length > 0) { p.countProperties = keys.map((k) => { const name = k; const o = fields.aggregate.counts[k]; let size = 100; if (o.__arguments) { const sz = o.__arguments.filter((a) => a.size); if (sz.length > 0) { size = sz[0].size.value; } } return { name, size }; }); } } return p; }; export async function assembleSearchParams(args: any, info: any, { authInfo }: ResultFunctionContext, q: any) { let query = q; if (args.first && args.last) { throw new Error( `either first or last should be provided, not both (passed in: first: ${args.first}), last: ${args.last}` ); } const size = args.first ? args.first : args.last ? args.last : 10; // page size const cursor = decodeCursor(args.cursor); const fieldsWithSubFieldsArgs = graphqlFields(info, {}, { processArguments: true }); const aggregateParams = getAggregateParameters(fieldsWithSubFieldsArgs); if (!authInfo.admin) { const addedConstraints = []; const client = await ClientRepository.findById(authInfo.apiClientId); const collectionService = new CollectionService(); const collections = await collectionService.findAllByApiClient(client, authInfo.admin); if (collections) { // layer collections constraint const collectionIds = collections.map((c) => c.id); addedConstraints.push({ collections_id_some: collectionIds }); } else { throw Error(`api client ${authInfo.apiClientId} has no access to collections`); } addedConstraints.push({ isRelease: true }); query = { AND: [query, ...addedConstraints], }; } return { cursor, size, aggregateParams, query }; } /** * Format search result for GQL output. */ const encodeSearchResult = ( searchMetadataService: SearchMetadataServiceSpec, from: number = 0, searchResult: SearchResult, type: string, searchSchemas: SearchSchema[], sort: Sort[], pagingParameters: PagingParameters ) => { const objectName = NODE_NAME_MAPPING[type]; if (!objectName) { throw new UnsupportedContainerType(`unsupported container type: ${type}`); } const count = searchResult.aggregations.count; const hasMore = from + searchResult.objects.length < count; const lastRecordInSet = searchResult.objects[searchResult.objects.length - 1]; const sortKeys = sort.map((s) => s.property); const sortValuesLastRecordInSet: any[] = Object.keys(lastRecordInSet) .filter((k) => sortKeys.indexOf(k) !== -1) .map((k) => sortValuesLastRecordInSet[k]); let startCursor; if (pagingParameters && pagingParameters) { startCursor = encode( JSON.stringify({ startRow: pagingParameters.from ? pagingParameters.from : 0, sortValues: pagingParameters.vals, }) ); } else { startCursor = encode( JSON.stringify({ startRow: 0, }) ); } return { pageInfo: { startCursor, hasNextPage: hasMore, hasPreviousPage: Boolean(from > 1), nextCursor: hasMore ? encodeCursor(searchResult.objects[searchResult.objects.length - 1].object, sortKeys) : undefined, }, edges: searchResult.objects.map((r, ix) => ({ node: { [objectName]: r.object, metaData: searchMetadataService.translateSearchMetadata(searchSchemas, r.metaData), }, cursor: encodeCursor(searchResult.objects[ix].object, sortKeys), })), aggregate: searchResult.aggregations, }; }; /** * Run search against ElasticSearch. */ export const search = async (args, context: ResultFunctionContext, info, type: string) => { const { cursor, size, aggregateParams, query } = await assembleSearchParams(args, info, context, args.where); const { authInfo, }: { authInfo: AuthInfo; } = context; const sort = getSort(args.sort); const pagingParameters = new PagingParameters(0, size, cursor.sortValues, !!args.last); const searchClient = new SearchClient(); const objects: SearchResult = await searchClient.query({ type, query, sort: getSort(args.sort), paging: pagingParameters, aggregate: aggregateParams, searchSchemas: await authInfo.searchSchemas(), }); const updateElements = args.updateElements; if (updateElements) { objects.objects.map(async (o) => { const container = o.object as PieConfigContainer; const pitsBuildService = new PitsBuildService(); await pitsBuildService.updatePieElements(container, authInfo.organizationId); // this could throw an error, which should be cascaded to the client as this is only done when asked for }); } const searchSchemas = await authInfo.searchSchemas(); const searchMetadataService = new SearchMetadataService(); const encoded = encodeSearchResult(searchMetadataService, 0, objects, type, searchSchemas, sort, pagingParameters); return encoded; }; /** * Produce ElasticSearch query. */ export const esQuery = async (args, context: ResultFunctionContext, info, type: string): Promise => { const { cursor, size, aggregateParams, query } = await assembleSearchParams(args, info, context, args.where); const { authInfo } = context; const searchClient = new SearchClient(); const cmd = await searchClient.queryCmd({ type, query, sort: getSort(args.sort), paging: new PagingParameters(0, size, cursor.sortValues, !!args.last), aggregate: aggregateParams, searchSchemas: await authInfo.searchSchemas(), }); return cmd; };