-
Notifications
You must be signed in to change notification settings - Fork 316
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
#RI-4380 BE Upload data in bulk base implementation #1930
Merged
ArtemHoruzhenko
merged 3 commits into
feature/RI-4290-upload_data_in_bulk
from
be/feature/RI-4290-upload_data_in_bulk
Apr 12, 2023
Merged
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
redisinsight/api/src/modules/bulk-actions/bulk-import.controller.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import { | ||
Body, | ||
ClassSerializerInterceptor, | ||
Controller, Post, | ||
UseInterceptors, UsePipes, ValidationPipe, | ||
} from '@nestjs/common'; | ||
import { | ||
ApiConsumes, ApiTags, | ||
} from '@nestjs/swagger'; | ||
import { ApiEndpoint } from 'src/decorators/api-endpoint.decorator'; | ||
import { FormDataRequest } from 'nestjs-form-data'; | ||
import { BulkImportService } from 'src/modules/bulk-actions/bulk-import.service'; | ||
import { UploadImportFileDto } from 'src/modules/bulk-actions/dto/upload-import-file.dto'; | ||
import { ClientMetadataParam } from 'src/common/decorators'; | ||
import { ClientMetadata } from 'src/common/models'; | ||
import { IBulkActionOverview } from 'src/modules/bulk-actions/interfaces/bulk-action-overview.interface'; | ||
|
||
@UsePipes(new ValidationPipe({ transform: true })) | ||
@UseInterceptors(ClassSerializerInterceptor) | ||
@ApiTags('Bulk Actions') | ||
@Controller('/bulk-actions/:id') | ||
export class BulkImportController { | ||
constructor(private readonly service: BulkImportService) {} | ||
|
||
@Post('import') | ||
@ApiConsumes('multipart/form-data') | ||
@FormDataRequest() | ||
@ApiEndpoint({ | ||
description: 'Import data from file', | ||
responses: [ | ||
{ | ||
type: Object, | ||
}, | ||
], | ||
}) | ||
async import( | ||
@Body() dto: UploadImportFileDto, | ||
@ClientMetadataParam({ | ||
databaseIdParam: 'id', | ||
}) clientMetadata: ClientMetadata, | ||
): Promise<IBulkActionOverview> { | ||
return this.service.import(clientMetadata, dto); | ||
} | ||
} |
119 changes: 119 additions & 0 deletions
119
redisinsight/api/src/modules/bulk-actions/bulk-import.service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
import { Injectable, Logger } from '@nestjs/common'; | ||
import { Readable } from 'stream'; | ||
import * as readline from 'readline'; | ||
import { wrapHttpError } from 'src/common/utils'; | ||
import { UploadImportFileDto } from 'src/modules/bulk-actions/dto/upload-import-file.dto'; | ||
import { DatabaseConnectionService } from 'src/modules/database/database-connection.service'; | ||
import { ClientMetadata } from 'src/common/models'; | ||
import { splitCliCommandLine } from 'src/utils/cli-helper'; | ||
import { BulkActionSummary } from 'src/modules/bulk-actions/models/bulk-action-summary'; | ||
import { IBulkActionOverview } from 'src/modules/bulk-actions/interfaces/bulk-action-overview.interface'; | ||
import { BulkActionStatus, BulkActionType } from 'src/modules/bulk-actions/constants'; | ||
|
||
const BATCH_LIMIT = 10_000; | ||
|
||
@Injectable() | ||
export class BulkImportService { | ||
private logger = new Logger('BulkImportService'); | ||
|
||
constructor( | ||
private readonly databaseConnectionService: DatabaseConnectionService, | ||
) {} | ||
|
||
private async executeBatch(client, batch: any[]): Promise<BulkActionSummary> { | ||
const result = new BulkActionSummary(); | ||
result.addProcessed(batch.length); | ||
|
||
try { | ||
if (client?.isCluster) { | ||
await Promise.all(batch.map(async ([command, args]) => { | ||
try { | ||
await client.call(command, args); | ||
result.addSuccess(1); | ||
} catch (e) { | ||
result.addFailed(1); | ||
} | ||
})); | ||
} else { | ||
(await client.pipeline(batch).exec()).forEach(([err]) => { | ||
if (err) { | ||
result.addFailed(1); | ||
} else { | ||
result.addSuccess(1); | ||
} | ||
}); | ||
} | ||
} catch (e) { | ||
this.logger.error('Unable to execute batch of commands', e); | ||
result.addFailed(batch.length); | ||
} | ||
|
||
return result; | ||
} | ||
|
||
/** | ||
* @param clientMetadata | ||
* @param dto | ||
*/ | ||
public async import(clientMetadata: ClientMetadata, dto: UploadImportFileDto): Promise<IBulkActionOverview> { | ||
const result: IBulkActionOverview = { | ||
id: 'empty', | ||
databaseId: clientMetadata.databaseId, | ||
type: BulkActionType.Import, | ||
summary: { | ||
processed: 0, | ||
succeed: 0, | ||
failed: 0, | ||
errors: [], | ||
}, | ||
progress: null, | ||
filter: null, | ||
status: BulkActionStatus.Completed, | ||
duration: Date.now(), | ||
}; | ||
|
||
try { | ||
const client = await this.databaseConnectionService.createClient(clientMetadata); | ||
|
||
const stream = Readable.from(dto.file.buffer); | ||
let batch = []; | ||
|
||
const batchResults: Promise<BulkActionSummary>[] = []; | ||
|
||
await new Promise((res) => { | ||
const rl = readline.createInterface(stream); | ||
rl.on('line', (line) => { | ||
const [command, ...args] = splitCliCommandLine((line)); | ||
if (batch.length >= BATCH_LIMIT) { | ||
batchResults.push(this.executeBatch(client, batch)); | ||
batch = []; | ||
} else { | ||
batch.push([command.toLowerCase(), args]); | ||
} | ||
}); | ||
rl.on('error', (error) => { | ||
result.summary.errors.push(error); | ||
result.status = BulkActionStatus.Failed; | ||
res(null); | ||
}); | ||
rl.on('close', () => { | ||
batchResults.push(this.executeBatch(client, batch)); | ||
res(null); | ||
}); | ||
}); | ||
|
||
(await Promise.all(batchResults)).forEach((batchResult) => { | ||
result.summary.processed += batchResult.getOverview().processed; | ||
result.summary.succeed += batchResult.getOverview().succeed; | ||
result.summary.failed += batchResult.getOverview().failed; | ||
}); | ||
|
||
result.duration = Date.now() - result.duration; | ||
|
||
return result; | ||
} catch (e) { | ||
this.logger.error('Unable to process an import file', e); | ||
throw wrapHttpError(e); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
17 changes: 17 additions & 0 deletions
17
redisinsight/api/src/modules/bulk-actions/dto/upload-import-file.dto.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import { ApiPropertyOptional } from '@nestjs/swagger'; | ||
import { IsNotEmpty } from 'class-validator'; | ||
import { | ||
IsFile, MaxFileSize, MemoryStoredFile, | ||
} from 'nestjs-form-data'; | ||
|
||
export class UploadImportFileDto { | ||
@ApiPropertyOptional({ | ||
type: 'string', | ||
format: 'binary', | ||
description: 'Import file (with list of commands to execute', | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I guess you lost close round bracket. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. thanks |
||
}) | ||
@IsNotEmpty() | ||
@IsFile() | ||
@MaxFileSize(100 * 1024 * 1024) | ||
file?: MemoryStoredFile; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe will be better to create another constant startBulkActionTime or something else, it will be more clear i guess. And in the end result.duration = Date.now() - startBulkActionTime. But it is up to you.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sure. if this will be more easy to understand