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(
|
32 | private readonly options: ChannelOptions
|
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 | throw {
|
52 | code: Status.RESOURCE_EXHAUSTED,
|
53 | details: `Sent message larger than max (${concreteMessage.message.length} vs. ${this.maxSendMessageSize})`,
|
54 | metadata: new Metadata()
|
55 | };
|
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 | throw {
|
71 | code: Status.RESOURCE_EXHAUSTED,
|
72 | details: `Received message larger than max (${concreteMessage.length} vs. ${this.maxReceiveMessageSize})`,
|
73 | metadata: new Metadata()
|
74 | };
|
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(): MaxMessageSizeFilter {
|
87 | return new MaxMessageSizeFilter(this.options);
|
88 | }
|
89 | }
|