forked from haraka/Haraka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
attachment_stream.js
109 lines (95 loc) · 2.74 KB
/
attachment_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
104
105
106
107
108
109
'use strict';
const Stream = require('stream');
class AttachmentStream extends Stream {
constructor (header) {
super();
this.header = header;
this.encoding = null;
this.paused = false;
this.end_emitted = false;
this.connection = null;
this.buffer = [];
}
emit_data (data) {
// console.log("YYY: DATA emit");
if (this.paused) {
return this.buffer.push(data);
}
if (this.encoding) {
this.emit('data', data.toString(this.encoding));
}
else {
this.emit('data', data);
}
}
emit_end (force) {
if (this.paused && !force) {
// console.log("YYY: end emit (cache)");
this.end_emitted = true;
}
else {
// console.log("YYY: end emit");
if (this.buffer.length > 0) {
while (this.buffer.length > 0) {
this.emit_data(this.buffer.shift());
}
}
this.emit('end');
}
}
pipe (dest, options) {
const self = this;
this.paused = false;
const pipe = Stream.prototype.pipe.call(this, dest, options);
dest.on('drain', () => {
// console.log("YYY: DRAIN!!!");
if (self.paused) self.resume();
});
dest.on('end', () => {
// console.log("YYY: END!!");
if (self.paused) self.resume();
});
dest.on('close', () => {
// console.log("YYY: CLOSE!!");
if (self.paused) self.resume();
});
return pipe;
}
setEncoding (enc) {
if (enc !== 'binary') {
throw "Unable to set encoding to anything other than binary";
}
this.encoding = enc;
}
pause () {
// console.log("YYY: PAUSE!!");
this.paused = true;
if (this.connection) {
// console.log("YYYY: Backpressure pause");
this.connection.pause();
}
}
resume () {
// console.log("YYY: RESUME!!");
if (this.connection) {
// console.log("YYYY: Backpressure resume");
this.connection.resume();
}
this.paused = false;
if (this.buffer.length) {
while (this.paused === false && this.buffer.length > 0) {
this.emit_data(this.buffer.shift());
}
if (this.buffer.length === 0 && this.end_emitted) {
this.emit('end');
}
}
else if (this.end_emitted) {
this.emit('end');
}
}
destroy () {
// console.log("YYYY: Stream destroyed");
}
}
exports.createStream = header => new AttachmentStream (header)