1 Commits

Author SHA1 Message Date
Romain Thouvenin
1fd15430a1 Replace GRPC call to geography with AMQP RPC 2024-03-22 22:33:24 +01:00
31 changed files with 387 additions and 623 deletions

View File

@@ -7,7 +7,52 @@ stages:
include: include:
- template: Security/SAST.gitlab-ci.yml - template: Security/SAST.gitlab-ci.yml
- template: Security/Secret-Detection.gitlab-ci.yml - template: Security/Secret-Detection.gitlab-ci.yml
- project: mobicoop/v3/gitlab-templates
file: ##############
- /ci/release.build-job.yml # TEST STAGE #
- /ci/service.test-job.yml ##############
test:
stage: test
image: docker/compose:latest
variables:
DOCKER_TLS_CERTDIR: ''
services:
- docker:dind
script:
- docker-compose -f docker-compose.ci.tools.yml -p matcher-tools --env-file ci/.env.ci up -d
- sh ci/wait-up.sh
- docker-compose -f docker-compose.ci.service.yml -p matcher-service --env-file ci/.env.ci up -d
- docker exec -t v3-matcher-api sh -c "npm run test:integration:ci"
coverage: /All files[^|]*\|[^|]*\s+([\d\.]+)/
rules:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH || $CI_COMMIT_MESSAGE =~ /--check/ || $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
when: always
###############
# BUILD STAGE #
###############
build:
stage: build
image: docker:20.10.22
variables:
DOCKER_TLS_CERTDIR: ''
services:
- docker:dind
before_script:
- echo -n $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER --password-stdin $CI_REGISTRY
script:
- export VERSION=$(docker run --rm -v "$PWD":/usr/src/app:ro -w /usr/src/app node:slim node -p "require('./package.json').version")
- docker pull $CI_REGISTRY_IMAGE:latest || true
- >
docker build
--pull
--cache-from $CI_REGISTRY_IMAGE:latest
--tag $CI_REGISTRY_IMAGE:$VERSION
--tag $CI_REGISTRY_IMAGE:latest
.
- docker push $CI_REGISTRY_IMAGE:$VERSION
- docker push $CI_REGISTRY_IMAGE:latest
only:
- main

View File

