Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(#9238): add functionality of getting people as an AsyncGenerator in cht-datasource #9281

Merged
Show file tree
Hide file tree
Changes from 54 commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
08e2b27
feat(#9237): Add functionality of getting people with pagination in c…
sugat009 Jul 15, 2024
ab92f0b
Update shared-libs/cht-datasource/src/local/libs/doc.ts
sugat009 Jul 17, 2024
de63197
feat(#9237): Address PR comments
sugat009 Jul 19, 2024
105d5db
Update shared-libs/cht-datasource/src/qualifier.ts
sugat009 Jul 23, 2024
2b92b4c
Update shared-libs/cht-datasource/test/local/person.spec.ts
sugat009 Jul 23, 2024
ba2e27a
Update shared-libs/cht-datasource/src/person.ts
sugat009 Jul 23, 2024
15068fa
Update shared-libs/cht-datasource/src/remote/person.ts
sugat009 Jul 23, 2024
a83a259
Update shared-libs/cht-datasource/src/person.ts
sugat009 Jul 23, 2024
29a3ad5
Update shared-libs/cht-datasource/src/index.ts
sugat009 Jul 23, 2024
8fbc245
feat(#9237): Address PR comments
sugat009 Jul 23, 2024
a99de72
feat(#9237): Add unit tests for getResources in remote mode
sugat009 Jul 23, 2024
d87c258
feat(#9237): Address PR comments
sugat009 Jul 24, 2024
c34716a
Write getAll generator in src/person.ts
sugat009 Jul 24, 2024
a9fb5eb
(#feat): Minor fix
sugat009 Jul 24, 2024
7b94447
Refactor the AsyncIterator
sugat009 Jul 25, 2024
4b534f3
Add documentation for new functions
sugat009 Jul 25, 2024
eff3972
Add unit tests
sugat009 Jul 25, 2024
9a94d36
Add comment on unit tests for clarity
sugat009 Jul 25, 2024
141cfab
Update shared-libs/cht-datasource/src/person.ts
sugat009 Jul 26, 2024
5daa8cf
Update shared-libs/cht-datasource/src/person.ts
sugat009 Jul 26, 2024
9015353
Address PR comments
sugat009 Jul 29, 2024
8be7b70
Avoid using spread operator in getDocumentStream function
sugat009 Jul 31, 2024
54da9fb
Fix documentation of previously changed functions
sugat009 Jul 31, 2024
6064c99
Update shared-libs/cht-datasource/src/person.ts
sugat009 Jul 26, 2024
9fb6c7b
Update shared-libs/cht-datasource/test/local/libs/lineage.spec.ts
sugat009 Jul 26, 2024
2364d82
Update shared-libs/cht-datasource/test/local/libs/lineage.spec.ts
sugat009 Jul 26, 2024
1b87d4a
Update shared-libs/cht-datasource/test/local/person.spec.ts
sugat009 Jul 26, 2024
9a828a6
feat(#9237): Address PR comments
sugat009 Jul 26, 2024
cd81f2d
Write getAll generator in src/person.ts
sugat009 Jul 24, 2024
cd344d5
Refactor the AsyncIterator
sugat009 Jul 25, 2024
5d7fc98
Add documentation for new functions
sugat009 Jul 25, 2024
4279c60
Add unit tests
sugat009 Jul 25, 2024
190f69e
Address PR comments
sugat009 Jul 29, 2024
cb34075
Fix conflict with target branch
sugat009 Jul 31, 2024
154b295
Fix conflict with target branch
sugat009 Jul 31, 2024
c233d0b
Update shared-libs/cht-datasource/src/person.ts
sugat009 Jul 31, 2024
a9cf536
Address PR comments
sugat009 Jul 31, 2024
318c1a4
Update shared-libs/cht-datasource/src/index.ts
sugat009 Aug 6, 2024
bc92ff3
Update shared-libs/cht-datasource/src/index.ts
sugat009 Aug 6, 2024
0e6e9ea
Update shared-libs/cht-datasource/src/person.ts
sugat009 Aug 6, 2024
d14ce9e
Remove limit and skip as arguments for getDocumentStream function
sugat009 Aug 6, 2024
36a5a87
Remove duplicate test case added during conflict resolution
sugat009 Aug 7, 2024
d87d293
Cleanup after refactoring
sugat009 Aug 7, 2024
2867a80
Implement cursor based pagination
sugat009 Aug 6, 2024
84c30c9
Fix unit tests according to implementation of cursor pagination
sugat009 Aug 6, 2024
d45f0d9
Add unit tests
sugat009 Jul 25, 2024
563ac81
Address PR comments
sugat009 Jul 29, 2024
fd72695
Avoid using spread operator in getDocumentStream function
sugat009 Jul 31, 2024
bab3c1e
Fix conflict with target branch
sugat009 Jul 31, 2024
0d305ff
Remove limit and skip as arguments for getDocumentStream function
sugat009 Aug 6, 2024
15b6e39
Cleanup after refactoring
sugat009 Aug 7, 2024
1d62657
Refactor getDocumentStream w.r.t. the cursor based pagination in getP…
sugat009 Aug 7, 2024
1057fe4
Fix merge conflicts with target branch
sugat009 Aug 7, 2024
88f39d7
Update shared-libs/cht-datasource/src/libs/core.ts
sugat009 Aug 8, 2024
60604a5
Change skip to cursor in all places and refactor fetchAndFilter funct…
sugat009 Aug 8, 2024
3eeb049
Fix eslint issues
sugat009 Aug 8, 2024
7e0355f
Merge branch '9193-api-endpoints-for-getting-contacts-by-type' into 9…
sugat009 Aug 12, 2024
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
23 changes: 23 additions & 0 deletions shared-libs/cht-datasource/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,29 @@ export const getDatasource = (ctx: DataContext) => {
* @throws Error if no UUID is provided
*/
getByUuidWithLineage: (uuid: string) => ctx.bind(Person.v1.getWithLineage)(Qualifier.byUuid(uuid)),

/**
* Returns an array of people for the provided page specifications.
* @param personType the type of people to return
* @param limit the maximum number of people to return. Default is 100.
* @param skip the number of people to skip. Default is 0.
* @returns an array of people for the provided page specifications
* @throws Error if no type is provided or if the type is not for a person
* @throws Error if the provided limit is `<= 0`
* @throws Error if the provided skip is `< 0`
* @see {@link getByType} which provides the same data, but without having to manually account for paging
*/
getPageByType: (personType: string, limit = 100, skip = 0) => ctx.bind(Person.v1.getPage)(
jkuester marked this conversation as resolved.
Show resolved Hide resolved
Qualifier.byContactType(personType), limit, skip
),

/**
* Returns a generator for fetching all people with the given type.
* @param personType the type of people to return
* @returns a generator for fetching all people with the given type
* @throws Error if no type is provided or if the type is not for a person
*/
getByType: (personType: string) => ctx.bind(Person.v1.getAll)(Qualifier.byContactType(personType)),
}
}
};
Expand Down
11 changes: 11 additions & 0 deletions shared-libs/cht-datasource/src/libs/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,14 @@ export const findById = <T extends Identifiable>(values: T[], id: string): Nulla
export abstract class AbstractDataContext implements DataContext {
readonly bind = <T>(fn: (ctx: DataContext) => T): T => fn(this);
}

/**
* Represents a page of results. The `data` array contains the results for this page. The `cursor` field contains a
* key that can be used to fetch the next page of results. If no `cursor` value is returned, there are no additional
* results available. (Note that no assumptions should be made about the _contents_ of the cursor string.)
* @typeParam T the type of the data in the page
*/
export interface Page<T> {
readonly data: T[];
readonly cursor: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we know that we have reached the end of the results, we should not return a cursor value.

  readonly cursor?: string;

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! I believe cursor's type should be

interface Page {
  readonly cursor: string | null;
}

That's more explicit to express "you've reached the end"

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should be more explicit and return "-1" and not nothing to indicate the end of iteration.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@m5r and I commented simultaneously, null should do as well.

}
22 changes: 21 additions & 1 deletion shared-libs/cht-datasource/src/libs/data-context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { hasField, isRecord } from './core';
import { hasField, isRecord, Page } from './core';
import { isLocalDataContext, LocalDataContext } from '../local/libs/data-context';
import { assertRemoteDataContext, isRemoteDataContext, RemoteDataContext } from '../remote/libs/data-context';

Expand Down Expand Up @@ -39,3 +39,23 @@ export const adapt = <T>(
assertRemoteDataContext(context);
return remote(context);
};

/** @internal */
export const getDocumentStream = async function* <S, T>(
fetchFunction: (args: S, l: number, s: number) => Promise<Page<T>>,
fetchFunctionArgs: S
): AsyncGenerator<T, void> {
const limit = 100;
let skip = 0;
const hasMoreResults = () => skip !== -1;

do {
const docs = await fetchFunction(fetchFunctionArgs, limit, skip);

for (const doc of docs.data) {
yield doc;
}

skip = Number(docs.cursor);
} while (hasMoreResults());
};
26 changes: 18 additions & 8 deletions shared-libs/cht-datasource/src/local/libs/doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,25 @@ export const getDocsByIds = (db: PouchDB.Database<Doc>) => async (uuids: string[
.filter((doc): doc is Doc => isDoc(doc));
};

const queryDocs = (db: PouchDB.Database<Doc>, view: string, options: PouchDB.Query.Options<Doc, unknown>) => db
.query(view, {...options})
.then(({ rows }) => rows.map(({ doc }) => isDoc(doc) ? doc : null));

/** @internal */
export const queryDocsByKey = (
export const queryDocsByRange = (
db: PouchDB.Database<Doc>,
view: string
) => async (key: string): Promise<Nullable<Doc>[]> => db
.query(view, {
startkey: [key],
endkey: [key, {}],
include_docs: true
})
.then(({ rows }) => rows.map(({ doc }) => isDoc(doc) ? doc : null));
) => async (
startkey: unknown,
endkey: unknown
): Promise<Nullable<Doc>[]> => queryDocs(db, view, { include_docs: true, startkey, endkey});

/** @internal */
export const queryDocsByKey = (
db: PouchDB.Database<Doc>,
view: string
) => async (
key: unknown,
limit: number,
skip: number
): Promise<Nullable<Doc>[]> => queryDocs(db, view, { include_docs: true, key, limit, skip });
9 changes: 5 additions & 4 deletions shared-libs/cht-datasource/src/local/libs/lineage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,18 @@ import {
Nullable
} from '../../libs/core';
import { Doc } from '../../libs/doc';
import { queryDocsByKey } from './doc';
import { queryDocsByRange } from './doc';
import logger from '@medic/logger';

/**
* Returns the identified document along with the parent documents recorded for its lineage. The returned array is
* sorted such that the identified document is the first element and the parent documents are in order of lineage.
* @internal
*/
export const getLineageDocsById = (
medicDb: PouchDB.Database<Doc>
): (id: string) => Promise<Nullable<Doc>[]> => queryDocsByKey(medicDb, 'medic-client/docs_by_id_lineage');
export const getLineageDocsById = (medicDb: PouchDB.Database<Doc>): (id: string) => Promise<Nullable<Doc>[]> => {
const fn = queryDocsByRange(medicDb, 'medic-client/docs_by_id_lineage');
return (id: string) => fn([id], [id, {}]);
};

/** @internal */
export const getPrimaryContactIds = (places: NonEmptyArray<Nullable<Doc>>): string[] => places
Expand Down
66 changes: 60 additions & 6 deletions shared-libs/cht-datasource/src/local/person.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { Doc } from '../libs/doc';
import contactTypeUtils from '@medic/contact-types-utils';
import { deepCopy, isNonEmptyArray, Nullable } from '../libs/core';
import { UuidQualifier } from '../qualifier';
import { deepCopy, isNonEmptyArray, Nullable, Page } from '../libs/core';
import { ContactTypeQualifier, UuidQualifier } from '../qualifier';
import * as Person from '../person';
import { getDocById, getDocsByIds } from './libs/doc';
import { getDocById, getDocsByIds, queryDocsByKey } from './libs/doc';
import { LocalDataContext, SettingsService } from './libs/data-context';
import logger from '@medic/logger';
import { getLineageDocsById, getPrimaryContactIds, hydrateLineage, hydratePrimaryContact } from './libs/lineage';

/** @internal */
export namespace v1 {
const isPerson = (settings: SettingsService, uuid: string, doc: Nullable<Doc>): doc is Person.v1.Person => {
const isPerson = (settings: SettingsService, doc: Nullable<Doc>, uuid = ''): doc is Person.v1.Person => {
if (!doc) {
logger.warn(`No person found for identifier [${uuid}].`);
return false;
Expand All @@ -28,7 +28,7 @@ export namespace v1 {
const getMedicDocById = getDocById(medicDb);
return async (identifier: UuidQualifier): Promise<Nullable<Person.v1.Person>> => {
const doc = await getMedicDocById(identifier.uuid);
if (!isPerson(settings, identifier.uuid, doc)) {
if (!isPerson(settings, doc, identifier.uuid)) {
return null;
}
return doc;
Expand All @@ -41,7 +41,7 @@ export namespace v1 {
const getMedicDocsById = getDocsByIds(medicDb);
return async (identifier: UuidQualifier): Promise<Nullable<Person.v1.PersonWithLineage>> => {
const [person, ...lineagePlaces] = await getLineageDocs(identifier.uuid);
if (!isPerson(settings, identifier.uuid, person)) {
if (!isPerson(settings, person, identifier.uuid)) {
return null;
}
// Intentionally not further validating lineage. For passivity, lineage problems should not block retrieval.
Expand All @@ -58,4 +58,58 @@ export namespace v1 {
return deepCopy(personWithLineage);
};
};

/** @internal */
export const getPage = ({ medicDb, settings }: LocalDataContext) => {
return async (
personType: ContactTypeQualifier,
limit: number,
skip: number
sugat009 marked this conversation as resolved.
Show resolved Hide resolved
): Promise<Page<Person.v1.Person>> => {
const personTypes = contactTypeUtils.getPersonTypes(settings.getAll());
const personTypesIds = personTypes.map((item) => item.id);

if (!personTypesIds.includes(personType.contactType)) {
throw new Error(`Invalid person type: ${personType.contactType}`);
}

const getDocsByPage = queryDocsByKey(medicDb, 'medic-client/contacts_by_type');

const fetchAndFilter = async (
Copy link
Contributor

@jkuester jkuester Aug 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solid logic here! 👍 I think we can tighten up the cursor calculation a bit (at least reduce the nesting if-statements):

const fetchAndFilter = async (
  currentLimit: number,
  currentSkip: number,
  currentPersons: Person.v1.Person[] = []
): Promise<Page<Person.v1.Person>> => {
  const docs = await getDocsByPage([personType.contactType], currentLimit, currentSkip);
  const noMoreResults = docs.length < currentLimit;
  const newPersons = docs.filter((doc): doc is Person.v1.Person => isPerson(settings, doc, doc?._id));

  // Need to slice here because we retrieve extra docs on re-fetches and may end up with too many.
  const overFetchCount = currentPersons.length + newPersons.length - limit || 0;
  const totalPersons = [...currentPersons, ...newPersons].slice(0, limit);
  if (noMoreResults) {
    return { data: totalPersons };
  }
  if (totalPersons.length === limit) {
    const nextSkip =  currentSkip + currentLimit - overFetchCount;
    return { data: totalPersons, cursor: (nextSkip).toString() };
  }

  // Re-fetch twice as many docs as we need to limit number of recursions
  const missingCount = currentLimit - newPersons.length;
  logger.debug(`Found [${missingCount}] invalid persons. Re-fetching additional records.`);
  const nextLimit = missingCount * 2;
  const nextSkip = currentSkip + currentLimit;
  return fetchAndFilter(nextLimit, nextSkip, totalPersons);
};

return fetchAndFilter(limit, skip);

currentLimit: number,
currentSkip: number,
personDocs: Person.v1.Person[],
totalDocsFetched = 0,
): Promise<Page<Person.v1.Person>> => {
const docs = await getDocsByPage([personType.contactType], currentLimit, currentSkip);
if (docs.length === 0) {
return { data: personDocs, cursor: '-1' };
}

const tempFilteredDocs = docs.filter((doc): doc is Person.v1.Person => isPerson(settings, doc, doc?._id));

personDocs.push(...tempFilteredDocs);
totalDocsFetched += docs.length;

if (personDocs.length >= limit) {
let cursor: number;
if (docs.length < currentLimit) {
cursor = -1;
} else {
cursor = skip + totalDocsFetched - (personDocs.length - limit);
}
return { data: personDocs.slice(0, limit), cursor: cursor.toString() };
}

return fetchAndFilter(
(currentLimit - tempFilteredDocs.length) * 2,
currentSkip + currentLimit,
personDocs,
totalDocsFetched
);
};

return fetchAndFilter(limit, skip, []);
};
};
}
87 changes: 85 additions & 2 deletions shared-libs/cht-datasource/src/person.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { isUuidQualifier, UuidQualifier } from './qualifier';
import { adapt, assertDataContext, DataContext } from './libs/data-context';
import { ContactTypeQualifier, isContactTypeQualifier, isUuidQualifier, UuidQualifier } from './qualifier';
import { adapt, assertDataContext, DataContext, getDocumentStream } from './libs/data-context';
import { Contact, NormalizedParent } from './libs/contact';
import * as Remote from './remote';
import * as Local from './local';
import * as Place from './place';
import { LocalDataContext } from './local/libs/data-context';
import { RemoteDataContext } from './remote/libs/data-context';
import { Page } from './libs/core';

/** */
export namespace v1 {
Expand All @@ -32,6 +33,26 @@ export namespace v1 {
}
};

const assertTypeQualifier: (qualifier: unknown) => asserts qualifier is ContactTypeQualifier = (
qualifier: unknown
) => {
if (!isContactTypeQualifier(qualifier)) {
throw new Error(`Invalid type [${JSON.stringify(qualifier)}].`);
}
};

const assertLimit = (limit: unknown) => {
if (typeof limit !== 'number' || !Number.isInteger(limit) || limit <= 0) {
throw new Error(`The limit must be a positive number: [${String(limit)}]`);
}
};

const assertSkip = (skip: unknown) => {
if (typeof skip !== 'number' || !Number.isInteger(skip) || skip < 0) {
throw new Error(`The skip must be a non-negative number: [${String(skip)}]`);
}
};

const getPerson = <T>(
localFn: (c: LocalDataContext) => (qualifier: UuidQualifier) => Promise<T>,
remoteFn: (c: RemoteDataContext) => (qualifier: UuidQualifier) => Promise<T>
Expand Down Expand Up @@ -59,4 +80,66 @@ export namespace v1 {
* @throws Error if the provided context or qualifier is invalid
*/
export const getWithLineage = getPerson(Local.Person.v1.getWithLineage, Remote.Person.v1.getWithLineage);

/**
* Returns a function for retrieving a paged array of people from the given data context.
* @param context the current data context
* @returns a function for retrieving a paged array of people
* @throws Error if a data context is not provided
* @see {@link getAll} which provides the same data, but without having to manually account for paging
*/
export const getPage = (
context: DataContext
sugat009 marked this conversation as resolved.
Show resolved Hide resolved
): typeof curriedFn => {
assertDataContext(context);
const fn = adapt(context, Local.Person.v1.getPage, Remote.Person.v1.getPage);

/**
* Returns an array of people for the provided page specifications.
* @param personType the type of people to return
* @param limit the maximum number of people to return. Default is 100.
* @param skip the number of people to skip. Default is 0.
* @returns an array of people for the provided page specifications.
* @throws Error if no type is provided or if the type is not for a person
* @throws Error if the provided `limit` value is `<=0`
* @throws Error if the provided `skip` value is `<0`
*/
const curriedFn = async (
personType: ContactTypeQualifier,
limit = 100,
skip = 0
): Promise<Page<Person>> => {
sugat009 marked this conversation as resolved.
Show resolved Hide resolved
assertTypeQualifier(personType);
assertLimit(limit);
assertSkip(skip);

return fn(personType, limit, skip);
};
return curriedFn;
};

/**
* Returns a function for getting a generator that fetches people from the given data context.
* @param context the current data context
* @returns a function for getting a generator that fetches people
* @throws Error if a data context is not provided
*/
export const getAll = (
context: DataContext
): typeof curriedGen => {
assertDataContext(context);

/**
* Returns a generator for fetching all people with the given type
* @param personType the type of people to return
* @returns a generator for fetching all people with the given type
* @throws Error if no type is provided or if the type is not for a person
*/
const curriedGen = async function* (personType: ContactTypeQualifier): AsyncGenerator<Person, void> {
assertTypeQualifier(personType);
const getPage = context.bind(v1.getPage);
yield* getDocumentStream(getPage, personType);
};
return curriedGen;
sugat009 marked this conversation as resolved.
Show resolved Hide resolved
};
}
28 changes: 28 additions & 0 deletions shared-libs/cht-datasource/src/qualifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,31 @@ export const byUuid = (uuid: string): UuidQualifier => {
export const isUuidQualifier = (identifier: unknown): identifier is UuidQualifier => {
return isRecord(identifier) && hasField(identifier, { name: 'uuid', type: 'string' });
};

/**
A qualifier that identifies contacts based on type.
*/
export type ContactTypeQualifier = Readonly<{ contactType: string }>;

/**
* Build the TypeQualifier that categorizes an entity by its type
* @param contactType the type of the entity
* @returns the type
* @throws Error if the type is invalid
*/
export const byContactType = (contactType: string): ContactTypeQualifier => {
if (!isString(contactType) || contactType.length === 0) {
throw new Error(`Invalid ContactType [${JSON.stringify(contactType)}].`);
}

return { contactType };
};

/**
* Returns `true` if the given qualifier is a {@link ContactTypeQualifier} otherwise `false`.
* @param contactType the type to check
* @returns `true` if the given type is a {@link ContactTypeQualifier}, otherwise `false`.
*/
export const isContactTypeQualifier = (contactType: unknown): contactType is ContactTypeQualifier => {
return isRecord(contactType) && hasField(contactType, { name: 'contactType', type: 'string' });
};
18 changes: 18 additions & 0 deletions shared-libs/cht-datasource/src/remote/libs/data-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,21 @@ export const getResource = (context: RemoteDataContext, path: string) => async <
throw error;
}
};

/** @internal */
export const getResources = (context: RemoteDataContext, path: string) => async <T>(
queryParams?: Record<string, string>,
): Promise<T> => {
const params = new URLSearchParams(queryParams).toString();
try {
const response = await fetch(`${context.url}/${path}?${params}`);
if (!response.ok) {
throw new Error(response.statusText);
}

return (await response.json()) as T;
} catch (error) {
logger.error(`Failed to fetch resources from ${context.url}/${path} with params: ${params}`, error);
throw error;
}
};
Loading
Loading