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 { WriteObject } from './call-interface';
|
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 | import { Metadata } from './metadata';
|
27 |
|
28 | export class MaxMessageSizeFilter extends BaseFilter implements Filter {
|
29 | private maxSendMessageSize: number = DEFAULT_MAX_SEND_MESSAGE_LENGTH;
|
30 | private maxReceiveMessageSize: number = DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
|
31 | constructor(options: ChannelOptions) {
|
32 | super();
|
33 | if ('grpc.max_send_message_length' in options) {
|
34 | this.maxSendMessageSize = options['grpc.max_send_message_length']!;
|
35 | }
|
36 | if ('grpc.max_receive_message_length' in options) {
|
37 | this.maxReceiveMessageSize = options['grpc.max_receive_message_length']!;
|
38 | }
|
39 | }
|
40 |
|
41 | async sendMessage(message: Promise<WriteObject>): Promise<WriteObject> {
|
42 | |
43 |
|
44 | if (this.maxSendMessageSize === -1) {
|
45 | return message;
|
46 | } else {
|
47 | const concreteMessage = await message;
|
48 | if (concreteMessage.message.length > this.maxSendMessageSize) {
|
49 | throw {
|
50 | code: Status.RESOURCE_EXHAUSTED,
|
51 | details: `Sent message larger than max (${concreteMessage.message.length} vs. ${this.maxSendMessageSize})`,
|
52 | metadata: new Metadata(),
|
53 | };
|
54 | } else {
|
55 | return concreteMessage;
|
56 | }
|
57 | }
|
58 | }
|
59 |
|
60 | async receiveMessage(message: Promise<Buffer>): Promise<Buffer> {
|
61 | |
62 |
|
63 | if (this.maxReceiveMessageSize === -1) {
|
64 | return message;
|
65 | } else {
|
66 | const concreteMessage = await message;
|
67 | if (concreteMessage.length > this.maxReceiveMessageSize) {
|
68 | throw {
|
69 | code: Status.RESOURCE_EXHAUSTED,
|
70 | details: `Received message larger than max (${concreteMessage.length} vs. ${this.maxReceiveMessageSize})`,
|
71 | metadata: new Metadata(),
|
72 | };
|
73 | } else {
|
74 | return concreteMessage;
|
75 | }
|
76 | }
|
77 | }
|
78 | }
|
79 |
|
80 | export class MaxMessageSizeFilterFactory
|
81 | implements FilterFactory<MaxMessageSizeFilter>
|
82 | {
|
83 | constructor(private readonly options: ChannelOptions) {}
|
84 |
|
85 | createFilter(): MaxMessageSizeFilter {
|
86 | return new MaxMessageSizeFilter(this.options);
|
87 | }
|
88 | }
|