Skip to content
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

Fix status and error callbacks #608

Merged
merged 2 commits into from
Aug 3, 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
76 changes: 52 additions & 24 deletions javascript/net/grpc/web/grpcwebclientreadablestream.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ const GrpcWebClientReadableStream = function(genericTransportInterface) {
*/
this.onEndCallback_ = null;

/**
* @private
* @type {boolean} Whether the stream has been aborted
*/
this.aborted_ = false;

/**
* @private
* @type {number} The stream parser position
Expand All @@ -119,16 +125,6 @@ const GrpcWebClientReadableStream = function(genericTransportInterface) {
if (!contentType) return;
contentType = contentType.toLowerCase();

var grpcStatusCode = self.xhr_.getStreamingResponseHeader(GRPC_STATUS);
var grpcStatusMessage = self.xhr_.getStreamingResponseHeader(GRPC_STATUS_MESSAGE);
if (grpcStatusCode && self.onStatusCallback_) {
self.onStatusCallback_(/** @type {!Status} */({
code: Number(grpcStatusCode),
details: grpcStatusMessage || '',
metadata: undefined,
}));
}

if (googString.startsWith(contentType, 'application/grpc-web-text')) {
var responseText = self.xhr_.getResponseText();
var newPos = responseText.length - responseText.length % 4;
Expand Down Expand Up @@ -157,15 +153,15 @@ const GrpcWebClientReadableStream = function(genericTransportInterface) {
}
if (FrameType.TRAILER in messages[i]) {
if (messages[i][FrameType.TRAILER].length > 0) {
var trailerString = "";
var trailerString = '';
for (var pos = 0; pos < messages[i][FrameType.TRAILER].length;
pos++) {
trailerString += String.fromCharCode(
messages[i][FrameType.TRAILER][pos]);
}
var trailers = self.parseHttp1Headers_(trailerString);
grpcStatusCode = StatusCode.OK;
grpcStatusMessage = "";
var grpcStatusCode = StatusCode.OK;
var grpcStatusMessage = '';
if (GRPC_STATUS in trailers) {
grpcStatusCode = trailers[GRPC_STATUS];
}
Expand Down Expand Up @@ -194,22 +190,53 @@ const GrpcWebClientReadableStream = function(genericTransportInterface) {
});

events.listen(this.xhr_, EventType.COMPLETE, function(e) {
if (!self.onErrorCallback_) return;
var lastErrorCode = self.xhr_.getLastErrorCode();
var grpcStatusCode;
var grpcStatusMessage = '';

// There's an XHR level error
if (lastErrorCode != ErrorCode.NO_ERROR) {
self.onErrorCallback_({
code: StatusCode.UNAVAILABLE,
message: ErrorCode.getDebugMessage(lastErrorCode)
});
switch (lastErrorCode) {
case ErrorCode.ABORT:
grpcStatusCode = StatusCode.ABORTED;
break;
case ErrorCode.TIMEOUT:
grpcStatusCode = StatusCode.DEADLINE_EXCEEDED;
break;
default:
grpcStatusCode = StatusCode.UNAVAILABLE;
}
if (grpcStatusCode == StatusCode.ABORTED && self.aborted_) {
return;
}
if (self.onErrorCallback_) {
self.onErrorCallback_({
code: grpcStatusCode,
message: ErrorCode.getDebugMessage(lastErrorCode)
});
}
return;
}

// Check whethere there are grpc specific response headers
var responseHeaders = self.xhr_.getResponseHeaders();
if (GRPC_STATUS in responseHeaders &&
Number(self.xhr_.getResponseHeader(GRPC_STATUS)) != StatusCode.OK) {
self.onErrorCallback_({
code: Number(self.xhr_.getResponseHeader(GRPC_STATUS)),
message: self.xhr_.getResponseHeader(GRPC_STATUS_MESSAGE)
});
if (GRPC_STATUS in responseHeaders) {
grpcStatusCode = self.xhr_.getResponseHeader(GRPC_STATUS);
if (GRPC_STATUS_MESSAGE in responseHeaders) {
grpcStatusMessage = self.xhr_.getResponseHeader(GRPC_STATUS_MESSAGE);
}
if (Number(grpcStatusCode) != StatusCode.OK && self.onErrorCallback_) {
self.onErrorCallback_({
code: Number(grpcStatusCode),
message: grpcStatusMessage,
});
}
if (self.onStatusCallback_) {
self.onStatusCallback_(/** @type {!Status} */({
code: Number(grpcStatusCode),
details: grpcStatusMessage,
}));
}
}
});
};
Expand Down Expand Up @@ -252,6 +279,7 @@ GrpcWebClientReadableStream.prototype.setResponseDeserializeFn =
* @export
*/
GrpcWebClientReadableStream.prototype.cancel = function() {
this.aborted_ = true;
this.xhr_.abort();
};

Expand Down
2 changes: 1 addition & 1 deletion net/grpc/gateway/examples/echo/node-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"@grpc/proto-loader": "^0.3.0",
"async": "^1.5.2",
"google-protobuf": "^3.6.0",
"grpc": "^1.15.0",
"@grpc/grpc-js": "^0.5.0",
"lodash": "^4.6.1"
}
}
14 changes: 9 additions & 5 deletions net/grpc/gateway/examples/echo/node-server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@

