Skip to content

Commit

Permalink
Merge afbca78 into 3cd4000
Browse files Browse the repository at this point in the history
  • Loading branch information
anonrig committed Jun 11, 2021
2 parents 3cd4000 + afbca78 commit 23f4c26
Show file tree
Hide file tree
Showing 9 changed files with 160 additions and 43 deletions.
38 changes: 20 additions & 18 deletions lib/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const assert = require('assert')
const Emitter = require('events')
const compose = require('@malijs/compose')
const grpc = require('@grpc/grpc-js')
const protoLoader = require('@grpc/proto-loader')

const _ = require('./lo')
const Context = require('./context')
Expand Down Expand Up @@ -81,7 +82,7 @@ class Mali extends Emitter {
let proto = path
if (load) {
let protoFilePath = path
const loadOptions = _.assign({}, options)
const loadOptions = Object.assign({}, options)

if (_.isObject(path) && path.root && path.file) {
protoFilePath = path.file
Expand All @@ -90,8 +91,7 @@ class Mali extends Emitter {
}
}

const pl = require('@grpc/proto-loader')
const pd = pl.loadSync(protoFilePath, loadOptions)
const pd = protoLoader.loadSync(protoFilePath, loadOptions)
proto = grpc.loadPackageDefinition(pd)
}

Expand All @@ -104,27 +104,29 @@ class Mali extends Emitter {
}

const picked = {}
_.forOwn(data, (v, k) => {
if (name.indexOf(k) >= 0 || name.indexOf(v.shortServiceName) >= 0) {

for (const k in data) {
const v = data[k]

if (name.includes(k) || name.includes(v.shortServiceName)) {
picked[k] = v
}
})

_.forOwn(picked, (v, k) => {
v.middleware = []
v.handlers = {}
_.forOwn(v.methods, (method, methodName) => {
v.handlers[methodName] = null
})
})
}

this.data = _.assign(this.data, picked)
for (const k in picked) {
picked[k].middleware = []
picked[k].handlers = {}

if (!this.name) {
if (Array.isArray(name)) {
this.name = name[0]
for (const method in picked[k].methods) {
picked[k].handlers[method] = null
}
}

Object.assign(this.data, picked)

if (!this.name && Array.isArray(name)) {
this.name = name[0]
}
}

/**
Expand Down
41 changes: 41 additions & 0 deletions lib/metadata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const grpc = require('@grpc/grpc-js')

/**
* Utility helper function to create <code>Metadata</code> object from plain Javascript object
* This strictly just calls <code>Metadata.add</code> with the key / value map of objects.
* If the value is a <code>Buffer</code> it's passed as is.
* If the value is a <code>Sting</code> it's passed as is.
* Else if the value defined and not a string we simply call <code>toString()</code>.
* Note that <code>Metadata</code> only accept string or buffer values.
* @param {Object} metadata Plain javascript object to tranform into <code>Metadata</code>
* If an instance of <code>Metadata</code> is passed in it is simply returned
* @return {Metadata} An instance of <code>Metadata</code>, or `undefined` if input is not an object
*/
module.exports = function create (metadata) {
if (typeof metadata !== 'object') {
return
}

if (metadata instanceof grpc.Metadata) {
return metadata
}

const meta = new grpc.Metadata()

for (const k in metadata) {
const v = metadata[k]
if (Buffer.isBuffer(v)) {
if (!k.endsWith('-bin')) {
throw new Error(`Metadata key "${k}" should end with "-bin" since it has a non-string value.`)
}
meta.add(k, v)
} else if (v !== null && typeof v !== 'undefined') {
const toAdd = typeof v === 'string' ? v : v.toString()
if (toAdd) {
meta.add(k, toAdd)
}
}
}

return meta
}
4 changes: 2 additions & 2 deletions lib/request.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const grpc = require('@grpc/grpc-js')
const CallType = require('@malijs/call-types')
const create = require('grpc-create-metadata')
const create = require('./metadata')

/**
* Mali Request class that encapsulates the request of a call.
Expand Down Expand Up @@ -34,7 +34,7 @@ class Request {
* @return {Object} request metadata
*/
getMetadata () {
return create(this.metadata, { addEmpty: false })
return create(this.metadata)
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/response.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const grpc = require('@grpc/grpc-js')
const CallType = require('@malijs/call-types')
const create = require('grpc-create-metadata')
const create = require('./metadata')

const _ = require('./lo')

Expand Down Expand Up @@ -71,7 +71,7 @@ class Response {
* @return {Object} response metadata
*/
getMetadata () {
return create(this.metadata, { addEmpty: false })
return create(this.metadata)
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const CallType = require('@malijs/call-types')
const destroy = require('destroy')
const first = require('ee-first')
const stream = require('stream')
const create = require('grpc-create-metadata')
const create = require('./metadata')

function onEnd (s, fn) {
const ee = first([
Expand All @@ -17,7 +17,7 @@ function onEnd (s, fn) {
function wrapEnd (ctx) {
const endFn = ctx.call.end
ctx.call.end = function end (statusMetadata) {
return endFn.call(ctx.call, create(statusMetadata, { addEmpty: false }) || ctx.response.getStatusMetadata())
return endFn.call(ctx.call, create(statusMetadata) || ctx.response.getStatusMetadata())
}
}

Expand Down
50 changes: 33 additions & 17 deletions package-lock.json

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

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"test": "nyc npm run linttest",
"coverage": "nyc report --reporter=text-lcov > ./coverage/lcov.info",
"apidocs": "jsdoc2md lib/*.js > api2.md",
"docs": "jsdoc2md lib/*.js --heading-depth 3 | ./fixdocs > api.md"
"docs": "jsdoc2md lib/*.js --heading-depth 3 | ./fixdocs > api.md",
"benchmark": "node test/benchmark.js"
},
"repository": {
"type": "git",
Expand Down Expand Up @@ -44,7 +45,6 @@
"delegates": "^1.0.0",
"destroy": "^1.0.4",
"ee-first": "^1.1.1",
"grpc-create-metadata": "^4.0.0",
"lodash.camelcase": "^4.3.0",
"lodash.concat": "^4.5.0",
"lodash.forown": "^4.4.0",
Expand All @@ -62,6 +62,7 @@
"@grpc/proto-loader": "^0.6.1",
"async": "^3.2.0",
"ava": "^3.15.0",
"benchmark": "^2.1.4",
"coveralls": "^3.1.0",
"google-protobuf": "^3.17.3",
"highland": "3.0.0-beta.10",
Expand Down
26 changes: 26 additions & 0 deletions test/benchmark.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const Benchmark = require('benchmark')
const metaCreate = require('../lib/metadata')
const Mali = require('../lib/app')
const path = require('path')

const suite = new Benchmark.Suite()

const largeMetadata = {
hello: 'world',
maxSafe: Number.MAX_SAFE_INTEGER
}

for (let i = 0; i < 5000; i++) {
largeMetadata[`key-${i}`] = `value-${i}`
}

suite
.add('metadata.create', () => {
metaCreate(largeMetadata)
})
.add('mali.addService', () => {
const app = new Mali()
app.addService(path.join(__dirname, './protos/helloworld.proto'), 'Greeter')
})
.on('cycle', (event) => console.log(event.target.toString()))
.run({ async: true })
31 changes: 31 additions & 0 deletions test/metadata.create.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const test = require('ava')
const grpc = require('@grpc/grpc-js')
const create = require('../lib/metadata')

test('should return undefined if not-object', (t) => {
t.is(create('hello'), undefined)
t.is(create(undefined), undefined)
})

test('should return grpc.Metadata', (t) => {
const meta = new grpc.Metadata()
meta.set('hello', 'world')

const returned = create(meta)
t.truthy(returned instanceof grpc.Metadata)
t.deepEqual(meta.get('hello'), ['world'])
})

test('should handle buffers', (t) => {
const meta = create({ 'john-bin': Buffer.from('snow'), 'non-existing': null, john: [] })
t.deepEqual(meta.get('john-bin'), [Buffer.from('snow')])
t.deepEqual(meta.get('non-existing'), [])
t.deepEqual(meta.get('john'), [])

try {
create({ john: Buffer.from('snow') })
t.fail()
} catch (error) {
t.is(error.message, 'Metadata key "john" should end with "-bin" since it has a non-string value.')
}
})

0 comments on commit 23f4c26

Please sign in to comment.