Skip to content

Commit 30aa585

Browse files
authored
perf(bigquery): run statements through jobs.query (#4352)
1 parent 8c024dd commit 30aa585

14 files changed

Lines changed: 1885 additions & 107 deletions
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import Foundation
2+
3+
public enum GoogleAccessTokenWait {
4+
// A cancelled caller stops waiting; the fetch, which other callers may share, runs on to its end.
5+
public static func token(from provider: any GoogleAccessTokenProviding) async throws -> String {
6+
let wait = TokenWait(provider: provider)
7+
return try await withTaskCancellationHandler {
8+
try await withCheckedThrowingContinuation { caller in
9+
wait.start(caller: caller)
10+
}
11+
} onCancel: {
12+
wait.cancel()
13+
}
14+
}
15+
}
16+
17+
private final class TokenWait: @unchecked Sendable {
18+
typealias Caller = CheckedContinuation<String, any Error>
19+
20+
private enum Stage {
21+
case notStarted
22+
case cancelledBeforeStart
23+
case waiting(Caller)
24+
case finished
25+
}
26+
27+
private let provider: any GoogleAccessTokenProviding
28+
private let lock = NSLock()
29+
private var stage = Stage.notStarted
30+
31+
init(provider: any GoogleAccessTokenProviding) {
32+
self.provider = provider
33+
}
34+
35+
func start(caller waiting: Caller) {
36+
let launches: Bool = lock.withLock {
37+
switch stage {
38+
case .notStarted:
39+
stage = .waiting(waiting)
40+
return true
41+
case .cancelledBeforeStart:
42+
stage = .finished
43+
return false
44+
case .waiting, .finished:
45+
return false
46+
}
47+
}
48+
guard launches else {
49+
waiting.resume(throwing: CancellationError())
50+
return
51+
}
52+
Task { [provider] in
53+
let result: Result<String, any Error>
54+
do {
55+
result = .success(try await provider.accessToken())
56+
} catch {
57+
result = .failure(error)
58+
}
59+
self.finish(with: result)
60+
}
61+
}
62+
63+
func cancel() {
64+
let waiting: Caller? = lock.withLock {
65+
switch stage {
66+
case .notStarted:
67+
stage = .cancelledBeforeStart
68+
return nil
69+
case .waiting(let caller):
70+
stage = .finished
71+
return caller
72+
case .cancelledBeforeStart, .finished:
73+
return nil
74+
}
75+
}
76+
waiting?.resume(throwing: CancellationError())
77+
}
78+
79+
private func finish(with result: Result<String, any Error>) {
80+
let waiting: Caller? = lock.withLock {
81+
guard case .waiting(let caller) = stage else { return nil }
82+
stage = .finished
83+
return caller
84+
}
85+
waiting?.resume(with: result)
86+
}
87+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import Foundation
2+
3+
public enum BigQueryRequestLoop {
4+
public struct Answer: Sendable {
5+
public let status: Int
6+
public let data: Data
7+
8+
public init(status: Int, data: Data) {
9+
self.status = status
10+
self.data = data
11+
}
12+
}
13+
14+
public static let rateLimitRetries = 3
15+
private static let unauthorizedStatus = 401
16+
private static let rateLimitedStatus = 429
17+
18+
// Nil when Stop came before a send. Stop is read again after the token fetch, which can take a round trip.
19+
public static func run<Token>(
20+
signals: BigQueryRequestSignals,
21+
authorize: () async throws -> Token,
22+
send: (Token) async throws -> Answer,
23+
refreshToken: () async -> Void,
24+
backoff: (Int) async throws -> Void
25+
) async throws -> Answer? {
26+
var rateLimitAttempt = 0
27+
var refreshedToken = false
28+
while true {
29+
guard !signals.isStopped() else { return nil }
30+
let token = try await authorize()
31+
guard signals.beginAttempt() else { return nil }
32+
let answer = try await send(token)
33+
if answer.status == unauthorizedStatus, !refreshedToken {
34+
refreshedToken = true
35+
await refreshToken()
36+
} else if answer.status == rateLimitedStatus, rateLimitAttempt < rateLimitRetries {
37+
rateLimitAttempt += 1
38+
try await backoff(rateLimitAttempt)
39+
} else {
40+
return answer
41+
}
42+
}
43+
}
44+
}
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import Foundation
2+
3+
public enum BigQueryStatementPolicy {
4+
public static let jobCreationMode = "JOB_CREATION_OPTIONAL"
5+
6+
// A stopped statement's job reference arrives within this wait, so its cancel can follow.
7+
public static let serverWaitMilliseconds = 2_000
8+
9+
public static let stopGrace: Duration = .seconds(1)
10+
11+
public static let stoppedRequestLimit: Duration = .seconds(10)
12+
13+
// The server caps an answer at 10 MB.
14+
public static let answerByteLimit = 32 * 1_024 * 1_024
15+
16+
// jobs.query answers a statement the server refuses with these, where jobs.insert reported them on the job.
17+
public static func isStatementRefusal(status: Int) -> Bool {
18+
status == 400 || status == 403 || status == 404 || status == 409
19+
}
20+
}
21+
22+
public struct BigQueryStatementRequest<Parameter: Encodable & Sendable>: Encodable, Sendable {
23+
public struct Dataset: Encodable, Sendable {
24+
public let projectId: String
25+
public let datasetId: String
26+
27+
public init(projectId: String, datasetId: String) {
28+
self.projectId = projectId
29+
self.datasetId = datasetId
30+
}
31+
}
32+
33+
public let query: String
34+
public let useLegacySql: Bool
35+
public let jobCreationMode: String
36+
// A retry with the same id returns the first request's statement instead of running it again.
37+
public let requestId: String
38+
public let maxResults: Int
39+
public let timeoutMs: Int
40+
public let location: String?
41+
public let defaultDataset: Dataset?
42+
public let maximumBytesBilled: String?
43+
public let parameterMode: String?
44+
public let queryParameters: [Parameter]?
45+
public let jobTimeoutMs: String?
46+
47+
public init(
48+
query: String,
49+
requestId: String,
50+
maxResults: Int,
51+
location: String?,
52+
defaultDataset: Dataset?,
53+
maximumBytesBilled: String?,
54+
parameterMode: String?,
55+
queryParameters: [Parameter]?,
56+
jobTimeoutMs: String?
57+
) {
58+
self.query = query
59+
self.useLegacySql = false
60+
self.jobCreationMode = BigQueryStatementPolicy.jobCreationMode
61+
self.requestId = requestId
62+
self.maxResults = maxResults
63+
self.timeoutMs = BigQueryStatementPolicy.serverWaitMilliseconds
64+
self.location = location
65+
self.defaultDataset = defaultDataset
66+
self.maximumBytesBilled = maximumBytesBilled
67+
self.parameterMode = parameterMode
68+
self.queryParameters = queryParameters
69+
self.jobTimeoutMs = jobTimeoutMs
70+
}
71+
}
72+
73+
public enum BigQueryStatementProgress: Equatable, Sendable {
74+
case finished(jobId: String?)
75+
case running(jobId: String)
76+
case unreadable
77+
78+
// A statement that finished without a job cannot page, so a page token with no job cannot be followed.
79+
public init(jobComplete: Bool?, jobId: String?, pageToken: String?) {
80+
if jobComplete == false {
81+
self = jobId.map { .running(jobId: $0) } ?? .unreadable
82+
} else if jobId == nil, pageToken != nil {
83+
self = .unreadable
84+
} else {
85+
self = .finished(jobId: jobId)
86+
}
87+
}
88+
89+
public static func jobToCancel(jobComplete: Bool?, jobId: String?) -> String? {
90+
guard case .running(let jobId) = BigQueryStatementProgress(jobComplete: jobComplete, jobId: jobId, pageToken: nil)
91+
else { return nil }
92+
return jobId
93+
}
94+
}

0 commit comments

Comments
 (0)