forked from pinpoint-apm/pinpoint-node-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc-stream.js
103 lines (88 loc) · 2.47 KB
/
grpc-stream.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Pinpoint Node.js Agent
* Copyright 2020-present NAVER Corp.
* Apache License v2.0
*/
'use strict'
const log = require('../utils/logger')
const ended = Symbol('ended')
const writableHighWaterMarkedSymbol = Symbol('writableHighWaterMark')
class GrpcStream {
constructor(name, makeStream) {
this.name = name
this.connectStream = makeStream
this.stream = this.connectStream()
}
get writable() {
if (!this.stream) {
return false
}
if (typeof this.stream.writable !== 'boolean') {
return !this.streamEnded
}
return this.stream.writable
}
get streamEnded() {
return !this.stream || this.streamEndedSymbol
}
get streamEndedSymbol() {
if (!this.stream) {
return undefined
}
return this.stream[ended]
}
get writableHighWaterMarked() {
if (!this.stream) {
return undefined
}
return this.stream[writableHighWaterMarkedSymbol]
}
write(data, rewriteAfterStreamEnd = true) {
try {
if (this.writableHighWaterMarked) {
return
}
if (!this.writable) {
this.end()
this.stream = this.connectStream()
}
const stream = this.stream
const result = stream.write(data, (error) => {
if (error) {
this.endWithStream(stream)
if (rewriteAfterStreamEnd) {
this.write(data, false)
}
log.error(`grpc-stream.js write error in write method's callback: ${error}`)
}
})
if (!result) {
stream[writableHighWaterMarkedSymbol] = true
stream.once('drain', () => {
stream[writableHighWaterMarkedSymbol] = false
})
}
} catch (error) {
if (error) {
log.error(`grpc-stream.js write error: ${error}`)
}
}
}
end() {
this.endWithStream(this.stream)
this.stream = null
}
endWithStream(stream) {
try {
if (stream) {
stream.end()
stream[ended] = true
}
} catch (error) {
if (error) {
log.error(`grpc-stream.js end error: ${error}`)
}
}
}
}
module.exports = GrpcStream