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

MARXAN-1374-BLMFinalResults-Puids-PNGdata #941

Merged
merged 13 commits into from
Apr 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { WebshotConfig } from '@marxan/webshot';
import { Command } from '@nestjs-architects/typed-cqrs';

export class StartBlmCalibration extends Command<void> {
constructor(
public readonly scenarioId: string,
public readonly blmValues: number[],
public readonly config: WebshotConfig,
) {
super();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ export class StartBlmCalibrationHandler
private readonly assets: AssetsService,
) {}

async execute({ scenarioId, blmValues }: StartBlmCalibration): Promise<void> {
async execute({
scenarioId,
blmValues,
config,
}: StartBlmCalibration): Promise<void> {
// In order to ensure that boundary data is included in assets array
// a non zero value should be provided to `forScenario` method of AssetsService
const nonZeroBLMValue = 1;
Expand All @@ -32,6 +36,7 @@ export class StartBlmCalibrationHandler
scenarioId,
blmValues,
assets,
config,
});

if (!job) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsArray, IsOptional } from 'class-validator';
import { IsArray, IsOptional, ValidateNested } from 'class-validator';
import { IsValidRange } from '@marxan-api/decorators/is-valid-range.decorator';
import { WebshotConfig } from '@marxan/webshot';
import { Type } from 'class-transformer';

export class StartScenarioBlmCalibrationDto {
@ApiProperty({ example: [0.001, 100], required: false })
@IsOptional()
@IsArray()
@IsValidRange()
range?: [number, number];

@ApiProperty()
@ValidateNested({ each: true })
@Type(() => WebshotConfig)
config!: WebshotConfig;
}
64 changes: 60 additions & 4 deletions api/apps/api/src/modules/scenarios/scenarios.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ import {
} from '@marxan-api/modules/access-control/scenarios-acl/locks/dto/scenario.lock.dto';
import { mapAclDomainToHttpError } from '@marxan-api/utils/acl.utils';
import { BaseTilesOpenApi } from '@marxan/tiles';
import { WebshotConfig, WebshotService } from '@marxan/webshot';
import { WebshotConfig, WebshotPdfConfig } from '@marxan/webshot';
import { AppSessionTokenCookie } from '@marxan-api/decorators/app-session-token-cookie.decorator';
import { setImagePngResponseHeadersForSuccessfulRequests } from '@marxan/utils';

Expand Down Expand Up @@ -131,7 +131,6 @@ export class ScenariosController {
private readonly zipFilesSerializer: ZipFilesSerializer,
private readonly planningUnitsSerializer: ScenarioPlanningUnitSerializer,
private readonly scenarioAclService: ScenarioAccessControl,
private readonly webshotService: WebshotService,
) {}

