Merge pull request #2914 from jcanizales/separate-headers-and-trailers

Separate headers and trailers
pull/2612/head
Michael Lumish 10 years ago
commit 58d7310fbc
  1. 8
      src/objective-c/GRPCClient/GRPCCall+OAuth2.m
  2. 56
      src/objective-c/GRPCClient/GRPCCall.h
  3. 59
      src/objective-c/GRPCClient/GRPCCall.m
  4. 8
      src/objective-c/tests/GRPCClientTests.m

@ -40,7 +40,7 @@ static NSString * const kChallengeHeader = @"www-authenticate";
@implementation GRPCCall (OAuth2) @implementation GRPCCall (OAuth2)
- (NSString *)oauth2AccessToken { - (NSString *)oauth2AccessToken {
NSString *headerValue = self.requestMetadata[kAuthorizationHeader]; NSString *headerValue = self.requestHeaders[kAuthorizationHeader];
if ([headerValue hasPrefix:kBearerPrefix]) { if ([headerValue hasPrefix:kBearerPrefix]) {
return [headerValue substringFromIndex:kBearerPrefix.length]; return [headerValue substringFromIndex:kBearerPrefix.length];
} else { } else {
@ -50,14 +50,14 @@ static NSString * const kChallengeHeader = @"www-authenticate";
- (void)setOauth2AccessToken:(NSString *)token { - (void)setOauth2AccessToken:(NSString *)token {
if (token) { if (token) {
self.requestMetadata[kAuthorizationHeader] = [kBearerPrefix stringByAppendingString:token]; self.requestHeaders[kAuthorizationHeader] = [kBearerPrefix stringByAppendingString:token];
} else { } else {
[self.requestMetadata removeObjectForKey:kAuthorizationHeader]; [self.requestHeaders removeObjectForKey:kAuthorizationHeader];
} }
} }
- (NSString *)oauth2ChallengeHeader { - (NSString *)oauth2ChallengeHeader {
return self.responseMetadata[kChallengeHeader]; return self.responseHeaders[kChallengeHeader];
} }
@end @end

@ -48,8 +48,10 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <RxLibrary/GRXWriter.h> #import <RxLibrary/GRXWriter.h>
// Key used in |NSError|'s |userInfo| dictionary to store the response metadata sent by the server. // Keys used in |NSError|'s |userInfo| dictionary to store the response headers and trailers sent by
extern id const kGRPCStatusMetadataKey; // the server.
extern id const kGRPCHeadersKey;
extern id const kGRPCTrailersKey;
// Represents a single gRPC remote call. // Represents a single gRPC remote call.
@interface GRPCCall : GRXWriter @interface GRPCCall : GRXWriter
@ -57,43 +59,49 @@ extern id const kGRPCStatusMetadataKey;
// These HTTP headers will be passed to the server as part of this call. Each HTTP header is a // These HTTP headers will be passed to the server as part of this call. Each HTTP header is a
// name-value pair with string names and either string or binary values. // name-value pair with string names and either string or binary values.
// //
// The passed dictionary has to use NSString keys, corresponding to the header names. The // The passed dictionary has to use NSString keys, corresponding to the header names. The value
// value associated to each can be a NSString object or a NSData object. E.g.: // associated to each can be a NSString object or a NSData object. E.g.:
// //
// call.requestMetadata = @{@"Authorization": @"Bearer ..."}; // call.requestHeaders = @{@"authorization": @"Bearer ..."};
// //
// call.requestMetadata[@"SomeBinaryHeader"] = someData; // call.requestHeaders[@"my-header-bin"] = someData;
// //
// After the call is started, modifying this won't have any effect. // After the call is started, trying to modify this property is an error.
// //
// For convenience, the property is initialized to an empty NSMutableDictionary, and the setter // For convenience, the property is initialized to an empty NSMutableDictionary, and the setter
// accepts (and copies) both mutable and immutable dictionaries. // accepts (and copies) both mutable and immutable dictionaries.
- (NSMutableDictionary *)requestMetadata; // nonatomic - (NSMutableDictionary *)requestHeaders; // nonatomic
- (void)setRequestMetadata:(NSDictionary *)requestMetadata; // nonatomic, copy - (void)setRequestHeaders:(NSDictionary *)requestHeaders; // nonatomic, copy
// This dictionary is populated with the HTTP headers received from the server. When the RPC ends, // This dictionary is populated with the HTTP headers received from the server. This happens before
// the HTTP trailers received are added to the dictionary too. It has the same structure as the // any response message is received from the server. It has the same structure as the request
// request metadata dictionary. // headers dictionary: Keys are NSString header names; names ending with the suffix "-bin" have a
// NSData value; the others have a NSString value.
// //
// The first time this object calls |writeValue| on the writeable passed to |startWithWriteable|, // The value of this property is nil until all response headers are received, and will change before
// the |responseMetadata| dictionary already contains the response headers. When it calls // any of -writeValue: or -writesFinishedWithError: are sent to the writeable.
// |writesFinishedWithError|, the dictionary contains both the response headers and trailers. @property(atomic, readonly) NSDictionary *responseHeaders;
@property(atomic, readonly) NSDictionary *responseMetadata;
// Same as responseHeaders, but populated with the HTTP trailers received from the server before the
// call finishes.
//
// The value of this property is nil until all response trailers are received, and will change
// before -writesFinishedWithError: is sent to the writeable.
@property(atomic, readonly) NSDictionary *responseTrailers;
// The request writer has to write NSData objects into the provided Writeable. The server will // The request writer has to write NSData objects into the provided Writeable. The server will
// receive each of those separately and in order. // receive each of those separately and in order as distinct messages.
// A gRPC call might not complete until the request writer finishes. On the other hand, the // A gRPC call might not complete until the request writer finishes. On the other hand, the request
// request finishing doesn't necessarily make the call to finish, as the server might continue // finishing doesn't necessarily make the call to finish, as the server might continue sending
// sending messages to the response side of the call indefinitely (depending on the semantics of // messages to the response side of the call indefinitely (depending on the semantics of the
// the specific remote method called). // specific remote method called).
// To finish a call right away, invoke cancel. // To finish a call right away, invoke cancel.
- (instancetype)initWithHost:(NSString *)host - (instancetype)initWithHost:(NSString *)host
path:(NSString *)path path:(NSString *)path
requestsWriter:(GRXWriter *)requestsWriter NS_DESIGNATED_INITIALIZER; requestsWriter:(GRXWriter *)requestsWriter NS_DESIGNATED_INITIALIZER;
// Finishes the request side of this call, notifies the server that the RPC // Finishes the request side of this call, notifies the server that the RPC should be cancelled, and
// should be cancelled, and finishes the response side of the call with an error // finishes the response side of the call with an error of code CANCELED.
// of code CANCELED.
- (void)cancel; - (void)cancel;
// TODO(jcanizales): Let specify a deadline. As a category of GRXWriter? // TODO(jcanizales): Let specify a deadline. As a category of GRXWriter?

@ -42,9 +42,13 @@
#import "private/NSDictionary+GRPC.h" #import "private/NSDictionary+GRPC.h"
#import "private/NSError+GRPC.h" #import "private/NSError+GRPC.h"
NSString * const kGRPCStatusMetadataKey = @"io.grpc.StatusMetadataKey"; NSString * const kGRPCHeadersKey = @"io.grpc.HeadersKey";
NSString * const kGRPCTrailersKey = @"io.grpc.TrailersKey";
@interface GRPCCall () <GRXWriteable> @interface GRPCCall () <GRXWriteable>
// Make them read-write.
@property(atomic, strong) NSDictionary *responseHeaders;
@property(atomic, strong) NSDictionary *responseTrailers;
@end @end
// The following methods of a C gRPC call object aren't reentrant, and thus // The following methods of a C gRPC call object aren't reentrant, and thus
@ -89,8 +93,7 @@ NSString * const kGRPCStatusMetadataKey = @"io.grpc.StatusMetadataKey";
// the response arrives. // the response arrives.
GRPCCall *_retainSelf; GRPCCall *_retainSelf;
NSMutableDictionary *_requestMetadata; NSMutableDictionary *_requestHeaders;
NSMutableDictionary *_responseMetadata;
} }
@synthesize state = _state; @synthesize state = _state;
@ -121,24 +124,19 @@ NSString * const kGRPCStatusMetadataKey = @"io.grpc.StatusMetadataKey";
_requestWriter = requestWriter; _requestWriter = requestWriter;
_requestMetadata = [NSMutableDictionary dictionary]; _requestHeaders = [NSMutableDictionary dictionary];
_responseMetadata = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
#pragma mark Metadata #pragma mark Metadata
- (NSMutableDictionary *)requestMetadata { - (NSMutableDictionary *)requestHeaders {
return _requestMetadata; return _requestHeaders;
} }
- (void)setRequestMetadata:(NSDictionary *)requestMetadata { - (void)setRequestHeaders:(NSDictionary *)requestHeaders {
_requestMetadata = [NSMutableDictionary dictionaryWithDictionary:requestMetadata]; _requestHeaders = [NSMutableDictionary dictionaryWithDictionary:requestHeaders];
}
- (NSDictionary *)responseMetadata {
return _responseMetadata;
} }
#pragma mark Finish #pragma mark Finish
@ -232,11 +230,10 @@ NSString * const kGRPCStatusMetadataKey = @"io.grpc.StatusMetadataKey";
#pragma mark Send headers #pragma mark Send headers
// TODO(jcanizales): Rename to commitHeaders. - (void)sendHeaders:(NSDictionary *)headers {
- (void)sendHeaders:(NSDictionary *)metadata {
// TODO(jcanizales): Add error handlers for async failures // TODO(jcanizales): Add error handlers for async failures
[_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMetadata alloc] [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMetadata alloc]
initWithMetadata:metadata ?: @{} handler:nil]]]; initWithMetadata:headers ?: @{} handler:nil]]];
} }
#pragma mark GRXWriteable implementation #pragma mark GRXWriteable implementation
@ -305,35 +302,45 @@ NSString * const kGRPCStatusMetadataKey = @"io.grpc.StatusMetadataKey";
// Both handlers will eventually be called, from the network queue. Writes can start immediately // Both handlers will eventually be called, from the network queue. Writes can start immediately
// after this. // after this.
// The first one (metadataHandler), when the response headers are received. // The first one (headersHandler), when the response headers are received.
// The second one (completionHandler), whenever the RPC finishes for any reason. // The second one (completionHandler), whenever the RPC finishes for any reason.
- (void)invokeCallWithMetadataHandler:(void(^)(NSDictionary *))metadataHandler - (void)invokeCallWithHeadersHandler:(void(^)(NSDictionary *))headersHandler
completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler { completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler {
// TODO(jcanizales): Add error handlers for async failures // TODO(jcanizales): Add error handlers for async failures
[_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc] [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc]
initWithHandler:metadataHandler]]]; initWithHandler:headersHandler]]];
[_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc] [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc]
initWithHandler:completionHandler]]]; initWithHandler:completionHandler]]];
} }
- (void)invokeCall { - (void)invokeCall {
__weak GRPCCall *weakSelf = self; __weak GRPCCall *weakSelf = self;
[self invokeCallWithMetadataHandler:^(NSDictionary *headers) { [self invokeCallWithHeadersHandler:^(NSDictionary *headers) {
// Response headers received. // Response headers received.
GRPCCall *strongSelf = weakSelf; GRPCCall *strongSelf = weakSelf;
if (strongSelf) { if (strongSelf) {
[strongSelf->_responseMetadata addEntriesFromDictionary:headers]; strongSelf.responseHeaders = headers;
[strongSelf startNextRead]; [strongSelf startNextRead];
} }
} completionHandler:^(NSError *error, NSDictionary *trailers) { } completionHandler:^(NSError *error, NSDictionary *trailers) {
GRPCCall *strongSelf = weakSelf; GRPCCall *strongSelf = weakSelf;
if (strongSelf) { if (strongSelf) {
[strongSelf->_responseMetadata addEntriesFromDictionary:trailers]; strongSelf.responseTrailers = trailers;
if (error) { if (error) {
NSMutableDictionary *userInfo = NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[NSMutableDictionary dictionaryWithDictionary:error.userInfo]; if (error.userInfo) {
userInfo[kGRPCStatusMetadataKey] = strongSelf->_responseMetadata; [userInfo addEntriesFromDictionary:error.userInfo];
}
userInfo[kGRPCTrailersKey] = strongSelf.responseTrailers;
// TODO(jcanizales): The C gRPC library doesn't guarantee that the headers block will be
// called before this one, so an error might end up with trailers but no headers. We
// shouldn't call finishWithError until ater both blocks are called. It is also when this is
// done that we can provide a merged view of response headers and trailers in a thread-safe
// way.
if (strongSelf.responseHeaders) {
userInfo[kGRPCHeadersKey] = strongSelf.responseHeaders;
}
error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo]; error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
} }
[strongSelf finishWithError:error]; [strongSelf finishWithError:error];
@ -356,7 +363,7 @@ NSString * const kGRPCStatusMetadataKey = @"io.grpc.StatusMetadataKey";
_retainSelf = self; _retainSelf = self;
_responseWriteable = [[GRXConcurrentWriteable alloc] initWithWriteable:writeable]; _responseWriteable = [[GRXConcurrentWriteable alloc] initWithWriteable:writeable];
[self sendHeaders:_requestMetadata]; [self sendHeaders:_requestHeaders];
[self invokeCall]; [self invokeCall];
} }

@ -168,11 +168,13 @@ static ProtoMethod *kUnaryCallMethod;
} completionHandler:^(NSError *errorOrNil) { } completionHandler:^(NSError *errorOrNil) {
XCTAssertNotNil(errorOrNil, @"Finished without error!"); XCTAssertNotNil(errorOrNil, @"Finished without error!");
XCTAssertEqual(errorOrNil.code, 16, @"Finished with unexpected error: %@", errorOrNil); XCTAssertEqual(errorOrNil.code, 16, @"Finished with unexpected error: %@", errorOrNil);
XCTAssertEqualObjects(call.responseMetadata, errorOrNil.userInfo[kGRPCStatusMetadataKey], XCTAssertEqualObjects(call.responseHeaders, errorOrNil.userInfo[kGRPCHeadersKey],
@"Metadata in the NSError object and call object differ."); @"Headers in the NSError object and call object differ.");
XCTAssertEqualObjects(call.responseTrailers, errorOrNil.userInfo[kGRPCTrailersKey],
@"Trailers in the NSError object and call object differ.");
NSString *challengeHeader = call.oauth2ChallengeHeader; NSString *challengeHeader = call.oauth2ChallengeHeader;
XCTAssertGreaterThan(challengeHeader.length, 0, XCTAssertGreaterThan(challengeHeader.length, 0,
@"No challenge in response headers %@", call.responseMetadata); @"No challenge in response headers %@", call.responseHeaders);
[expectation fulfill]; [expectation fulfill];
}]; }];

Loading…
Cancel
Save