2
0

main.swift 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  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. import Dispatch
  17. import Foundation
  18. import GRPC
  19. import NIO
  20. import NIOHPACK
  21. import NIOHTTP1
  22. import NIOSSL
  23. import OAuth2
  24. /// Create a client and return a future to provide its value.
  25. func makeServiceClient(
  26. host: String,
  27. port: Int,
  28. eventLoopGroup: MultiThreadedEventLoopGroup
  29. ) -> Google_Cloud_Language_V1_LanguageServiceNIOClient {
  30. let connection = ClientConnection.usingPlatformAppropriateTLS(for: eventLoopGroup)
  31. .connect(host: host, port: port)
  32. return Google_Cloud_Language_V1_LanguageServiceNIOClient(channel: connection)
  33. }
  34. enum AuthError: Error {
  35. case noTokenProvider
  36. case tokenProviderFailed
  37. }
  38. /// Get an auth token and return a future to provide its value.
  39. func getAuthToken(
  40. scopes: [String],
  41. eventLoop: EventLoop
  42. ) -> EventLoopFuture<String> {
  43. let promise = eventLoop.makePromise(of: String.self)
  44. guard let provider = DefaultTokenProvider(scopes: scopes) else {
  45. promise.fail(AuthError.noTokenProvider)
  46. return promise.futureResult
  47. }
  48. do {
  49. try provider.withToken { token, error in
  50. if let token = token,
  51. let accessToken = token.AccessToken {
  52. promise.succeed(accessToken)
  53. } else if let error = error {
  54. promise.fail(error)
  55. } else {
  56. promise.fail(AuthError.tokenProviderFailed)
  57. }
  58. }
  59. } catch {
  60. promise.fail(error)
  61. }
  62. return promise.futureResult
  63. }
  64. /// Main program. Make a sample API request.
  65. do {
  66. let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  67. // Get an auth token.
  68. let scopes = ["https://www.googleapis.com/auth/cloud-language"]
  69. let authToken = try getAuthToken(
  70. scopes: scopes,
  71. eventLoop: eventLoopGroup.next()
  72. ).wait()
  73. // Create a service client.
  74. let service = makeServiceClient(
  75. host: "language.googleapis.com",
  76. port: 443,
  77. eventLoopGroup: eventLoopGroup
  78. )
  79. // Use CallOptions to send the auth token (necessary) and set a custom timeout (optional).
  80. let headers: HPACKHeaders = ["authorization": "Bearer \(authToken)"]
  81. let callOptions = CallOptions(customMetadata: headers, timeLimit: TimeLimit.timeout(.seconds(30)))
  82. print("CALL OPTIONS\n\(callOptions)\n")
  83. // Construct the API request.
  84. let request = Google_Cloud_Language_V1_AnnotateTextRequest.with {
  85. $0.document = .with {
  86. $0.type = .plainText
  87. $0
  88. .content =
  89. "The Caterpillar and Alice looked at each other for some time in silence: at last the Caterpillar took the hookah out of its mouth, and addressed her in a languid, sleepy voice. `Who are you?' said the Caterpillar."
  90. }
  91. $0.features = .with {
  92. $0.extractSyntax = true
  93. $0.extractEntities = true
  94. $0.extractDocumentSentiment = true
  95. $0.extractEntitySentiment = true
  96. $0.classifyText = true
  97. }
  98. }
  99. print("REQUEST MESSAGE\n\(request)")
  100. // Create/start the API call.
  101. let call = service.annotateText(request, callOptions: callOptions)
  102. call.response.whenSuccess { response in
  103. print("CALL SUCCEEDED WITH RESPONSE\n\(response)")
  104. }
  105. call.response.whenFailure { error in
  106. print("CALL FAILED WITH ERROR\n\(error)")
  107. }
  108. // wait() on the status to stop the program from exiting.
  109. let status = try call.status.wait()
  110. print("CALL STATUS\n\(status)")
  111. } catch {
  112. print("EXAMPLE FAILED WITH ERROR\n\(error)")
  113. }