UNPKG

8.98 kBJavaScriptView Raw
1"use strict";
2/*
3 * Copyright 2019 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18Object.defineProperty(exports, "__esModule", { value: true });
19exports.Metadata = void 0;
20const logging_1 = require("./logging");
21const constants_1 = require("./constants");
22const LEGAL_KEY_REGEX = /^[0-9a-z_.-]+$/;
23const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/;
24function isLegalKey(key) {
25 return LEGAL_KEY_REGEX.test(key);
26}
27function isLegalNonBinaryValue(value) {
28 return LEGAL_NON_BINARY_VALUE_REGEX.test(value);
29}
30function isBinaryKey(key) {
31 return key.endsWith('-bin');
32}
33function isCustomMetadata(key) {
34 return !key.startsWith('grpc-');
35}
36function normalizeKey(key) {
37 return key.toLowerCase();
38}
39function validate(key, value) {
40 if (!isLegalKey(key)) {
41 throw new Error('Metadata key "' + key + '" contains illegal characters');
42 }
43 if (value !== null && value !== undefined) {
44 if (isBinaryKey(key)) {
45 if (!(value instanceof Buffer)) {
46 throw new Error("keys that end with '-bin' must have Buffer values");
47 }
48 }
49 else {
50 if (value instanceof Buffer) {
51 throw new Error("keys that don't end with '-bin' must have String values");
52 }
53 if (!isLegalNonBinaryValue(value)) {
54 throw new Error('Metadata string value "' + value + '" contains illegal characters');
55 }
56 }
57 }
58}
59/**
60 * A class for storing metadata. Keys are normalized to lowercase ASCII.
61 */
62class Metadata {
63 constructor(options) {
64 this.internalRepr = new Map();
65 if (options === undefined) {
66 this.options = {};
67 }
68 else {
69 this.options = options;
70 }
71 }
72 /**
73 * Sets the given value for the given key by replacing any other values
74 * associated with that key. Normalizes the key.
75 * @param key The key to whose value should be set.
76 * @param value The value to set. Must be a buffer if and only
77 * if the normalized key ends with '-bin'.
78 */
79 set(key, value) {
80 key = normalizeKey(key);
81 validate(key, value);
82 this.internalRepr.set(key, [value]);
83 }
84 /**
85 * Adds the given value for the given key by appending to a list of previous
86 * values associated with that key. Normalizes the key.
87 * @param key The key for which a new value should be appended.
88 * @param value The value to add. Must be a buffer if and only
89 * if the normalized key ends with '-bin'.
90 */
91 add(key, value) {
92 key = normalizeKey(key);
93 validate(key, value);
94 const existingValue = this.internalRepr.get(key);
95 if (existingValue === undefined) {
96 this.internalRepr.set(key, [value]);
97 }
98 else {
99 existingValue.push(value);
100 }
101 }
102 /**
103 * Removes the given key and any associated values. Normalizes the key.
104 * @param key The key whose values should be removed.
105 */
106 remove(key) {
107 key = normalizeKey(key);
108 validate(key);
109 this.internalRepr.delete(key);
110 }
111 /**
112 * Gets a list of all values associated with the key. Normalizes the key.
113 * @param key The key whose value should be retrieved.
114 * @return A list of values associated with the given key.
115 */
116 get(key) {
117 key = normalizeKey(key);
118 validate(key);
119 return this.internalRepr.get(key) || [];
120 }
121 /**
122 * Gets a plain object mapping each key to the first value associated with it.
123 * This reflects the most common way that people will want to see metadata.
124 * @return A key/value mapping of the metadata.
125 */
126 getMap() {
127 const result = {};
128 this.internalRepr.forEach((values, key) => {
129 if (values.length > 0) {
130 const v = values[0];
131 result[key] = v instanceof Buffer ? v.slice() : v;
132 }
133 });
134 return result;
135 }
136 /**
137 * Clones the metadata object.
138 * @return The newly cloned object.
139 */
140 clone() {
141 const newMetadata = new Metadata(this.options);
142 const newInternalRepr = newMetadata.internalRepr;
143 this.internalRepr.forEach((value, key) => {
144 const clonedValue = value.map((v) => {
145 if (v instanceof Buffer) {
146 return Buffer.from(v);
147 }
148 else {
149 return v;
150 }
151 });
152 newInternalRepr.set(key, clonedValue);
153 });
154 return newMetadata;
155 }
156 /**
157 * Merges all key-value pairs from a given Metadata object into this one.
158 * If both this object and the given object have values in the same key,
159 * values from the other Metadata object will be appended to this object's
160 * values.
161 * @param other A Metadata object.
162 */
163 merge(other) {
164 other.internalRepr.forEach((values, key) => {
165 const mergedValue = (this.internalRepr.get(key) || []).concat(values);
166 this.internalRepr.set(key, mergedValue);
167 });
168 }
169 setOptions(options) {
170 this.options = options;
171 }
172 getOptions() {
173 return this.options;
174 }
175 /**
176 * Creates an OutgoingHttpHeaders object that can be used with the http2 API.
177 */
178 toHttp2Headers() {
179 // NOTE: Node <8.9 formats http2 headers incorrectly.
180 const result = {};
181 this.internalRepr.forEach((values, key) => {
182 // We assume that the user's interaction with this object is limited to
183 // through its public API (i.e. keys and values are already validated).
184 result[key] = values.map((value) => {
185 if (value instanceof Buffer) {
186 return value.toString('base64');
187 }
188 else {
189 return value;
190 }
191 });
192 });
193 return result;
194 }
195 // For compatibility with the other Metadata implementation
196 _getCoreRepresentation() {
197 return this.internalRepr;
198 }
199 /**
200 * This modifies the behavior of JSON.stringify to show an object
201 * representation of the metadata map.
202 */
203 toJSON() {
204 const result = {};
205 for (const [key, values] of this.internalRepr.entries()) {
206 result[key] = values;
207 }
208 return result;
209 }
210 /**
211 * Returns a new Metadata object based fields in a given IncomingHttpHeaders
212 * object.
213 * @param headers An IncomingHttpHeaders object.
214 */
215 static fromHttp2Headers(headers) {
216 const result = new Metadata();
217 Object.keys(headers).forEach((key) => {
218 // Reserved headers (beginning with `:`) are not valid keys.
219 if (key.charAt(0) === ':') {
220 return;
221 }
222 const values = headers[key];
223 try {
224 if (isBinaryKey(key)) {
225 if (Array.isArray(values)) {
226 values.forEach((value) => {
227 result.add(key, Buffer.from(value, 'base64'));
228 });
229 }
230 else if (values !== undefined) {
231 if (isCustomMetadata(key)) {
232 values.split(',').forEach((v) => {
233 result.add(key, Buffer.from(v.trim(), 'base64'));
234 });
235 }
236 else {
237 result.add(key, Buffer.from(values, 'base64'));
238 }
239 }
240 }
241 else {
242 if (Array.isArray(values)) {
243 values.forEach((value) => {
244 result.add(key, value);
245 });
246 }
247 else if (values !== undefined) {
248 result.add(key, values);
249 }
250 }
251 }
252 catch (error) {
253 const message = `Failed to add metadata entry ${key}: ${values}. ${error.message}. For more information see https://github.com/grpc/grpc-node/issues/1173`;
254 logging_1.log(constants_1.LogVerbosity.ERROR, message);
255 }
256 });
257 return result;
258 }
259}
260exports.Metadata = Metadata;
261//# sourceMappingURL=metadata.js.map
\No newline at end of file