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

Add middleware for logging requests/responses via the grpc-web-devtools #442

Merged
merged 12 commits into from
Oct 17, 2023
5 changes: 5 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
lib
es
coverage
.DS_Store
6 changes: 6 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Change Log

All notable changes to this project will be documented in this file. See
[Conventional Commits](https://conventionalcommits.org) for commit guidelines.

## 1.0.0 (2023-09-14)
20 changes: 20 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2023 Sebastian Halder
aikoven marked this conversation as resolved.
Show resolved Hide resolved

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 changes: 36 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# nice-grpc-client-middleware-devtools [![npm version][npm-image]][npm-url]

Client middleware for [nice-grpc](https://github.com/deeplay-io/nice-grpc) that
enables seeing grpc-web requests in [grpc-web-tools](https://github.com/SafetyCulture/grpc-web-devtools).

## Installation

```
npm install nice-grpc-client-middleware-devtools
```

## Usage

```ts
import {
createClientFactory,
createChannel,
ClientError,
Status,
} from 'nice-grpc';
import {devtoolsLoggingMiddleware} from 'nice-grpc-client-middleware-deadline';

const clientFactory = createClientFactory().use(devtoolsLoggingMiddlware);

const channel = createChannel(address);
const client = clientFactory.create(ExampleService, channel);

const response = await client.exampleMethod(request);
// The request and response will be visible in the Browser extension
```

Alternatively, only logging for unary requests can be achieved by using `devtoolsUnaryLoggingMiddleware`
or logging for streaming requests by using `devtoolsStreamLoggingMiddleware`.

[npm-image]: https://badge.fury.io/js/nice-grpc-client-middleware-devtools.svg
[npm-url]: https://badge.fury.io/js/nice-grpc-client-middleware-devtools
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.ts
*.js
21 changes: 21 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/fixtures/test.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
syntax = "proto3";

package nice_grpc.test;

service Test {
rpc TestUnary(TestRequest) returns(TestResponse){};
rpc TestServerStream(TestRequest) returns(stream TestResponse){};
rpc TestClientStream(stream TestRequest) returns(TestResponse){};
rpc TestBidiStream(stream TestRequest) returns(stream TestResponse){};
}

service Test2 {
rpc TestUnary(TestRequest) returns(TestResponse){};
}

message TestRequest {
string id = 1;
}
message TestResponse {
string id = 1;
}
12 changes: 12 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/** @type {import('@jest/types').Config.GlobalConfig} */
module.exports = {
testPathIgnorePatterns: ['/node_modules/', '/lib/'],
preset: 'ts-jest',
testEnvironment: 'node',
testTimeout: 15000,
reporters: ['default', 'github-actions'],
collectCoverage: true,
coverageDirectory: 'coverage',
coverageReporters: ['lcov', 'text'],
coveragePathIgnorePatterns: ['/node_modules/', '/lib/'],
};
36 changes: 36 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "nice-grpc-client-middleware-devtools",
"version": "1.0.0",
"description": "Client middleware for nice-grpc to work with grpc-web-devtools https://github.com/SafetyCulture/grpc-web-devtools",
"repository": "deeplay-io/nice-grpc",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"files": [
"lib",
"src",
"!src/**/*.test.ts",
"!src/**/__tests__"
],
"scripts": {
"clean": "rimraf lib",
"test": "jest",
"build": "tsc -P tsconfig.build.json",
"prepublishOnly": "npm run clean && npm run build && npm test",
"build:proto": "grpc_tools_node_protoc --plugin=protoc-gen-grpc=./node_modules/.bin/grpc_tools_node_protoc_plugin --plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts --js_out=import_style=commonjs,binary:./fixtures --ts_out=grpc_js:./fixtures --grpc_out=grpc_js:./fixtures -I fixtures fixtures/*.proto",
"prepare": "npm run build:proto"
},
"author": "Sebastian Halder",
"license": "MIT",
"devDependencies": {
"@tsconfig/recommended": "^1.0.1",
"@types/google-protobuf": "^3.7.4",
"abort-controller-x": "^0.4.0",
"google-protobuf": "^3.14.0",
"grpc-tools": "^1.10.0",
"grpc_tools_node_protoc_ts": "^5.0.1",
"nice-grpc": "^2.1.5"
},
"dependencies": {
"nice-grpc-common": "^2.0.2"
}
}
14 changes: 14 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import defer = require('defer-promise');
import {forever} from 'abort-controller-x';
import {
createChannel,
createClientFactory,
createServer,
ServerError,
Status,
} from 'nice-grpc';
import {deadlineMiddleware} from '.';
import {TestService} from '../fixtures/test_grpc_pb';
import {TestRequest, TestResponse} from '../fixtures/test_pb';

// TODO: Can this middleware be tested?
180 changes: 180 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { isAbortError } from 'abort-controller-x';
aikoven marked this conversation as resolved.
Show resolved Hide resolved
import { Message } from 'google-protobuf';
import {
CallOptions,
ClientError,
ClientMiddleware,
ClientMiddlewareCall,
composeClientMiddleware,
} from 'nice-grpc-web';
aikoven marked this conversation as resolved.
Show resolved Hide resolved

export const devtoolsUnaryLoggingMiddleware: ClientMiddleware = async function* devtoolsLoggingMiddleware<Request, Response>(
call: ClientMiddlewareCall<Request, Response>,
options: CallOptions
): AsyncGenerator<Response, Response | void, undefined> {
// skip streaming calls
if (call.requestStream || call.responseStream) {
return yield* call.next(call.request, options);
}

const { path } = call.method;

let reqObj: any = undefined;

// TODO: When would it not be a jspb.Message?
if (call.request instanceof Message) {
const reqMsg = call.request as Message;
reqObj = reqMsg.toObject();
} else {
//eslint-disable-next-line
reqObj = call.request;
// console.warn('TODO: Request isn\'t a jspb.Message');
}
aikoven marked this conversation as resolved.
Show resolved Hide resolved

try {
const result = yield* call.next(call.request, options);
let resObj: any = undefined;
// TODO: When would it not be a jspb.Message?
if (result instanceof Message) {
const resMsg = result as Message;
resObj = resMsg.toObject();
} else {
//eslint-disable-next-line
resObj = result;
// console.warn("TODO: Response isn't a jspb.Message");
}
window.postMessage(
{
method: path,
methodType: 'unary',
request: reqObj,
response: resObj,
type: '__GRPCWEB_DEVTOOLS__',
},
'*'
);
return result;
} catch (error) {
if (error instanceof ClientError) {
window.postMessage(
{
error: {
code: error?.code,
message: `${error?.message || error}`,
// meta: error?.meta,
// methodName: error?.methodName,
name: error?.name,
// serviceName: error?.serviceName,
aikoven marked this conversation as resolved.
Show resolved Hide resolved
stack: error?.stack,
},
method: path,
methodType: 'unary',
request: reqObj,
type: '__GRPCWEB_DEVTOOLS__',
},
'*'
);
} else if (isAbortError(error)) {
//eslint-disable-next-line
console.debug('GRPC REQUEST CANCEL', path);
} else {
//eslint-disable-next-line
console.error('GRPC RESPONSE FAILURE', path, error);
}
aikoven marked this conversation as resolved.
Show resolved Hide resolved

throw error;
}
};

export const devtoolsStreamLoggingMiddleware: ClientMiddleware = async function* devtoolsLoggingMiddleware<Request, Response>(
call: ClientMiddlewareCall<Request, Response>,
options: CallOptions
): AsyncGenerator<Response, Response | void, undefined> {
const { path } = call.method;

let reqObj: any = undefined;

// TODO: When would it not be a jspb.Message?
if (call.request instanceof Message) {
const reqMsg = call.request as Message;
reqObj = reqMsg.toObject();
} else {
//eslint-disable-next-line
reqObj = call.request;
}

if (!call.responseStream && !call.requestStream) {
// UNARY
return yield* call.next(call.request, options);
}
// server streaming
let first = true;
try {
for await (const response of call.next(call.request, options)) {
// log response here
let resObj: any = undefined;
if (response instanceof Message) {
const resMsg = response as Message;
resObj = resMsg.toObject();
} else {
resObj = response;
}
if (first) {
window.postMessage(
{
method: path,
methodType: 'server_streaming',
request: reqObj,
type: '__GRPCWEB_DEVTOOLS__',
},
'*'
);
first = false;
}
window.postMessage(
{
method: path,
methodType: 'server_streaming',
response: resObj,
type: '__GRPCWEB_DEVTOOLS__',
},
'*'
);

yield response;
}
} catch (error) {
if (error instanceof ClientError) {
window.postMessage(
{
error: {
code: error?.code,
message: `${error?.message || error}`,
// meta: error?.meta,
// methodName: error?.methodName,
name: error?.name,
// serviceName: error?.serviceName,
stack: error?.stack,
},
method: path,
methodType: 'server_streaming',
type: '__GRPCWEB_DEVTOOLS__',
},
'*'
);
} else if (isAbortError(error)) {
//eslint-disable-next-line
console.debug('GRPC REQUEST CANCEL', path);
} else {
//eslint-disable-next-line
console.error('GRPC RESPONSE FAILURE', path, error);
}

throw error;
}
};

export const devtoolsLoggingMiddleware: ClientMiddleware = composeClientMiddleware(
devtoolsUnaryLoggingMiddleware,
devtoolsStreamLoggingMiddleware
);
aikoven marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig",
"exclude": ["src/**/__tests__/**/*.ts", "src/**/*.test.ts"]
}
12 changes: 12 additions & 0 deletions packages/nice-grpc-client-middleware-devtools/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "@tsconfig/recommended/tsconfig.json",
"compilerOptions": {
"target": "ES2018",
"outDir": "lib",
"sourceMap": true,
"declaration": true,
"stripInternal": true
},
"files": ["src/index.ts"],
"include": ["src/**/__tests__/**/*.ts", "src/**/*.test.ts"]
}