Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reformat async code #1383

Merged
merged 2 commits into from
Apr 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
- uses: actions/checkout@v2
- name: "Formatting and License Headers check"
run: |
SWIFTFORMAT_VERSION=0.46.3
SWIFTFORMAT_VERSION=0.49.4
git clone --depth 1 --branch "$SWIFTFORMAT_VERSION" "https://github.com/nicklockwood/SwiftFormat" "$HOME/SwiftFormat"
swift build --package-path "$HOME/SwiftFormat" --product swiftformat
export PATH=$PATH:"$(swift build --package-path "$HOME/SwiftFormat" --show-bin-path)"
Expand Down
3 changes: 3 additions & 0 deletions .swiftformat
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,6 @@

# Don't prefer using key paths for trivial closures.
--disable preferKeyPath

# Put ACLs on declarations within an extension rather than the extension itself.
--extensionacl on-declarations
2 changes: 1 addition & 1 deletion Examples/Google/NaturalLanguage/Sources/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func getAuthToken(
do {
try provider.withToken { token, error in
if let token = token,
let accessToken = token.AccessToken {
let accessToken = token.AccessToken {
promise.succeed(accessToken)
} else if let error = error {
promise.fail(error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
self.navController?.navigationBar.prefersLargeTitles = false

let viewController: UIViewController = ViewController()
navController?.pushViewController(viewController, animated: false)
self.navController?.pushViewController(viewController, animated: false)

self.window = UIWindow(windowScene: windowScene)
self.window!.rootViewController = self.navController
Expand Down
6 changes: 4 additions & 2 deletions Examples/Google/SpeechToText/Sources/SpeechService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,10 @@ final class SpeechService {
)
}

func stream(_ data: Data,
completion: ((Google_Cloud_Speech_V1_StreamingRecognizeResponse) -> Void)? = nil) {
func stream(
_ data: Data,
completion: ((Google_Cloud_Speech_V1_StreamingRecognizeResponse) -> Void)? = nil
) {
switch self.state {
case .idle:
// Initialize the bidirectional stream
Expand Down
6 changes: 4 additions & 2 deletions Examples/Google/SpeechToText/Sources/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ final class ViewController: UIViewController {
private let speechService: SpeechService
private let audioStreamManager: AudioStreamManager

init(speechService: SpeechService,
audioStreamManager: AudioStreamManager) {
init(
speechService: SpeechService,
audioStreamManager: AudioStreamManager
) {
self.speechService = speechService
self.audioStreamManager = audioStreamManager

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,13 @@ final class AsyncPingPongRequestMaker: RequestMaker {
/// - requestMessage: Pre-made request message to use possibly repeatedly.
/// - logger: Where to log useful diagnostics.
/// - stats: Where to record statistics on latency.
init(config: Grpc_Testing_ClientConfig,
client: Grpc_Testing_BenchmarkServiceClient,
requestMessage: Grpc_Testing_SimpleRequest,
logger: Logger,
stats: StatsWithLock) {
init(
config: Grpc_Testing_ClientConfig,
client: Grpc_Testing_BenchmarkServiceClient,
requestMessage: Grpc_Testing_SimpleRequest,
logger: Logger,
stats: StatsWithLock
) {
self.client = client
self.requestMessage = requestMessage
self.logger = logger
Expand All @@ -70,7 +72,7 @@ final class AsyncPingPongRequestMaker: RequestMaker {
let endTime = grpcTimeNow()
self.stats.add(latency: endTime - startTime)
if !self.stopRequested,
self.messagesPerStream == 0 || messagesSent < self.messagesPerStream {
self.messagesPerStream == 0 || messagesSent < self.messagesPerStream {
messagesSent += 1
startTime = endTime // Use end of previous request as the start of the next.
streamingCall!.sendMessage(self.requestMessage, promise: nil)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,13 @@ final class AsyncUnaryRequestMaker: RequestMaker {
/// - requestMessage: Pre-made request message to use possibly repeatedly.
/// - logger: Where to log useful diagnostics.
/// - stats: Where to record statistics on latency.
init(config: Grpc_Testing_ClientConfig,
client: Grpc_Testing_BenchmarkServiceClient,
requestMessage: Grpc_Testing_SimpleRequest,
logger: Logger,
stats: StatsWithLock) {
init(
config: Grpc_Testing_ClientConfig,
client: Grpc_Testing_BenchmarkServiceClient,
requestMessage: Grpc_Testing_SimpleRequest,
logger: Logger,
stats: StatsWithLock
) {
self.client = client
self.requestMessage = requestMessage
self.logger = logger
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ final class AsyncQPSServerImpl: Grpc_Testing_BenchmarkServiceProvider {

/// One request followed by one response.
/// The server returns the client payload as-is.
func unaryCall(request: Grpc_Testing_SimpleRequest,
context: StatusOnlyCallContext) -> EventLoopFuture<Grpc_Testing_SimpleResponse> {
func unaryCall(
request: Grpc_Testing_SimpleRequest,
context: StatusOnlyCallContext
) -> EventLoopFuture<Grpc_Testing_SimpleResponse> {
do {
return context.eventLoop
.makeSucceededFuture(try AsyncQPSServerImpl.processSimpleRPC(request: request))
Expand Down Expand Up @@ -93,8 +95,10 @@ final class AsyncQPSServerImpl: Grpc_Testing_BenchmarkServiceProvider {
}

/// Make a payload for sending back to the client.
private static func makePayload(type: Grpc_Testing_PayloadType,
size: Int) throws -> Grpc_Testing_Payload {
private static func makePayload(
type: Grpc_Testing_PayloadType,
size: Int
) throws -> Grpc_Testing_Payload {
if type != .compressable {
// Making a payload which is not compressable is hard - and not implemented in
// other implementations too.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ protocol RequestMaker {
/// - requestMessage: Pre-made request message to use possibly repeatedly.
/// - logger: Where to log useful diagnostics.
/// - stats: Where to record statistics on latency.
init(config: Grpc_Testing_ClientConfig,
client: Grpc_Testing_BenchmarkServiceClient,
requestMessage: Grpc_Testing_SimpleRequest,
logger: Logger,
stats: StatsWithLock)
init(
config: Grpc_Testing_ClientConfig,
client: Grpc_Testing_BenchmarkServiceClient,
requestMessage: Grpc_Testing_SimpleRequest,
logger: Logger,
stats: StatsWithLock
)

/// Initiate a request sequence to the server.
/// - returns: A future which completes when the request-response sequence is complete.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ extension StatusCounts {
/// Convert status count to a protobuf for sending to the driver process.
/// - returns: The protobuf message for sending.
public func toRequestResultCounts() -> [Grpc_Testing_RequestResultCount] {
return counts.map { (key, value) -> Grpc_Testing_RequestResultCount in
return counts.map { key, value -> Grpc_Testing_RequestResultCount in
var grpc = Grpc_Testing_RequestResultCount()
grpc.count = value
grpc.statusCode = Int32(key)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,20 @@ class WorkerServiceImpl: Grpc_Testing_WorkerServiceProvider {
}

/// Just return the core count - unary call
func coreCount(request: Grpc_Testing_CoreRequest,
context: StatusOnlyCallContext) -> EventLoopFuture<Grpc_Testing_CoreResponse> {
func coreCount(
request: Grpc_Testing_CoreRequest,
context: StatusOnlyCallContext
) -> EventLoopFuture<Grpc_Testing_CoreResponse> {
context.logger.notice("coreCount queried")
let cores = Grpc_Testing_CoreResponse.with { $0.cores = Int32(System.coreCount) }
return context.eventLoop.makeSucceededFuture(cores)
}

/// Quit this worker
func quitWorker(request: Grpc_Testing_Void,
context: StatusOnlyCallContext) -> EventLoopFuture<Grpc_Testing_Void> {
func quitWorker(
request: Grpc_Testing_Void,
context: StatusOnlyCallContext
) -> EventLoopFuture<Grpc_Testing_Void> {
context.logger.warning("quitWorker called")
self.finishedPromise.succeed(())
return context.eventLoop.makeSucceededFuture(Grpc_Testing_Void())
Expand All @@ -109,8 +113,10 @@ class WorkerServiceImpl: Grpc_Testing_WorkerServiceProvider {

/// Handle a request to setup a server.
/// Makes a new server and sets it running.
private func handleServerSetup(context: StreamingResponseCallContext<Grpc_Testing_ServerStatus>,
config: Grpc_Testing_ServerConfig) {
private func handleServerSetup(
context: StreamingResponseCallContext<Grpc_Testing_ServerStatus>,
config: Grpc_Testing_ServerConfig
) {
context.logger.info("server setup requested")
guard self.runningServer == nil else {
context.logger.error("server already running")
Expand Down Expand Up @@ -159,8 +165,10 @@ class WorkerServiceImpl: Grpc_Testing_WorkerServiceProvider {
// MARK: Create Server

/// Start a server running of the requested type.
private func runServerBody(context: StreamingResponseCallContext<Grpc_Testing_ServerStatus>,
serverConfig: Grpc_Testing_ServerConfig) {
private func runServerBody(
context: StreamingResponseCallContext<Grpc_Testing_ServerStatus>,
serverConfig: Grpc_Testing_ServerConfig
) {
var serverConfig = serverConfig
self.serverPortOverride.map { serverConfig.port = Int32($0) }

Expand Down Expand Up @@ -228,8 +236,10 @@ class WorkerServiceImpl: Grpc_Testing_WorkerServiceProvider {
}

/// Setup a client as described by the message from the driver.
private func handleClientSetup(context: StreamingResponseCallContext<Grpc_Testing_ClientStatus>,
config: Grpc_Testing_ClientConfig) {
private func handleClientSetup(
context: StreamingResponseCallContext<Grpc_Testing_ClientStatus>,
config: Grpc_Testing_ClientConfig
) {
context.logger.info("client setup requested")
guard self.runningClient == nil else {
context.logger.error("client already running")
Expand Down Expand Up @@ -282,8 +292,10 @@ class WorkerServiceImpl: Grpc_Testing_WorkerServiceProvider {
// MARK: Create Client

/// Setup and run a client of the requested type.
private func runClientBody(context: StreamingResponseCallContext<Grpc_Testing_ClientStatus>,
clientConfig: Grpc_Testing_ClientConfig) {
private func runClientBody(
context: StreamingResponseCallContext<Grpc_Testing_ClientStatus>,
clientConfig: Grpc_Testing_ClientConfig
) {
do {
self.runningClient = try WorkerServiceImpl.makeClient(
context: context,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ private func degreesToRadians(_ degrees: Double) -> Double {
}

extension Routeguide_Point {
func distance(to other: Routeguide_Point) -> Double {
fileprivate func distance(to other: Routeguide_Point) -> Double {
// Radius of Earth in meters
let radius = 6_371_000.0
// Points are in the E7 representation (degrees multiplied by 10**7 and rounded to the nearest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ public struct GRPCAsyncBidirectionalStreamingCall<Request: Sendable, Response: S
/// received. However, it is not necessary for the response to have been consumed before reading
/// this property.
public var initialMetadata: HPACKHeaders {
// swiftformat:disable:next redundantGet
get async throws {
try await self.responseParts.initialMetadata.get()
}
Expand All @@ -58,7 +57,6 @@ public struct GRPCAsyncBidirectionalStreamingCall<Request: Sendable, Response: S
///
/// - Important: Awaiting this property will suspend until the responses have been consumed.
public var trailingMetadata: HPACKHeaders {
// swiftformat:disable:next redundantGet
get async throws {
try await self.responseParts.trailingMetadata.get()
}
Expand All @@ -68,7 +66,6 @@ public struct GRPCAsyncBidirectionalStreamingCall<Request: Sendable, Response: S
///
/// - Important: Awaiting this property will suspend until the responses have been consumed.
public var status: GRPCStatus {
// swiftformat:disable:next redundantGet
get async {
// force-try acceptable because any error is encapsulated in a successful GRPCStatus future.
try! await self.responseParts.status.get()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,13 @@ public struct GRPCAsyncClientStreamingCall<Request: Sendable, Response: Sendable
///
/// - Important: The initial metadata will only be available when the response has been received.
public var initialMetadata: HPACKHeaders {
// swiftformat:disable:next redundantGet
get async throws {
try await self.responseParts.initialMetadata.get()
}
}

/// The response returned by the server.
public var response: Response {
// swiftformat:disable:next redundantGet
get async throws {
try await self.responseParts.response.get()
}
Expand All @@ -60,7 +58,6 @@ public struct GRPCAsyncClientStreamingCall<Request: Sendable, Response: Sendable
///
/// - Important: Awaiting this property will suspend until the responses have been consumed.
public var trailingMetadata: HPACKHeaders {
// swiftformat:disable:next redundantGet
get async throws {
try await self.responseParts.trailingMetadata.get()
}
Expand All @@ -70,7 +67,6 @@ public struct GRPCAsyncClientStreamingCall<Request: Sendable, Response: Sendable
///
/// - Important: Awaiting this property will suspend until the responses have been consumed.
public var status: GRPCStatus {
// swiftformat:disable:next redundantGet
get async {
// force-try acceptable because any error is encapsulated in a successful GRPCStatus future.
try! await self.responseParts.status.get()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ extension GRPCAsyncRequestStreamWriter {
internal let _compressionEnabled: Bool

@usableFromInline
internal let _send: @Sendable(Request, MessageMetadata) -> Void
internal let _send: @Sendable (Request, MessageMetadata) -> Void

@usableFromInline
internal let _finish: @Sendable() -> Void
internal let _finish: @Sendable () -> Void

@inlinable
internal init(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ internal final class AsyncResponseStreamWriterDelegate<Response: Sendable>: Asyn
internal let _context: GRPCAsyncServerCallContext

@usableFromInline
internal let _send: @Sendable(Response, MessageMetadata) -> Void
internal let _send: @Sendable (Response, MessageMetadata) -> Void

@usableFromInline
internal let _finish: @Sendable(GRPCStatus) -> Void
internal let _finish: @Sendable (GRPCStatus) -> Void

@usableFromInline
internal let _compressionEnabledOnServer: Bool
Expand All @@ -70,8 +70,8 @@ internal final class AsyncResponseStreamWriterDelegate<Response: Sendable>: Asyn
internal init(
context: GRPCAsyncServerCallContext,
compressionIsEnabled: Bool,
send: @escaping @Sendable(Response, MessageMetadata) -> Void,
finish: @escaping @Sendable(GRPCStatus) -> Void
send: @escaping @Sendable (Response, MessageMetadata) -> Void,
finish: @escaping @Sendable (GRPCStatus) -> Void
) {
self._context = context
self._compressionEnabledOnServer = compressionIsEnabled
Expand Down
12 changes: 6 additions & 6 deletions Sources/GRPC/AsyncAwaitSupport/GRPCAsyncServerHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ extension GRPCAsyncServerHandler {
requestDeserializer: Deserializer,
responseSerializer: Serializer,
interceptors: [ServerInterceptor<Request, Response>],
wrapping unary: @escaping @Sendable(Request, GRPCAsyncServerCallContext) async throws
wrapping unary: @escaping @Sendable (Request, GRPCAsyncServerCallContext) async throws
-> Response
) {
self._handler = .init(
Expand All @@ -85,7 +85,7 @@ extension GRPCAsyncServerHandler {
requestDeserializer: Deserializer,
responseSerializer: Serializer,
interceptors: [ServerInterceptor<Request, Response>],
wrapping clientStreaming: @escaping @Sendable(
wrapping clientStreaming: @escaping @Sendable (
GRPCAsyncRequestStream<Request>,
GRPCAsyncServerCallContext
) async throws -> Response
Expand All @@ -108,7 +108,7 @@ extension GRPCAsyncServerHandler {
requestDeserializer: Deserializer,
responseSerializer: Serializer,
interceptors: [ServerInterceptor<Request, Response>],
wrapping serverStreaming: @escaping @Sendable(
wrapping serverStreaming: @escaping @Sendable (
Request,
GRPCAsyncResponseStreamWriter<Response>,
GRPCAsyncServerCallContext
Expand All @@ -135,7 +135,7 @@ extension GRPCAsyncServerHandler {
requestDeserializer: Deserializer,
responseSerializer: Serializer,
interceptors: [ServerInterceptor<Request, Response>],
wrapping bidirectional: @escaping @Sendable(
wrapping bidirectional: @escaping @Sendable (
GRPCAsyncRequestStream<Request>,
GRPCAsyncResponseStreamWriter<Response>,
GRPCAsyncServerCallContext
Expand Down Expand Up @@ -181,7 +181,7 @@ internal final class AsyncServerHandler<

/// The user provided function to execute.
@usableFromInline
internal let userHandler: @Sendable(
internal let userHandler: @Sendable (
GRPCAsyncRequestStream<Request>,
GRPCAsyncResponseStreamWriter<Response>,
GRPCAsyncServerCallContext
Expand Down Expand Up @@ -263,7 +263,7 @@ internal final class AsyncServerHandler<
requestDeserializer: Deserializer,
responseSerializer: Serializer,
interceptors: [ServerInterceptor<Request, Response>],
userHandler: @escaping @Sendable(
userHandler: @escaping @Sendable (
GRPCAsyncRequestStream<Request>,
GRPCAsyncResponseStreamWriter<Response>,
GRPCAsyncServerCallContext
Expand Down
Loading