UNPKG

16.7 kBPlain TextView Raw
1/*
2 * Copyright 2019 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
18/* This file implements gRFC A2 and the service config spec:
19 * https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md
20 * https://github.com/grpc/grpc/blob/master/doc/service_config.md. Each
21 * function here takes an object with unknown structure and returns its
22 * specific object type if the input has the right structure, and throws an
23 * error otherwise. */
24
25/* The any type is purposely used here. All functions validate their input at
26 * runtime */
27/* eslint-disable @typescript-eslint/no-explicit-any */
28
29import * as os from 'os';
30import { Status } from './constants';
31import { Duration } from './duration';
32import {
33 LoadBalancingConfig,
34 validateLoadBalancingConfig,
35} from './load-balancer';
36
37export interface MethodConfigName {
38 service?: string;
39 method?: string;
40}
41
42export interface RetryPolicy {
43 maxAttempts: number;
44 initialBackoff: string;
45 maxBackoff: string;
46 backoffMultiplier: number;
47 retryableStatusCodes: (Status | string)[];
48}
49
50export interface HedgingPolicy {
51 maxAttempts: number;
52 hedgingDelay?: string;
53 nonFatalStatusCodes?: (Status | string)[];
54}
55
56export interface MethodConfig {
57 name: MethodConfigName[];
58 waitForReady?: boolean;
59 timeout?: Duration;
60 maxRequestBytes?: number;
61 maxResponseBytes?: number;
62 retryPolicy?: RetryPolicy;
63 hedgingPolicy?: HedgingPolicy;
64}
65
66export interface RetryThrottling {
67 maxTokens: number;
68 tokenRatio: number;
69}
70
71export interface ServiceConfig {
72 loadBalancingPolicy?: string;
73 loadBalancingConfig: LoadBalancingConfig[];
74 methodConfig: MethodConfig[];
75 retryThrottling?: RetryThrottling;
76}
77
78export interface ServiceConfigCanaryConfig {
79 clientLanguage?: string[];
80 percentage?: number;
81 clientHostname?: string[];
82 serviceConfig: ServiceConfig;
83}
84
85/**
86 * Recognizes a number with up to 9 digits after the decimal point, followed by
87 * an "s", representing a number of seconds.
88 */
89const DURATION_REGEX = /^\d+(\.\d{1,9})?s$/;
90
91/**
92 * Client language name used for determining whether this client matches a
93 * `ServiceConfigCanaryConfig`'s `clientLanguage` list.
94 */
95const CLIENT_LANGUAGE_STRING = 'node';
96
97function validateName(obj: any): MethodConfigName {
98 // In this context, and unset field and '' are considered the same
99 if ('service' in obj && obj.service !== '') {
100 if (typeof obj.service !== 'string') {
101 throw new Error(
102 `Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`
103 );
104 }
105 if ('method' in obj && obj.method !== '') {
106 if (typeof obj.method !== 'string') {
107 throw new Error(
108 `Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`
109 );
110 }
111 return {
112 service: obj.service,
113 method: obj.method,
114 };
115 } else {
116 return {
117 service: obj.service,
118 };
119 }
120 } else {
121 if ('method' in obj && obj.method !== undefined) {
122 throw new Error(
123 `Invalid method config name: method set with empty or unset service`
124 );
125 }
126 return {};
127 }
128}
129
130function validateRetryPolicy(obj: any): RetryPolicy {
131 if (
132 !('maxAttempts' in obj) ||
133 !Number.isInteger(obj.maxAttempts) ||
134 obj.maxAttempts < 2
135 ) {
136 throw new Error(
137 'Invalid method config retry policy: maxAttempts must be an integer at least 2'
138 );
139 }
140 if (
141 !('initialBackoff' in obj) ||
142 typeof obj.initialBackoff !== 'string' ||
143 !DURATION_REGEX.test(obj.initialBackoff)
144 ) {
145 throw new Error(
146 'Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer followed by s'
147 );
148 }
149 if (
150 !('maxBackoff' in obj) ||
151 typeof obj.maxBackoff !== 'string' ||
152 !DURATION_REGEX.test(obj.maxBackoff)
153 ) {
154 throw new Error(
155 'Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer followed by s'
156 );
157 }
158 if (
159 !('backoffMultiplier' in obj) ||
160 typeof obj.backoffMultiplier !== 'number' ||
161 obj.backoffMultiplier <= 0
162 ) {
163 throw new Error(
164 'Invalid method config retry policy: backoffMultiplier must be a number greater than 0'
165 );
166 }
167 if (
168 !('retryableStatusCodes' in obj && Array.isArray(obj.retryableStatusCodes))
169 ) {
170 throw new Error(
171 'Invalid method config retry policy: retryableStatusCodes is required'
172 );
173 }
174 if (obj.retryableStatusCodes.length === 0) {
175 throw new Error(
176 'Invalid method config retry policy: retryableStatusCodes must be non-empty'
177 );
178 }
179 for (const value of obj.retryableStatusCodes) {
180 if (typeof value === 'number') {
181 if (!Object.values(Status).includes(value)) {
182 throw new Error(
183 'Invalid method config retry policy: retryableStatusCodes value not in status code range'
184 );
185 }
186 } else if (typeof value === 'string') {
187 if (!Object.values(Status).includes(value.toUpperCase())) {
188 throw new Error(
189 'Invalid method config retry policy: retryableStatusCodes value not a status code name'
190 );
191 }
192 } else {
193 throw new Error(
194 'Invalid method config retry policy: retryableStatusCodes value must be a string or number'
195 );
196 }
197 }
198 return {
199 maxAttempts: obj.maxAttempts,
200 initialBackoff: obj.initialBackoff,
201 maxBackoff: obj.maxBackoff,
202 backoffMultiplier: obj.backoffMultiplier,
203 retryableStatusCodes: obj.retryableStatusCodes,
204 };
205}
206
207function validateHedgingPolicy(obj: any): HedgingPolicy {
208 if (
209 !('maxAttempts' in obj) ||
210 !Number.isInteger(obj.maxAttempts) ||
211 obj.maxAttempts < 2
212 ) {
213 throw new Error(
214 'Invalid method config hedging policy: maxAttempts must be an integer at least 2'
215 );
216 }
217 if (
218 'hedgingDelay' in obj &&
219 (typeof obj.hedgingDelay !== 'string' ||
220 !DURATION_REGEX.test(obj.hedgingDelay))
221 ) {
222 throw new Error(
223 'Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s'
224 );
225 }
226 if ('nonFatalStatusCodes' in obj && Array.isArray(obj.nonFatalStatusCodes)) {
227 for (const value of obj.nonFatalStatusCodes) {
228 if (typeof value === 'number') {
229 if (!Object.values(Status).includes(value)) {
230 throw new Error(
231 'Invlid method config hedging policy: nonFatalStatusCodes value not in status code range'
232 );
233 }
234 } else if (typeof value === 'string') {
235 if (!Object.values(Status).includes(value.toUpperCase())) {
236 throw new Error(
237 'Invlid method config hedging policy: nonFatalStatusCodes value not a status code name'
238 );
239 }
240 } else {
241 throw new Error(
242 'Invlid method config hedging policy: nonFatalStatusCodes value must be a string or number'
243 );
244 }
245 }
246 }
247 const result: HedgingPolicy = {
248 maxAttempts: obj.maxAttempts,
249 };
250 if (obj.hedgingDelay) {
251 result.hedgingDelay = obj.hedgingDelay;
252 }
253 if (obj.nonFatalStatusCodes) {
254 result.nonFatalStatusCodes = obj.nonFatalStatusCodes;
255 }
256 return result;
257}
258
259function validateMethodConfig(obj: any): MethodConfig {
260 const result: MethodConfig = {
261 name: [],
262 };
263 if (!('name' in obj) || !Array.isArray(obj.name)) {
264 throw new Error('Invalid method config: invalid name array');
265 }
266 for (const name of obj.name) {
267 result.name.push(validateName(name));
268 }
269 if ('waitForReady' in obj) {
270 if (typeof obj.waitForReady !== 'boolean') {
271 throw new Error('Invalid method config: invalid waitForReady');
272 }
273 result.waitForReady = obj.waitForReady;
274 }
275 if ('timeout' in obj) {
276 if (typeof obj.timeout === 'object') {
277 if (
278 !('seconds' in obj.timeout) ||
279 !(typeof obj.timeout.seconds === 'number')
280 ) {
281 throw new Error('Invalid method config: invalid timeout.seconds');
282 }
283 if (
284 !('nanos' in obj.timeout) ||
285 !(typeof obj.timeout.nanos === 'number')
286 ) {
287 throw new Error('Invalid method config: invalid timeout.nanos');
288 }
289 result.timeout = obj.timeout;
290 } else if (
291 typeof obj.timeout === 'string' &&
292 DURATION_REGEX.test(obj.timeout)
293 ) {
294 const timeoutParts = obj.timeout
295 .substring(0, obj.timeout.length - 1)
296 .split('.');
297 result.timeout = {
298 seconds: timeoutParts[0] | 0,
299 nanos: (timeoutParts[1] ?? 0) | 0,
300 };
301 } else {
302 throw new Error('Invalid method config: invalid timeout');
303 }
304 }
305 if ('maxRequestBytes' in obj) {
306 if (typeof obj.maxRequestBytes !== 'number') {
307 throw new Error('Invalid method config: invalid maxRequestBytes');
308 }
309 result.maxRequestBytes = obj.maxRequestBytes;
310 }
311 if ('maxResponseBytes' in obj) {
312 if (typeof obj.maxResponseBytes !== 'number') {
313 throw new Error('Invalid method config: invalid maxRequestBytes');
314 }
315 result.maxResponseBytes = obj.maxResponseBytes;
316 }
317 if ('retryPolicy' in obj) {
318 if ('hedgingPolicy' in obj) {
319 throw new Error(
320 'Invalid method config: retryPolicy and hedgingPolicy cannot both be specified'
321 );
322 } else {
323 result.retryPolicy = validateRetryPolicy(obj.retryPolicy);
324 }
325 } else if ('hedgingPolicy' in obj) {
326 result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy);
327 }
328 return result;
329}
330
331export function validateRetryThrottling(obj: any): RetryThrottling {
332 if (
333 !('maxTokens' in obj) ||
334 typeof obj.maxTokens !== 'number' ||
335 obj.maxTokens <= 0 ||
336 obj.maxTokens > 1000
337 ) {
338 throw new Error(
339 'Invalid retryThrottling: maxTokens must be a number in (0, 1000]'
340 );
341 }
342 if (
343 !('tokenRatio' in obj) ||
344 typeof obj.tokenRatio !== 'number' ||
345 obj.tokenRatio <= 0
346 ) {
347 throw new Error(
348 'Invalid retryThrottling: tokenRatio must be a number greater than 0'
349 );
350 }
351 return {
352 maxTokens: +(obj.maxTokens as number).toFixed(3),
353 tokenRatio: +(obj.tokenRatio as number).toFixed(3),
354 };
355}
356
357export function validateServiceConfig(obj: any): ServiceConfig {
358 const result: ServiceConfig = {
359 loadBalancingConfig: [],
360 methodConfig: [],
361 };
362 if ('loadBalancingPolicy' in obj) {
363 if (typeof obj.loadBalancingPolicy === 'string') {
364 result.loadBalancingPolicy = obj.loadBalancingPolicy;
365 } else {
366 throw new Error('Invalid service config: invalid loadBalancingPolicy');
367 }
368 }
369 if ('loadBalancingConfig' in obj) {
370 if (Array.isArray(obj.loadBalancingConfig)) {
371 for (const config of obj.loadBalancingConfig) {
372 result.loadBalancingConfig.push(validateLoadBalancingConfig(config));
373 }
374 } else {
375 throw new Error('Invalid service config: invalid loadBalancingConfig');
376 }
377 }
378 if ('methodConfig' in obj) {
379 if (Array.isArray(obj.methodConfig)) {
380 for (const methodConfig of obj.methodConfig) {
381 result.methodConfig.push(validateMethodConfig(methodConfig));
382 }
383 }
384 }
385 if ('retryThrottling' in obj) {
386 result.retryThrottling = validateRetryThrottling(obj.retryThrottling);
387 }
388 // Validate method name uniqueness
389 const seenMethodNames: MethodConfigName[] = [];
390 for (const methodConfig of result.methodConfig) {
391 for (const name of methodConfig.name) {
392 for (const seenName of seenMethodNames) {
393 if (
394 name.service === seenName.service &&
395 name.method === seenName.method
396 ) {
397 throw new Error(
398 `Invalid service config: duplicate name ${name.service}/${name.method}`
399 );
400 }
401 }
402 seenMethodNames.push(name);
403 }
404 }
405 return result;
406}
407
408function validateCanaryConfig(obj: any): ServiceConfigCanaryConfig {
409 if (!('serviceConfig' in obj)) {
410 throw new Error('Invalid service config choice: missing service config');
411 }
412 const result: ServiceConfigCanaryConfig = {
413 serviceConfig: validateServiceConfig(obj.serviceConfig),
414 };
415 if ('clientLanguage' in obj) {
416 if (Array.isArray(obj.clientLanguage)) {
417 result.clientLanguage = [];
418 for (const lang of obj.clientLanguage) {
419 if (typeof lang === 'string') {
420 result.clientLanguage.push(lang);
421 } else {
422 throw new Error(
423 'Invalid service config choice: invalid clientLanguage'
424 );
425 }
426 }
427 } else {
428 throw new Error('Invalid service config choice: invalid clientLanguage');
429 }
430 }
431 if ('clientHostname' in obj) {
432 if (Array.isArray(obj.clientHostname)) {
433 result.clientHostname = [];
434 for (const lang of obj.clientHostname) {
435 if (typeof lang === 'string') {
436 result.clientHostname.push(lang);
437 } else {
438 throw new Error(
439 'Invalid service config choice: invalid clientHostname'
440 );
441 }
442 }
443 } else {
444 throw new Error('Invalid service config choice: invalid clientHostname');
445 }
446 }
447 if ('percentage' in obj) {
448 if (
449 typeof obj.percentage === 'number' &&
450 0 <= obj.percentage &&
451 obj.percentage <= 100
452 ) {
453 result.percentage = obj.percentage;
454 } else {
455 throw new Error('Invalid service config choice: invalid percentage');
456 }
457 }
458 // Validate that no unexpected fields are present
459 const allowedFields = [
460 'clientLanguage',
461 'percentage',
462 'clientHostname',
463 'serviceConfig',
464 ];
465 for (const field in obj) {
466 if (!allowedFields.includes(field)) {
467 throw new Error(
468 `Invalid service config choice: unexpected field ${field}`
469 );
470 }
471 }
472 return result;
473}
474
475function validateAndSelectCanaryConfig(
476 obj: any,
477 percentage: number
478): ServiceConfig {
479 if (!Array.isArray(obj)) {
480 throw new Error('Invalid service config list');
481 }
482 for (const config of obj) {
483 const validatedConfig = validateCanaryConfig(config);
484 /* For each field, we check if it is present, then only discard the
485 * config if the field value does not match the current client */
486 if (
487 typeof validatedConfig.percentage === 'number' &&
488 percentage > validatedConfig.percentage
489 ) {
490 continue;
491 }
492 if (Array.isArray(validatedConfig.clientHostname)) {
493 let hostnameMatched = false;
494 for (const hostname of validatedConfig.clientHostname) {
495 if (hostname === os.hostname()) {
496 hostnameMatched = true;
497 }
498 }
499 if (!hostnameMatched) {
500 continue;
501 }
502 }
503 if (Array.isArray(validatedConfig.clientLanguage)) {
504 let languageMatched = false;
505 for (const language of validatedConfig.clientLanguage) {
506 if (language === CLIENT_LANGUAGE_STRING) {
507 languageMatched = true;
508 }
509 }
510 if (!languageMatched) {
511 continue;
512 }
513 }
514 return validatedConfig.serviceConfig;
515 }
516 throw new Error('No matching service config found');
517}
518
519/**
520 * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents,
521 * and select a service config with selection fields that all match this client. Most of these steps
522 * can fail with an error; the caller must handle any errors thrown this way.
523 * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt
524 * @param percentage A number chosen from the range [0, 100) that is used to select which config to use
525 * @return The service configuration to use, given the percentage value, or null if the service config
526 * data has a valid format but none of the options match the current client.
527 */
528export function extractAndSelectServiceConfig(
529 txtRecord: string[][],
530 percentage: number
531): ServiceConfig | null {
532 for (const record of txtRecord) {
533 if (record.length > 0 && record[0].startsWith('grpc_config=')) {
534 /* Treat the list of strings in this record as a single string and remove
535 * "grpc_config=" from the beginning. The rest should be a JSON string */
536 const recordString = record.join('').substring('grpc_config='.length);
537 const recordJson: any = JSON.parse(recordString);
538 return validateAndSelectCanaryConfig(recordJson, percentage);
539 }
540 }
541 return null;
542}