Skip to content

Commit e14a7ca

Browse files
committed
initial support for compressing responses
1 parent 71a3d0a commit e14a7ca

9 files changed

Lines changed: 94 additions & 31 deletions

File tree

‎src/harness/harness.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ namespace Utils {
7070
return Buffer ? Buffer.byteLength(s, encoding) : s.length;
7171
}
7272

73+
export function compress(s: string): any {
74+
return Buffer ? new Buffer(s, "utf8") : { s, length: s.length };
75+
}
76+
7377
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
7478
const environment = getExecutionEnvironment();
7579
switch (environment) {

‎src/harness/harnessLanguageService.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,8 @@ namespace Harness.LanguageService {
572572
this.writeMessage(message);
573573
}
574574

575+
writeCompressedData() {
576+
}
575577

576578
readFile(fileName: string): string {
577579
if (fileName.indexOf(Harness.Compiler.defaultLibFileName) >= 0) {
@@ -690,7 +692,8 @@ namespace Harness.LanguageService {
690692
const server = new ts.server.Session(serverHost,
691693
{ isCancellationRequested: () => false },
692694
/*useOneInferredProject*/ false,
693-
Buffer ? Buffer.byteLength : (string: string, encoding?: string) => string.length,
695+
Utils.byteLength,
696+
Utils.compress,
694697
process.hrtime, serverHost);
695698

696699
// Fake the connection between the client and the server

‎src/server/node.d.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,15 @@ declare namespace NodeJS {
397397
}
398398
}
399399

400+
declare namespace NodeJS {
401+
namespace zlib {
402+
export interface GZip {
403+
gzipSync(buf: Buffer): Buffer;
404+
}
405+
export function createGZip(): GZip;
406+
}
407+
}
408+
400409
declare namespace NodeJS {
401410
namespace fs {
402411
interface Stats {

‎src/server/protocol.d.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ declare namespace ts.server.protocol {
3030
* Object containing arguments for the command
3131
*/
3232
arguments?: any;
33+
34+
canCompressResponse?: boolean;
3335
}
3436

3537
/**

‎src/server/server.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,22 @@
44
/* tslint:disable:no-null-keyword */
55

66
namespace ts.server {
7+
78
const readline: NodeJS.ReadLine = require("readline");
89
const fs: typeof NodeJS.fs = require("fs");
10+
const zlib: typeof NodeJS.zlib = require("zlib");
911

1012
const rl = readline.createInterface({
1113
input: process.stdin,
1214
output: process.stdout,
1315
terminal: false,
1416
});
1517

18+
function compress(s: string): CompressedData {
19+
const gzip = zlib.createGZip();
20+
return <CompressedData><any>gzip.gzipSync(new Buffer(s, "utf8"));
21+
}
22+
1623
class Logger implements ts.server.Logger {
1724
private fd = -1;
1825
private seq = 0;
@@ -92,7 +99,7 @@ namespace ts.server {
9299

93100
class IOSession extends Session {
94101
constructor(host: ServerHost, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, logger: ts.server.Logger) {
95-
super(host, cancellationToken, useSingleInferredProject, Buffer.byteLength, process.hrtime, logger);
102+
super(host, cancellationToken, useSingleInferredProject, Buffer.byteLength, compress, process.hrtime, logger);
96103
}
97104

98105
exit() {
@@ -260,15 +267,16 @@ namespace ts.server {
260267
const pollingWatchedFileSet = createPollingWatchedFileSet();
261268
const logger = createLoggerFromEnv();
262269

263-
const pending: string[] = [];
270+
const pending: Buffer[] = [];
264271
let canWrite = true;
265-
function writeMessage(s: string) {
272+
273+
function writeMessage(buf: Buffer) {
266274
if (!canWrite) {
267-
pending.push(s);
275+
pending.push(buf);
268276
}
269277
else {
270278
canWrite = false;
271-
process.stdout.write(new Buffer(s, "utf8"), setCanWriteFlagAndWriteMessageIfNecessary);
279+
process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary);
272280
}
273281
}
274282

@@ -279,10 +287,16 @@ namespace ts.server {
279287
}
280288
}
281289

290+
function writeCompressedData(prefix: string, compressed: CompressedData, suffix: string): void {
291+
sys.write(prefix);
292+
writeMessage(<Buffer><any>compressed);
293+
sys.write(suffix);
294+
}
295+
282296
const sys = <ServerHost>ts.sys;
283297

284298
// Override sys.write because fs.writeSync is not reliable on Node 4
285-
sys.write = (s: string) => writeMessage(s);
299+
sys.write = (s: string) => writeMessage(new Buffer(s, "utf8"));
286300
sys.watchFile = (fileName, callback) => {
287301
const watchedFile = pollingWatchedFileSet.addFile(fileName, callback);
288302
return {
@@ -294,6 +308,7 @@ namespace ts.server {
294308
sys.clearTimeout = clearTimeout;
295309
sys.setImmediate = setImmediate;
296310
sys.clearImmediate = clearImmediate;
311+
sys.writeCompressedData = writeCompressedData;
297312

298313
let cancellationToken: HostCancellationToken;
299314
try {

‎src/server/session.ts‎

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,15 @@ namespace ts.server {
1010
stack?: string;
1111
}
1212

13+
export interface CompressedData {
14+
__compressedDataTag: any;
15+
length: number;
16+
}
17+
18+
export interface ServerHost {
19+
writeCompressedData(prefix: string, data: CompressedData, suffix: string): void;
20+
}
21+
1322
export function generateSpaces(n: number): string {
1423
if (!spaceCache[n]) {
1524
let strBuilder = "";
@@ -183,6 +192,7 @@ namespace ts.server {
183192
cancellationToken: HostCancellationToken,
184193
useSingleInferredProject: boolean,
185194
private byteLength: (buf: string, encoding?: string) => number,
195+
private compress: (s: string) => CompressedData,
186196
private hrtime: (start?: number[]) => number[],
187197
private logger: Logger) {
188198
this.projectService =
@@ -215,13 +225,27 @@ namespace ts.server {
215225
this.host.write(line + this.host.newLine);
216226
}
217227

218-
public send(msg: protocol.Message) {
228+
private sendCompressedDataToClient(prefix: string, data: CompressedData) {
229+
this.host.writeCompressedData(prefix, data, this.host.newLine);
230+
}
231+
232+
public send(msg: protocol.Message, canCompressResponse: boolean) {
219233
const json = JSON.stringify(msg);
220234
if (this.logger.isVerbose()) {
221235
this.logger.info(msg.type + ": " + json);
222236
}
223-
this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) +
224-
"\r\n\r\n" + json);
237+
const len = this.byteLength(json, "utf8");
238+
if (len < 84000 || !canCompressResponse) {
239+
this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + "\r\n\r\n" + json);
240+
}
241+
else {
242+
// TODO: measure time
243+
const compressed = this.compress(json);
244+
if (this.logger.isVerbose()) {
245+
this.logger.info(`compressed message to ${compressed.length}`);
246+
}
247+
this.sendCompressedDataToClient(`Content-Length: ${compressed.length + 1}`, compressed);
248+
}
225249
}
226250

227251
public configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]) {
@@ -236,7 +260,7 @@ namespace ts.server {
236260
diagnostics: bakedDiags
237261
}
238262
};
239-
this.send(ev);
263+
this.send(ev, /*canCompressResponse*/ false);
240264
}
241265

242266
public event(info: any, eventName: string) {
@@ -246,10 +270,10 @@ namespace ts.server {
246270
event: eventName,
247271
body: info,
248272
};
249-
this.send(ev);
273+
this.send(ev, /*canCompressResponse*/ false);
250274
}
251275

252-
private response(info: any, cmdName: string, reqSeq = 0, errorMsg?: string) {
276+
private response(info: any, cmdName: string, canCompressResponse: boolean, reqSeq = 0, errorMsg?: string) {
253277
const res: protocol.Response = {
254278
seq: 0,
255279
type: "response",
@@ -263,11 +287,11 @@ namespace ts.server {
263287
else {
264288
res.message = errorMsg;
265289
}
266-
this.send(res);
290+
this.send(res, canCompressResponse);
267291
}
268292

269-
public output(body: any, commandName: string, requestSequence = 0, errorMessage?: string) {
270-
this.response(body, commandName, requestSequence, errorMessage);
293+
public output(body: any, commandName: string, canCompressResponse: boolean, requestSequence = 0, errorMessage?: string) {
294+
this.response(body, commandName, canCompressResponse, requestSequence, errorMessage);
271295
}
272296

273297
private getLocation(position: number, scriptInfo: ScriptInfo): protocol.Location {
@@ -1030,7 +1054,7 @@ namespace ts.server {
10301054
this.changeSeq++;
10311055
// make sure no changes happen before this one is finished
10321056
if (project.reloadScript(file)) {
1033-
this.output(undefined, CommandNames.Reload, reqSeq);
1057+
this.output(undefined, CommandNames.Reload, /*canCompressResponse*/ false, reqSeq);
10341058
}
10351059
}
10361060
}
@@ -1407,7 +1431,7 @@ namespace ts.server {
14071431
},
14081432
[CommandNames.Configure]: (request: protocol.ConfigureRequest) => {
14091433
this.projectService.setHostConfiguration(request.arguments);
1410-
this.output(undefined, CommandNames.Configure, request.seq);
1434+
this.output(undefined, CommandNames.Configure, /*canCompressResponse*/ false, request.seq);
14111435
return this.notRequired();
14121436
},
14131437
[CommandNames.Reload]: (request: protocol.ReloadRequest) => {
@@ -1473,7 +1497,7 @@ namespace ts.server {
14731497
}
14741498
else {
14751499
this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request));
1476-
this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command);
1500+
this.output(undefined, CommandNames.Unknown, /*canCompressResponse*/ false, request.seq, "Unrecognized JSON command: " + request.command);
14771501
return { responseRequired: false };
14781502
}
14791503
}
@@ -1501,22 +1525,23 @@ namespace ts.server {
15011525
this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf");
15021526
}
15031527
if (response) {
1504-
this.output(response, request.command, request.seq);
1528+
this.output(response, request.command, request.canCompressResponse, request.seq);
15051529
}
15061530
else if (responseRequired) {
1507-
this.output(undefined, request.command, request.seq, "No content available.");
1531+
this.output(undefined, request.command, /*canCompressResponse*/ false, request.seq, "No content available.");
15081532
}
15091533
}
15101534
catch (err) {
15111535
if (err instanceof OperationCanceledException) {
15121536
// Handle cancellation exceptions
1513-
this.output({ canceled: true }, request.command, request.seq);
1537+
this.output({ canceled: true }, request.command, /*canCompressResponse*/ false, request.seq);
15141538
return;
15151539
}
15161540
this.logError(err, message);
15171541
this.output(
15181542
undefined,
15191543
request ? request.command : CommandNames.Unknown,
1544+
/*canCompressResponse*/ false,
15201545
request ? request.seq : 0,
15211546
"Error processing request. " + (<StackTraceError>err).message + "\n" + (<StackTraceError>err).stack);
15221547
}

‎tests/cases/unittests/cachingInServerLSHost.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ namespace ts {
2929
writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => {
3030
throw new Error("NYI");
3131
},
32+
writeCompressedData() {
33+
throw new Error("NYI");
34+
},
3235
resolvePath: (path: string): string => {
3336
throw new Error("NYI");
3437
},

‎tests/cases/unittests/session.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ namespace ts.server {
2323
setTimeout(callback, ms, ...args) { return 0; },
2424
clearTimeout(timeoutId) { },
2525
setImmediate: () => 0,
26-
clearImmediate() {}
26+
clearImmediate() {},
27+
writeCompressedData() {}
2728
};
2829
const nullCancellationToken: HostCancellationToken = { isCancellationRequested: () => false };
2930
const mockLogger: Logger = {
@@ -42,7 +43,7 @@ namespace ts.server {
4243
let lastSent: protocol.Message;
4344

4445
beforeEach(() => {
45-
session = new Session(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, Utils.byteLength, process.hrtime, mockLogger);
46+
session = new Session(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, Utils.byteLength, Utils.compress, process.hrtime, mockLogger);
4647
session.send = (msg: protocol.Message) => {
4748
lastSent = msg;
4849
};
@@ -180,7 +181,7 @@ namespace ts.server {
180181

181182
session.send = Session.prototype.send;
182183
assert(session.send);
183-
expect(session.send(msg)).to.not.exist;
184+
expect(session.send(msg, /*canCompressResponse*/ false)).to.not.exist;
184185
expect(lastWrittenToHost).to.equal(resultMsg);
185186
});
186187
});
@@ -248,7 +249,7 @@ namespace ts.server {
248249
};
249250
const command = "test";
250251

251-
session.output(body, command);
252+
session.output(body, command, /*canCompressResponse*/ false);
252253

253254
expect(lastSent).to.deep.equal({
254255
seq: 0,
@@ -267,7 +268,7 @@ namespace ts.server {
267268
lastSent: protocol.Message;
268269
customHandler = "testhandler";
269270
constructor() {
270-
super(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, Utils.byteLength, process.hrtime, mockLogger);
271+
super(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, Utils.byteLength, Utils.compress, process.hrtime, mockLogger);
271272
this.addProtocolHandler(this.customHandler, () => {
272273
return { response: undefined, responseRequired: true };
273274
});
@@ -286,7 +287,7 @@ namespace ts.server {
286287
};
287288
const command = "test";
288289

289-
session.output(body, command);
290+
session.output(body, command, /*canCompressResponse*/ false);
290291

291292
expect(session.lastSent).to.deep.equal({
292293
seq: 0,
@@ -325,7 +326,7 @@ namespace ts.server {
325326
class InProcSession extends Session {
326327
private queue: protocol.Request[] = [];
327328
constructor(private client: InProcClient) {
328-
super(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, Utils.byteLength, process.hrtime, mockLogger);
329+
super(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, Utils.byteLength, Utils.compress, process.hrtime, mockLogger);
329330
this.addProtocolHandler("echo", (req: protocol.Request) => ({
330331
response: req.arguments,
331332
responseRequired: true
@@ -346,11 +347,11 @@ namespace ts.server {
346347
({ response } = this.executeCommand(msg));
347348
}
348349
catch (e) {
349-
this.output(undefined, msg.command, msg.seq, e.toString());
350+
this.output(undefined, msg.command, /*canCompressResponse*/ false, msg.seq, e.toString());
350351
return;
351352
}
352353
if (response) {
353-
this.output(response, msg.command, msg.seq);
354+
this.output(response, msg.command, /*canCompressResponse*/ false, msg.seq);
354355
}
355356
}
356357

‎tests/cases/unittests/tsserverProjectSystem.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,7 @@ namespace ts {
366366
readonly getExecutingFilePath = () => this.executingFilePath;
367367
readonly getCurrentDirectory = () => this.currentDirectory;
368368
readonly writeFile = (path: string, content: string) => notImplemented();
369+
readonly writeCompressedData = () => notImplemented();
369370
readonly write = (s: string) => notImplemented();
370371
readonly createDirectory = (s: string) => notImplemented();
371372
readonly exit = () => notImplemented();

0 commit comments

Comments
 (0)