Skip to content

Commit

Permalink
Upgrade to new grpc-web interceptors
Browse files Browse the repository at this point in the history
  • Loading branch information
joeyberkovitz committed May 7, 2020
1 parent 907601d commit 5ac43a2
Show file tree
Hide file tree
Showing 21 changed files with 293 additions and 154 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public List<String> genTokens(int userID, String userAgent){
User user = db.withExtension(UserDao.class, d->d.getUser(userID));

Date issueDate = new Date();
Date expDate = Date.from(issueDate.toInstant().plus(Duration.ofHours(1)));
Date expDate = Date.from(issueDate.toInstant().plus(Duration.ofSeconds(10)));
Date refreshExp = Date.from(issueDate.toInstant().plus(Duration.ofDays(1)));
Date notBefore = Date.from(issueDate.toInstant().minus(Duration.ofMinutes(5)));
String authToken = Jwts.builder()
Expand Down
25 changes: 25 additions & 0 deletions spring/src/main/js/reservdjs/grpc-web/externs.js
Original file line number Diff line number Diff line change
@@ -1 +1,26 @@
var module;

/**
* List of functions we want to preserve when running the closure compiler
* with --compilation_level=ADVANCED_OPTIMIZATIONS.
*/
module.ClientReadableStream = function() {};
module.ClientReadableStream.prototype.on = function(eventType, callback) {};
module.ClientReadableStream.prototype.cancel = function() {};

module.GenericClient = function() {};
module.GenericClient.prototype.unaryCall = function(request) {};
module.GenericClient.prototype.call = function(requestMessage,
methodDescriptor) {};

module.UnaryInterceptor = function() {};
module.UnaryInterceptor.prototype.intercept = function(request, invoker) {};

module.StreamInterceptor = function() {};
module.StreamInterceptor.prototype.intercept = function(request, invoker) {};

module.Request = function() {};
module.Request.prototype.getRequestMessage = function() {};
module.Request.prototype.getMethodDescriptor = function() {};
module.Request.prototype.getMetadata = function() {};
module.Request.prototype.getCallOptions = function() {};
103 changes: 53 additions & 50 deletions spring/src/main/js/reservdjs/grpc-web/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion spring/src/main/js/reservdjs/grpc-web/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "grpc-web",
"version": "1.0.8",
"version": "1.1.0-rc.1",
"author": "Google Inc.",
"description": "gRPC-Web Client Runtime Library",
"homepage": "https://grpc.io/",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,19 +202,21 @@ describe('grpc-web generated code (commonjs+grpcwebtext)', function() {
var request = new EchoRequest();
request.setMessage('aaa');
MockXMLHttpRequest.onSend = function(xhr) {
xhr.respond(200, {'Content-Type': 'application/grpc-web-text'},
// a single data frame with an 'aaa' message, followed by,
// a trailer frame with content 'grpc-status:0'
'AAAAAAUKA2FhYYAAAAAPZ3JwYy1zdGF0dXM6MA0K');
xhr.respond(
200, {'Content-Type': 'application/grpc-web-text'},
// a single data frame with an 'aaa' message, followed by,
// a trailer frame with content 'grpc-status: 0\d\ax-custom-1: ababab'
'AAAAAAUKA2FhYYAAAAAkZ3JwYy1zdGF0dXM6IDANCngtY3VzdG9tLTE6IGFiYWJhYg0K');
};
var call = echoService.echo(request, {'custom-header-1':'value1'},
function(err, response) {
assert.equal('aaa', response.getMessage());
});
call.on('status', function(status) {
assert.equal('object', typeof status.metadata);
assert.equal(true, 'grpc-status' in status.metadata);
assert.equal(0, parseInt(status.metadata['grpc-status']));
assert.equal(false, 'grpc-status' in status.metadata);
assert.equal(true, 'x-custom-1' in status.metadata);
assert.equal('ababab', status.metadata['x-custom-1']);
done();
});
});
Expand Down
25 changes: 25 additions & 0 deletions spring/src/main/js/reservdjs/node_modules/grpc-web/externs.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

103 changes: 53 additions & 50 deletions spring/src/main/js/reservdjs/node_modules/grpc-web/index.js

Large diffs are not rendered by default.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

83 changes: 80 additions & 3 deletions spring/src/main/js/reservdjs/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,95 @@
<script>
import * as client from './proto/RestaurantServiceServiceClientPb';
import {CustomRPCClient} from "@/proto/CustomRPCClient";
import {RestaurantServiceClient} from "./proto/RestaurantServiceServiceClientPb";
import {RestaurantServiceClient, UserServiceClient} from "./proto/RestaurantServiceServiceClientPb";
import {ReservationServiceClient} from "@/proto/RestaurantServiceServiceClientPb";
import {GetCategoryRequest, RefreshRequest, Restaurant} from "@/proto/RestaurantService_pb";
import store, {UserState} from "@/store";
import router from "@/router";
export default {
created() {
console.log("app running");
const authClient = new client.AuthServiceClient(this.$store.getters.config.host,null,null);
const restaurantClient = new CustomRPCClient(RestaurantServiceClient, this.$store.getters.config.host);
const reservationClient = new CustomRPCClient(ReservationServiceClient, this.$store.getters.config.host);
this.$store.commit('setAuthClient', authClient);
const authInterceptor = function () {
return null;
};
authInterceptor.prototype.intercept = function (request, invoker) {
const InterceptedStream = function(stream) {
this.stream = stream;
this.cbKeys = ["data", "error", "status", "metadata", "end"];
this.cb = {};
for(let i = 0; i < this.cbKeys.length; i++){
this.cb[this.cbKeys[i]] = [];
if(this.cbKeys[i] == "error"){
this.stream.on("error", (err) => {
if(err.code == 16){
console.log("Intercepted AUTH ERROR");
const authClient = store.getters.grpc.authClient;
const refreshRequest = new RefreshRequest();
refreshRequest.setRefreshtoken(store.getters.user.refreshToken);
refreshRequest.setUseragent(navigator.userAgent);
authClient.refreshToken(refreshRequest, {}, (err, resp) => {
if(err){
console.log("Failed to refresh");
store.commit('storeUserState', null);
router.push("/login");
}
else{
const userState = new UserState();
userState.refreshToken = resp.getRefreshtoken();
userState.authToken = resp.getAuthtoken();
store.commit('storeUserState', userState);
console.log("Rerunning request");
console.log(this);
const meta = request.getMetadata();
meta['Authorization'] = store.getters.user.authToken;
const s2 = new InterceptedStream(invoker(request));
s2.on('data', this.cb['data'][0]);
console.log("S2");
console.log(s2);
console.log(this.cb['data'][0]);
}
});
}
else{
console.log("Intercepted error code: " + err.code);
for(let j = 0; j < this.cb["error"].length; j++){
this.cb['error'][j](err);
}
}
})
}
else{
this.stream.on(this.cbKeys[i], (response) => {
console.log("Running CBs for " + this.cbKeys[i]);
for(let j = 0; j < this.cb[this.cbKeys[i]].length; j++){
console.log(j);
this.cb[this.cbKeys[i]][j](response);
}
})
}
}
};
InterceptedStream.prototype.on = function(eventType, callback) {
this.cb[eventType].push(callback);
return this;
};
const meta = request.getMetadata();
meta['Authorization'] = store.getters.user.authToken;
return new InterceptedStream(invoker(request));
}
const restaurantClient = new RestaurantServiceClient(this.$store.getters.config.host, null, {'streamInterceptors': [new authInterceptor()]});
const userClient = new UserServiceClient(this.$store.getters.config.host, null, {'streamInterceptors': [new authInterceptor()]});
const reservationClient = new ReservationServiceClient(this.$store.getters.config.host, null, {'streamInterceptors': [new authInterceptor()]});
this.$store.commit('setRestaurantClient', restaurantClient);
this.$store.commit('setReservationClient', reservationClient);
this.$store.commit('setUserClient', userClient);
},
methods: {
loggedIn(){
Expand Down
6 changes: 3 additions & 3 deletions spring/src/main/js/reservdjs/src/components/ManageTables.vue
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
this.tables = [];
const req = new Restaurant();
req.setId(this.$route.params.id);
const promise = this.client.client.getTablesByRestaurant(req, {}, err => {
const promise = this.client.getTablesByRestaurant(req, {}, err => {
if(err) {
console.log(err);
this.snackBarMessage = err.message;
Expand Down Expand Up @@ -108,7 +108,7 @@
table.setLabel(this.form.label);
table.setCapacity(this.form.capacity);
req.setTable(table);
this.client.client.createTable(req, {}, (err, res) => {
this.client.createTable(req, {}, (err, res) => {
console.log(res, err);
if(!err)
this.tables.push(res);
Expand All @@ -122,7 +122,7 @@
delTab: function(toDelete) {
const req = new Table();
req.setId(toDelete);
this.client.client.deleteTable(req, {}, err => {
this.client.deleteTable(req, {}, err => {
if(err) {
console.log(err);
this.snackBarMessage = err.message;
Expand Down
6 changes: 3 additions & 3 deletions spring/src/main/js/reservdjs/src/components/ManageUsers.vue
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
this.users = [];
const req = new Restaurant();
req.setId(this.$route.params.id);
const promise = this.client.client.getUsersByRestaurant(req, {}, err => {
const promise = this.client.getUsersByRestaurant(req, {}, err => {
if(err) {
console.log(err);
this.snackBarMessage = err.message;
Expand All @@ -73,7 +73,7 @@
const user = new User();
user.setId(toDelete);
req.setUser(user);
this.client.client.deleteRelationship(req, {}, err => {
this.client.deleteRelationship(req, {}, err => {
if(err) {
console.log(err);
this.snackBarMessage = err.message;
Expand All @@ -94,7 +94,7 @@
user.setUsername(toAdd);
req.setUser(user);
req.setRole(Relationship.UserRole.MANAGER);
this.client.client.addRelationship(req, {}, err => {
this.client.addRelationship(req, {}, err => {
if(err) {
console.log(err);
this.snackBarMessage = err.message;
Expand Down
11 changes: 5 additions & 6 deletions spring/src/main/js/reservdjs/src/components/ReservationList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,9 @@
return "";
},
cancel(reservation) {
const resClient = new CustomRPCClient(ReservationServiceClient, this.$store.getters.config.host);
this.resClient = this.$store.getters.grpc.reservationClient;
reservation.setStatus(Reservation.ReservationStatus.CANCELLED);
resClient.client.setReservation(reservation, {}, err => {
this.resClient.setReservation(reservation, {}, err => {
if(err) {
console.log(err);
this.snackBarMessage = err.message;
Expand All @@ -149,7 +149,6 @@
});
},
invite(username, reservationOrig, inviteBool) {
const resClient = new CustomRPCClient(ReservationServiceClient, this.$store.getters.config.host);
const request = new InviteMessage();
const reservation = new Reservation();
reservation.setId(reservationOrig.details.getId());
Expand All @@ -167,7 +166,7 @@
this.showSnackBar = true;
}
reservationOrig.invites = [];
const promise2 = resClient.client.listReservationUsers(reservation, {}, err => {
const promise2 = this.resClient.listReservationUsers(reservation, {}, err => {
if(err) {
console.log(err);
this.snackBarMessage = err.message;
Expand All @@ -179,9 +178,9 @@
});
}
if(inviteBool)
resClient.client.inviteReservation(request, {}, callback);
this.resClient.inviteReservation(request, {}, callback);
else
resClient.client.removeReservationUser(request, {}, callback);
this.resClient.removeReservationUser(request, {}, callback);
},
view(restId) {
this.$router.push("/restaurant/view/" + restId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@
test(){
const restaurant = new Restaurant();
restaurant.setId(1);
this.client.client.getRestaurant(restaurant, {}, (err, response) => {
this.client.getRestaurant(restaurant, {}, (err, response) => {
console.log(err, response);
});
},
Expand Down Expand Up @@ -217,7 +217,7 @@
if(this.create) {
console.log(restaurant)
this.client.client.createRestaurant(restaurant, {}, (err, response) => {
this.client.createRestaurant(restaurant, {}, (err, response) => {
console.log(err, response);
if(!err)
this.$router.push("/restaurant/manage/" + response.getId());
Expand All @@ -228,7 +228,7 @@
});
} else {
restaurant.setId(this.$route.params.id);
this.client.client.setRestaurant(restaurant, {}, (err, response) => {
this.client.setRestaurant(restaurant, {}, (err, response) => {
console.log(err, response);
if(err){
this.snackBarMessage = err.message;
Expand All @@ -252,7 +252,7 @@
this.manageBool = 1;
const req = new Restaurant();
req.setId(this.$route.params.id);
this.client.client.getRestaurant(req, {}, (err, response) => {
this.client.getRestaurant(req, {}, (err, response) => {
this.form.name = response.getName();
this.form.capacity = response.getCapacity();
this.form.rtime = response.getRtime();
Expand Down
14 changes: 9 additions & 5 deletions spring/src/main/js/reservdjs/src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Vuex from 'vuex'
import {
AuthServiceClient,
ReservationServiceClient,
RestaurantServiceClient
RestaurantServiceClient, UserServiceClient
} from "@/proto/RestaurantServiceServiceClientPb";
import VuexPersistence from "vuex-persist";
import {CustomRPCClient} from "@/proto/CustomRPCClient";
Expand All @@ -19,8 +19,9 @@ export class ConfigState {

export class GrpcState {
public authClient!: AuthServiceClient;
public restaurantClient!: CustomRPCClient<RestaurantServiceClient>;
public reservationClient!: CustomRPCClient<ReservationServiceClient>;
public restaurantClient!: RestaurantServiceClient;
public reservationClient!: ReservationServiceClient;
public userClient!: UserServiceClient;
}

export interface State {
Expand Down Expand Up @@ -56,12 +57,15 @@ export default new Vuex.Store<State>({
setAuthClient(state, payload: AuthServiceClient){
state.grpc.authClient = payload
},
setRestaurantClient(state, payload: CustomRPCClient<RestaurantServiceClient>){
setRestaurantClient(state, payload: RestaurantServiceClient){
state.grpc.restaurantClient = payload
},
setReservationClient(state, payload: CustomRPCClient<ReservationServiceClient>){
setReservationClient(state, payload: ReservationServiceClient){
state.grpc.reservationClient = payload
},
setUserClient(state, payload: UserServiceClient){
state.grpc.userClient = payload
},
storeUserState(state, payload: UserState){
state.user = payload;
}
Expand Down
Loading

0 comments on commit 5ac43a2

Please sign in to comment.