File size: 11,777 Bytes
77731d1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
/*
* Copyright 2022 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { CallCredentials } from './call-credentials';
import {
Call,
InterceptingListener,
MessageContext,
StatusObject,
} from './call-interface';
import { SubchannelCall } from './subchannel-call';
import { ConnectivityState } from './connectivity-state';
import { LogVerbosity, Status } from './constants';
import { Deadline, getDeadlineTimeoutString } from './deadline';
import { InternalChannel } from './internal-channel';
import { Metadata } from './metadata';
import { PickResultType } from './picker';
import { CallConfig } from './resolver';
import { splitHostPort } from './uri-parser';
import * as logging from './logging';
import { restrictControlPlaneStatusCode } from './control-plane-status';
import * as http2 from 'http2';
const TRACER_NAME = 'load_balancing_call';
export type RpcProgress = 'NOT_STARTED' | 'DROP' | 'REFUSED' | 'PROCESSED';
export interface StatusObjectWithProgress extends StatusObject {
progress: RpcProgress;
}
export interface LoadBalancingCallInterceptingListener
extends InterceptingListener {
onReceiveStatus(status: StatusObjectWithProgress): void;
}
export class LoadBalancingCall implements Call {
private child: SubchannelCall | null = null;
private readPending = false;
private pendingMessage: { context: MessageContext; message: Buffer } | null =
null;
private pendingHalfClose = false;
private ended = false;
private serviceUrl: string;
private metadata: Metadata | null = null;
private listener: InterceptingListener | null = null;
private onCallEnded: ((statusCode: Status) => void) | null = null;
constructor(
private readonly channel: InternalChannel,
private readonly callConfig: CallConfig,
private readonly methodName: string,
private readonly host: string,
private readonly credentials: CallCredentials,
private readonly deadline: Deadline,
private readonly callNumber: number
) {
const splitPath: string[] = this.methodName.split('/');
let serviceName = '';
/* The standard path format is "/{serviceName}/{methodName}", so if we split
* by '/', the first item should be empty and the second should be the
* service name */
if (splitPath.length >= 2) {
serviceName = splitPath[1];
}
const hostname = splitHostPort(this.host)?.host ?? 'localhost';
/* Currently, call credentials are only allowed on HTTPS connections, so we
* can assume that the scheme is "https" */
this.serviceUrl = `https://${hostname}/${serviceName}`;
}
private trace(text: string): void {
logging.trace(
LogVerbosity.DEBUG,
TRACER_NAME,
'[' + this.callNumber + '] ' + text
);
}
private outputStatus(status: StatusObject, progress: RpcProgress) {
if (!this.ended) {
this.ended = true;
this.trace(
'ended with status: code=' +
status.code +
' details="' +
status.details +
'"'
);
const finalStatus = { ...status, progress };
this.listener?.onReceiveStatus(finalStatus);
this.onCallEnded?.(finalStatus.code);
}
}
doPick() {
if (this.ended) {
return;
}
if (!this.metadata) {
throw new Error('doPick called before start');
}
this.trace('Pick called');
const pickResult = this.channel.doPick(
this.metadata,
this.callConfig.pickInformation
);
const subchannelString = pickResult.subchannel
? '(' +
pickResult.subchannel.getChannelzRef().id +
') ' +
pickResult.subchannel.getAddress()
: '' + pickResult.subchannel;
this.trace(
'Pick result: ' +
PickResultType[pickResult.pickResultType] +
' subchannel: ' +
subchannelString +
' status: ' +
pickResult.status?.code +
' ' +
pickResult.status?.details
);
switch (pickResult.pickResultType) {
case PickResultType.COMPLETE:
this.credentials
.generateMetadata({ service_url: this.serviceUrl })
.then(
credsMetadata => {
/* If this call was cancelled (e.g. by the deadline) before
* metadata generation finished, we shouldn't do anything with
* it. */
if (this.ended) {
this.trace('Credentials metadata generation finished after call ended');
return;
}
const finalMetadata = this.metadata!.clone();
finalMetadata.merge(credsMetadata);
if (finalMetadata.get('authorization').length > 1) {
this.outputStatus(
{
code: Status.INTERNAL,
details:
'"authorization" metadata cannot have multiple values',
metadata: new Metadata(),
},
'PROCESSED'
);
}
if (
pickResult.subchannel!.getConnectivityState() !==
ConnectivityState.READY
) {
this.trace(
'Picked subchannel ' +
subchannelString +
' has state ' +
ConnectivityState[
pickResult.subchannel!.getConnectivityState()
] +
' after getting credentials metadata. Retrying pick'
);
this.doPick();
return;
}
if (this.deadline !== Infinity) {
finalMetadata.set(
'grpc-timeout',
getDeadlineTimeoutString(this.deadline)
);
}
try {
this.child = pickResult
.subchannel!.getRealSubchannel()
.createCall(finalMetadata, this.host, this.methodName, {
onReceiveMetadata: metadata => {
this.trace('Received metadata');
this.listener!.onReceiveMetadata(metadata);
},
onReceiveMessage: message => {
this.trace('Received message');
this.listener!.onReceiveMessage(message);
},
onReceiveStatus: status => {
this.trace('Received status');
if (
status.rstCode ===
http2.constants.NGHTTP2_REFUSED_STREAM
) {
this.outputStatus(status, 'REFUSED');
} else {
this.outputStatus(status, 'PROCESSED');
}
},
});
} catch (error) {
this.trace(
'Failed to start call on picked subchannel ' +
subchannelString +
' with error ' +
(error as Error).message
);
this.outputStatus(
{
code: Status.INTERNAL,
details:
'Failed to start HTTP/2 stream with error ' +
(error as Error).message,
metadata: new Metadata(),
},
'NOT_STARTED'
);
return;
}
this.callConfig.onCommitted?.();
pickResult.onCallStarted?.();
this.onCallEnded = pickResult.onCallEnded;
this.trace(
'Created child call [' + this.child.getCallNumber() + ']'
);
if (this.readPending) {
this.child.startRead();
}
if (this.pendingMessage) {
this.child.sendMessageWithContext(
this.pendingMessage.context,
this.pendingMessage.message
);
}
if (this.pendingHalfClose) {
this.child.halfClose();
}
},
(error: Error & { code: number }) => {
// We assume the error code isn't 0 (Status.OK)
const { code, details } = restrictControlPlaneStatusCode(
typeof error.code === 'number' ? error.code : Status.UNKNOWN,
`Getting metadata from plugin failed with error: ${error.message}`
);
this.outputStatus(
{
code: code,
details: details,
metadata: new Metadata(),
},
'PROCESSED'
);
}
);
break;
case PickResultType.DROP:
const { code, details } = restrictControlPlaneStatusCode(
pickResult.status!.code,
pickResult.status!.details
);
setImmediate(() => {
this.outputStatus(
{ code, details, metadata: pickResult.status!.metadata },
'DROP'
);
});
break;
case PickResultType.TRANSIENT_FAILURE:
if (this.metadata.getOptions().waitForReady) {
this.channel.queueCallForPick(this);
} else {
const { code, details } = restrictControlPlaneStatusCode(
pickResult.status!.code,
pickResult.status!.details
);
setImmediate(() => {
this.outputStatus(
{ code, details, metadata: pickResult.status!.metadata },
'PROCESSED'
);
});
}
break;
case PickResultType.QUEUE:
this.channel.queueCallForPick(this);
}
}
cancelWithStatus(status: Status, details: string): void {
this.trace(
'cancelWithStatus code: ' + status + ' details: "' + details + '"'
);
this.child?.cancelWithStatus(status, details);
this.outputStatus(
{ code: status, details: details, metadata: new Metadata() },
'PROCESSED'
);
}
getPeer(): string {
return this.child?.getPeer() ?? this.channel.getTarget();
}
start(
metadata: Metadata,
listener: LoadBalancingCallInterceptingListener
): void {
this.trace('start called');
this.listener = listener;
this.metadata = metadata;
this.doPick();
}
sendMessageWithContext(context: MessageContext, message: Buffer): void {
this.trace('write() called with message of length ' + message.length);
if (this.child) {
this.child.sendMessageWithContext(context, message);
} else {
this.pendingMessage = { context, message };
}
}
startRead(): void {
this.trace('startRead called');
if (this.child) {
this.child.startRead();
} else {
this.readPending = true;
}
}
halfClose(): void {
this.trace('halfClose called');
if (this.child) {
this.child.halfClose();
} else {
this.pendingHalfClose = true;
}
}
setCredentials(credentials: CallCredentials): void {
throw new Error('Method not implemented.');
}
getCallNumber(): number {
return this.callNumber;
}
}
|