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: upload raw log block to s3 #591

Merged
merged 4 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
10 changes: 10 additions & 0 deletions ci/config.json.ci
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,16 @@
"milisecondInterval": 60000
}
},
"uploadBlockRawLogToS3": {
"key": "uploadBlockRawLogToS3",
"millisecondCrawl": 1000,
"blocksPerCall": 100
},
"uploadTransactionRawLogToS3": {
"key": "uploadTransactionRawLogToS3",
"millisecondCrawl": 1000,
"blocksPerCall": 100
},
"jobCreateConstraintInTransactionPartition": {
"jobRepeatCheckNeedCreateConstraint": {
"millisecondRepeatJob": 600000
Expand Down
10 changes: 10 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,16 @@
},
"statementTimeout": 600000
},
"uploadBlockRawLogToS3": {
"key": "uploadBlockRawLogToS3",
"millisecondCrawl": 1000,
"blocksPerCall": 100
},
"uploadTransactionRawLogToS3": {
"key": "uploadTransactionRawLogToS3",
"millisecondCrawl": 1000,
"blocksPerCall": 100
},
"jobCreateConstraintInTransactionPartition": {
"jobRepeatCheckNeedCreateConstraint": {
"millisecondRepeatJob": 600000
Expand Down
5 changes: 5 additions & 0 deletions src/common/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export const BULL_JOB_NAME = {
JOB_CHECK_TRANSACTION_CONSTRAINT:
'job:check-need-create-transaction-constraint',
JOB_CREATE_EVENT_CONSTRAIN: 'job:create-event-constraint',
UPLOAD_BLOCK_RAW_LOG_TO_S3: 'job:upload-block-raw-log-to-s3',
JOB_CREATE_TRANSACTION_CONSTRAINT: 'job:create-transaction-constraint',
};

Expand Down Expand Up @@ -379,6 +380,10 @@ export const SERVICE = {
path: 'v1.HoroscopeHandlerService.getData',
},
},
UploadBlockRawLogToS3: {
key: 'UploadBlockRawLogToS3',
path: 'v1.UploadBlockRawLogToS3',
},
},
};

Expand Down
49 changes: 49 additions & 0 deletions src/common/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { fromBech32 } from '@cosmjs/encoding';
import _ from 'lodash';
import { SemVer } from 'semver';
import AWS from 'aws-sdk';

