Skip to content

Commit eda6655

Browse files
committed
implement tx caching on v1 get_transaction
1 parent 2d58c18 commit eda6655

File tree

2 files changed

+90
-19
lines changed

2 files changed

+90
-19
lines changed

api/routes/v1-history/get_transaction/get_transaction.ts

Lines changed: 86 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,18 @@ import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
22
import {mergeActionMeta, timedQuery} from "../../../helpers/functions";
33
import {createHash} from "crypto";
44
import flatstr from 'flatstr';
5+
import {GetInfoResult} from "eosjs/dist/eosjs-rpc-interfaces";
56

67
async function getTransaction(fastify: FastifyInstance, request: FastifyRequest) {
78
if (typeof request.body === 'string') {
89
request.body = JSON.parse(request.body)
910
}
1011
const body: any = request.body;
11-
const pResults = await Promise.all([fastify.eosjs.rpc.get_info(), fastify.elastic['search']({
12-
"index": fastify.manager.chain + '-action-*',
13-
"body": {
14-
"query": {
15-
"bool": {
16-
must: [
17-
{term: {"trx_id": body.id.toLowerCase()}}
18-
]
19-
}
20-
},
21-
"sort": {
22-
"global_sequence": "asc"
23-
}
24-
}
25-
})]);
26-
const results = pResults[1];
12+
const redis = fastify.redis;
13+
const trxId = body.id.toLowerCase();
14+
const conf = fastify.manager.config;
15+
const cachedData = await redis.hgetall('trx_' + trxId);
16+
2717
const response: any = {
2818
"id": body.id,
2919
"trx": {
@@ -42,11 +32,89 @@ async function getTransaction(fastify: FastifyInstance, request: FastifyRequest)
4232
},
4333
"block_num": 0,
4434
"block_time": "",
45-
"last_irreversible_block": pResults[0].last_irreversible_block_num,
35+
"last_irreversible_block": undefined,
4636
"traces": []
4737
};
4838

49-
const hits = results['body']['hits']['hits'];
39+
let hits;
40+
41+
// build get_info request with caching
42+
const $getInfo = new Promise<GetInfoResult>(resolve => {
43+
const key = `${fastify.manager.chain}_get_info`;
44+
fastify.redis.get(key).then(value => {
45+
if (value) {
46+
resolve(JSON.parse(value));
47+
} else {
48+
fastify.eosjs.rpc.get_info().then(value1 => {
49+
fastify.redis.set(key, JSON.stringify(value1), 'EX', 6);
50+
resolve(value1);
51+
}).catch((reason) => {
52+
console.log(reason);
53+
response.error = 'failed to get last_irreversible_block_num'
54+
resolve(null);
55+
});
56+
}
57+
});
58+
});
59+
60+
// reconstruct hits from cached data
61+
if (cachedData && Object.keys(cachedData).length > 0) {
62+
const gsArr = [];
63+
for (let cachedDataKey in cachedData) {
64+
gsArr.push(cachedData[cachedDataKey]);
65+
}
66+
gsArr.sort((a, b) => {
67+
return a.global_sequence - b.global_sequence;
68+
});
69+
hits = gsArr.map(value => {
70+
return {
71+
_source: JSON.parse(value)
72+
};
73+
});
74+
const promiseResults = await Promise.all([
75+
redis.ttl('trx_' + trxId),
76+
$getInfo
77+
]);
78+
response.cache_expires_in = promiseResults[0];
79+
response.last_irreversible_block = promiseResults[1].last_irreversible_block_num;
80+
}
81+
82+
// search on ES if cache is not present
83+
if (!hits) {
84+
const _size = conf.api.limits.get_trx_actions || 100;
85+
const blockHint = parseInt(body.block_num_hint, 10);
86+
let indexPattern = '';
87+
if (blockHint) {
88+
const idxPart = Math.ceil(blockHint / conf.settings.index_partition_size).toString().padStart(6, '0');
89+
indexPattern = fastify.manager.chain + `-action-${conf.settings.index_version}-${idxPart}`;
90+
} else {
91+
indexPattern = fastify.manager.chain + '-action-*';
92+
}
93+
let pResults;
94+
try {
95+
96+
// build search request
97+
const $search = fastify.elastic.search({
98+
index: indexPattern,
99+
size: _size,
100+
body: {
101+
query: {bool: {must: [{term: {trx_id: trxId}}]}},
102+
sort: {global_sequence: "asc"}
103+
}
104+
});
105+
106+
// execute in parallel
107+
pResults = await Promise.all([$getInfo, $search]);
108+
} catch (e) {
109+
console.log(e.message);
110+
if (e.meta.statusCode === 404) {
111+
return response;
112+
}
113+
}
114+
hits = pResults[1]['body']['hits']['hits'];
115+
response.last_irreversible_block = pResults[0].last_irreversible_block_num;
116+
}
117+
50118

51119
if (hits.length > 0) {
52120
const actions = hits;

api/routes/v1-history/get_transaction/index.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ export default function (fastify: FastifyInstance, opts: any, next) {
99
tags: ['history'],
1010
body: {
1111
type: ['object', 'string'],
12-
properties: {id: {description: 'transaction id', type: 'string'}},
12+
properties: {
13+
id: {description: 'transaction id', type: 'string'},
14+
block_num_hint: {description: 'block number hint', type: 'integer'},
15+
},
1316
required: ["id"]
1417
}
1518
});

0 commit comments

Comments
 (0)