@@ -156,18 +156,13 @@ The app exposes the following [gRPC](https://grpc.io/) services :
- **strict** (boolean, optional): if set to true, allow matching only with similar frequency ads (_default : false_) - **strict** (boolean, optional): if set to true, allow matching only with similar frequency ads (_default : false_)
- **fromDate**: start date for recurrent ad, carpool date for punctual ad - **fromDate**: start date for recurrent ad, carpool date for punctual ad
- **toDate**: end date for recurrent ad, same as fromDate for punctual ad - **toDate**: end date for recurrent ad, same as fromDate for punctual ad
- **schedule**: an optional array of schedule items, a schedule item containing : - **schedule**: an array of schedule items, a schedule item containing :
- the week day as a number, from 0 (sunday) to 6 (saturday) if the ad is recurrent (default to fromDate day for punctual search) - the week day as a number, from 0 (sunday) to 6 (saturday) if the ad is recurrent (default to fromDate day for punctual search)
- the departure time (as HH:MM) - the departure time (as HH:MM)
- the margin around the departure time in seconds (optional) (_default : 900_) - the margin around the departure time in seconds (optional) (_default : 900_)
_If the schedule is not set, the driver departure time is guessed to be the ideal departure time to reach the passenger, and the passenger departure time is guessed to be the ideal pick up time for the driver_
- **seatsProposed** (integer, optional): number of seats proposed as driver (_default : 3_) - **seatsProposed** (integer, optional): number of seats proposed as driver (_default : 3_)
- **seatsRequested** (integer, optional): number of seats requested as passenger (_default : 1_) - **seatsRequested** (integer, optional): number of seats requested as passenger (_default : 1_)
- **waypoints**: an array of addresses that represent the waypoints of the journey (only first and last waypoints are used for passenger ads). Note that positions are **required** and **must** be consecutives - **waypoints**: an array of addresses that represent the waypoints of the journey (only first and last waypoints are used for passenger ads). Note that positions are **required** and **must** be consecutives
- **excludedAdId** (optional): the id of an ad to be excluded from the results (useful to avoid self-matchings)
- **algorithmType** (optional): the type of algorithm to use (as of 2023-09-28, only the default `PASSENGER_ORIENTED` is accepted) - **algorithmType** (optional): the type of algorithm to use (as of 2023-09-28, only the default `PASSENGER_ORIENTED` is accepted)
- **remoteness** (integer, optional): an integer to indicate the maximum flying distance (in metres) between the driver route and the passenger pick-up / drop-off points (_default : 15000_) - **remoteness** (integer, optional): an integer to indicate the maximum flying distance (in metres) between the driver route and the passenger pick-up / drop-off points (_default : 15000_)
- **useProportion** (boolean, optional): a boolean to indicate if the matching algorithm will compare the distance of the passenger route against the distance of the driver route (_default : 1_). Works in combination with **proportion** parameter - **useProportion** (boolean, optional): a boolean to indicate if the matching algorithm will compare the distance of the passenger route against the distance of the driver route (_default : 1_). Works in combination with **proportion** parameter
@@ -219,6 +214,10 @@ If the matching is successful, you will get a result, containing :
Matching is a time-consuming process, so the results of a matching request are stored in cache before being paginated and returned to the requester. Matching is a time-consuming process, so the results of a matching request are stored in cache before being paginated and returned to the requester.
An id is attributed to the overall results of a request : on further requests (for example to query for different pages of results), the requester can provide this id and get in return the cached data, avoiding another longer process of computing the results from scratch. Obviously, new computing must be done periodically to get fresh new results ! An id is attributed to the overall results of a request : on further requests (for example to query for different pages of results), the requester can provide this id and get in return the cached data, avoiding another longer process of computing the results from scratch. Obviously, new computing must be done periodically to get fresh new results !
There's also a basic cache to store the results of the _same_ request sent multiple times successively.
Cache TTLs are customizable in the `.env` file.
## Tests / ESLint / Prettier ## Tests / ESLint / Prettier
Tests are run outside the container for ease of use (switching between different environments inside containers using prisma is complicated and error prone). Tests are run outside the container for ease of use (switching between different environments inside containers using prisma is complicated and error prone).

View File

@@ -11,11 +11,10 @@ services:
- .:/usr/src/app - .:/usr/src/app
env_file: env_file:
- .env - .env
command: npm run start:debug command: npm run start:dev
ports: ports:
- ${SERVICE_PORT:-5005}:${SERVICE_PORT:-5005} - ${SERVICE_PORT:-5005}:${SERVICE_PORT:-5005}
- ${HEALTH_SERVICE_PORT:-6005}:${HEALTH_SERVICE_PORT:-6005} - ${HEALTH_SERVICE_PORT:-6005}:${HEALTH_SERVICE_PORT:-6005}
- 9225:9229
networks: networks:
v3-network: v3-network:
aliases: aliases:

View File

@@ -1,6 +1,6 @@
{ {
"name": "@mobicoop/matcher", "name": "@mobicoop/matcher",
"version": "1.6.0", "version": "1.5.5",
"description": "Mobicoop V3 Matcher", "description": "Mobicoop V3 Matcher",
"author": "sbriat", "author": "sbriat",
"private": true, "private": true,
@@ -11,7 +11,7 @@
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start", "start": "nest start",
"start:dev": "nest start --watch", "start:dev": "nest start --watch",
"start:debug": "nest start --debug 0.0.0.0:9229 --watch", "start:debug": "nest start --debug --watch",
"start:prod": "node dist/main", "start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"lint:check": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix-dry-run --ignore-path .gitignore", "lint:check": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix-dry-run --ignore-path .gitignore",

View File

@@ -1,24 +0,0 @@
import { ArgumentsHost, Catch, Logger } from '@nestjs/common';
import { BaseRpcExceptionFilter } from '@nestjs/microservices';
import { Observable } from 'rxjs';
@Catch()
export class LogCauseExceptionFilter extends BaseRpcExceptionFilter {
private static readonly causeLogger = new Logger('RpcExceptionsHandler');
catch(exception: any, host: ArgumentsHost): Observable<any> {
const response = super.catch(exception, host);
const cause = exception.cause;
if (cause) {
if (this.isError(cause)) {
LogCauseExceptionFilter.causeLogger.error(
'Caused by: ' + cause.message,
cause.stack,
);
} else {
LogCauseExceptionFilter.causeLogger.error('Caused by: ' + cause);
}
}
return response;
}
}

View File

@@ -19,3 +19,4 @@ export const AD_CONFIGURATION_REPOSITORY = Symbol(
'AD_CONFIGURATION_REPOSITORY', 'AD_CONFIGURATION_REPOSITORY',
); );
export const GEOGRAPHY_PACKAGE = Symbol('GEOGRAPHY_PACKAGE'); export const GEOGRAPHY_PACKAGE = Symbol('GEOGRAPHY_PACKAGE');
export const GEOGRAPHY_SERVICE = Symbol('GEOGRAPHY_SERVICE');

View File

@@ -12,6 +12,7 @@ import {
MATCHING_REPOSITORY, MATCHING_REPOSITORY,
AD_CONFIGURATION_REPOSITORY, AD_CONFIGURATION_REPOSITORY,
GEOGRAPHY_PACKAGE, GEOGRAPHY_PACKAGE,
GEOGRAPHY_SERVICE,
} from './ad.di-tokens'; } from './ad.di-tokens';
import { MessageBrokerPublisher } from '@mobicoop/message-broker-module'; import { MessageBrokerPublisher } from '@mobicoop/message-broker-module';
import { AdRepository } from './infrastructure/ad.repository'; import { AdRepository } from './infrastructure/ad.repository';
@@ -64,6 +65,20 @@ const imports = [
}), }),
}, },
]), ]),
ClientsModule.register([
{
name: GEOGRAPHY_SERVICE,
transport: Transport.RMQ,
options: {
//TODO read from config
urls: [`${process.env.MESSAGE_BROKER_URI}`],
queue: 'geography',
queueOptions: {
durable: true,
},
},
},
]),
CacheModule.registerAsync<RedisClientOptions>({ CacheModule.registerAsync<RedisClientOptions>({
imports: [ConfigModule], imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({ useFactory: async (configService: ConfigService) => ({

View File

@@ -1,9 +1,9 @@
import { CandidateEntity } from '@modules/ad/core/domain/candidate.entity'; import { CandidateEntity } from '@modules/ad/core/domain/candidate.entity';
import { Completer } from './completer.abstract';
import { MatchQuery } from '../match.query';
import { Step } from '../../../types/step.type';
import { CarpoolPathItem } from '@modules/ad/core/domain/value-objects/carpool-path-item.value-object'; import { CarpoolPathItem } from '@modules/ad/core/domain/value-objects/carpool-path-item.value-object';
import { RouteResponse } from '../../../ports/georouter.port'; import { RouteResponse } from '../../../ports/georouter.port';
import { Step } from '../../../types/step.type';
import { MatchQuery } from '../match.query';
import { Completer } from './completer.abstract';
export class RouteCompleter extends Completer { export class RouteCompleter extends Completer {
protected readonly type: RouteCompleterType; protected readonly type: RouteCompleterType;
@@ -48,7 +48,10 @@ export class RouteCompleter extends Completer {
): Promise<RouteResponse> => ): Promise<RouteResponse> =>
this.query.routeProvider.getRoute({ this.query.routeProvider.getRoute({
waypoints: (candidate.getProps().carpoolPath as CarpoolPathItem[]).map( waypoints: (candidate.getProps().carpoolPath as CarpoolPathItem[]).map(
(carpoolPathItem: CarpoolPathItem) => carpoolPathItem, (carpoolPathItem: CarpoolPathItem) => ({
lon: carpoolPathItem.lon,
lat: carpoolPathItem.lat,
}),
), ),
detailsSettings: detailsSettings, detailsSettings: detailsSettings,
}); });

View File

@@ -165,7 +165,7 @@ export class MatchQueryHandler implements IQueryHandler {
frequency: query.frequency, frequency: query.frequency,
fromDate: query.fromDate, fromDate: query.fromDate,
toDate: query.toDate, toDate: query.toDate,
schedule: query.schedule?.map((scheduleItem: ScheduleItem) => ({ schedule: query.schedule.map((scheduleItem: ScheduleItem) => ({
day: scheduleItem.day as number, day: scheduleItem.day as number,
time: scheduleItem.time, time: scheduleItem.time,
margin: scheduleItem.margin as number, margin: scheduleItem.margin as number,

View File

@@ -21,12 +21,11 @@ export class MatchQuery extends QueryBase {
readonly frequency: Frequency; readonly frequency: Frequency;
fromDate: string; fromDate: string;
toDate: string; toDate: string;
schedule?: ScheduleItem[]; schedule: ScheduleItem[];
seatsProposed?: number; seatsProposed?: number;
seatsRequested?: number; seatsRequested?: number;
strict?: boolean; strict?: boolean;
readonly waypoints: Waypoint[]; readonly waypoints: Waypoint[];
excludedAdId?: string;
algorithmType?: AlgorithmType; algorithmType?: AlgorithmType;
remoteness?: number; remoteness?: number;
useProportion?: boolean; useProportion?: boolean;
@@ -57,7 +56,6 @@ export class MatchQuery extends QueryBase {
this.seatsRequested = props.seatsRequested; this.seatsRequested = props.seatsRequested;
this.strict = props.strict; this.strict = props.strict;
this.waypoints = props.waypoints; this.waypoints = props.waypoints;
this.excludedAdId = props.excludedAdId;
this.algorithmType = props.algorithmType; this.algorithmType = props.algorithmType;
this.remoteness = props.remoteness; this.remoteness = props.remoteness;
this.useProportion = props.useProportion; this.useProportion = props.useProportion;
@@ -75,7 +73,7 @@ export class MatchQuery extends QueryBase {
} }
setMissingMarginDurations = (defaultMarginDuration: number): MatchQuery => { setMissingMarginDurations = (defaultMarginDuration: number): MatchQuery => {
this.schedule?.forEach((day: ScheduleItem) => { this.schedule.forEach((day: ScheduleItem) => {
if (day.margin === undefined) day.margin = defaultMarginDuration; if (day.margin === undefined) day.margin = defaultMarginDuration;
}); });
return this; return this;
@@ -138,8 +136,6 @@ export class MatchQuery extends QueryBase {
setDatesAndSchedule = ( setDatesAndSchedule = (
datetimeTransformer: DateTimeTransformerPort, datetimeTransformer: DateTimeTransformerPort,
): MatchQuery => { ): MatchQuery => {
// no transformation if schedule is not set
if (this.schedule === undefined) return this;
const initialFromDate: string = this.fromDate; const initialFromDate: string = this.fromDate;
this.fromDate = datetimeTransformer.fromDate( this.fromDate = datetimeTransformer.fromDate(
{ {
@@ -213,7 +209,10 @@ export class MatchQuery extends QueryBase {
pathCreator.getBasePaths().map(async (path: Path) => ({ pathCreator.getBasePaths().map(async (path: Path) => ({
type: path.type, type: path.type,
route: await this.routeProvider.getRoute({ route: await this.routeProvider.getRoute({
waypoints: path.waypoints, waypoints: path.waypoints.map((p) => ({
lon: p.lon,
lat: p.lat,
})),
}), }),
})), })),
) )
@@ -229,9 +228,8 @@ export class MatchQuery extends QueryBase {
} }
}); });
} catch (e: any) { } catch (e: any) {
throw new Error('Unable to find a route for given waypoints', { console.log(e.stack || e);
cause: e, throw new Error('Unable to find a route for given waypoints');
});
} }
return this; return this;
}; };

View File

@@ -19,6 +19,7 @@ export class PassengerOrientedSelector extends Selector {
query: this._createQueryString(Role.PASSENGER), query: this._createQueryString(Role.PASSENGER),
role: Role.PASSENGER, role: Role.PASSENGER,
}); });
return ( return (
await Promise.all( await Promise.all(
queryStringRoles.map<Promise<AdsRole>>( queryStringRoles.map<Promise<AdsRole>>(
@@ -73,7 +74,7 @@ export class PassengerOrientedSelector extends Selector {
driverSchedule: driverSchedule:
adsRole.role == Role.PASSENGER adsRole.role == Role.PASSENGER
? adEntity.getProps().schedule ? adEntity.getProps().schedule
: this.query.schedule?.map((scheduleItem: ScheduleItem) => ({ : this.query.schedule.map((scheduleItem: ScheduleItem) => ({
day: scheduleItem.day as number, day: scheduleItem.day as number,
time: scheduleItem.time, time: scheduleItem.time,
margin: scheduleItem.margin as number, margin: scheduleItem.margin as number,
@@ -81,7 +82,7 @@ export class PassengerOrientedSelector extends Selector {
passengerSchedule: passengerSchedule:
adsRole.role == Role.DRIVER adsRole.role == Role.DRIVER
? adEntity.getProps().schedule ? adEntity.getProps().schedule
: this.query.schedule?.map((scheduleItem: ScheduleItem) => ({ : this.query.schedule.map((scheduleItem: ScheduleItem) => ({
day: scheduleItem.day as number, day: scheduleItem.day as number,
time: scheduleItem.time, time: scheduleItem.time,
margin: scheduleItem.margin as number, margin: scheduleItem.margin as number,
@@ -136,7 +137,6 @@ export class PassengerOrientedSelector extends Selector {
this._whereStrict(), this._whereStrict(),
this._whereDate(), this._whereDate(),
this._whereSchedule(role), this._whereSchedule(role),
this._whereExcludedAd(),
this._whereAzimuth(), this._whereAzimuth(),
this._whereProportion(role), this._whereProportion(role),
this._whereRemoteness(role), this._whereRemoteness(role),
@@ -155,9 +155,7 @@ export class PassengerOrientedSelector extends Selector {
: ''; : '';
private _whereDate = (): string => private _whereDate = (): string =>
this.query.frequency == Frequency.PUNCTUAL `(\
? `("fromDate" <= '${this.query.fromDate}' AND "toDate" >= '${this.query.fromDate}')`
: `(\
(\ (\
"fromDate" <= '${this.query.fromDate}' AND "fromDate" <= '${this.query.toDate}' AND\ "fromDate" <= '${this.query.fromDate}' AND "fromDate" <= '${this.query.toDate}' AND\
"toDate" >= '${this.query.toDate}' AND "toDate" >= '${this.query.fromDate}'\ "toDate" >= '${this.query.toDate}' AND "toDate" >= '${this.query.fromDate}'\
@@ -174,8 +172,6 @@ export class PassengerOrientedSelector extends Selector {
)`; )`;
private _whereSchedule = (role: Role): string => { private _whereSchedule = (role: Role): string => {
// no schedule filtering if schedule is not set
if (this.query.schedule === undefined) return '';
const schedule: string[] = []; const schedule: string[] = [];
// we need full dates to compare times, because margins can lead to compare on previous or next day // we need full dates to compare times, because margins can lead to compare on previous or next day
// - first we establish a base calendar (up to a week) // - first we establish a base calendar (up to a week)
@@ -186,7 +182,7 @@ export class PassengerOrientedSelector extends Selector {
// - then we compare each resulting day of the schedule with each day of calendar, // - then we compare each resulting day of the schedule with each day of calendar,
// adding / removing margin depending on the role // adding / removing margin depending on the role
scheduleDates.map((date: Date) => { scheduleDates.map((date: Date) => {
(this.query.schedule as ScheduleItem[]) this.query.schedule
.filter( .filter(
(scheduleItem: ScheduleItem) => date.getUTCDay() == scheduleItem.day, (scheduleItem: ScheduleItem) => date.getUTCDay() == scheduleItem.day,
) )
@@ -207,9 +203,6 @@ export class PassengerOrientedSelector extends Selector {
return ''; return '';
}; };
private _whereExcludedAd = (): string =>
this.query.excludedAdId ? `ad.uuid <> '${this.query.excludedAdId}'` : '';
private _wherePassengerSchedule = ( private _wherePassengerSchedule = (
date: Date, date: Date,
scheduleItem: ScheduleItem, scheduleItem: ScheduleItem,
@@ -317,11 +310,6 @@ export class PassengerOrientedSelector extends Selector {
} }
}; };
/**
* Returns an array of dates containing all the dates (limited to 7 by default) between 2 boundary dates.
*
* The array length can be limited to a _max_ number of dates (default: 7)
*/
private _datesBetweenBoundaries = ( private _datesBetweenBoundaries = (
firstDate: string, firstDate: string,
lastDate: string, lastDate: string,

View File

@@ -1,28 +1,21 @@
import { import { AggregateRoot, AggregateID } from '@mobicoop/ddd-library';
AggregateID,
AggregateRoot,
ArgumentInvalidException,
} from '@mobicoop/ddd-library';
import { Role } from './ad.types';
import { CalendarTools } from './calendar-tools.service';
import { import {
CandidateProps, CandidateProps,
CreateCandidateProps, CreateCandidateProps,
Target, Target,
} from './candidate.types'; } from './candidate.types';
import { ActorTime } from './value-objects/actor-time.value-object';
import { Actor } from './value-objects/actor.value-object';
import { import {
CarpoolPathItem, CarpoolPathItem,
CarpoolPathItemProps, CarpoolPathItemProps,
} from './value-objects/carpool-path-item.value-object'; } from './value-objects/carpool-path-item.value-object';
import { JourneyItem } from './value-objects/journey-item.value-object';
import { Journey, JourneyProps } from './value-objects/journey.value-object';
import {
ScheduleItem,
ScheduleItemProps,
} from './value-objects/schedule-item.value-object';
import { Step, StepProps } from './value-objects/step.value-object'; import { Step, StepProps } from './value-objects/step.value-object';
import { ScheduleItem } from './value-objects/schedule-item.value-object';
import { Journey } from './value-objects/journey.value-object';
import { CalendarTools } from './calendar-tools.service';
import { JourneyItem } from './value-objects/journey-item.value-object';
import { Actor } from './value-objects/actor.value-object';
import { ActorTime } from './value-objects/actor-time.value-object';
import { Role } from './ad.types';
export class CandidateEntity extends AggregateRoot<CandidateProps> { export class CandidateEntity extends AggregateRoot<CandidateProps> {
protected readonly _id: AggregateID; protected readonly _id: AggregateID;
@@ -60,26 +53,18 @@ export class CandidateEntity extends AggregateRoot<CandidateProps> {
* This is a tedious process : additional information can be found in deeper methods ! * This is a tedious process : additional information can be found in deeper methods !
*/ */
createJourneys = (): CandidateEntity => { createJourneys = (): CandidateEntity => {
// driver and passenger schedules are eventually mandatory
if (!this.props.driverSchedule) this._createDriverSchedule();
if (!this.props.passengerSchedule) this._createPassengerSchedule();
this.props.journeys = this.props.driverSchedule!.reduce(
(accJourneys: JourneyProps[], driverScheduleItem: ScheduleItem) => {
try { try {
this.props.journeys = this.props.driverSchedule
// first we create the journeys // first we create the journeys
const journey = this._createJourney(driverScheduleItem); .map((driverScheduleItem: ScheduleItem) =>
this._createJourney(driverScheduleItem),
)
// then we filter the ones with invalid pickups // then we filter the ones with invalid pickups
if (journey.hasValidPickUp()) { .filter((journey: Journey) => journey.hasValidPickUp());
accJourneys.push(journey);
}
} catch (e) { } catch (e) {
// irrelevant journeys fall here // irrelevant journeys fall here
// eg. no available day for the given date range // eg. no available day for the given date range
} }
return accJourneys;
},
new Array<JourneyProps>(),
);
return this; return this;
}; };
@@ -97,136 +82,6 @@ export class CandidateEntity extends AggregateRoot<CandidateProps> {
(1 + this.props.spacetimeDetourRatio.maxDistanceDetourRatio) (1 + this.props.spacetimeDetourRatio.maxDistanceDetourRatio)
: false; : false;
/**
* Create the driver schedule based on the passenger schedule
*/
private _createDriverSchedule = (): void => {
let driverSchedule: Array<ScheduleItemProps | undefined> =
this.props.passengerSchedule!.map(
(scheduleItemProps: ScheduleItemProps) => ({
day: scheduleItemProps.day,
time: scheduleItemProps.time,
margin: scheduleItemProps.margin,
}),
);
// adjust the driver theoretical schedule :
// we guess the ideal driver departure time based on the duration to
// reach the passenger starting point from the driver starting point
driverSchedule = driverSchedule
.map((scheduleItemProps: ScheduleItemProps) => {
try {
const driverDate: Date = CalendarTools.firstDate(
scheduleItemProps.day,
this.props.dateInterval,
);
const driverStartDatetime: Date = CalendarTools.datetimeWithSeconds(
driverDate,
scheduleItemProps.time,
-this._passengerStartDuration(),
);
return <ScheduleItemProps>{
day: driverDate.getUTCDay(),
margin: scheduleItemProps.margin,
time: `${driverStartDatetime
.getUTCHours()
.toString()
.padStart(2, '0')}:${driverStartDatetime
.getUTCMinutes()
.toString()
.padStart(2, '0')}`,
};
} catch (e) {
// no possible driver date or time
// TODO : find a test case !
return undefined;
}
})
.filter(
(scheduleItemProps: ScheduleItemProps | undefined) =>
scheduleItemProps !== undefined,
);
this.props.driverSchedule = driverSchedule.map(
(scheduleItemProps: ScheduleItemProps) => ({
day: scheduleItemProps.day,
time: scheduleItemProps.time,
margin: scheduleItemProps.margin,
}),
);
};
/**
* Return the duration to reach the passenger starting point from the driver starting point
*/
private _passengerStartDuration = (): number => {
let passengerStartStepIndex = 0;
this.props.carpoolPath?.forEach(
(carpoolPathItem: CarpoolPathItem, index: number) => {
carpoolPathItem.actors.forEach((actor: Actor) => {
if (actor.role == Role.PASSENGER && actor.target == Target.START)
passengerStartStepIndex = index;
});
},
);
return this.props.steps![passengerStartStepIndex].duration;
};
/**
* Create the passenger schedule based on the driver schedule
*/
private _createPassengerSchedule = (): void => {
let passengerSchedule: Array<ScheduleItemProps | undefined> =
this.props.driverSchedule!.map(
(scheduleItemProps: ScheduleItemProps) => ({
day: scheduleItemProps.day,
time: scheduleItemProps.time,
margin: scheduleItemProps.margin,
}),
);
// adjust the passenger theoretical schedule :
// we guess the ideal passenger departure time based on the duration to
// reach the passenger starting point from the driver starting point
passengerSchedule = passengerSchedule
.map((scheduleItemProps: ScheduleItemProps) => {
try {
const passengerDate: Date = CalendarTools.firstDate(
scheduleItemProps.day,
this.props.dateInterval,
);
const passengeStartDatetime: Date = CalendarTools.datetimeWithSeconds(
passengerDate,
scheduleItemProps.time,
this._passengerStartDuration(),
);
return {
day: passengerDate.getUTCDay(),
margin: scheduleItemProps.margin,
time: `${passengeStartDatetime
.getUTCHours()
.toString()
.padStart(2, '0')}:${passengeStartDatetime
.getUTCMinutes()
.toString()
.padStart(2, '0')}`,
};
} catch (e) {
// no possible passenger date or time
// TODO : find a test case !
return undefined;
}
})
.filter(
(scheduleItemProps: ScheduleItemProps | undefined) =>
scheduleItemProps !== undefined,
);
this.props.passengerSchedule = passengerSchedule.map(
(scheduleItemProps: ScheduleItemProps) => ({
day: scheduleItemProps.day,
time: scheduleItemProps.time,
margin: scheduleItemProps.margin,
}),
);
};
private _createJourney = (driverScheduleItem: ScheduleItem): Journey => private _createJourney = (driverScheduleItem: ScheduleItem): Journey =>
new Journey({ new Journey({
firstDate: CalendarTools.firstDate( firstDate: CalendarTools.firstDate(
@@ -361,7 +216,7 @@ export class CandidateEntity extends AggregateRoot<CandidateProps> {
* Find the passenger schedule item with the minimum duration between a given date and the dates of the passenger schedule * Find the passenger schedule item with the minimum duration between a given date and the dates of the passenger schedule
*/ */
private _minPassengerScheduleItemGapForDate = (date: Date): ScheduleItemGap => private _minPassengerScheduleItemGapForDate = (date: Date): ScheduleItemGap =>
(this.props.passengerSchedule as ScheduleItemProps[]) this.props.passengerSchedule
// first map the passenger schedule to "real" dates (we use unix epoch date as base) // first map the passenger schedule to "real" dates (we use unix epoch date as base)
.map( .map(
(scheduleItem: ScheduleItem) => (scheduleItem: ScheduleItem) =>
@@ -400,10 +255,6 @@ export class CandidateEntity extends AggregateRoot<CandidateProps> {
validate(): void { validate(): void {
// entity business rules validation to protect it's invariant before saving entity to a database // entity business rules validation to protect it's invariant before saving entity to a database
if (!this.props.driverSchedule && !this.props.passengerSchedule)
throw new ArgumentInvalidException(
'at least the driver or the passenger schedule is required',
);
} }
} }

View File

@@ -11,8 +11,8 @@ export interface CandidateProps {
frequency: Frequency; frequency: Frequency;
driverWaypoints: PointProps[]; driverWaypoints: PointProps[];
passengerWaypoints: PointProps[]; passengerWaypoints: PointProps[];
driverSchedule?: ScheduleItemProps[]; driverSchedule: ScheduleItemProps[];
passengerSchedule?: ScheduleItemProps[]; passengerSchedule: ScheduleItemProps[];
driverDistance: number; driverDistance: number;
driverDuration: number; driverDuration: number;
dateInterval: DateInterval; dateInterval: DateInterval;
@@ -33,8 +33,8 @@ export interface CreateCandidateProps {
driverDuration: number; driverDuration: number;
driverWaypoints: PointProps[]; driverWaypoints: PointProps[];
passengerWaypoints: PointProps[]; passengerWaypoints: PointProps[];
driverSchedule?: ScheduleItemProps[]; driverSchedule: ScheduleItemProps[];
passengerSchedule?: ScheduleItemProps[]; passengerSchedule: ScheduleItemProps[];
spacetimeDetourRatio: SpacetimeDetourRatio; spacetimeDetourRatio: SpacetimeDetourRatio;
dateInterval: DateInterval; dateInterval: DateInterval;
} }

View File

@@ -1,7 +1,7 @@
import { Role } from './ad.types';
import { Point } from './value-objects/point.value-object';
import { PathCreatorException } from './match.errors';
import { Route } from '../application/types/route.type'; import { Route } from '../application/types/route.type';
import { Role } from './ad.types';
import { PathCreatorException } from './match.errors';
import { Point } from './value-objects/point.value-object';
export class PathCreator { export class PathCreator {
constructor( constructor(

View File

@@ -2,7 +2,8 @@ import {
ArgumentOutOfRangeException, ArgumentOutOfRangeException,
ValueObject, ValueObject,
} from '@mobicoop/ddd-library'; } from '@mobicoop/ddd-library';
import { ActorProps } from './actor.value-object'; import { Actor, ActorProps } from './actor.value-object';
import { Role } from '../ad.types';
import { Point, PointProps } from './point.value-object'; import { Point, PointProps } from './point.value-object';
/** Note: /** Note:
@@ -35,5 +36,12 @@ export class CarpoolPathItem extends ValueObject<CarpoolPathItemProps> {
}); });
if (props.actors.length <= 0) if (props.actors.length <= 0)
throw new ArgumentOutOfRangeException('at least one actor is required'); throw new ArgumentOutOfRangeException('at least one actor is required');
if (
props.actors.filter((actor: Actor) => actor.role == Role.DRIVER).length >
1
)
throw new ArgumentOutOfRangeException(
'a carpoolStep can contain only one driver',
);
} }
} }

View File

@@ -42,8 +42,8 @@ export class JourneyItem extends ValueObject<JourneyItemProps> {
(actorTime: ActorTime) => actorTime.role == Role.DRIVER, (actorTime: ActorTime) => actorTime.role == Role.DRIVER,
) as ActorTime ) as ActorTime
).firstDatetime; ).firstDatetime;
return `${driverTime.getUTCHours().toString().padStart(2, '0')}:${driverTime return `${driverTime.getHours().toString().padStart(2, '0')}:${driverTime
.getUTCMinutes() .getMinutes()
.toString() .toString()
.padStart(2, '0')}`; .padStart(2, '0')}`;
}; };

View File

@@ -46,29 +46,6 @@ export class Journey extends ValueObject<JourneyProps> {
const driverActorTime = passengerDepartureJourneyItem.actorTimes.find( const driverActorTime = passengerDepartureJourneyItem.actorTimes.find(
(actorTime: ActorTime) => actorTime.role == Role.DRIVER, (actorTime: ActorTime) => actorTime.role == Role.DRIVER,
) as ActorTime; ) as ActorTime;
// TODO : check if the following conditions are even to the ones used in the return
// 4 possibilities to be valid :
// - 1 : the driver time boundaries are within the passenger time boundaries
// - 2 : the max driver time boundary is within the passenger time boundaries
// - 3 : the min driver time boundary is within the passenger time boundaries
// - 4 : the passenger time boundaries are within the driver time boundaries
// return (
// // 1
// (driverActorTime.firstMinDatetime >=
// passengerDepartureActorTime.firstMinDatetime &&
// driverActorTime.firstMaxDatetime <=
// passengerDepartureActorTime.firstMaxDatetime) ||
// // 2 & 4
// (driverActorTime.firstMinDatetime <=
// passengerDepartureActorTime.firstMinDatetime &&
// driverActorTime.firstMaxDatetime >=
// passengerDepartureActorTime.firstMinDatetime) ||
// // 3
// (driverActorTime.firstMinDatetime >=
// passengerDepartureActorTime.firstMinDatetime &&
// driverActorTime.firstMinDatetime <=
// passengerDepartureActorTime.firstMaxDatetime)
// );
return ( return (
(passengerDepartureActorTime.firstMinDatetime <= (passengerDepartureActorTime.firstMinDatetime <=
driverActorTime.firstMaxDatetime && driverActorTime.firstMaxDatetime &&

View File

@@ -14,7 +14,7 @@ export interface MatchQueryProps {
frequency: Frequency; frequency: Frequency;
fromDate: string; fromDate: string;
toDate: string; toDate: string;
schedule?: ScheduleItemProps[]; schedule: ScheduleItemProps[];
seatsProposed: number; seatsProposed: number;
seatsRequested: number; seatsRequested: number;
strict: boolean; strict: boolean;
@@ -50,7 +50,7 @@ export class MatchQuery extends ValueObject<MatchQueryProps> {
return this.props.toDate; return this.props.toDate;
} }
get schedule(): ScheduleItemProps[] | undefined { get schedule(): ScheduleItemProps[] {
return this.props.schedule; return this.props.schedule;
} }

View File

@@ -1,35 +1,26 @@
import { Inject, Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { Observable, lastValueFrom } from 'rxjs'; import { Observable, lastValueFrom } from 'rxjs';
import { Inject, Injectable, OnModuleInit } from '@nestjs/common'; import { GEOGRAPHY_SERVICE } from '../ad.di-tokens';
import { ClientGrpc } from '@nestjs/microservices';
import { GRPC_GEOROUTER_SERVICE_NAME } from '@src/app.constants';
import { import {
GeorouterPort, GeorouterPort,
RouteRequest, RouteRequest,
RouteResponse, RouteResponse,
} from '../core/application/ports/georouter.port'; } from '../core/application/ports/georouter.port';
import { GEOGRAPHY_PACKAGE } from '../ad.di-tokens';
interface GeorouterService { interface GeorouterService {
getRoute(request: RouteRequest): Observable<RouteResponse>; getRoute(request: RouteRequest): Observable<RouteResponse>;
} }
@Injectable() @Injectable()
export class Georouter implements GeorouterPort, OnModuleInit { export class Georouter implements GeorouterPort {
private georouterService: GeorouterService; private georouterService: GeorouterService;
constructor(@Inject(GEOGRAPHY_PACKAGE) private readonly client: ClientGrpc) {} constructor(
@Inject(GEOGRAPHY_SERVICE) private readonly client: ClientProxy,
onModuleInit() { ) {}
this.georouterService = this.client.getService<GeorouterService>(
GRPC_GEOROUTER_SERVICE_NAME,
);
}
getRoute = async (request: RouteRequest): Promise<RouteResponse> => { getRoute = async (request: RouteRequest): Promise<RouteResponse> => {
try { return lastValueFrom(this.client.send('getRoute', request));
return await lastValueFrom(this.georouterService.getRoute(request));
} catch (error: any) {
throw error;
}
}; };
} }

View File

@@ -1,11 +1,10 @@
import { ResponseBase } from '@mobicoop/ddd-library'; import { ResponseBase } from '@mobicoop/ddd-library';
import { JourneyResponseDto } from './journey.response.dto'; import { JourneyResponseDto } from './journey.response.dto';
import { Frequency } from '@modules/ad/core/domain/ad.types';
export class MatchResponseDto extends ResponseBase { export class MatchResponseDto extends ResponseBase {
adId: string; adId: string;
role: string; role: string;
frequency: Frequency; frequency: string;
distance: number; distance: number;
duration: number; duration: number;
initialDistance: number; initialDistance: number;

View File

@@ -58,9 +58,8 @@ export class MatchRequestDto {
@Type(() => ScheduleItemDto) @Type(() => ScheduleItemDto)
@IsArray() @IsArray()
@ArrayMinSize(1) @ArrayMinSize(1)
@IsOptional()
@ValidateNested({ each: true }) @ValidateNested({ each: true })
schedule?: ScheduleItemDto[]; schedule: ScheduleItemDto[];
@IsOptional() @IsOptional()
@IsInt() @IsInt()
@@ -81,10 +80,6 @@ export class MatchRequestDto {
@ValidateNested({ each: true }) @ValidateNested({ each: true })
waypoints: WaypointDto[]; waypoints: WaypointDto[];
@IsUUID()
@IsOptional()
excludedAdId?: string;
@IsOptional() @IsOptional()
@IsEnum(AlgorithmType) @IsEnum(AlgorithmType)
algorithmType?: AlgorithmType; algorithmType?: AlgorithmType;

View File

@@ -1,18 +1,18 @@
import { Controller, Inject, UseInterceptors, UsePipes } from '@nestjs/common';
import { GrpcMethod, RpcException } from '@nestjs/microservices';
import { RpcValidationPipe } from '@mobicoop/ddd-library'; import { RpcValidationPipe } from '@mobicoop/ddd-library';
import { AD_ROUTE_PROVIDER } from '@modules/ad/ad.di-tokens'; import { RpcExceptionCode } from '@mobicoop/ddd-library';
import { GeorouterPort } from '@modules/ad/core/application/ports/georouter.port';
import { MatchQuery } from '@modules/ad/core/application/queries/match/match.query';
import { MatchingResult } from '@modules/ad/core/application/queries/match/match.query-handler';
import { MatchEntity } from '@modules/ad/core/domain/match.entity';
import { MatchMapper } from '@modules/ad/match.mapper';
import { Controller, Inject, UseFilters, UsePipes } from '@nestjs/common';
import { QueryBus } from '@nestjs/cqrs';
import { GrpcMethod } from '@nestjs/microservices';
import { LogCauseExceptionFilter } from '@src/log-cause.exception-filter';
import { MatchingPaginatedResponseDto } from '../dtos/matching.paginated.response.dto'; import { MatchingPaginatedResponseDto } from '../dtos/matching.paginated.response.dto';
import { QueryBus } from '@nestjs/cqrs';
import { MatchRequestDto } from './dtos/match.request.dto'; import { MatchRequestDto } from './dtos/match.request.dto';
import { MatchQuery } from '@modules/ad/core/application/queries/match/match.query';
import { MatchEntity } from '@modules/ad/core/domain/match.entity';
import { AD_ROUTE_PROVIDER } from '@modules/ad/ad.di-tokens';
import { MatchMapper } from '@modules/ad/match.mapper';
import { MatchingResult } from '@modules/ad/core/application/queries/match/match.query-handler';
import { CacheInterceptor, CacheKey } from '@nestjs/cache-manager';
import { GeorouterPort } from '@modules/ad/core/application/ports/georouter.port';
@UseFilters(LogCauseExceptionFilter)
@UsePipes( @UsePipes(
new RpcValidationPipe({ new RpcValidationPipe({
whitelist: false, whitelist: false,
@@ -28,8 +28,11 @@ export class MatchGrpcController {
private readonly matchMapper: MatchMapper, private readonly matchMapper: MatchMapper,
) {} ) {}
@CacheKey('MatcherServiceMatch')
@UseInterceptors(CacheInterceptor)
@GrpcMethod('MatcherService', 'Match') @GrpcMethod('MatcherService', 'Match')
async match(data: MatchRequestDto): Promise<MatchingPaginatedResponseDto> { async match(data: MatchRequestDto): Promise<MatchingPaginatedResponseDto> {
try {
const matchingResult: MatchingResult = await this.queryBus.execute( const matchingResult: MatchingResult = await this.queryBus.execute(
new MatchQuery(data, this.routeProvider), new MatchQuery(data, this.routeProvider),
); );
@@ -42,5 +45,11 @@ export class MatchGrpcController {
perPage: matchingResult.perPage, perPage: matchingResult.perPage,
total: matchingResult.total, total: matchingResult.total,
}); });
} catch (e) {
throw new RpcException({
code: RpcExceptionCode.UNKNOWN,
message: e.message,
});
}
} }
} }

View File

@@ -16,17 +16,16 @@ message MatchRequest {
repeated ScheduleItem schedule = 7; repeated ScheduleItem schedule = 7;
bool strict = 8; bool strict = 8;
repeated Waypoint waypoints = 9; repeated Waypoint waypoints = 9;
string excludedAdId = 10; AlgorithmType algorithmType = 10;
AlgorithmType algorithmType = 11; int32 remoteness = 11;
int32 remoteness = 12; bool useProportion = 12;
bool useProportion = 13; float proportion = 13;
float proportion = 14; bool useAzimuth = 14;
bool useAzimuth = 15; int32 azimuthMargin = 15;
int32 azimuthMargin = 16; float maxDetourDistanceRatio = 16;
float maxDetourDistanceRatio = 17; float maxDetourDurationRatio = 17;
float maxDetourDurationRatio = 18; optional int32 page = 18;
optional int32 page = 19; optional int32 perPage = 19;
optional int32 perPage = 20;
} }
message ScheduleItem { message ScheduleItem {
@@ -59,16 +58,15 @@ enum AlgorithmType {
message Match { message Match {
string adId = 1; string adId = 1;
string role = 2; string role = 2;
Frequency frequency = 3; int32 distance = 3;
int32 distance = 4; int32 duration = 4;
int32 duration = 5; int32 initialDistance = 5;
int32 initialDistance = 6; int32 initialDuration = 6;
int32 initialDuration = 7; int32 distanceDetour = 7;
int32 distanceDetour = 8; int32 durationDetour = 8;
int32 durationDetour = 9; double distanceDetourPercentage = 9;
double distanceDetourPercentage = 10; double durationDetourPercentage = 10;
double durationDetourPercentage = 11; repeated Journey journeys = 11;
repeated Journey journeys = 12;
} }
message Journey { message Journey {

View File

@@ -64,7 +64,7 @@ export class MatchingMapper
toDate: entity.getProps().query.toDate, toDate: entity.getProps().query.toDate,
schedule: entity schedule: entity
.getProps() .getProps()
.query.schedule?.map((scheduleItem: ScheduleItem) => ({ .query.schedule.map((scheduleItem: ScheduleItem) => ({
day: scheduleItem.day, day: scheduleItem.day,
time: scheduleItem.time, time: scheduleItem.time,
margin: scheduleItem.margin, margin: scheduleItem.margin,

View File

@@ -1,4 +1,3 @@
import { ArgumentInvalidException } from '@mobicoop/ddd-library';
import { Frequency, Role } from '@modules/ad/core/domain/ad.types'; import { Frequency, Role } from '@modules/ad/core/domain/ad.types';
import { CandidateEntity } from '@modules/ad/core/domain/candidate.entity'; import { CandidateEntity } from '@modules/ad/core/domain/candidate.entity';
import { import {
@@ -7,10 +6,7 @@ import {
} from '@modules/ad/core/domain/candidate.types'; } from '@modules/ad/core/domain/candidate.types';
import { Actor } from '@modules/ad/core/domain/value-objects/actor.value-object'; import { Actor } from '@modules/ad/core/domain/value-objects/actor.value-object';
import { CarpoolPathItemProps } from '@modules/ad/core/domain/value-objects/carpool-path-item.value-object'; import { CarpoolPathItemProps } from '@modules/ad/core/domain/value-objects/carpool-path-item.value-object';
import { import { Journey } from '@modules/ad/core/domain/value-objects/journey.value-object';
Journey,
JourneyProps,
} from '@modules/ad/core/domain/value-objects/journey.value-object';
import { PointProps } from '@modules/ad/core/domain/value-objects/point.value-object'; import { PointProps } from '@modules/ad/core/domain/value-objects/point.value-object';
import { ScheduleItemProps } from '@modules/ad/core/domain/value-objects/schedule-item.value-object'; import { ScheduleItemProps } from '@modules/ad/core/domain/value-objects/schedule-item.value-object';
import { StepProps } from '@modules/ad/core/domain/value-objects/step.value-object'; import { StepProps } from '@modules/ad/core/domain/value-objects/step.value-object';
@@ -37,7 +33,7 @@ const waypointsSet2: PointProps[] = [
}, },
]; ];
const mondayAt7: ScheduleItemProps[] = [ const schedule1: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '07:00', time: '07:00',
@@ -45,7 +41,7 @@ const mondayAt7: ScheduleItemProps[] = [
}, },
]; ];
const mondayAt710: ScheduleItemProps[] = [ const schedule2: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '07:10', time: '07:10',
@@ -53,7 +49,7 @@ const mondayAt710: ScheduleItemProps[] = [
}, },
]; ];
const weekdayMornings: ScheduleItemProps[] = [ const schedule3: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '06:30', time: '06:30',
@@ -81,7 +77,7 @@ const weekdayMornings: ScheduleItemProps[] = [
}, },
]; ];
const schooldayMornings: ScheduleItemProps[] = [ const schedule4: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '06:50', time: '06:50',
@@ -104,7 +100,7 @@ const schooldayMornings: ScheduleItemProps[] = [
}, },
]; ];
const saturdayNightAndMondayMorning: ScheduleItemProps[] = [ const schedule5: ScheduleItemProps[] = [
{ {
day: 0, day: 0,
time: '00:02', time: '00:02',
@@ -117,7 +113,7 @@ const saturdayNightAndMondayMorning: ScheduleItemProps[] = [
}, },
]; ];
const mondayAndSaturdayNights: ScheduleItemProps[] = [ const schedule6: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '23:10', time: '23:10',
@@ -130,7 +126,7 @@ const mondayAndSaturdayNights: ScheduleItemProps[] = [
}, },
]; ];
const thursdayEvening: ScheduleItemProps[] = [ const schedule7: ScheduleItemProps[] = [
{ {
day: 4, day: 4,
time: '19:00', time: '19:00',
@@ -266,8 +262,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: mondayAt7, driverSchedule: schedule1,
passengerSchedule: mondayAt710, passengerSchedule: schedule2,
spacetimeDetourRatio, spacetimeDetourRatio,
}); });
expect(candidateEntity.id.length).toBe(36); expect(candidateEntity.id.length).toBe(36);
@@ -286,8 +282,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: mondayAt7, driverSchedule: schedule1,
passengerSchedule: mondayAt710, passengerSchedule: schedule2,
spacetimeDetourRatio, spacetimeDetourRatio,
}).setCarpoolPath(carpoolPath1); }).setCarpoolPath(carpoolPath1);
expect(candidateEntity.getProps().carpoolPath).toHaveLength(2); expect(candidateEntity.getProps().carpoolPath).toHaveLength(2);
@@ -306,8 +302,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: mondayAt7, driverSchedule: schedule1,
passengerSchedule: mondayAt710, passengerSchedule: schedule2,
spacetimeDetourRatio, spacetimeDetourRatio,
}).setMetrics(352688, 14587); }).setMetrics(352688, 14587);
expect(candidateEntity.getProps().distance).toBe(352688); expect(candidateEntity.getProps().distance).toBe(352688);
@@ -328,8 +324,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: mondayAt7, driverSchedule: schedule1,
passengerSchedule: mondayAt710, passengerSchedule: schedule2,
spacetimeDetourRatio, spacetimeDetourRatio,
}).setMetrics(458690, 13980); }).setMetrics(458690, 13980);
expect(candidateEntity.isDetourValid()).toBeFalsy(); expect(candidateEntity.isDetourValid()).toBeFalsy();
@@ -347,8 +343,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: mondayAt7, driverSchedule: schedule1,
passengerSchedule: mondayAt710, passengerSchedule: schedule2,
spacetimeDetourRatio, spacetimeDetourRatio,
}).setMetrics(352368, 18314); }).setMetrics(352368, 18314);
expect(candidateEntity.isDetourValid()).toBeFalsy(); expect(candidateEntity.isDetourValid()).toBeFalsy();
@@ -369,8 +365,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: mondayAt7, driverSchedule: schedule1,
passengerSchedule: mondayAt710, passengerSchedule: schedule2,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)
@@ -378,95 +374,6 @@ describe('Candidate entity', () => {
.createJourneys(); .createJourneys();
expect(candidateEntity.getProps().journeys).toHaveLength(1); expect(candidateEntity.getProps().journeys).toHaveLength(1);
}); });
it('should create journeys for a single date without driver schedule', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
role: Role.PASSENGER,
frequency: Frequency.PUNCTUAL,
dateInterval: {
lowerDate: '2023-08-28',
higherDate: '2023-08-28',
},
driverWaypoints: waypointsSet1,
passengerWaypoints: waypointsSet2,
driverDistance: 350145,
driverDuration: 13548,
driverSchedule: undefined,
passengerSchedule: mondayAt710,
spacetimeDetourRatio,
})
.setCarpoolPath(carpoolPath2)
.setSteps(steps)
.createJourneys();
expect(candidateEntity.getProps().journeys).toHaveLength(1);
// computed driver start time should be 06:49
expect(
(
candidateEntity.getProps().journeys as JourneyProps[]
)[0].journeyItems[0].actorTimes[0].firstDatetime.getUTCMinutes(),
).toBe(49);
expect(
(
candidateEntity.getProps().journeys as JourneyProps[]
)[0].journeyItems[0].actorTimes[0].firstDatetime.getUTCHours(),
).toBe(6);
});
it('should create journeys for a single date without passenger schedule', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
role: Role.PASSENGER,
frequency: Frequency.PUNCTUAL,
dateInterval: {
lowerDate: '2023-08-28',
higherDate: '2023-08-28',
},
driverWaypoints: waypointsSet1,
passengerWaypoints: waypointsSet2,
driverDistance: 350145,
driverDuration: 13548,
driverSchedule: mondayAt7,
passengerSchedule: undefined,
spacetimeDetourRatio,
})
.setCarpoolPath(carpoolPath2)
.setSteps(steps)
.createJourneys();
expect(candidateEntity.getProps().journeys).toHaveLength(1);
// computed passenger start time should be 07:20
expect(
(
candidateEntity.getProps().journeys as JourneyProps[]
)[0].journeyItems[1].actorTimes[0].firstDatetime.getUTCMinutes(),
).toBe(20);
expect(
(
candidateEntity.getProps().journeys as JourneyProps[]
)[0].journeyItems[1].actorTimes[0].firstDatetime.getUTCHours(),
).toBe(7);
});
it('should throw without driver and passenger schedule', () => {
expect(() =>
CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
role: Role.PASSENGER,
frequency: Frequency.PUNCTUAL,
dateInterval: {
lowerDate: '2023-08-28',
higherDate: '2023-08-28',
},
driverWaypoints: waypointsSet1,
passengerWaypoints: waypointsSet2,
driverDistance: 350145,
driverDuration: 13548,
driverSchedule: undefined,
passengerSchedule: undefined,
spacetimeDetourRatio,
})
.setCarpoolPath(carpoolPath2)
.setSteps(steps)
.createJourneys(),
).toThrow(ArgumentInvalidException);
});
it('should create journeys for multiple dates', () => { it('should create journeys for multiple dates', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({ const candidateEntity: CandidateEntity = CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0', id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
@@ -480,8 +387,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: weekdayMornings, driverSchedule: schedule3,
passengerSchedule: schooldayMornings, passengerSchedule: schedule4,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)
@@ -517,8 +424,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: saturdayNightAndMondayMorning, driverSchedule: schedule5,
passengerSchedule: mondayAndSaturdayNights, passengerSchedule: schedule6,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)
@@ -550,33 +457,6 @@ describe('Candidate entity', () => {
)[0].journeyItems[1].actorTimes[1].firstMinDatetime.getUTCMinutes(), )[0].journeyItems[1].actorTimes[1].firstMinDatetime.getUTCMinutes(),
).toBe(42); ).toBe(42);
}); });
it('should create a journey for a punctual search from a recurrent driver schedule', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
role: Role.PASSENGER,
frequency: Frequency.PUNCTUAL,
dateInterval: {
lowerDate: '2024-04-01', //This is a Monday
higherDate: '2024-04-01',
},
driverWaypoints: waypointsSet1,
passengerWaypoints: waypointsSet2,
driverDistance: 350145,
driverDuration: 13548,
driverSchedule: weekdayMornings,
passengerSchedule: mondayAt7,
spacetimeDetourRatio,
})
.setCarpoolPath(carpoolPath2)
.setSteps(steps)
.createJourneys();
expect(candidateEntity.getProps().journeys).toHaveLength(1);
expect(
(
candidateEntity.getProps().journeys as Journey[]
)[0].firstDate.getDate(),
).toBe(1);
});
it('should not create journeys if dates does not match', () => { it('should not create journeys if dates does not match', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({ const candidateEntity: CandidateEntity = CandidateEntity.create({
@@ -591,8 +471,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: mondayAt7, driverSchedule: schedule1,
passengerSchedule: thursdayEvening, passengerSchedule: schedule7,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)
@@ -615,8 +495,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: mondayAt7, driverSchedule: schedule1,
passengerSchedule: thursdayEvening, passengerSchedule: schedule7,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)

View File

@@ -33,4 +33,22 @@ describe('Carpool Path Item value object', () => {
}); });
}).toThrow(ArgumentOutOfRangeException); }).toThrow(ArgumentOutOfRangeException);
}); });
it('should throw an exception if actors contains more than one driver', () => {
expect(() => {
new CarpoolPathItem({
lat: 48.689445,
lon: 6.17651,
actors: [
new Actor({
role: Role.DRIVER,
target: Target.NEUTRAL,
}),
new Actor({
role: Role.DRIVER,
target: Target.START,
}),
],
});
}).toThrow(ArgumentOutOfRangeException);
});
}); });

View File

@@ -44,7 +44,7 @@ describe('Match Query value object', () => {
expect(matchQueryVO.frequency).toBe(Frequency.PUNCTUAL); expect(matchQueryVO.frequency).toBe(Frequency.PUNCTUAL);
expect(matchQueryVO.fromDate).toBe('2023-09-01'); expect(matchQueryVO.fromDate).toBe('2023-09-01');
expect(matchQueryVO.toDate).toBe('2023-09-01'); expect(matchQueryVO.toDate).toBe('2023-09-01');
expect(matchQueryVO.schedule?.length).toBe(1); expect(matchQueryVO.schedule.length).toBe(1);
expect(matchQueryVO.seatsProposed).toBe(3); expect(matchQueryVO.seatsProposed).toBe(3);
expect(matchQueryVO.seatsRequested).toBe(1); expect(matchQueryVO.seatsRequested).toBe(1);
expect(matchQueryVO.strict).toBe(false); expect(matchQueryVO.strict).toBe(false);

View File

@@ -1,9 +1,6 @@
import { DateTimeTransformerPort } from '@modules/ad/core/application/ports/datetime-transformer.port'; import { DateTimeTransformerPort } from '@modules/ad/core/application/ports/datetime-transformer.port';
import { GeorouterPort } from '@modules/ad/core/application/ports/georouter.port'; import { GeorouterPort } from '@modules/ad/core/application/ports/georouter.port';
import { import { MatchQuery } from '@modules/ad/core/application/queries/match/match.query';
MatchQuery,
ScheduleItem,
} from '@modules/ad/core/application/queries/match/match.query';
import { AlgorithmType } from '@modules/ad/core/application/types/algorithm.types'; import { AlgorithmType } from '@modules/ad/core/application/types/algorithm.types';
import { Waypoint } from '@modules/ad/core/application/types/waypoint.type'; import { Waypoint } from '@modules/ad/core/application/types/waypoint.type';
import { Frequency } from '@modules/ad/core/domain/ad.types'; import { Frequency } from '@modules/ad/core/domain/ad.types';
@@ -138,9 +135,9 @@ describe('Match Query', () => {
expect(matchQuery.maxDetourDurationRatio).toBe(0.3); expect(matchQuery.maxDetourDurationRatio).toBe(0.3);
expect(matchQuery.fromDate).toBe('2023-08-27'); expect(matchQuery.fromDate).toBe('2023-08-27');
expect(matchQuery.toDate).toBe('2023-08-27'); expect(matchQuery.toDate).toBe('2023-08-27');
expect((matchQuery.schedule as ScheduleItem[])[0].day).toBe(0); expect(matchQuery.schedule[0].day).toBe(0);
expect((matchQuery.schedule as ScheduleItem[])[0].time).toBe('23:05'); expect(matchQuery.schedule[0].time).toBe('23:05');
expect((matchQuery.schedule as ScheduleItem[])[0].margin).toBe(900); expect(matchQuery.schedule[0].margin).toBe(900);
}); });
it('should set good values for seats', async () => { it('should set good values for seats', async () => {

View File

@@ -47,7 +47,6 @@ const matchQuery = new MatchQuery(
], ],
strict: false, strict: false,
waypoints: [originWaypoint, destinationWaypoint], waypoints: [originWaypoint, destinationWaypoint],
excludedAdId: '758618c6-dd82-4199-a548-0205161b04d7',
}, },
bareMockGeorouter, bareMockGeorouter,
); );

View File

@@ -1,3 +1,4 @@
import { RpcExceptionCode } from '@mobicoop/ddd-library';
import { AD_ROUTE_PROVIDER } from '@modules/ad/ad.di-tokens'; import { AD_ROUTE_PROVIDER } from '@modules/ad/ad.di-tokens';
import { MatchingResult } from '@modules/ad/core/application/queries/match/match.query-handler'; import { MatchingResult } from '@modules/ad/core/application/queries/match/match.query-handler';
import { AlgorithmType } from '@modules/ad/core/application/types/algorithm.types'; import { AlgorithmType } from '@modules/ad/core/application/types/algorithm.types';
@@ -13,6 +14,7 @@ import { MatchGrpcController } from '@modules/ad/interface/grpc-controllers/matc
import { MatchMapper } from '@modules/ad/match.mapper'; import { MatchMapper } from '@modules/ad/match.mapper';
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { QueryBus } from '@nestjs/cqrs'; import { QueryBus } from '@nestjs/cqrs';
import { RpcException } from '@nestjs/microservices';
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from '@nestjs/testing';
import { bareMockGeorouter } from '../georouter.mock'; import { bareMockGeorouter } from '../georouter.mock';
@@ -54,7 +56,9 @@ const recurrentMatchRequestDto: MatchRequestDto = {
}; };
const mockQueryBus = { const mockQueryBus = {
execute: jest.fn().mockImplementationOnce( execute: jest
.fn()
.mockImplementationOnce(
() => () =>
<MatchingResult>{ <MatchingResult>{
id: '43c83ae2-f4b0-4ac6-b8bf-8071801924d4', id: '43c83ae2-f4b0-4ac6-b8bf-8071801924d4',
@@ -173,7 +177,10 @@ const mockQueryBus = {
], ],
total: 1, total: 1,
}, },
), )
.mockImplementationOnce(() => {
throw new Error();
}),
}; };
const mockMatchMapper = { const mockMatchMapper = {
@@ -310,4 +317,16 @@ describe('Match Grpc Controller', () => {
expect(matchingPaginatedResponseDto.perPage).toBe(10); expect(matchingPaginatedResponseDto.perPage).toBe(10);
expect(mockQueryBus.execute).toHaveBeenCalledTimes(1); expect(mockQueryBus.execute).toHaveBeenCalledTimes(1);
}); });
it('should throw a generic RpcException', async () => {
jest.spyOn(mockQueryBus, 'execute');
expect.assertions(3);
try {
await matchGrpcController.match(recurrentMatchRequestDto);
} catch (e: any) {
expect(e).toBeInstanceOf(RpcException);
expect(e.error.code).toBe(RpcExceptionCode.UNKNOWN);
}
expect(mockQueryBus.execute).toHaveBeenCalledTimes(1);
});
}); });

View File

@@ -7,7 +7,6 @@
"experimentalDecorators": true, "experimentalDecorators": true,
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"target": "es2017", "target": "es2017",
"lib": ["es2022"],
"sourceMap": true, "sourceMap": true,
"outDir": "./dist", "outDir": "./dist",
"baseUrl": "./", "baseUrl": "./",