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

Migration/fix service agreement #3402

Open
wants to merge 8 commits into
base: release/v6.5.2
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions ot-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,12 @@ class OTNode {
this.logger,
this.config,
);

MigrationExecutor.executeServiceAgreementFixMigration(
this.container,
this.logger,
this.config,
);
}

checkNodeVersion() {
Expand Down
31 changes: 31 additions & 0 deletions src/migration/migration-executor.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import GetOldServiceAgreementsMigration from './get-old-service-agreements-migra
import ServiceAgreementPruningMigration from './service-agreement-pruning-migration.js';
import RemoveDuplicateServiceAgreementMigration from './remove-duplicate-service-agreement-migration.js';
import DevnetNeuroPruningMigration from './devnet-neuro-pruning-migration.js';
import ServiceAgreementFixMigration from './service-agreement-fix-migration.js';

class MigrationExecutor {
static async executePullShardingTableMigration(container, logger, config) {
Expand Down Expand Up @@ -529,6 +530,36 @@ class MigrationExecutor {
}
}

static async executeServiceAgreementFixMigration(container, logger, config) {
if (
process.env.NODE_ENV === NODE_ENVIRONMENTS.DEVELOPMENT ||
process.env.NODE_ENV === NODE_ENVIRONMENTS.TEST
)
return;

const repositoryModuleManager = container.resolve('repositoryModuleManager');
const blockchainModuleManager = container.resolve('blockchainModuleManager');
const serviceAgreementService = container.resolve('serviceAgreementService');

const migration = new ServiceAgreementFixMigration(
'serviceAgreementFixMigration',
logger,
config,
repositoryModuleManager,
blockchainModuleManager,
serviceAgreementService,
);
if (!(await migration.migrationAlreadyExecuted())) {
try {
await migration.migrate();
} catch (error) {
logger.error(
`Unable to execute service agreement fix migration. Error: ${error.message}`,
);
}
}
}

static exitNode(code = 0) {
process.exit(code);
}
Expand Down
113 changes: 113 additions & 0 deletions src/migration/service-agreement-fix-migration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import BaseMigration from './base-migration.js';
import { NODE_ENVIRONMENTS, CONTENT_ASSET_HASH_FUNCTION_ID } from '../constants/constants.js';

const NUMBER_OF_ASSETS_FROM_DB = 1_000_000;
const BATCH_FOR_RPC_CALLS = 25;

class ServiceAgreementFixMigration extends BaseMigration {
constructor(
migrationName,
logger,
config,
repositoryModuleManager,
blockchainModuleManager,
serviceAgreementService,
) {
super(migrationName, logger, config);
this.repositoryModuleManager = repositoryModuleManager;
this.blockchainModuleManager = blockchainModuleManager;
this.serviceAgreementService = serviceAgreementService;
}

async executeMigration() {
let blockchainId;
switch (process.env.NODE_ENV) {
case NODE_ENVIRONMENTS.DEVNET:
blockchainId = 'otp:2160';
break;
case NODE_ENVIRONMENTS.TESTNET:
blockchainId = 'otp:20430';
break;
case NODE_ENVIRONMENTS.MAINENET:
default:
blockchainId = 'otp:2043';
}

// Get count of service agreement for neuroweb
const serviceAgreementCount =
await this.repositoryModuleManager.getCountOfServiceAgreementsByBlockchain(
blockchainId,
);

// In batches
const numberOfIteration = Math.ceil(serviceAgreementCount / NUMBER_OF_ASSETS_FROM_DB);
for (let i = 0; i < numberOfIteration; i += 1) {
let serviceAgreementToBeUpdated = [];
const serviceAgreementBatch =
// eslint-disable-next-line no-await-in-loop
await this.repositoryModuleManager.getServiceAgreementsByBlockchainInBatches(
blockchainId,
NUMBER_OF_ASSETS_FROM_DB,
i * NUMBER_OF_ASSETS_FROM_DB,
);
for (let j = 0; j < serviceAgreementBatch.length; j += BATCH_FOR_RPC_CALLS) {
const currentBatch = serviceAgreementBatch.slice(j, j + BATCH_FOR_RPC_CALLS);

const batchPromises = currentBatch.map((serviceAgreement) =>
Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not sure this would work, nodes will start executing this simultaneously, will be a huge RPC load

Copy link
Collaborator

Choose a reason for hiding this comment

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

If we don't do it in batches it will last too long, we can make batches smaller

this.compareDataWithOnChainData(serviceAgreement),
);
// eslint-disable-next-line no-await-in-loop
const results = await Promise.all(batchPromises);

const mismatches = results.filter((result) => result !== null);

if (mismatches.length > 0) {
this.logger.trace(`Mismatches found: ${mismatches.length}`);
serviceAgreementToBeUpdated = serviceAgreementToBeUpdated.concat(mismatches);
}
}
if (serviceAgreementToBeUpdated.length > 0) {
// eslint-disable-next-line no-await-in-loop
await this.repositoryModuleManager.updateAssertionIdServiceAgreement(
blockchainId,
serviceAgreementToBeUpdated,
);
}
}
}

async compareDataWithOnChainData(serviceAgreement) {
let assertionId;
try {
assertionId = await this.blockchainModuleManager.getAssertionIdByIndex(
serviceAgreement.blockchainId,
serviceAgreement.assetStorageContractAddress,
serviceAgreement.tokenId,
0,
);
} catch (error) {
this.logger.warn(
`Unable to fetch assertionIdfor token id: ${serviceAgreement.tokenId}`,
);
return null;
}

if (serviceAgreement.asssertionId !== assertionId) {
const serviceAgreementId = this.serviceAgreementService.generateId(
serviceAgreement.blockchainId,
serviceAgreement.assetStorageContractAddress,
serviceAgreement.tokenId,
assertionId,
CONTENT_ASSET_HASH_FUNCTION_ID, // 1 - sha256
);
return {
tokenId: serviceAgreement.tokenId,
assertionId,
serviceAgreementId,
};
}
return null;
}
}

export default ServiceAgreementFixMigration;
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,51 @@ class ServiceAgreementRepository {
order: [['token_id']],
});
}

