1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | import { BaseFilter, Filter, FilterFactory } from './filter';
|
19 | import { Call, WriteObject } from './call-stream';
|
20 | import {
|
21 | Status,
|
22 | DEFAULT_MAX_SEND_MESSAGE_LENGTH,
|
23 | DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH,
|
24 | } from './constants';
|
25 | import { ChannelOptions } from './channel-options';
|
26 |
|
27 | export class MaxMessageSizeFilter extends BaseFilter implements Filter {
|
28 | private maxSendMessageSize: number = DEFAULT_MAX_SEND_MESSAGE_LENGTH;
|
29 | private maxReceiveMessageSize: number = DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
|
30 | constructor(
|
31 | private readonly options: ChannelOptions,
|
32 | private readonly callStream: Call
|
33 | ) {
|
34 | super();
|
35 | if ('grpc.max_send_message_length' in options) {
|
36 | this.maxSendMessageSize = options['grpc.max_send_message_length']!;
|
37 | }
|
38 | if ('grpc.max_receive_message_length' in options) {
|
39 | this.maxReceiveMessageSize = options['grpc.max_receive_message_length']!;
|
40 | }
|
41 | }
|
42 |
|
43 | async sendMessage(message: Promise<WriteObject>): Promise<WriteObject> {
|
44 | |
45 |
|
46 | if (this.maxSendMessageSize === -1) {
|
47 | return message;
|
48 | } else {
|
49 | const concreteMessage = await message;
|
50 | if (concreteMessage.message.length > this.maxSendMessageSize) {
|
51 | this.callStream.cancelWithStatus(
|
52 | Status.RESOURCE_EXHAUSTED,
|
53 | `Sent message larger than max (${concreteMessage.message.length} vs. ${this.maxSendMessageSize})`
|
54 | );
|
55 | return Promise.reject<WriteObject>('Message too large');
|
56 | } else {
|
57 | return concreteMessage;
|
58 | }
|
59 | }
|
60 | }
|
61 |
|
62 | async receiveMessage(message: Promise<Buffer>): Promise<Buffer> {
|
63 | |
64 |
|
65 | if (this.maxReceiveMessageSize === -1) {
|
66 | return message;
|
67 | } else {
|
68 | const concreteMessage = await message;
|
69 | if (concreteMessage.length > this.maxReceiveMessageSize) {
|
70 | this.callStream.cancelWithStatus(
|
71 | Status.RESOURCE_EXHAUSTED,
|
72 | `Received message larger than max (${concreteMessage.length} vs. ${this.maxReceiveMessageSize})`
|
73 | );
|
74 | return Promise.reject<Buffer>('Message too large');
|
75 | } else {
|
76 | return concreteMessage;
|
77 | }
|
78 | }
|
79 | }
|
80 | }
|
81 |
|
82 | export class MaxMessageSizeFilterFactory
|
83 | implements FilterFactory<MaxMessageSizeFilter> {
|
84 | constructor(private readonly options: ChannelOptions) {}
|
85 |
|
86 | createFilter(callStream: Call): MaxMessageSizeFilter {
|
87 | return new MaxMessageSizeFilter(this.options, callStream);
|
88 | }
|
89 | }
|