@ApiOperation({
Expand Down Expand Up @@ -202,6 +201,46 @@ export class ScenariosController {
return await this.proxyService.proxyTileRequest(req, response);
}

@BaseTilesOpenApi()
@ApiOperation({
description: 'Get tiles for a scenario blm values to generate maps.',
})
@ApiParam({
name: 'id',
description: 'scenario id',
type: String,
required: true,
example: 'e5c3b978-908c-49d3-b1e3-89727e9f999c',
})
@Get(':id/calibration/tiles/:blmValue/:z/:x/:y.mvt')
async proxyPlanningUnitsBlmValuesTiles(
@Req() req: RequestWithAuthenticatedUser,
@Res() response: Response,
@Param('id', ParseUUIDPipe) scenarioId: string,
) {
/* Due to the usage of proxyService in other modules
the ACL control for this endpoint is placed in the controller */
const scenario = await this.service.getById(scenarioId, {
authenticatedUser: req.user,
});

if (isLeft(scenario)) {
throw mapAclDomainToHttpError(scenario.left, {
userId: req.user.id,
resourceType: scenarioResource.name.plural,
});
}
if (
!(await this.scenarioAclService.canViewBlmResults(
req.user.id,
scenario.right.projectId,
))
) {
throw new ForbiddenException();
}
return await this.proxyService.proxyTileRequest(req, response);
}

@BaseTilesOpenApi()
@ApiParam({
name: 'scenarioIdA',
Expand Down Expand Up @@ -1048,14 +1087,31 @@ export class ScenariosController {
@Post(`:id/calibration`)
async startCalibration(
@Param('id', ParseUUIDPipe) id: string,
@Body() { range }: StartScenarioBlmCalibrationDto,
@Body() blmCalibrationConfig: StartScenarioBlmCalibrationDto,
@Req() req: RequestWithAuthenticatedUser,
@AppSessionTokenCookie() appSessionTokenCookie: string,
): Promise<JsonApiAsyncJobMeta> {
const { config, range } = blmCalibrationConfig;
/**
* If a frontend app session token was provided via cookie, use this to let
* the webshot service authenticate to the app, otherwise fall back to
* looking for the relevant cookies in the body of the request.
*
* @todo Remove this once the new auth workflow via `Cookie` header is
* stable.
*/
const configForWebshot = appSessionTokenCookie
? {
...config,
cookie: appSessionTokenCookie,
}
: config;
const result = await this.service.startBlmCalibration(
id,
{
authenticatedUser: req.user,
},
configForWebshot,
range,
);

Expand Down Expand Up @@ -1219,7 +1275,7 @@ export class ScenariosController {
@Header('content-type', 'application/pdf')
@Post('/:scenarioId/solutions/report')
async getSummaryReportForProject(
@Body() config: WebshotConfig,
@Body() config: WebshotPdfConfig,
@Param('scenarioId', ParseUUIDPipe) scenarioId: string,
@Res() res: Response,
@Req() req: RequestWithAuthenticatedUser,
Expand Down
8 changes: 6 additions & 2 deletions api/apps/api/src/modules/scenarios/scenarios.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ import { FeatureCollection } from 'geojson';
import {
unknownPdfWebshotError,
WebshotConfig,
WebshotPdfConfig,
WebshotService,
} from '@marxan/webshot';
import { blmImageMock } from './__mock__/blm-image-mock';
Expand Down Expand Up @@ -581,6 +582,7 @@ export class ScenariosService {
async startBlmCalibration(
id: string,
userInfo: AppInfoDTO,
config: WebshotConfig,
rangeToUpdate?: [number, number],
): Promise<
Either<
Expand Down Expand Up @@ -616,7 +618,7 @@ export class ScenariosService {
if (isLeft(scenarioBlmValues)) return scenarioBlmValues;

await this.commandBus.execute(
new StartBlmCalibration(id, scenarioBlmValues.right.values),
new StartBlmCalibration(id, scenarioBlmValues.right.values, config),
);

return right(true);
Expand Down Expand Up @@ -1236,7 +1238,7 @@ export class ScenariosService {
async getSummaryReportFor(
scenarioId: string,
userId: string,
configForWebshot: WebshotConfig,
configForWebshot: WebshotPdfConfig,
): Promise<
Either<
| typeof forbiddenError
Expand All @@ -1252,6 +1254,7 @@ export class ScenariosService {
if (isLeft(scenario)) {
return scenario;
}
const webshotUrl = AppConfig.get('webshot.url') as string;

/** @debt Refactor to use @nestjs/common's StreamableFile
(https://docs.nestjs.com/techniques/streaming-files#streamable-file-class)
Expand All @@ -1260,6 +1263,7 @@ export class ScenariosService {
scenarioId,
scenario.right.projectId,
configForWebshot,
webshotUrl,
);

return pdfStream;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${ownerToken}`)
.send({
range: blmRange,
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
})
.expect(HttpStatus.CREATED),
WhenContributorLaunchesCalibration: async () => {
Expand All @@ -97,6 +98,7 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${viewerToken}`)
.send({
range: blmRange,
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
ThenCalibrationResultsShouldBeAvailable: async () => {
const response: { body: BlmCalibrationRunResultDto[] } = await request(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,10 @@ const getFixtures = async () => {
GivenScenarioBlmWasUpdated: async () => {
await request(app.getHttpServer())
.post(`/api/v1/scenarios/${scenarioId}/calibration`)
.send({ range: updatedBlmRange })
.send({
range: updatedBlmRange,
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
})
.set('Authorization', `Bearer ${ownerToken}`);
},
WhenAskingForBlmRangeForScenario: () => {
Expand Down
15 changes: 15 additions & 0 deletions api/apps/api/test/scenarios/start-scenario-calibration.fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${ownerToken}`)
.send({
range: updatedRange,
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
WithoutRange: async () =>
await request(app.getHttpServer())
Expand All @@ -119,6 +120,7 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${contributorToken}`)
.send({
range: updatedRange,
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
WithoutRange: async () =>
await request(app.getHttpServer())
Expand All @@ -132,6 +134,7 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${viewerToken}`)
.send({
range: updatedRange,
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
WithoutRange: async () =>
await request(app.getHttpServer())
Expand All @@ -158,20 +161,23 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${ownerToken}`)
.send({
range: [-1, -50],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
RangeWithAMinGreaterThanMax: async () =>
await request(app.getHttpServer())
.post(`/api/v1/scenarios/${scenarioId}/calibration`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({
range: [50, 1],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
RangeWithValuesThatAreNotNumbers: async () =>
await request(app.getHttpServer())
.post(`/api/v1/scenarios/${scenarioId}/calibration`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({
range: [1, '50'],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
RunningExport: async () => {
projectChecker.addPendingExportForProject(projectId);
Expand All @@ -180,6 +186,7 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${ownerToken}`)
.send({
range: [1, 50],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
});
},
};
Expand All @@ -192,20 +199,23 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${contributorToken}`)
.send({
range: [-1, -50],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
RangeWithAMinGreaterThanMax: async () =>
await request(app.getHttpServer())
.post(`/api/v1/scenarios/${scenarioId}/calibration`)
.set('Authorization', `Bearer ${contributorToken}`)
.send({
range: [50, 1],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
RangeWithValuesThatAreNotNumbers: async () =>
await request(app.getHttpServer())
.post(`/api/v1/scenarios/${scenarioId}/calibration`)
.set('Authorization', `Bearer ${contributorToken}`)
.send({
range: [1, '50'],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
RunningExport: async () => {
projectChecker.addPendingExportForProject(projectId);
Expand All @@ -214,6 +224,7 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${contributorToken}`)
.send({
range: [1, 50],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
});
},
};
Expand All @@ -226,20 +237,23 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${viewerToken}`)
.send({
range: [-1, -50],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
RangeWithAMinGreaterThanMax: async () =>
await request(app.getHttpServer())
.post(`/api/v1/scenarios/${scenarioId}/calibration`)
.set('Authorization', `Bearer ${viewerToken}`)
.send({
range: [50, 1],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
RangeWithValuesThatAreNotNumbers: async () =>
await request(app.getHttpServer())
.post(`/api/v1/scenarios/${scenarioId}/calibration`)
.set('Authorization', `Bearer ${viewerToken}`)
.send({
range: [1, '50'],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
}),
RunningExport: async () => {
projectChecker.addPendingExportForProject(projectId);
Expand All @@ -248,6 +262,7 @@ export const getFixtures = async () => {
.set('Authorization', `Bearer ${viewerToken}`)
.send({
range: [1, 50],
config: { baseUrl: 'example/png', cookie: 'randomCookie' },
});
},
};
Expand Down
3 changes: 3 additions & 0 deletions api/apps/geoprocessing/config/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
"api": {
"url": "http://api:3000"
},
"webshot": {
"url": "http://webshot:3000"
},
"geo": {
"daemonListenPort": 3000
},
Expand Down
Loading