/
protobuf-payload-converters.ts
243 lines (211 loc) · 7.73 KB
/
protobuf-payload-converters.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import * as protoJsonSerializer from 'proto3-json-serializer';
import type { Message, Namespace, Root, Type } from 'protobufjs';
import { decode, encode } from '../encoding';
import { PayloadConverterError, ValueError } from '../errors';
import { Payload } from '../interfaces';
import { errorMessage, hasOwnProperties, hasOwnProperty, isRecord } from '../type-helpers';
import {
BinaryPayloadConverter,
CompositePayloadConverter,
JsonPayloadConverter,
PayloadConverterWithEncoding,
UndefinedPayloadConverter,
} from './payload-converter';
import { encodingTypes, METADATA_ENCODING_KEY, METADATA_MESSAGE_TYPE_KEY } from './types';
const GLOBAL_BUFFER = globalThis.constructor.constructor('return globalThis.Buffer')();
abstract class ProtobufPayloadConverter implements PayloadConverterWithEncoding {
protected readonly root: Root | undefined;
public abstract encodingType: string;
public abstract toPayload<T>(value: T): Payload | undefined;
public abstract fromPayload<T>(payload: Payload): T;
// Don't use type Root here because root.d.ts doesn't export Root, so users would have to type assert
constructor(root?: unknown) {
if (root) {
if (!isRoot(root)) {
throw new TypeError('root must be an instance of a protobufjs Root');
}
this.root = root;
}
}
protected validatePayload(content: Payload): { messageType: Type; data: Uint8Array } {
if (content.data === undefined || content.data === null) {
throw new ValueError('Got payload with no data');
}
if (!content.metadata || !(METADATA_MESSAGE_TYPE_KEY in content.metadata)) {
throw new ValueError(`Got protobuf payload without metadata.${METADATA_MESSAGE_TYPE_KEY}`);
}
if (!this.root) {
throw new PayloadConverterError('Unable to deserialize protobuf message without `root` being provided');
}
const messageTypeName = decode(content.metadata[METADATA_MESSAGE_TYPE_KEY]);
let messageType;
try {
messageType = this.root.lookupType(messageTypeName);
} catch (e) {
if (errorMessage(e)?.includes('no such type')) {
throw new PayloadConverterError(
`Got a \`${messageTypeName}\` protobuf message but cannot find corresponding message class in \`root\``
);
}
throw e;
}
return { messageType, data: content.data };
}
protected constructPayload({ messageTypeName, message }: { messageTypeName: string; message: Uint8Array }): Payload {
return {
metadata: {
[METADATA_ENCODING_KEY]: encode(this.encodingType),
[METADATA_MESSAGE_TYPE_KEY]: encode(messageTypeName),
},
data: message,
};
}
}
/**
* Converts between protobufjs Message instances and serialized Protobuf Payload
*/
export class ProtobufBinaryPayloadConverter extends ProtobufPayloadConverter {
public encodingType = encodingTypes.METADATA_ENCODING_PROTOBUF;
/**
* @param root The value returned from {@link patchProtobufRoot}
*/
constructor(root?: unknown) {
super(root);
}
public toPayload(value: unknown): Payload | undefined {
if (!isProtobufMessage(value)) {
return undefined;
}
return this.constructPayload({
messageTypeName: getNamespacedTypeName(value.$type),
message: value.$type.encode(value).finish(),
});
}
public fromPayload<T>(content: Payload): T {
const { messageType, data } = this.validatePayload(content);
// Wrap with Uint8Array from this context to ensure `instanceof` works
const localData = data ? new Uint8Array(data.buffer, data.byteOffset, data.length) : data;
return messageType.decode(localData) as unknown as T;
}
}
/**
* Converts between protobufjs Message instances and serialized JSON Payload
*/
export class ProtobufJsonPayloadConverter extends ProtobufPayloadConverter {
public encodingType = encodingTypes.METADATA_ENCODING_PROTOBUF_JSON;
/**
* @param root The value returned from {@link patchProtobufRoot}
*/
constructor(root?: unknown) {
super(root);
}
public toPayload(value: unknown): Payload | undefined {
if (!isProtobufMessage(value)) {
return undefined;
}
const hasBufferChanged = setBufferInGlobal();
try {
const jsonValue = protoJsonSerializer.toProto3JSON(value);
return this.constructPayload({
messageTypeName: getNamespacedTypeName(value.$type),
message: encode(JSON.stringify(jsonValue)),
});
} finally {
resetBufferInGlobal(hasBufferChanged);
}
}
public fromPayload<T>(content: Payload): T {
const hasBufferChanged = setBufferInGlobal();
try {
const { messageType, data } = this.validatePayload(content);
const res = protoJsonSerializer.fromProto3JSON(messageType, JSON.parse(decode(data))) as unknown as T;
if (Buffer.isBuffer(res)) {
return new Uint8Array(res) as any;
}
replaceBuffers(res);
return res;
} finally {
resetBufferInGlobal(hasBufferChanged);
}
}
}
function replaceBuffers<X>(obj: X) {
const replaceBuffersImpl = <Y>(value: any, key: string | number, target: Y) => {
if (Buffer.isBuffer(value)) {
// Need to copy. `Buffer` manages a pool slab, internally reused when Buffer objects are GC.
type T = keyof typeof target;
target[key as T] = new Uint8Array(value) as any;
} else {
replaceBuffers(value);
}
};
if (obj != null && typeof obj === 'object') {
// Performance optimization for large arrays
if (Array.isArray(obj)) {
obj.forEach(replaceBuffersImpl);
} else {
for (const [key, value] of Object.entries(obj)) {
replaceBuffersImpl(value, key, obj);
}
}
}
}
function setBufferInGlobal(): boolean {
if (typeof globalThis.Buffer === 'undefined') {
globalThis.Buffer = GLOBAL_BUFFER;
return true;
}
return false;
}
function resetBufferInGlobal(hasChanged: boolean): void {
if (hasChanged) {
delete (globalThis as any).Buffer;
}
}
function isProtobufType(type: unknown): type is Type {
return (
isRecord(type) &&
// constructor.name may get mangled by minifiers; thanksfuly protobufjs also sets a className property
(type.constructor as any).className === 'Type' &&
hasOwnProperties(type, ['parent', 'name', 'create', 'encode', 'decode']) &&
typeof type.name === 'string' &&
typeof type.create === 'function' &&
typeof type.encode === 'function' &&
typeof type.decode === 'function'
);
}
function isProtobufMessage(value: unknown): value is Message {
return isRecord(value) && hasOwnProperty(value, '$type') && isProtobufType(value.$type);
}
function getNamespacedTypeName(node: Type | Namespace): string {
if (node.parent && !isRoot(node.parent)) {
return getNamespacedTypeName(node.parent) + '.' + node.name;
} else {
return node.name;
}
}
function isRoot(root: unknown): root is Root {
// constructor.name may get mangled by minifiers; thanksfuly protobufjs also sets a className property
return isRecord(root) && (root.constructor as any).className === 'Root';
}
export interface DefaultPayloadConverterWithProtobufsOptions {
/**
* The `root` provided to {@link ProtobufJsonPayloadConverter} and {@link ProtobufBinaryPayloadConverter}
*/
protobufRoot: Record<string, unknown>;
}
export class DefaultPayloadConverterWithProtobufs extends CompositePayloadConverter {
// Match the order used in other SDKs.
//
// Go SDK:
// https://github.com/temporalio/sdk-go/blob/5e5645f0c550dcf717c095ae32c76a7087d2e985/converter/default_data_converter.go#L28
constructor({ protobufRoot }: DefaultPayloadConverterWithProtobufsOptions) {
super(
new UndefinedPayloadConverter(),
new BinaryPayloadConverter(),
new ProtobufJsonPayloadConverter(protobufRoot),
new ProtobufBinaryPayloadConverter(protobufRoot),
new JsonPayloadConverter()
);
}
}