Skip to content

Commit 4f0eedc

Browse files
committed
replaced unreliable race condition with idiomatic timeout using .then()
1 parent 2557ed4 commit 4f0eedc

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

api/index.js

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -63,37 +63,32 @@ fastify.post('/public/:publicKey', async (request, reply) => {
6363
const { publicKey } = request.params;
6464
const redirectOnOk = request.query.ok;
6565
const redirectOnErr = request.query.err;
66-
const data = JSON.stringify(request.body);
67-
let webhook, webhookUsed, timeoutID;
6866
try {
6967
if (helper.validate(publicKey) !== 'public') throw 401;
7068

71-
// Try posting the data to webhook, if any. On fail, store/bin data for later retrieval.
69+
const data = JSON.stringify(request.body);
70+
let webhookUsed;
71+
72+
// Try posting the data to webhook, if any, with timeout. On fail, store/bin data for later retrieval.
7273
try {
73-
webhook = await helper.cacheGet(publicKey, 'hook');
74-
if (webhook == null) throw 'No webhook';
75-
const fetchStartedAt = Date.now();
76-
const response = await fetch(webhook, {
74+
const webhook = await helper.cacheGet(publicKey, 'hook');
75+
if (webhook == null) throw new Error('No webhook');
76+
77+
await fetch(webhook, {
7778
method: "POST",
7879
headers: { "Content-type": "application/json" },
7980
body: data,
8081
signal: AbortSignal.timeout(webhookTimeout)
82+
}).then((response) => {
83+
if (! response.ok) throw new Error(response.status);
84+
return response.text();
8185
})
82-
/* Set race condition for aborting `await response.text()` below,
83-
after the time remaining from `WEBHOOK_TIMEOUT`. */
84-
timeoutID = setTimeout(() => {
85-
throw new Error('Webhook timeout');
86-
}, webhookTimeout - Date.now() + fetchStartedAt
87-
)
88-
await response.text();
89-
clearTimeout(timeoutID);
90-
if (! response.ok) throw response.status;
86+
9187
webhookUsed = webhook;
9288
} catch (err) {
93-
clearTimeout(timeoutID);
9489
await helper.publicProduce(publicKey, data);
95-
await helper.cacheDel(publicKey, 'hook'); // Delete webhook from cache if webhook is of no use!
96-
webhookUsed = null;
90+
// Delete webhook from cache if webhook is of no use!
91+
if (err.message !== 'No webhook') await helper.cacheDel(publicKey, 'hook');
9792
}
9893

9994
if (redirectOnOk == null) {

0 commit comments

Comments
 (0)