Skip to content
This repository was archived by the owner on Nov 18, 2025. It is now read-only.

Commit d27f7fa

Browse files
fix: refactor createByteLengthFunction, warn if fails (#1331)
* fix: refactor createByteLengthFunction, warn if fails * fix: formatting
1 parent b810d37 commit d27f7fa

3 files changed

Lines changed: 35 additions & 8 deletions

File tree

src/fallback.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,20 @@ export class GrpcClient {
334334

335335
return serviceStub;
336336
}
337+
338+
/**
339+
* Creates a 'bytelength' function for a given proto message class.
340+
*
341+
* See {@link BundleDescriptor} about the meaning of the return value.
342+
*
343+
* @param {function} message - a constructor function that is generated by
344+
* protobuf.js. Assumes 'encoder' field in the message.
345+
* @return {function(Object):number} - a function to compute the byte length
346+
* for an object.
347+
*/
348+
static createByteLengthFunction(message: typeof protobuf.Message) {
349+
return gax.createByteLengthFunction(message);
350+
}
337351
}
338352

339353
/**

src/gax.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
* Google API Extensions
1919
*/
2020

21+
import type {Message} from 'protobufjs';
22+
import {warn} from './warnings';
2123
import {BundleOptions} from './bundlingCalls/bundleExecutor';
2224
import {toLowerCamelCase} from './util';
2325

@@ -702,3 +704,20 @@ export function constructSettings(
702704

703705
return defaults;
704706
}
707+
708+
export function createByteLengthFunction(message: typeof Message) {
709+
return function getByteLength(obj: {}) {
710+
try {
711+
return message.encode(obj).finish().length;
712+
} catch (err) {
713+
const stringified = JSON.stringify(obj);
714+
warn(
715+
'error_encoding_protobufjs_object',
716+
`Cannot encode protobuf.js object: ${stringified}: ${err}`
717+
);
718+
// We failed to encode the object properly, let's just return an upper boundary of its length.
719+
// It's only needed for calculating the size of the batch, so it's safe if it's bigger than needed.
720+
return stringified.length;
721+
}
722+
};
723+
}

src/grpc.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -531,14 +531,8 @@ export class GrpcClient {
531531
* @return {function(Object):number} - a function to compute the byte length
532532
* for an object.
533533
*/
534-
static createByteLengthFunction(message: {
535-
encode: (obj: {}) => {
536-
finish: () => Array<{}>;
537-
};
538-
}) {
539-
return function getByteLength(obj: {}) {
540-
return message.encode(obj).finish().length;
541-
};
534+
static createByteLengthFunction(message: typeof protobuf.Message) {
535+
return gax.createByteLengthFunction(message);
542536
}
543537
}
544538

0 commit comments

Comments
 (0)