export default class Utils {
public static isValidAddress(address: string, length = -1) {
Expand Down Expand Up @@ -215,4 +216,52 @@ export default class Utils {
const semver = new SemVer(version1);
return semver.compare(version2);
}

public static async uploadDataToS3(
id: string,
s3Client: AWS.S3,
fileName: string,
contentType: string,
data: Buffer,
bucketName: string,
s3Gateway: string,
overwrite = false
) {
const foundS3Object = await s3Client
.headObject({
Bucket: bucketName,
Key: fileName,
})
.promise()
.catch((err) => {
if (err.name === 'NotFound') {
return null;
}
console.error(err);
return err;
});
if (foundS3Object && !overwrite) {
console.warn(`This S3 key is found in S3: ${fileName}`);
return;
Copy link
Member

Choose a reason for hiding this comment

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

chỗ này nên log là bị duplicate ra, vì chắc là có vấn đề mới duplicate

Copy link
Member Author

Choose a reason for hiding this comment

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

done

Copy link
Member

Choose a reason for hiding this comment

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

chỗ này nằm ngoài service nên ko có logger à?
vậy thì nên throw rồi để hàm gọi nó tự xử lý

Copy link
Member

Choose a reason for hiding this comment

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

log như này có hiện ra ko ko biết

Copy link
Member Author

Choose a reason for hiding this comment

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

throw ra ngoài thì chỗ Promise.all có thể fail luôn cả job đó anh

Copy link
Member Author

Choose a reason for hiding this comment

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

done

}

// eslint-disable-next-line consistent-return
return s3Client
.upload({
Key: fileName,
Body: data,
Bucket: bucketName,
ContentType: contentType,
})
.promise()
.then(
(response: { Location: string; Key: string }) => ({
key: s3Gateway ? s3Gateway + response.Key : response.Key,
id,
}),
(err: string) => {
throw new Error(err);
}
);
}
}
98 changes: 98 additions & 0 deletions src/services/crawl-block/upload_block_raw_log_to_s3.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/* eslint-disable no-await-in-loop */
import { Service } from '@ourparentcenter/moleculer-decorators-extended';
import { ServiceBroker } from 'moleculer';
import Utils from '../../common/utils/utils';
import { Block, BlockCheckpoint } from '../../models';
import BullableService, { QueueHandler } from '../../base/bullable.service';
import { Config, BULL_JOB_NAME, SERVICE } from '../../common';
import config from '../../../config.json' assert { type: 'json' };
import knex from '../../common/utils/db_connection';
import { S3Service } from '../../common/utils/s3';

const s3Client = S3Service.connectS3();
@Service({
name: SERVICE.V1.UploadBlockRawLogToS3.key,
version: 1,
})
export default class UploadBlockRawLogToS3 extends BullableService {
public constructor(public broker: ServiceBroker) {
super(broker);
}

@QueueHandler({
queueName: BULL_JOB_NAME.UPLOAD_BLOCK_RAW_LOG_TO_S3,
jobName: BULL_JOB_NAME.UPLOAD_BLOCK_RAW_LOG_TO_S3,
})
async uplodaBlockRawLogToS3() {
const [startBlock, endBlock, updateBlockCheckpoint] =
await BlockCheckpoint.getCheckpoint(
BULL_JOB_NAME.UPLOAD_BLOCK_RAW_LOG_TO_S3,
[BULL_JOB_NAME.CRAWL_BLOCK],
peara marked this conversation as resolved.
Show resolved Hide resolved
config.uploadBlockRawLogToS3.key
);
if (startBlock > endBlock) {
return;
}
this.logger.info(`startBlock: ${startBlock} to endBlock: ${endBlock}`);
const listBlock = await Block.query()
.select('height', 'hash', 'data')
.where('height', '>', startBlock)
.andWhere('height', '<=', endBlock);
const resultUploadS3 = (
await Promise.all(
listBlock.map((block) =>
Utils.uploadDataToS3(
block.height.toString(),
s3Client,
`rawlog/${config.chainId}/block/${block.height}`,
Copy link
Member

Choose a reason for hiding this comment

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

thêm đc network name sau rawlog ko?
với cả block -> blocks
ví dụ:
rawlog/aura/xstaxy-1/blocks/12341234

Copy link
Member Author

Choose a reason for hiding this comment

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

lại phải tạo thêm biến trong config.json nên em không thêm network name đâu

Copy link
Member

Choose a reason for hiding this comment

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

thêm vào đi cho đẹp, nhỡ có chain nào dở hơi nó để tên trùng
cơ mà bên network.json cũng đang ko có tên chain, kể ra cũng hơi thiếu nhưng chưa thấy dùng ở đâu

Copy link
Member Author

Choose a reason for hiding this comment

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

added

'application/json',
Buffer.from(JSON.stringify(block.data)),
Config.BUCKET,
Config.S3_GATEWAY,
false
)
)
)
).filter((e) => e !== undefined);
peara marked this conversation as resolved.
Show resolved Hide resolved

const stringListUpdate = resultUploadS3.map(
(item) =>
`(${item?.id}, '${JSON.stringify({
linkS3: item?.key,
})}'::json)`
);

await knex.transaction(async (trx) => {
if (resultUploadS3.length > 0) {
await knex.raw(
`UPDATE block SET data = temp.data from (VALUES ${stringListUpdate}) as temp(height, data) where temp.height = block.height`
);
}

updateBlockCheckpoint.height = endBlock;
await BlockCheckpoint.query()
.insert(updateBlockCheckpoint)
.onConflict('job_name')
.merge()
.transacting(trx);
});
}

async _start(): Promise<void> {
this.createJob(
BULL_JOB_NAME.UPLOAD_BLOCK_RAW_LOG_TO_S3,
BULL_JOB_NAME.UPLOAD_BLOCK_RAW_LOG_TO_S3,
{},
{
removeOnComplete: true,
removeOnFail: {
count: 3,
},
repeat: {
every: config.uploadBlockRawLogToS3.millisecondCrawl,
},
}
);
return super._start();
}
}
Loading