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(marxan-run): expose endpoints for starting/cancelling marxan execution #311

Merged
merged 2 commits into from
Jul 7, 2021
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
43 changes: 43 additions & 0 deletions api/apps/api/src/modules/scenarios/scenarios.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
ApiUnauthorizedResponse,
ApiForbiddenResponse,
ApiParam,
ApiAcceptedResponse,
} from '@nestjs/swagger';
import { apiGlobalPrefixes } from '@marxan-api/api.config';
import { JwtAuthGuard } from '@marxan-api/guards/jwt-auth.guard';
Expand Down Expand Up @@ -64,6 +65,9 @@ import { ProxyService } from '@marxan-api/modules/proxy/proxy.service';
const basePath = `${apiGlobalPrefixes.v1}/scenarios`;
const solutionsSubPath = `:id/marxan/run/:runId/solutions`;

const marxanRunTag = 'Marxan Run';
const marxanFilesTag = 'Marxan Run - Files';
Copy link
Member

Choose a reason for hiding this comment

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

especially if we want to expand the use of @ApiTags() as we go + retrospectively, maybe this tag may be called marxanRunFilesTag (we'd have marxanFilesTags for the range of file upload operations we support, for example)


@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiTags(scenarioResource.className)
Expand Down Expand Up @@ -245,6 +249,7 @@ export class ScenariosController {
);
}

@ApiTags(marxanFilesTag)
@ApiOperation({ description: `Resolve scenario's input parameter file.` })
@Get(':id/marxan/dat/input.dat')
@ApiProduces('text/plain')
Expand All @@ -255,6 +260,7 @@ export class ScenariosController {
return await this.service.getInputParameterFile(id);
}

@ApiTags(marxanFilesTag)
@ApiOperation({ description: `Resolve scenario's spec file.` })
@Get(':id/marxan/dat/spec.dat')
@ApiProduces('text/plain')
Expand Down Expand Up @@ -310,6 +316,41 @@ export class ScenariosController {
);
}

@ApiOperation({
description: `Request start of the Marxan execution.`,
summary: `Request start of the Marxan execution.`,
})
@ApiTags(marxanRunTag)
@ApiQuery({
name: `blm`,
required: false,
type: Number,
})
@ApiAcceptedResponse({
description: `No content.`,
})
@Post(`:id/marxan`)
async executeMarxanRun(
@Param(`id`, ParseUUIDPipe) id: string,
@Query(`blm`) blm?: number,
) {
await this.service.run(id, blm);
}

@ApiOperation({
description: `Cancel running Marxan execution.`,
summary: `Cancel running Marxan execution.`,
})
@ApiTags(marxanRunTag)
@ApiAcceptedResponse({
description: `No content.`,
})
@Delete(`:id/marxan`)
async cancelMaraxnRun(@Param(`id`, ParseUUIDPipe) id: string) {
await this.service.cancel(id);
}

@ApiTags(marxanRunTag)
@ApiOkResponse({
type: ScenarioSolutionResultDto,
})
Expand All @@ -324,6 +365,7 @@ export class ScenariosController {
);
}

@ApiTags(marxanRunTag)
@ApiOkResponse({
type: ScenarioSolutionResultDto,
})
Expand All @@ -345,6 +387,7 @@ export class ScenariosController {
);
}

