UNPKG

3.13 kBPlain TextView Raw
1import * as IlpPacket from 'ilp-packet'
2import {
3 Middleware,
4 MiddlewareCallback,
5 MiddlewareServices,
6 Pipelines
7} from '../types/middleware'
8import Stats from '../services/stats'
9import { AccountInfo } from '../types/accounts'
10
11export default class StatsMiddleware implements Middleware {
12 private stats: Stats
13
14 private getInfo: (accountId: string) => AccountInfo
15
16 constructor (opts: {}, { stats, getInfo }: MiddlewareServices) {
17 this.stats = stats
18 this.getInfo = getInfo
19 }
20
21 async applyToPipelines (pipelines: Pipelines, accountId: string) {
22 const accountInfo = this.getInfo(accountId)
23 if (!accountInfo) {
24 throw new Error('could not load info for account. accountId=' + accountId)
25 }
26 const account = { accountId, accountInfo }
27 pipelines.incomingData.insertLast({
28 name: 'stats',
29 method: async (data: Buffer, next: MiddlewareCallback<Buffer, Buffer>) => {
30 try {
31 const result = await next(data)
32 if (result[0] === IlpPacket.Type.TYPE_ILP_FULFILL) {
33 this.stats.incomingDataPackets.increment(account, { result: 'fulfilled' })
34 } else {
35 this.stats.incomingDataPackets.increment(account, { result: 'rejected' })
36 }
37 return result
38 } catch (err) {
39 this.stats.incomingDataPackets.increment(account, { result: 'failed' })
40 throw err
41 }
42 }
43 })
44
45 pipelines.incomingMoney.insertLast({
46 name: 'stats',
47 method: async (amount: string, next: MiddlewareCallback<string, void>) => {
48 try {
49 const result = await next(amount)
50 this.stats.incomingMoney.setValue(account, { result: 'succeeded' }, +amount)
51 return result
52 } catch (err) {
53 this.stats.incomingMoney.setValue(account, { result: 'failed' }, +amount)
54 throw err
55 }
56 }
57 })
58
59 pipelines.outgoingData.insertLast({
60 name: 'stats',
61 method: async (data: Buffer, next: MiddlewareCallback<Buffer, Buffer>) => {
62 try {
63 const result = await next(data)
64 if (result[0] === IlpPacket.Type.TYPE_ILP_FULFILL) {
65 this.stats.outgoingDataPackets.increment(account, { result: 'fulfilled' })
66 } else {
67 const rejectPacket = IlpPacket.deserializeIlpReject(result)
68 const { code } = rejectPacket
69 this.stats.outgoingDataPackets.increment(account,
70 { result: 'rejected', code })
71 }
72 return result
73 } catch (err) {
74 this.stats.outgoingDataPackets.increment(account, { result: 'failed' })
75 throw err
76 }
77 }
78 })
79
80 pipelines.outgoingMoney.insertLast({
81 name: 'stats',
82 method: async (amount: string, next: MiddlewareCallback<string, void>) => {
83 try {
84 const result = await next(amount)
85 this.stats.outgoingMoney.setValue(account, { result: 'succeeded' }, +amount)
86 return result
87 } catch (err) {
88 this.stats.outgoingMoney.setValue(account, { result: 'failed' }, +amount)
89 throw err
90 }
91 }
92 })
93 }
94}