Browse Source

Continue to refine prototype generated code.

Tim Burks 9 years ago
parent
commit
e88fb702b4

+ 1 - 1
Examples/Echo/Swift/Echo/AppDelegate.swift

@@ -37,7 +37,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
 
   @IBOutlet weak var window: NSWindow!
 
-  var echoProvider : EchoProvider!
+  var echoProvider : Echo_EchoProvider!
   var insecureServer: Echo_EchoServer!
   var secureServer: Echo_EchoServer!
 

+ 8 - 8
Examples/Echo/Swift/Echo/EchoProvider.swift

@@ -35,13 +35,13 @@ import Foundation
 
 class EchoProvider : Echo_EchoProvider {
 
-  // Get returns requests as they were received.
-  func Get(request : Echo_EchoRequest) throws -> Echo_EchoResponse {
+  // get returns requests as they were received.
+  func get(request : Echo_EchoRequest) throws -> Echo_EchoResponse {
     return Echo_EchoResponse(text:"Swift echo get: " + request.text)
   }
 
-  // Expand splits a request into words and returns each word in a separate message.
-  func Expand(request : Echo_EchoRequest, session : Echo_EchoExpandSession) throws -> Void {
+  // expand splits a request into words and returns each word in a separate message.
+  func expand(request : Echo_EchoRequest, session : Echo_EchoExpandSession) throws -> Void {
     let parts = request.text.components(separatedBy: " ")
     var i = 0
     for part in parts {
@@ -51,8 +51,8 @@ class EchoProvider : Echo_EchoProvider {
     }
   }
 
-  // Collect collects a sequence of messages and returns them concatenated when the caller closes.
-  func Collect(session : Echo_EchoCollectSession) throws -> Void {
+  // collect collects a sequence of messages and returns them concatenated when the caller closes.
+  func collect(session : Echo_EchoCollectSession) throws -> Void {
     var parts : [String] = []
     while true {
       do {
@@ -68,8 +68,8 @@ class EchoProvider : Echo_EchoProvider {
     try session.SendAndClose(response)
   }
 
-  // Update streams back messages as they are received in an input stream.
-  func Update(session : Echo_EchoUpdateSession) throws -> Void {
+  // update streams back messages as they are received in an input stream.
+  func update(session : Echo_EchoUpdateSession) throws -> Void {
     var count = 0
     while true {
       do {

+ 40 - 69
Examples/Echo/Swift/Echo/EchoViewController.swift

@@ -126,57 +126,44 @@ class EchoViewController : NSViewController, NSTextFieldDelegate {
       service = Echo_EchoService(address:address, certificates:certificates, host:host)
     }
     if let service = service {
-      service.channel.host = "example.com" // sample override
+      service.host = "example.com" // sample override
+      service.metadata = Metadata(["x-goog-api-key":"YOUR_API_KEY",
+                                   "x-ios-bundle-identifier":Bundle.main.bundleIdentifier!])
     }
   }
 
   func callServer(address:String, host:String) throws -> Void {
     prepareService(address:address, host:host)
-
-    let requestMetadata = Metadata(["x-goog-api-key":"YOUR_API_KEY",
-                                    "x-ios-bundle-identifier":Bundle.main.bundleIdentifier!])
-
+    guard let service = service else {
+      return
+    }
     if (self.callSelectButton.selectedSegment == 0) {
       // NONSTREAMING
-      if let service = service {
-        var requestMessage = Echo_EchoRequest()
-        requestMessage.text = self.messageField.stringValue
-        self.displayMessageSent(requestMessage.text)
-
-        // service.get() is a blocking call
-        DispatchQueue.global().async {
-          let result = service.get(requestMessage)
-          switch result {
-          case .Response(let responseMessage):
-            self.displayMessageReceived(responseMessage.text)
-          case .CallResult(let result):
-            self.displayMessageReceived("No message received. \(result)")
-          case .Error(let error):
-            self.displayMessageReceived("No message received. \(error)")
-          }
+      let requestMessage = Echo_EchoRequest(text:self.messageField.stringValue)
+      self.displayMessageSent(requestMessage.text)
+      // run this asynchronously because service.get() is a blocking call
+      DispatchQueue.global().async {
+        do {
+          let responseMessage = try service.get(requestMessage)
+          self.displayMessageReceived(responseMessage.text)
+        } catch (let error) {
+          self.displayMessageReceived("No message received. \(error)")
         }
       }
     }
     else if (self.callSelectButton.selectedSegment == 1) {
       // STREAMING EXPAND
       if (!nowStreaming) {
-        guard let service = service else {
-          return
-        }
-        var requestMessage = Echo_EchoRequest()
-        requestMessage.text = self.messageField.stringValue
-        self.expandCall = service.expand(requestMessage)
+        let requestMessage = Echo_EchoRequest(text:self.messageField.stringValue)
+        self.expandCall = try service.expand(requestMessage)
         self.displayMessageSent(requestMessage.text)
-        try! self.receiveExpandMessage()
+        try self.receiveExpandMessages()
       }
     }
     else if (self.callSelectButton.selectedSegment == 2) {
       // STREAMING COLLECT
       if (!nowStreaming) {
-        guard let service = service else {
-          return
-        }
-        collectCall = service.collect()
+        collectCall = try service.collect()
         nowStreaming = true
         closeButton.isEnabled = true
       }
@@ -185,11 +172,8 @@ class EchoViewController : NSViewController, NSTextFieldDelegate {
     else if (self.callSelectButton.selectedSegment == 3) {
       // STREAMING UPDATE
       if (!nowStreaming) {
-        guard let service = service else {
-          return
-        }
-        updateCall = service.update()
-        try self.receiveUpdateMessage()
+        updateCall = try service.update()
+        try self.receiveUpdateMessages()
         nowStreaming = true
         closeButton.isEnabled = true
       }
@@ -197,23 +181,21 @@ class EchoViewController : NSViewController, NSTextFieldDelegate {
     }
   }
 
-  func receiveExpandMessage() throws -> Void {
+  func receiveExpandMessages() throws -> Void {
     guard let expandCall = expandCall else {
       return
     }
     DispatchQueue.global().async {
       var running = true
       while running {
-        let result = expandCall.Receive()
-        switch result {
-        case .Response(let responseMessage):
+        do {
+          let responseMessage = try expandCall.Receive()
           self.displayMessageReceived(responseMessage.text)
-        case .CallResult(let result):
-          self.displayMessageReceived("No message received. \(result)")
+        } catch Echo_EchoClientError.endOfStream {
+          self.displayMessageReceived("Done.")
           running = false
-        case .Error(let error):
+        } catch (let error) {
           self.displayMessageReceived("No message received. \(error)")
-          running = false
         }
       }
     }
@@ -221,42 +203,37 @@ class EchoViewController : NSViewController, NSTextFieldDelegate {
 
   func sendCollectMessage() {
     if let collectCall = collectCall {
-      var requestMessage = Echo_EchoRequest()
-      requestMessage.text = self.messageField.stringValue
+      let requestMessage = Echo_EchoRequest(text:self.messageField.stringValue)
       self.displayMessageSent(requestMessage.text)
-      _ = collectCall.Send(requestMessage)
+      collectCall.Send(requestMessage)
     }
   }
 
   func sendUpdateMessage() {
     if let updateCall = updateCall {
-      var requestMessage = Echo_EchoRequest()
-      requestMessage.text = self.messageField.stringValue
+      let requestMessage = Echo_EchoRequest(text:self.messageField.stringValue)
       self.displayMessageSent(requestMessage.text)
-      _ = updateCall.Send(message:requestMessage)
+      updateCall.Send(requestMessage)
     }
   }
 
-  func receiveUpdateMessage() throws -> Void {
+  func receiveUpdateMessages() throws -> Void {
     guard let updateCall = updateCall else {
       return
     }
     DispatchQueue.global().async {
       var running = true
       while running {
-        let result = updateCall.Receive()
-        switch result {
-        case .Response(let responseMessage):
+        do {
+          let responseMessage = try updateCall.Receive()
           self.displayMessageReceived(responseMessage.text)
-        case .CallResult(let result):
-          self.displayMessageReceived("No message received. \(result)")
+        } catch Echo_EchoClientError.endOfStream {
+          self.displayMessageReceived("Done.")
           running = false
-        case .Error(let error):
+        } catch (let error) {
           self.displayMessageReceived("No message received. \(error)")
-          running = false
         }
       }
-
     }
   }
 
@@ -268,13 +245,10 @@ class EchoViewController : NSViewController, NSTextFieldDelegate {
       self.closeButton.isEnabled = false
     }
     if let collectCall = collectCall {
-      let result = collectCall.CloseAndReceive()
-      switch result {
-      case .Response(let responseMessage):
+      do {
+        let responseMessage = try collectCall.CloseAndReceive()
         self.displayMessageReceived(responseMessage.text)
-      case .CallResult(let result):
-        self.displayMessageReceived("No message received. \(result)")
-      case .Error(let error):
+      } catch (let error) {
         self.displayMessageReceived("No message received. \(error)")
       }
       self.collectCall = nil
@@ -283,6 +257,3 @@ class EchoViewController : NSViewController, NSTextFieldDelegate {
     }
   }
 }
-
-
-

+ 118 - 110
Examples/Echo/Swift/Echo/echo.client.pb.swift

@@ -36,12 +36,10 @@
 import Foundation
 import gRPC
 
-// this is probably going to go.
-public enum EchoResult {
-  case Response(r: Echo_EchoResponse)
-  // these last two should be merged
-  case CallResult(c: CallResult)
-  case Error(s: String)
+public enum Echo_EchoClientError : Error {
+  case endOfStream
+  case invalidMessageReceived
+  case error(c: CallResult)
 }
 
 //
@@ -54,24 +52,31 @@ public class Echo_EchoGetCall {
     self.call = channel.makeCall("/echo.Echo/Get")
   }
 
-  // Call this with the message to send,
-  // the callback will be called after the request is received.
-  fileprivate func perform(request: Echo_EchoRequest,
-                           callback:@escaping (EchoResult) -> Void)
-    -> Void {
-      let requestMessageData = try! request.serializeProtobuf()
-      let requestMetadata = Metadata()
-      try! call.perform(message: requestMessageData,
-                        metadata: requestMetadata)
-      {(callResult) in
-        print("Client received status \(callResult.statusCode) \(callResult.statusMessage!)")
-        if let messageData = callResult.resultData {
-          let responseMessage = try! Echo_EchoResponse(protobuf:messageData)
-          callback(EchoResult.Response(r: responseMessage))
-        } else {
-          callback(EchoResult.CallResult(c: callResult))
-        }
+  fileprivate func run(request: Echo_EchoRequest,
+                       metadata: Metadata) throws -> Echo_EchoResponse {
+    let done = NSCondition()
+    var callResult : CallResult!
+    var responseMessage : Echo_EchoResponse?
+    let requestMessageData = try! request.serializeProtobuf()
+    try! call.perform(message: requestMessageData,
+                      metadata: metadata)
+    {(_callResult) in
+      callResult = _callResult
+      if let messageData = callResult.resultData {
+        responseMessage = try? Echo_EchoResponse(protobuf:messageData)
       }
+      done.lock()
+      done.signal()
+      done.unlock()
+    }
+    done.lock()
+    done.wait()
+    done.unlock()
+    if let responseMessage = responseMessage {
+      return responseMessage
+    } else {
+      throw Echo_EchoClientError.error(c: callResult)
+    }
   }
 }
 
@@ -85,43 +90,42 @@ public class Echo_EchoExpandCall {
     self.call = channel.makeCall("/echo.Echo/Expand")
   }
 
-  // Call this once with the message to send,
-  // the callback will be called after the request is initiated.
-  fileprivate func perform(request: Echo_EchoRequest,
-                           callback:@escaping (CallResult) -> Void)
-    -> Void {
-      let requestMessageData = try! request.serializeProtobuf()
-      let requestMetadata = Metadata()
-      try! call.startServerStreaming(message: requestMessageData,
-                                     metadata: requestMetadata)
-      {(callResult) in
-        callback(callResult)
-      }
+  // Call this once with the message to send.
+  fileprivate func run(request: Echo_EchoRequest, metadata: Metadata) throws -> Echo_EchoExpandCall {
+    let requestMessageData = try! request.serializeProtobuf()
+    try! call.startServerStreaming(message: requestMessageData,
+                                   metadata: metadata,
+                                   completion:{(CallResult) in })
+    return self
   }
 
-  // Call this to wait for a result.
-  // BLOCKING
-  public func Receive() -> EchoResult {
+  // Call this to wait for a result. Blocks.
+  public func Receive() throws -> Echo_EchoResponse {
+    var returnError : Echo_EchoClientError?
+    var returnMessage : Echo_EchoResponse!
     let done = NSCondition()
-    var result : EchoResult!
-    try! call.receiveMessage() {(data) in
-      if let data = data {
-        if let responseMessage = try? Echo_EchoResponse(protobuf:data) {
-          result = EchoResult.Response(r: responseMessage)
+    do {
+      try call.receiveMessage() {(data) in
+        if let data = data {
+          returnMessage = try? Echo_EchoResponse(protobuf:data)
+          if returnMessage == nil {
+            returnError = Echo_EchoClientError.invalidMessageReceived
+          }
         } else {
-          result = EchoResult.Error(s: "INVALID RESPONSE")
+          returnError = Echo_EchoClientError.endOfStream
         }
-      } else {
-        result = EchoResult.Error(s: "EOM")
+        done.lock()
+        done.signal()
+        done.unlock()
       }
       done.lock()
-      done.signal()
+      done.wait()
       done.unlock()
     }
-    done.lock()
-    done.wait()
-    done.unlock()
-    return result
+    if let returnError = returnError {
+      throw returnError
+    }
+    return returnMessage
   }
 }
 
@@ -136,8 +140,9 @@ public class Echo_EchoCollectCall {
   }
 
   // Call this to start a call.
-  fileprivate func start(metadata:Metadata, completion:@escaping (() -> Void)) throws {
-    try self.call.start(metadata: metadata, completion:completion)
+  fileprivate func run(metadata:Metadata) throws -> Echo_EchoCollectCall {
+    try self.call.start(metadata: metadata, completion:{})
+    return self
   }
 
   // Call this to send each message in the request stream.
@@ -146,39 +151,37 @@ public class Echo_EchoCollectCall {
     _ = call.sendMessage(data:messageData)
   }
 
-  // Call this to close the connection and wait for a response.
-  // BLOCKING
-  public func CloseAndReceive() -> EchoResult {
+  // Call this to close the connection and wait for a response. Blocks.
+  public func CloseAndReceive() throws -> Echo_EchoResponse {
+    var returnError : Echo_EchoClientError?
+    var returnMessage : Echo_EchoResponse!
     let done = NSCondition()
-    var result : EchoResult!
 
     do {
       try self.receiveMessage() {(responseMessage) in
         if let responseMessage = responseMessage {
-          result = EchoResult.Response(r: responseMessage)
+          returnMessage = responseMessage
         } else {
-          result = EchoResult.Error(s: "INVALID RESPONSE")
+          returnError = Echo_EchoClientError.invalidMessageReceived
         }
         done.lock()
         done.signal()
         done.unlock()
       }
-    } catch (let error) {
-      print("ERROR A: \(error)")
-    }
-    do {
       try call.close(completion:{
         print("closed")
       })
+      done.lock()
+      done.wait()
+      done.unlock()
     } catch (let error) {
       print("ERROR B: \(error)")
     }
 
-    done.lock()
-    done.wait()
-    done.unlock()
-
-    return result
+    if let returnError = returnError {
+      throw returnError
+    }
+    return returnMessage
   }
 
   // Call this to receive a message.
@@ -212,8 +215,9 @@ public class Echo_EchoUpdateCall {
     self.call = channel.makeCall("/echo.Echo/Update")
   }
 
-  fileprivate func start(metadata:Metadata, completion:@escaping (() -> Void)) throws {
-    try self.call.start(metadata: metadata, completion:completion)
+  fileprivate func run(metadata:Metadata) throws -> Echo_EchoUpdateCall {
+    try self.call.start(metadata: metadata, completion:{})
+    return self
   }
 
   fileprivate func receiveMessage(callback:@escaping (Echo_EchoResponse?) throws -> Void) throws {
@@ -230,26 +234,35 @@ public class Echo_EchoUpdateCall {
     }
   }
 
-  public func Receive() -> EchoResult {
+  public func Receive() throws -> Echo_EchoResponse {
+    var returnError : Echo_EchoClientError?
+    var returnMessage : Echo_EchoResponse!
     let done = NSCondition()
-    var result : EchoResult!
-    try! self.receiveMessage() {responseMessage in
-      if let responseMessage = responseMessage {
-        result = EchoResult.Response(r: responseMessage)
-      } else {
-        result = EchoResult.Error(s: "EOM")
+    do {
+      try call.receiveMessage() {(data) in
+        if let data = data {
+          returnMessage = try? Echo_EchoResponse(protobuf:data)
+          if returnMessage == nil {
+            returnError = Echo_EchoClientError.invalidMessageReceived
+          }
+        } else {
+          returnError = Echo_EchoClientError.endOfStream
+        }
+        done.lock()
+        done.signal()
+        done.unlock()
       }
       done.lock()
-      done.signal()
+      done.wait()
       done.unlock()
     }
-    done.lock()
-    done.wait()
-    done.unlock()
-    return result
+    if let returnError = returnError {
+      throw returnError
+    }
+    return returnMessage
   }
 
-  public func Send(message:Echo_EchoRequest) {
+  public func Send(_ message:Echo_EchoRequest) {
     let messageData = try! message.serializeProtobuf()
     _ = call.sendMessage(data:messageData)
   }
@@ -269,59 +282,54 @@ public class Echo_EchoUpdateCall {
 
 // Call methods of this class to make API calls.
 public class Echo_EchoService {
-  public var channel: Channel
+  private var channel: Channel
+
+  public var metadata : Metadata
+
+  public var host : String {
+    get {
+      return self.channel.host
+    }
+    set {
+      self.channel.host = newValue
+    }
+  }
 
   public init(address: String) {
     gRPC.initialize()
     channel = Channel(address:address)
+    metadata = Metadata()
   }
 
   public init(address: String, certificates: String?, host: String?) {
     gRPC.initialize()
     channel = Channel(address:address, certificates:certificates, host:host)
+    metadata = Metadata()
   }
 
   // Synchronous. Unary.
-  public func get(_ requestMessage: Echo_EchoRequest) -> EchoResult {
-    let call = Echo_EchoGetCall(channel)
-    let done = NSCondition()
-    var finalResult : EchoResult!
-    call.perform(request:requestMessage) {(result) in
-      finalResult = result
-      done.lock()
-      done.signal()
-      done.unlock()
-    }
-    done.lock()
-    done.wait()
-    done.unlock()
-    return finalResult
+  public func get(_ request: Echo_EchoRequest) throws -> Echo_EchoResponse {
+    return try Echo_EchoGetCall(channel).run(request:request, metadata:metadata)
   }
 
   // Asynchronous. Server-streaming.
   // Send the initial message.
   // Use methods on the returned object to get streamed responses.
-  public func expand(_ requestMessage: Echo_EchoRequest) -> Echo_EchoExpandCall {
-    let call = Echo_EchoExpandCall(channel)
-    call.perform(request:requestMessage) {response in }
-    return call
+  public func expand(_ request: Echo_EchoRequest) throws -> Echo_EchoExpandCall {
+    return try Echo_EchoExpandCall(channel).run(request:request, metadata:metadata)
   }
 
   // Asynchronous. Client-streaming.
   // Use methods on the returned object to stream messages and
   // to close the connection and wait for a final response.
-  public func collect() -> Echo_EchoCollectCall {
-    let call = Echo_EchoCollectCall(channel)
-    try! call.start(metadata:Metadata(), completion:{})
-    return call
+  public func collect() throws -> Echo_EchoCollectCall {
+    return try Echo_EchoCollectCall(channel).run(metadata:metadata)
   }
 
   // Asynchronous. Bidirectional-streaming.
   // Use methods on the returned object to stream messages,
   // to wait for replies, and to close the connection.
-  public func update() -> Echo_EchoUpdateCall {
-    let call = Echo_EchoUpdateCall(channel)
-    try! call.start(metadata:Metadata(), completion:{})
-    return call
+  public func update() throws -> Echo_EchoUpdateCall {
+    return try Echo_EchoUpdateCall(channel).run(metadata:metadata)
   }
 }

+ 8 - 8
Examples/Echo/Swift/Echo/echo.server.pb.swift

@@ -41,10 +41,10 @@ public enum Echo_EchoServerError : Error {
 }
 
 public protocol Echo_EchoProvider {
-  func Get(request : Echo_EchoRequest) throws -> Echo_EchoResponse
-  func Collect(session : Echo_EchoCollectSession) throws -> Void
-  func Expand(request : Echo_EchoRequest, session : Echo_EchoExpandSession) throws -> Void
-  func Update(session : Echo_EchoUpdateSession) throws -> Void
+  func get(request : Echo_EchoRequest) throws -> Echo_EchoResponse
+  func collect(session : Echo_EchoCollectSession) throws
+  func expand(request : Echo_EchoRequest, session : Echo_EchoExpandSession) throws
+  func update(session : Echo_EchoUpdateSession) throws
 }
 
 // unary
@@ -62,7 +62,7 @@ public class Echo_EchoGetSession {
       try handler.receiveMessage(initialMetadata:Metadata()) {(requestData) in
         if let requestData = requestData {
           let requestMessage = try! Echo_EchoRequest(protobuf:requestData)
-          let replyMessage = try! self.provider.Get(request:requestMessage)
+          let replyMessage = try! self.provider.get(request:requestMessage)
           try self.handler.sendResponse(message:replyMessage.serializeProtobuf(),
                                         statusCode: 0,
                                         statusMessage: "OK",
@@ -98,7 +98,7 @@ public class Echo_EchoExpandSession {
           // to keep providers from blocking the server thread,
           // we dispatch them to another queue.
           queue.async {
-            try! self.provider.Expand(request:requestMessage, session: self)
+            try! self.provider.expand(request:requestMessage, session: self)
             try! self.handler.sendStatus(statusCode:0,
                                          statusMessage:"OK",
                                          trailingMetadata:Metadata(),
@@ -156,7 +156,7 @@ public class Echo_EchoCollectSession {
       print("EchoCollectSession run")
       try self.handler.sendMetadata(initialMetadata:Metadata()) {
         queue.async {
-          try! self.provider.Collect(session:self)
+          try! self.provider.collect(session:self)
         }
       }
     } catch (let callError) {
@@ -219,7 +219,7 @@ public class Echo_EchoUpdateSession {
     do {
       try self.handler.sendMetadata(initialMetadata:Metadata()) {
         queue.async {
-          try! self.provider.Update(session:self)
+          try! self.provider.update(session:self)
         }
       }
     } catch (let callError) {