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: refactor createByteLengthFunction, warn if fails #1331

Merged
merged 2 commits into from
Aug 29, 2022
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
14 changes: 14 additions & 0 deletions src/fallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,20 @@ export class GrpcClient {

return serviceStub;
}

/**
* Creates a 'bytelength' function for a given proto message class.
*
* See {@link BundleDescriptor} about the meaning of the return value.
*
* @param {function} message - a constructor function that is generated by
* protobuf.js. Assumes 'encoder' field in the message.
* @return {function(Object):number} - a function to compute the byte length
* for an object.
*/
static createByteLengthFunction(message: typeof protobuf.Message) {
return gax.createByteLengthFunction(message);
}
}

/**
Expand Down
19 changes: 19 additions & 0 deletions src/gax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
* Google API Extensions
*/

import type {Message} from 'protobufjs';
import {warn} from './warnings';
import {BundleOptions} from './bundlingCalls/bundleExecutor';
import {toLowerCamelCase} from './util';

Expand Down Expand Up @@ -702,3 +704,20 @@ export function constructSettings(

return defaults;
}

export function createByteLengthFunction(message: typeof Message) {
return function getByteLength(obj: {}) {
try {
return message.encode(obj).finish().length;
} catch (err) {
const stringified = JSON.stringify(obj);
warn(
'error_encoding_protobufjs_object',
`Cannot encode protobuf.js object: ${stringified}: ${err}`
);
// We failed to encode the object properly, let's just return an upper boundary of its length.
// It's only needed for calculating the size of the batch, so it's safe if it's bigger than needed.
return stringified.length;
}
};
}
10 changes: 2 additions & 8 deletions src/grpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -531,14 +531,8 @@ export class GrpcClient {
* @return {function(Object):number} - a function to compute the byte length
* for an object.
*/
static createByteLengthFunction(message: {
encode: (obj: {}) => {
finish: () => Array<{}>;
};
}) {
return function getByteLength(obj: {}) {
return message.encode(obj).finish().length;
};
static createByteLengthFunction(message: typeof protobuf.Message) {
return gax.createByteLengthFunction(message);
}
}

Expand Down