Skip to content

Fix a couple things in Typescript client #13863

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/SignalR/clients/ts/signalr/src/HttpConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ export class HttpConnection implements IConnection {
});

if (response.statusCode !== 200) {
return Promise.reject(new Error(`Unexpected status code returned from negotiate ${response.statusCode}`));
return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`));
}

const negotiateResponse = JSON.parse(response.content as string) as INegotiateResponse;
Expand Down Expand Up @@ -475,8 +475,8 @@ export class HttpConnection implements IConnection {
}

if (this.connectionState === ConnectionState.Connecting) {
this.logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection hasn't yet left the in the connecting state.`);
return;
this.logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better throw rather than no-op and log a warning if stopConnection is called while the connection is in the connecting state. HubConnection should await any start tasks in stop() and protect us from this actually occurring.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you wanting me to change that behavior in this PR?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's not too risky, yes. I don't want to have to spin a new PR for some code cleanup. If it causes a bunch of tests to fail, or you feel it's risky, we can make it another PR.

throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`);
}

if (this.connectionState === ConnectionState.Disconnecting) {
Expand Down Expand Up @@ -626,7 +626,7 @@ export class TransportSendQueue {
offset += item.byteLength;
}

return result;
return result.buffer;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

? who uses this?

Copy link
Member Author

@BrennanConroy BrennanConroy Sep 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The getDataDetail method which prints the info I put in the summary

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting that the type checker didn't catch this.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ArrayBuffer is a weird type. It has basically no public members, you have to wrap it in a view like Uint8Array. It's possible that, because of that, the result object technically does adhere to the ArrayBuffer interface (structurally, since that's all TS actually cares about).

Short answer: Type checker be weird

}
}

Expand Down
6 changes: 5 additions & 1 deletion src/SignalR/clients/ts/signalr/src/WebSocketTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,11 @@ export class WebSocketTransport implements ITransport {
}
};

webSocket.onclose = (event: CloseEvent) => this.close(event);
webSocket.onclose = (event: CloseEvent) => {
if (this.webSocket) {
this.close(event);
}
};
});
}

Expand Down
58 changes: 53 additions & 5 deletions src/SignalR/clients/ts/signalr/tests/HttpConnection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { HttpTransportType, ITransport, TransferFormat } from "../src/ITransport
import { getUserAgentHeader } from "../src/Utils";

import { HttpError } from "../src/Errors";
import { ILogger, LogLevel } from "../src/ILogger";
import { NullLogger } from "../src/Loggers";
import { EventSourceConstructor, WebSocketConstructor } from "../src/Polyfills";

Expand Down Expand Up @@ -192,9 +193,9 @@ describe("HttpConnection", () => {
const connection = new HttpConnection("http://tempuri.org", options);
await expect(connection.start(TransferFormat.Text))
.rejects
.toThrow("Unexpected status code returned from negotiate 999");
.toThrow("Unexpected status code returned from negotiate '999'");
},
"Failed to start the connection: Error: Unexpected status code returned from negotiate 999");
"Failed to start the connection: Error: Unexpected status code returned from negotiate '999'");
});

it("all transport failure errors get aggregated", async () => {
Expand Down Expand Up @@ -1151,6 +1152,53 @@ describe("HttpConnection", () => {
}, "Failed to start the connection: Error: nope");
});

it("logMessageContent displays correctly with binary data", async () => {
await VerifyLogger.run(async (logger) => {
const availableTransport = { transport: "LongPolling", transferFormats: ["Text", "Binary"] };

let sentMessage = "";
const captureLogger: ILogger = {
log: (logLevel: LogLevel, message: string) => {
if (logLevel === LogLevel.Trace && message.search("data of length") > 0) {
sentMessage = message;
}

logger.log(logLevel, message);
},
};

let httpClientGetCount = 0;
const options: IHttpConnectionOptions = {
...commonOptions,
httpClient: new TestHttpClient()
.on("POST", () => ({ connectionId: "42", availableTransports: [availableTransport] }))
.on("GET", () => {
httpClientGetCount++;
if (httpClientGetCount === 1) {
// First long polling request must succeed so start completes
return "";
}
return Promise.resolve();
})
.on("DELETE", () => new HttpResponse(202)),
logMessageContent: true,
logger: captureLogger,
transport: HttpTransportType.LongPolling,
} as IHttpConnectionOptions;

const connection = new HttpConnection("http://tempuri.org", options);
connection.onreceive = () => null;
try {
await connection.start(TransferFormat.Binary);
await connection.send(new Uint8Array([0x68, 0x69, 0x20, 0x3a, 0x29]));
} finally {
await connection.stop();
}

expect(sentMessage).toBe("(LongPolling transport) sending data. Binary data of length 5. Content: '0x68 0x69 0x20 0x3a 0x29'.");
});
});

describe(".constructor", () => {
it("throws if no Url is provided", async () => {
// Force TypeScript to let us call the constructor incorrectly :)
Expand Down Expand Up @@ -1413,7 +1461,7 @@ describe("TransportSendQueue", () => {

const queue = new TransportSendQueue(transport);

const first = queue.send(new Uint8Array([4, 5, 6]));
const first = queue.send(new Uint8Array([4, 5, 6]).buffer);
// This should allow first to enter transport.send
promiseSource1.resolve();
// Wait until we're inside transport.send
Expand All @@ -1428,8 +1476,8 @@ describe("TransportSendQueue", () => {
await Promise.all([first, second, third]);

expect(sendMock.mock.calls.length).toBe(2);
expect(sendMock.mock.calls[0][0]).toEqual(new Uint8Array([4, 5, 6]));
expect(sendMock.mock.calls[1][0]).toEqual(new Uint8Array([7, 8, 10, 12, 14]));
expect(sendMock.mock.calls[0][0]).toEqual(new Uint8Array([4, 5, 6]).buffer);
expect(sendMock.mock.calls[1][0]).toEqual(new Uint8Array([7, 8, 10, 12, 14]).buffer);

await queue.stop();
});
Expand Down
30 changes: 30 additions & 0 deletions src/SignalR/clients/ts/signalr/tests/WebSocketTransport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,36 @@ describe("WebSocketTransport", () => {
.toBe("WebSocket is not in the OPEN state");
});
});

it("does not run onclose callback if Transport does not fully connect and exits", async () => {
await VerifyLogger.run(async (logger) => {
(global as any).ErrorEvent = TestErrorEvent;
const webSocket = new WebSocketTransport(new TestHttpClient(), undefined, logger, true, TestWebSocket);

const connectPromise = webSocket.connect("http://example.com", TransferFormat.Text);

await TestWebSocket.webSocket.closeSet;

let closeCalled: boolean = false;
let error: Error;
webSocket.onclose = (e) => {
closeCalled = true;
error = e!;
};

const message = new TestCloseEvent();
message.wasClean = false;
message.code = 1;
message.reason = "just cause";
TestWebSocket.webSocket.onclose(message);

expect(closeCalled).toBe(false);
expect(error!).toBeUndefined();

TestWebSocket.webSocket.onerror(new TestEvent());
await expect(connectPromise).rejects.toThrow("There was an error with the transport.");
});
});
});

async function createAndStartWebSocket(logger: ILogger, url?: string, accessTokenFactory?: (() => string | Promise<string>), format?: TransferFormat): Promise<WebSocketTransport> {
Expand Down