@ApiTags(marxanFilesTag)
@Header('Content-Type', 'text/csv')
@ApiOkResponse({
schema: {
Expand Down
20 changes: 19 additions & 1 deletion api/apps/api/src/modules/scenarios/scenarios.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { BadRequestException, HttpService, Injectable } from '@nestjs/common';
import {
BadRequestException,
HttpService,
Injectable,
NotImplementedException,
} from '@nestjs/common';
import { FetchSpecification } from 'nestjs-base-service';
import { classToClass } from 'class-transformer';
import * as stream from 'stream';
Expand Down Expand Up @@ -150,6 +155,19 @@ export class ScenariosService {
return this.specDatService.getSpecDatContent(scenarioId);
}

async run(scenarioId: string, _blm?: number): Promise<void> {
await this.assertScenario(scenarioId);
// TODO ensure not running yet
// TODO submit
throw new NotImplementedException();
}

async cancel(scenarioId: string): Promise<void> {
await this.assertScenario(scenarioId);
// TODO ensure it is running
throw new NotImplementedException();
}

private async assertScenario(scenarioId: string) {
await this.crudService.getById(scenarioId);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { PromiseType } from 'utility-types';
import { getFixtures } from './fixtures';

let fixtures: PromiseType<ReturnType<typeof getFixtures>>;

beforeAll(async () => {
fixtures = await getFixtures();
});

afterAll(async () => {
await fixtures.cleanup();
});

describe(`Marxan run`, () => {
beforeAll(async () => {
await fixtures.GivenUserIsLoggedIn();
await fixtures.GivenProjectOrganizationExists();
await fixtures.GivenScenarioExists(`Mouse`);
await fixtures.GivenCostSurfaceTemplateFilled();
await fixtures.WhenMarxanExecutionIsRequested();
await fixtures.WhenMarxanExecutionIsCompleted();
await fixtures.ThenResultsAreAvailable();
Comment on lines +16 to +22
Copy link
Member

Choose a reason for hiding this comment

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

I love this

});

it(`should work in near future`, () => {
expect(true).toBeTruthy();
});
});
66 changes: 66 additions & 0 deletions api/apps/api/test/business-critical/marxan-run/fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { bootstrapApplication } from '../../utils/api-application';
import { GivenUserIsLoggedIn } from '../../steps/given-user-is-logged-in';
import { GivenProjectExists } from '../../steps/given-project';
import { GivenScenarioExists } from '../../steps/given-scenario-exists';
import { ScenarioType } from '@marxan-api/modules/scenarios/scenario.api.entity';
import { ScenariosTestUtils } from '../../utils/scenarios.test.utils';

export const getFixtures = async () => {
const app: INestApplication = await bootstrapApplication();
const cleanups: (() => Promise<void>)[] = [];

let authToken: string;
let project: string;
let scenario: string;

return {
GivenUserIsLoggedIn: async () => {
authToken = await GivenUserIsLoggedIn(app);
},
GivenProjectOrganizationExists: async () => {
const organizationProject = await GivenProjectExists(app, authToken, {
countryCode: 'AGO',
adminAreaLevel1Id: 'AGO.15_1',
adminAreaLevel2Id: 'AGO.15.4_1',
});

project = organizationProject.projectId;
cleanups.push(organizationProject.cleanup);
},
GivenScenarioExists: async (name: string) => {
scenario = (
await GivenScenarioExists(app, project, authToken, {
name,
type: ScenarioType.marxan,
})
).id;
cleanups.push(() =>
ScenariosTestUtils.deleteScenario(app, authToken, scenario),
);
},
GivenCostSurfaceTemplateFilled: async () => {
const template = await request(app.getHttpServer())
.get(`/api/v1/scenarios/${scenario}/cost-surface/shapefile-template`)
.set('Authorization', `Bearer ${authToken}`);
console.log(template.body);
},
WhenMarxanExecutionIsRequested: async () => {
// TODO currently not implemented yet: 501
await request(app.getHttpServer())
.post(`/api/v1/scenarios/${scenario}/marxan`)
.set('Authorization', `Bearer ${authToken}`);
},
WhenMarxanExecutionIsCompleted: async () => {
return void 0;
},
ThenResultsAreAvailable: async () => {
return void 0;
},
cleanup: async () => {
await Promise.all(cleanups.map((c) => c()));
await app.close();
},
};
};
7 changes: 6 additions & 1 deletion api/apps/api/test/steps/given-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import { E2E_CONFIG } from '../e2e.config';
export const GivenProjectExists = async (
app: INestApplication,
jwt: string,
adminArea?: {
countryCode?: string;
adminAreaLevel1Id?: string;
adminAreaLevel2Id?: string;
},
): Promise<{
projectId: string;
organizationId: string;
Expand All @@ -20,7 +25,7 @@ export const GivenProjectExists = async (
).data.id;
const projectId = (
await ProjectsTestUtils.createProject(app, jwt, {
...E2E_CONFIG.projects.valid.minimal(),
...E2E_CONFIG.projects.valid.minimalInGivenAdminArea(adminArea),
organizationId,
})
).data.id;
Expand Down
2 changes: 2 additions & 0 deletions api/apps/api/test/steps/given-scenario-exists.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ export const GivenScenarioExists = async (
app: INestApplication,
projectId: string,
jwtToken: string,
options?: Partial<CreateScenarioDTO>,
) => {
const createScenarioDTO: Partial<CreateScenarioDTO> = {
...E2E_CONFIG.scenarios.valid.minimal(),
...options,
projectId,
};
return (
Expand Down