1 2
import { create as createLogger } from '../common/log'
2 2
const log = createLogger('expire-middleware')
3 2
import * as IlpPacket from 'ilp-packet'
4
import { Middleware, MiddlewareCallback, Pipelines } from '../types/middleware'
5 2
const { TransferTimedOutError } = IlpPacket.Errors
6

7 2
export default class ExpireMiddleware implements Middleware {
8
  async applyToPipelines (pipelines: Pipelines, accountId: string) {
9 2
    pipelines.outgoingData.insertLast({
10
      name: 'expire',
11
      method: async (data: Buffer, next: MiddlewareCallback<Buffer, Buffer>) => {
12 2
        if (data[0] === IlpPacket.Type.TYPE_ILP_PREPARE) {
13 2
          const { executionCondition, expiresAt } = IlpPacket.deserializeIlpPrepare(data)
14

15 2
          const duration = expiresAt.getTime() - Date.now()
16

17 2
          const promise = next(data)
18

19
          let timeout: NodeJS.Timer
20 2
          const timeoutPromise: Promise<Buffer> = new Promise((resolve, reject) => {
21 2
            timeout = setTimeout(() => {
22 2
              log.debug('packet expired. cond=%s expiresAt=%s', executionCondition.slice(0, 6).toString('base64'), expiresAt.toISOString())
23 2
              reject(new TransferTimedOutError('packet expired.'))
24
            }, duration)
25
          })
26

27 2
          return Promise.race([
28 2
            promise.then((data) => { clearTimeout(timeout); return data }),
29
            timeoutPromise
30
          ])
31
        }
32

33 0
        return next(data)
34
      }
35
    })
36
  }
37
}

Read our documentation on viewing source code .

Loading