-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathtransport_http_stream.ts
More file actions
216 lines (198 loc) · 6.44 KB
/
Copy pathtransport_http_stream.ts
File metadata and controls
216 lines (198 loc) · 6.44 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/** @internal */
export class HttpStreamTransport {
endpoint: string;
options: any;
_abortController: any | null;
_utf8decoder: TextDecoder;
_protocol: string;
constructor(endpoint, options) {
this.endpoint = endpoint;
this.options = options;
this._abortController = null;
this._utf8decoder = new TextDecoder();
this._protocol = 'json';
}
name() {
return 'http_stream';
}
subName() {
return 'http_stream';
}
emulation() {
return true;
}
_handleErrors(response: any) {
if (!response.ok) throw new Error(response.status);
return response;
}
_fetchEventTarget(self, endpoint: string, options: object) {
const eventTarget = new EventTarget();
// fetch with connection timeout maybe? https://github.com/github/fetch/issues/175
const fetchFunc = self.options.fetch;
fetchFunc(endpoint, options)
.then(self._handleErrors)
.then(response => {
eventTarget.dispatchEvent(new Event('open'));
let jsonStreamBuf = '';
let jsonStreamPos = 0;
let protoStreamBuf = new Uint8Array();
const reader = response.body.getReader();
return new self.options.readableStream({
start(controller) {
function pump() {
return reader.read().then(({ done, value }) => {
// When no more data needs to be consumed, close the stream
if (done) {
eventTarget.dispatchEvent(new Event('close'));
controller.close();
return;
}
try {
if (self._protocol === 'json') {
jsonStreamBuf += self._utf8decoder.decode(value);
while (jsonStreamPos < jsonStreamBuf.length) {
if (jsonStreamBuf[jsonStreamPos] === '\n') {
const line = jsonStreamBuf.substring(0, jsonStreamPos);
eventTarget.dispatchEvent(new MessageEvent('message', { data: line }));
jsonStreamBuf = jsonStreamBuf.substring(jsonStreamPos + 1);
jsonStreamPos = 0;
} else {
++jsonStreamPos;
}
}
} else {
const mergedArray = new Uint8Array(protoStreamBuf.length + value.length);
mergedArray.set(protoStreamBuf);
mergedArray.set(value, protoStreamBuf.length);
protoStreamBuf = mergedArray;
while (true) {
const result = self.options.decoder.decodeReply(protoStreamBuf);
if (result.ok) {
const data = protoStreamBuf.slice(0, result.pos);
eventTarget.dispatchEvent(new MessageEvent('message', { data: data }));
protoStreamBuf = protoStreamBuf.slice(result.pos);
continue;
}
break;
}
}
} catch (error) {
// @ts-ignore - improve later.
eventTarget.dispatchEvent(new Event('error', { detail: error }));
eventTarget.dispatchEvent(new Event('close'));
controller.close();
return;
}
pump();
}).catch(function (e) {
// @ts-ignore - improve later.
eventTarget.dispatchEvent(new Event('error', { detail: e }));
eventTarget.dispatchEvent(new Event('close'));
controller.close();
return;
});
}
return pump();
}
});
})
.catch(error => {
// @ts-ignore - improve later.
eventTarget.dispatchEvent(new Event('error', { detail: error }));
eventTarget.dispatchEvent(new Event('close'));
});
return eventTarget;
}
supported() {
return this.options.fetch !== null &&
this.options.readableStream !== null &&
typeof TextDecoder !== 'undefined' &&
typeof AbortController !== 'undefined' &&
typeof EventTarget !== 'undefined' &&
typeof Event !== 'undefined' &&
typeof MessageEvent !== 'undefined' &&
typeof Error !== 'undefined';
}
initialize(protocol: string, callbacks: any, initialData: any) {
this._protocol = protocol;
this._abortController = new AbortController();
let headers: any;
let body: any;
if (protocol === 'json') {
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
body = initialData;
} else {
headers = {
'Accept': 'application/octet-stream',
'Content-Type': 'application/octet-stream'
};
body = initialData;
}
const fetchOptions = {
method: 'POST',
headers: headers,
body: body,
mode: 'cors',
credentials: 'same-origin',
signal: this._abortController.signal
}
const eventTarget = this._fetchEventTarget(
this,
this.endpoint,
fetchOptions
);
eventTarget.addEventListener('open', () => {
callbacks.onOpen();
});
eventTarget.addEventListener('error', (e) => {
this._abortController.abort();
callbacks.onError(e);
});
eventTarget.addEventListener('close', () => {
this._abortController.abort();
callbacks.onClose({
code: 4,
reason: 'connection closed'
});
});
eventTarget.addEventListener('message', (e: any) => {
callbacks.onMessage(e.data);
});
}
close() {
// _abortController is only assigned in initialize().
this._abortController?.abort();
}
send(data: any, session: string, node: string) {
let headers: any;
let body: any;
const req = {
session: session,
node: node,
data: data
};
if (this._protocol === 'json') {
headers = {
'Content-Type': 'application/json'
};
body = JSON.stringify(req);
} else {
headers = {
'Content-Type': 'application/octet-stream'
};
body = this.options.encoder.encodeEmulationRequest(req);
}
const fetchFunc = this.options.fetch;
const fetchOptions = {
method: 'POST',
headers: headers,
body: body,
mode: 'cors',
credentials: 'same-origin',
}
fetchFunc(this.options.emulationEndpoint, fetchOptions);
}
}