var PROTO_PATH = __dirname + '/../echo.proto';

var assert = require('assert');
var async = require('async');
var _ = require('lodash');
var grpc = require('grpc');
var grpc = require('@grpc/grpc-js');
var protoLoader = require('@grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
PROTO_PATH,
Expand Down Expand Up @@ -89,8 +90,8 @@ function doServerStreamingEcho(call) {
}

/**
* Get a new server with the handler functions in this file bound to the methods
* it serves.
* Get a new server with the handler functions in this file bound to the
* methods it serves.
* @return {!Server} The new server object
*/
function getServer() {
Expand All @@ -106,8 +107,11 @@ function getServer() {
if (require.main === module) {
// If this is run as a script, start a server on an unused port
var echoServer = getServer();
echoServer.bind('0.0.0.0:9090', grpc.ServerCredentials.createInsecure());
echoServer.start();
echoServer.bindAsync('0.0.0.0:9090', grpc.ServerCredentials.createInsecure(),
(err, port) => {
assert.ifError(err);
echoServer.start();
});
}

exports.getServer = getServer;
46 changes: 29 additions & 17 deletions net/grpc/gateway/examples/echo/ts-example/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,13 @@ import {EchoRequest, EchoResponse, ServerStreamingEchoRequest, ServerStreamingEc
class EchoApp {
static readonly INTERVAL = 500; // ms
static readonly MAX_STREAM_MESSAGES = 50;

echoService_: EchoServiceClient;
stream: grpcWeb.ClientReadableStream<ServerStreamingEchoResponse> | null;

constructor(echoService: EchoServiceClient) {
this.echoService_ = echoService;
this.stream = null;
}

static addMessage(message: string, cssClass: string) {
Expand Down Expand Up @@ -76,19 +79,26 @@ class EchoApp {
});
}

echoError(msg: string) {
EchoApp.addLeftMessage(msg);
echoError() {
EchoApp.addLeftMessage('Error');
const request = new EchoRequest();
request.setMessage(msg);
request.setMessage('error');
this.echoService_.echoAbort(
request, {}, (err: grpcWeb.Error, response: EchoResponse) => {
if (err) {
if (err.code !== grpcWeb.StatusCode.OK) {
EchoApp.addRightMessage(
'Error code: ' + err.code + ' "' + err.message + '"');
}
request, {}, (err: grpcWeb.Error, response: EchoResponse) => {
if (err) {
if (err.code !== grpcWeb.StatusCode.OK) {
EchoApp.addRightMessage(
'Error code: ' + err.code + ' "' + decodeURI(err.message) + '"');
}
});
}
});
}

cancel() {
EchoApp.addLeftMessage('Cancel');
if (this.stream) {
this.stream.cancel();
}
}

repeatEcho(msg: string, count: number) {
Expand All @@ -101,23 +111,23 @@ class EchoApp {
request.setMessageCount(count);
request.setMessageInterval(EchoApp.INTERVAL);

const stream = this.echoService_.serverStreamingEcho(
this.stream = this.echoService_.serverStreamingEcho(
request, {'custom-header-1': 'value1'});
const self = this;
stream.on('data', (response: ServerStreamingEchoResponse) => {
this.stream.on('data', (response: ServerStreamingEchoResponse) => {
EchoApp.addRightMessage(response.getMessage());
});
stream.on('status', (status: grpcWeb.Status) => {
this.stream.on('status', (status: grpcWeb.Status) => {
if (status.metadata) {
console.log('Received metadata');
console.log(status.metadata);
}
});
stream.on('error', (err: grpcWeb.Error) => {
this.stream.on('error', (err: grpcWeb.Error) => {
EchoApp.addRightMessage(
'Error code: ' + err.code + ' "' + err.message + '"');
});
stream.on('end', () => {
this.stream.on('end', () => {
console.log('stream end signal received');
});
}
Expand All @@ -132,11 +142,13 @@ class EchoApp {
const count = msg.substr(0, msg.indexOf(' '));
if (/^\d+$/.test(count)) {
this.repeatEcho(msg.substr(msg.indexOf(' ') + 1), Number(count));
} else if (count === 'err') {
this.echoError(msg.substr(msg.indexOf(' ') + 1));
} else {
this.echo(msg);
}
} else if (msg === 'error') {
this.echoError();
} else if (msg === 'cancel') {
this.cancel();
} else {
this.echo(msg);
}
Expand Down