Skip to content

Commit 42d81bf

Browse files
committed
Add timeout to accept suggestion
1 parent 6e78f06 commit 42d81bf

File tree

1 file changed

+39
-7
lines changed

1 file changed

+39
-7
lines changed

EditorExtension/AcceptSuggestionCommand.swift

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,15 @@ class AcceptSuggestionCommand: NSObject, XCSourceEditorCommand, CommandType {
1313
) {
1414
Task {
1515
do {
16-
let service = try getService()
17-
if let content = try await service.getSuggestionAcceptedCode(
18-
editorContent: .init(invocation)
19-
) {
20-
invocation.accept(content)
21-
}
22-
completionHandler(nil)
16+
try await (Task(timeout: 7) {
17+
let service = try getService()
18+
if let content = try await service.getSuggestionAcceptedCode(
19+
editorContent: .init(invocation)
20+
) {
21+
invocation.accept(content)
22+
}
23+
completionHandler(nil)
24+
}.value)
2325
} catch is CancellationError {
2426
completionHandler(nil)
2527
} catch {
@@ -28,3 +30,33 @@ class AcceptSuggestionCommand: NSObject, XCSourceEditorCommand, CommandType {
2830
}
2931
}
3032
}
33+
34+
/// https://gist.github.com/swhitty/9be89dfe97dbb55c6ef0f916273bbb97
35+
extension Task where Failure == Error {
36+
// Start a new Task with a timeout. If the timeout expires before the operation is
37+
// completed then the task is cancelled and an error is thrown.
38+
init(
39+
priority: TaskPriority? = nil,
40+
timeout: TimeInterval,
41+
operation: @escaping @Sendable () async throws -> Success
42+
) {
43+
self = Task(priority: priority) {
44+
try await withThrowingTaskGroup(of: Success.self) { group -> Success in
45+
group.addTask(operation: operation)
46+
group.addTask {
47+
try await _Concurrency.Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
48+
throw TimeoutError()
49+
}
50+
guard let success = try await group.next() else {
51+
throw _Concurrency.CancellationError()
52+
}
53+
group.cancelAll()
54+
return success
55+
}
56+
}
57+
}
58+
}
59+
60+
private struct TimeoutError: LocalizedError {
61+
var errorDescription: String? = "Task timed out before completion"
62+
}

0 commit comments

Comments
 (0)