1 | import { create as createLogger } from '../common/log'
|
2 | const log = createLogger('expire-middleware')
|
3 | import * as IlpPacket from 'ilp-packet'
|
4 | import { Middleware, MiddlewareCallback, Pipelines } from '../types/middleware'
|
5 | const { TransferTimedOutError } = IlpPacket.Errors
|
6 |
|
7 | export default class ExpireMiddleware implements Middleware {
|
8 | async applyToPipelines (pipelines: Pipelines, accountId: string) {
|
9 | pipelines.outgoingData.insertLast({
|
10 | name: 'expire',
|
11 | method: async (data: Buffer, next: MiddlewareCallback<Buffer, Buffer>) => {
|
12 | if (data[0] === IlpPacket.Type.TYPE_ILP_PREPARE) {
|
13 | const { executionCondition, expiresAt } = IlpPacket.deserializeIlpPrepare(data)
|
14 |
|
15 | const duration = expiresAt.getTime() - Date.now()
|
16 |
|
17 | const promise = next(data)
|
18 |
|
19 | let timeout: NodeJS.Timer
|
20 | const timeoutPromise: Promise<Buffer> = new Promise((resolve, reject) => {
|
21 | timeout = setTimeout(() => {
|
22 | log.debug('packet expired. cond=%s expiresAt=%s', executionCondition.slice(0, 6).toString('base64'), expiresAt.toISOString())
|
23 | reject(new TransferTimedOutError('packet expired.'))
|
24 | }, duration)
|
25 | })
|
26 |
|
27 | return Promise.race([
|
28 | promise.then((data) => { clearTimeout(timeout); return data }),
|
29 | timeoutPromise
|
30 | ])
|
31 | }
|
32 |
|
33 | return next(data)
|
34 | }
|
35 | })
|
36 | }
|
37 | }
|