Skip to content

Commit

Permalink
Parallel d1 request and second dns request to improve performance
Browse files Browse the repository at this point in the history
  • Loading branch information
crzidea committed Sep 14, 2024
1 parent 93beafa commit 032b349
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions workers.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,30 +42,36 @@ export default {
return new Response('Unsupported method', { status: 405 });
}

async function queryDnsWithClientIp() {
const response = await queryDns(queryData, clientIp)
const buffer = await response.arrayBuffer()
const dnsResponse = parseDnsResponse(buffer)
if (!dnsResponse.answers.length || !isIPv4(dnsResponse.answers[0] || !clientIp)) {
return new Response(buffer, response);
}
const queryCountryInfoStart = Date.now();
const responseIpSample = dnsResponse.answers[0];
const responseIpCountry = await ip2country(responseIpSample)
const queryCountryInfoEnd = Date.now();
console.log(`Response Sample: ${responseIpSample}, ${responseIpCountry}`)
console.log(`Query Country Info Time: ${queryCountryInfoEnd - queryCountryInfoStart}ms`)
if (clientCountry === responseIpCountry) {
return new Response(buffer, response);
}
return null
}

const queryUpstreamStart = Date.now();
const [response, alternativeResponse] = await Promise.all([
queryDns(queryData, clientIp),
queryDnsWithClientIp(),
queryDns(queryData, alternativeIp)
]);
const queryUpstreamEnd = Date.now();

const buffer = await response.arrayBuffer()
const dnsResponse = parseDnsResponse(buffer)
if (!dnsResponse.answers.length || !isIPv4(dnsResponse.answers[0] || !clientIp)) {
return new Response(buffer, response);
}

const queryCountryInfoStart = Date.now();
const responseIpSample = dnsResponse.answers[0];
const responseIpCountry = await ip2country(responseIpSample)
const queryCountryInfoEnd = Date.now();

console.log(`Response Sample: ${responseIpSample}, ${responseIpCountry}`)
console.log(`Query Upstream Time: ${queryUpstreamEnd - queryUpstreamStart}ms`)
console.log(`Query Country Info Time: ${queryCountryInfoEnd - queryCountryInfoStart}ms`)

if (clientCountry === responseIpCountry) {
return new Response(buffer, response);
if (response) {
return response;
} else {
return new Response(alternativeResponse.body, alternativeResponse);
}
Expand Down

0 comments on commit 032b349

Please sign in to comment.