UNPKG

2.32 kBPlain TextView Raw
1/*
2 * Copyright 2021 gRPC authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18import { isIP } from 'net';
19
20export interface TcpSubchannelAddress {
21 port: number;
22 host: string;
23}
24
25export interface IpcSubchannelAddress {
26 path: string;
27}
28/**
29 * This represents a single backend address to connect to. This interface is a
30 * subset of net.SocketConnectOpts, i.e. the options described at
31 * https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener.
32 * Those are in turn a subset of the options that can be passed to http2.connect.
33 */
34
35export type SubchannelAddress = TcpSubchannelAddress | IpcSubchannelAddress;
36
37export function isTcpSubchannelAddress(
38 address: SubchannelAddress
39): address is TcpSubchannelAddress {
40 return 'port' in address;
41}
42
43export function subchannelAddressEqual(
44 address1?: SubchannelAddress,
45 address2?: SubchannelAddress
46): boolean {
47 if (!address1 && !address2) {
48 return true;
49 }
50 if (!address1 || !address2) {
51 return false;
52 }
53 if (isTcpSubchannelAddress(address1)) {
54 return (
55 isTcpSubchannelAddress(address2) &&
56 address1.host === address2.host &&
57 address1.port === address2.port
58 );
59 } else {
60 return !isTcpSubchannelAddress(address2) && address1.path === address2.path;
61 }
62}
63
64export function subchannelAddressToString(address: SubchannelAddress): string {
65 if (isTcpSubchannelAddress(address)) {
66 return address.host + ':' + address.port;
67 } else {
68 return address.path;
69 }
70}
71
72const DEFAULT_PORT = 443;
73
74export function stringToSubchannelAddress(
75 addressString: string,
76 port?: number
77): SubchannelAddress {
78 if (isIP(addressString)) {
79 return {
80 host: addressString,
81 port: port ?? DEFAULT_PORT,
82 };
83 } else {
84 return {
85 path: addressString,
86 };
87 }
88}