async getCountOfServiceAgreementsByBlockchain(blockchainId) {
return this.model.count({
where: {
blockchainId,
},
});
}

async getServiceAgreementsByBlockchainInBatches(blockchainId, batchSize, offset) {
return this.model.findAll({
where: { blockchainId },
limit: batchSize,
offset,
});
}

async updateAssertionIdServiceAgreement(blockchainId, serviceAgreementsToBeUpdated) {
const tokenIds = serviceAgreementsToBeUpdated.map(
(serviceAgreement) => serviceAgreement.tokenId,
);
const assertionIdCase = serviceAgreementsToBeUpdated
.map(({ tokenId, assertionId }) => `WHEN token_id = ${tokenId} THEN '${assertionId}'`)
.join(' ');

const serviceAgreementIdCase = serviceAgreementsToBeUpdated
.map(
({ tokenId, serviceAgreementId }) =>
`WHEN token_id = ${tokenId} THEN '${serviceAgreementId}'`,
)
.join(' ');

const query = `
UPDATE service_agreement
SET
assertion_id = CASE ${assertionIdCase} ELSE assertion_id END,
agreement_id = CASE ${serviceAgreementIdCase} ELSE agreement_id END
WHERE blockchain_id = :blockchainId AND token_id IN (:tokenIds);
`;

await this.sequelize.query(query, {
replacements: { blockchainId, tokenIds },
type: Sequelize.QueryTypes.UPDATE,
});
}
}

export default ServiceAgreementRepository;
21 changes: 21 additions & 0 deletions src/modules/repository/repository-module-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,27 @@ class RepositoryModuleManager extends BaseModuleManager {
async getParanetsBlockchains() {
return this.getRepository('paranet').getParanetsBlockchains();
}

async getCountOfServiceAgreementsByBlockchain(blockchainId) {
return this.getRepository('service_agreement').getCountOfServiceAgreementsByBlockchain(
blockchainId,
);
}

async getServiceAgreementsByBlockchainInBatches(blockchainId, batchSize, offset) {
return this.getRepository('service_agreement').getServiceAgreementsByBlockchainInBatches(
blockchainId,
batchSize,
offset,
);
}

async updateAssertionIdServiceAgreement(blockchainId, serviceAgreementsToBeUpdated) {
return this.getRepository('service_agreement').updateAssertionIdServiceAgreement(
blockchainId,
serviceAgreementsToBeUpdated,
);
}
}

export default RepositoryModuleManager;
Loading