Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
Signed-off-by: artembuslaev <[email protected]>
  • Loading branch information
artembuslaev committed Apr 3, 2024
1 parent bf7be1d commit 80b8d28
Show file tree
Hide file tree
Showing 16 changed files with 278 additions and 130 deletions.
2 changes: 1 addition & 1 deletion api-gateway/src/api/service/artifact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export class ArtifactApi {
})
@ApiConsumes('multipart/form-data')
@ApiBody({
description: 'Form data with artifacts',
description: 'Form data with artifacts.',
required: true,
schema: {
type: 'array',
Expand Down
104 changes: 72 additions & 32 deletions api-gateway/src/api/service/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1213,11 +1213,19 @@ export class PolicyApi {
const engineService = new PolicyEngine();
const versionOfTopicId = req.query ? req.query.versionOfTopicId : null;
try {
const policies = await engineService.importMessage(req.user, req.body.messageId, versionOfTopicId, req.body.metadata);
const policies = await engineService.importMessage(
req.user,
req.body.messageId,
versionOfTopicId,
req.body.metadata
);
return res.status(201).send(policies);
} catch (error) {
new Logger().error(error, ['API_GATEWAY']);
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
throw new HttpException(
error.message,
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}

Expand Down Expand Up @@ -1247,14 +1255,29 @@ export class PolicyApi {
const messageId = req.body.messageId;
const versionOfTopicId = req.query ? req.query.versionOfTopicId : null;
const taskManager = new TaskManager();
const task = taskManager.start(TaskAction.IMPORT_POLICY_MESSAGE, user.id);
RunFunctionAsync<ServiceError>(async () => {
const engineService = new PolicyEngine();
await engineService.importMessageAsync(user, messageId, versionOfTopicId, task, req.body.metadata);
}, async (error) => {
new Logger().error(error, ['API_GATEWAY']);
taskManager.addError(task.taskId, { code: 500, message: 'Unknown error: ' + error.message });
});
const task = taskManager.start(
TaskAction.IMPORT_POLICY_MESSAGE,
user.id
);
RunFunctionAsync<ServiceError>(
async () => {
const engineService = new PolicyEngine();
await engineService.importMessageAsync(
user,
messageId,
versionOfTopicId,
task,
req.body.metadata
);
},
async (error) => {
new Logger().error(error, ['API_GATEWAY']);
taskManager.addError(task.taskId, {
code: 500,
message: 'Unknown error: ' + error.message,
});
}
);
return res.status(202).send(task);
}

Expand Down Expand Up @@ -1402,7 +1425,7 @@ export class PolicyApi {
})
@ApiConsumes('multipart/form-data')
@ApiBody({
description: 'Form data with policy file and metadata',
description: 'Form data with policy file and metadata.',
required: true,
schema: {
type: 'object',
Expand Down Expand Up @@ -1442,11 +1465,15 @@ export class PolicyApi {
@Query('versionOfTopicId') versionOfTopicId,
): Promise<any> {
try {
const policyFile = files.find(item => item.fieldname === 'policyFile');
const policyFile = files.find(
(item) => item.fieldname === 'policyFile'
);
if (!policyFile) {
throw new Error('There is no policy file');
}
const metadata = files.find(item => item.fieldname === 'metadata');
const metadata = files.find(
(item) => item.fieldname === 'metadata'
);
const engineService = new PolicyEngine();
return await engineService.importFile(
user,
Expand All @@ -1456,7 +1483,10 @@ export class PolicyApi {
);
} catch (error) {
new Logger().error(error, ['API_GATEWAY']);
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
throw new HttpException(
error.message,
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}

Expand Down Expand Up @@ -1538,7 +1568,7 @@ export class PolicyApi {
})
@ApiConsumes('multipart/form-data')
@ApiBody({
description: 'Form data with policy file and metadata',
description: 'Form data with policy file and metadata.',
required: true,
schema: {
type: 'object',
Expand Down Expand Up @@ -1579,24 +1609,34 @@ export class PolicyApi {
): Promise<any> {
const taskManager = new TaskManager();
const task = taskManager.start(TaskAction.IMPORT_POLICY_FILE, user.id);
RunFunctionAsync<ServiceError>(async () => {
const policyFile = files.find(item => item.fieldname === 'policyFile');
if (!policyFile) {
throw new Error('There is no policy file');
RunFunctionAsync<ServiceError>(
async () => {
const policyFile = files.find(
(item) => item.fieldname === 'policyFile'
);
if (!policyFile) {
throw new Error('There is no policy file');
}
const metadata = files.find(
(item) => item.fieldname === 'metadata'
);
const engineService = new PolicyEngine();
await engineService.importFileAsync(
user,
policyFile.buffer,
versionOfTopicId,
task,
metadata?.buffer && JSON.parse(metadata.buffer.toString())
);
},
async (error) => {
new Logger().error(error, ['API_GATEWAY']);
taskManager.addError(task.taskId, {
code: 500,
message: 'Unknown error: ' + error.message,
});
}
const metadata = files.find(item => item.fieldname === 'metadata');
const engineService = new PolicyEngine();
await engineService.importFileAsync(
user,
policyFile.buffer,
versionOfTopicId,
task,
metadata?.buffer && JSON.parse(metadata.buffer.toString())
);
}, async (error) => {
new Logger().error(error, ['API_GATEWAY']);
taskManager.addError(task.taskId, { code: 500, message: 'Unknown error: ' + error.message });
});
);
return task;
}

Expand Down
32 changes: 22 additions & 10 deletions api-gateway/src/api/service/tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,7 @@ export class ToolsApi {
}

/**
* Import tool from IPFS
* Import tool from file with metadata
*/
@Post('/import/file-metadata')
@ApiSecurity('bearerAuth')
Expand All @@ -732,7 +732,7 @@ export class ToolsApi {
})
@ApiConsumes('multipart/form-data')
@ApiBody({
description: 'Form data with policy file and metadata',
description: 'Form data with tool file and metadata.',
required: true,
schema: {
type: 'object',
Expand Down Expand Up @@ -762,20 +762,32 @@ export class ToolsApi {
})
@UseInterceptors(AnyFilesInterceptor())
@HttpCode(HttpStatus.CREATED)
async toolImportFileWithMetadata(@Req() req, @UploadedFiles() files: any): Promise<any> {
async toolImportFileWithMetadata(
@Req() req,
@UploadedFiles() files: any
): Promise<any> {
await checkPermission(UserRole.STANDARD_REGISTRY)(req.user);
const guardian = new Guardians();
try {
const file = files.find(item => item.fieldname === 'file');
const file = files.find((item) => item.fieldname === 'file');
if (!file) {
throw new Error('There is no tool file');
}
const metadata = files.find(item => item.fieldname === 'metadata');
const tool = await guardian.importToolFile(file.buffer, req.user.did, JSON.parse(metadata.buffer.toString()));
const metadata = files.find(
(item) => item.fieldname === 'metadata'
);
const tool = await guardian.importToolFile(
file.buffer,
req.user.did,
metadata?.buffer && JSON.parse(metadata.buffer.toString())
);
return tool;
} catch (error) {
new Logger().error(error, ['API_GATEWAY']);
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
throw new HttpException(
error.message,
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}

Expand Down Expand Up @@ -830,7 +842,7 @@ export class ToolsApi {
}

/**
* Import tool from IPFS (Async)
* Import tool from file with metadata (Async)
*/
@Post('/push/import/file-metadata')
@ApiSecurity('bearerAuth')
Expand All @@ -842,12 +854,12 @@ export class ToolsApi {
})
@ApiConsumes('multipart/form-data')
@ApiBody({
description: 'Form data with policy file and metadata',
description: 'Form data with tool file and metadata.',
required: true,
schema: {
type: 'object',
properties: {
'policyFile': {
'file': {
type: 'string',
format: 'binary',
},
Expand Down
9 changes: 5 additions & 4 deletions api-gateway/src/helpers/guardians.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Singleton } from '@helpers/decorators/singleton';
import { ApplicationStates, CommonSettings, ContractAPI, ContractType, GenerateUUIDv4, IArtifact, IChainItem, IContract, IDidObject, IRetirePool, IRetireRequest, ISchema, IToken, ITokenInfo, IUser, IVCDocument, IVPDocument, MessageAPI, RetireTokenPool, RetireTokenRequest, SchemaNode, SuggestionsOrderPriority } from '@guardian/interfaces';
import { ApplicationStates, CommonSettings, ContractAPI, ContractType, GenerateUUIDv4, IArtifact, IChainItem, IContract, IDidObject, IRetirePool, IRetireRequest, ISchema, IToken, ITokenInfo, IUser, IVCDocument, IVPDocument, MessageAPI, PolicyToolMetadata, RetireTokenPool, RetireTokenRequest, SchemaNode, SuggestionsOrderPriority } from '@guardian/interfaces';
import { IAuthUser, NatsService } from '@guardian/common';
import { NewTask } from './task-manager';

Expand Down Expand Up @@ -173,7 +173,6 @@ export class Guardians extends NatsService {
/**
* Update token
* @param token
* @param task
*/
public async updateToken(token: IToken | any): Promise<any> {
return await this.sendMessage(MessageAPI.UPDATE_TOKEN, { token });
Expand Down Expand Up @@ -1951,8 +1950,9 @@ export class Guardians extends NatsService {
* Load tool file for import
* @param zip
* @param owner
* @param metadata
*/
public async importToolFile(zip: any, owner: string, metadata?: any) {
public async importToolFile(zip: any, owner: string, metadata?: PolicyToolMetadata) {
return await this.sendMessage(MessageAPI.TOOL_IMPORT_FILE, { zip, owner, metadata });
}

Expand Down Expand Up @@ -1988,8 +1988,9 @@ export class Guardians extends NatsService {
* @param zip
* @param owner
* @param task
* @param metadata
*/
public async importToolFileAsync(zip: any, owner: string, task: NewTask, metadata?: any) {
public async importToolFileAsync(zip: any, owner: string, task: NewTask, metadata?: PolicyToolMetadata) {
return await this.sendMessage(MessageAPI.TOOL_IMPORT_FILE_ASYNC, { zip, owner, task, metadata });
}

Expand Down
15 changes: 10 additions & 5 deletions api-gateway/src/helpers/policy-engine.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Singleton } from '@helpers/decorators/singleton';
import { DocumentType, GenerateUUIDv4, MigrationConfig, PolicyEngineEvents } from '@guardian/interfaces';
import { DocumentType, GenerateUUIDv4, MigrationConfig, PolicyEngineEvents, PolicyToolMetadata } from '@guardian/interfaces';
import { IAuthUser, NatsService } from '@guardian/common';
import { NewTask } from './task-manager';

Expand Down Expand Up @@ -269,12 +269,13 @@ export class PolicyEngine extends NatsService {
* @param user
* @param zip
* @param versionOfTopicId
* @param metadata
*/
public async importFile(
user: IAuthUser,
zip: Buffer,
versionOfTopicId?: string,
metadata?: { tools: { [key: string]: string } }
metadata?: PolicyToolMetadata
) {
return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_FILE, {
zip,
Expand All @@ -290,13 +291,14 @@ export class PolicyEngine extends NatsService {
* @param zip
* @param versionOfTopicId
* @param task
* @param metadata
*/
public async importFileAsync(
user: IAuthUser,
zip: Buffer,
versionOfTopicId: string,
task: NewTask,
metadata?: { tools: { [key: string]: string } }
metadata?: PolicyToolMetadata
) {
return await this.sendMessage(
PolicyEngineEvents.POLICY_IMPORT_FILE_ASYNC,
Expand All @@ -308,12 +310,14 @@ export class PolicyEngine extends NatsService {
* Import policy from message
* @param user
* @param messageId
* @param versionOfTopicId
* @param metadata
*/
public async importMessage(
user: IAuthUser,
messageId: string,
versionOfTopicId: string,
metadata?: { tools: { [key: string]: string } }
metadata?: PolicyToolMetadata
) {
return await this.sendMessage(
PolicyEngineEvents.POLICY_IMPORT_MESSAGE,
Expand All @@ -327,13 +331,14 @@ export class PolicyEngine extends NatsService {
* @param messageId
* @param versionOfTopicId
* @param task
* @param metadata
*/
public async importMessageAsync(
user: IAuthUser,
messageId: string,
versionOfTopicId: string,
task: NewTask,
metadata?: { tools: { [key: string]: string } }
metadata?: PolicyToolMetadata
) {
return await this.sendMessage(
PolicyEngineEvents.POLICY_IMPORT_MESSAGE_ASYNC,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@
</div>

<div *ngIf="!isFile" class="field">
<div class="field-name">Description</div>
<div class="field-value">{{ tool.description }}</div>
<div class="field-name">Tools</div>
<div class="field-value">{{ tools }}</div>
</div>

<div *ngIf="isFile && toolConfigs && toolForm" class="fields-container">
Expand Down Expand Up @@ -159,7 +159,7 @@
</div>
<div [ngSwitch]="!!(xlsx && errors?.length)">
<p-button *ngSwitchCase="true" (click)="onImport()" label="Skip & Import"></p-button>
<p-button *ngSwitchCase="false" [disabled]="!!toolForm && !toolForm.valid" (click)="onImport()" label="Import"></p-button>
<p-button *ngSwitchCase="false" [disabled]="!toolForm?.valid" (click)="onImport()" label="Import"></p-button>
</div>
</div>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ export class PreviewPolicyDialog {
])
);
}
this.tools = this.toolConfigs.map((tool) => tool.name).join(', ');
}

if (this.config.data.module) {
Expand Down
Loading

0 comments on commit 80b8d28

Please sign in to comment.