-
Notifications
You must be signed in to change notification settings - Fork 2
Replace polling with database-tick waits in PlatformAPI #88
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
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
f2651bc
1
KishanBagaria fa29fdf
harden database-tick waits: backstop, graceful watcher fallback, canc…
KishanBagaria 3fbb0e4
ensureDatabase: skip redundant cache write on hits
indent[bot] 737c1fa
address code review: backstop/cancellation tests, idempotent watcher …
KishanBagaria 9343d8c
fix concurrent change-listener setup race and unstarted-watcher cleanup
KishanBagaria a375898
fix database listener teardown
KishanBagaria d04d9dc
-
KishanBagaria fb3344c
$compound-engineering:ce-simplify-code
KishanBagaria 47f6850
Update todos.md
KishanBagaria 493aae7
fix(imdatabase): retry missing database file watchers
KishanBagaria c76a431
fix(platform): retry database change listener startup
KishanBagaria acb5d46
refactor(platform): collapse listener setup retry state
KishanBagaria 9da67ee
simplify
KishanBagaria File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| import Foundation | ||
| import IMDatabase | ||
| import IMessageCore | ||
| import PlatformSDK | ||
|
|
||
| private let sentMessageLinkWaitTimeout: TimeInterval = 1.5 | ||
|
|
||
| // Re-query at least this often even without a tick: FSEvents notifications can be | ||
| // dropped or coalesced, so a missed tick costs ~1s instead of the full timeout. | ||
| private let databaseTickBackstopInterval: TimeInterval = 1.0 | ||
| private let loadedAttachmentMinimumRequeryInterval: TimeInterval = 0.25 | ||
|
|
||
| enum DatabaseTickWaits { | ||
| typealias SentMessageID = (rowID: Int, guid: String) | ||
|
|
||
| private enum WaitResult<T> { | ||
| case finished(T) | ||
| case waitingUntil(Date) | ||
| } | ||
|
|
||
| static func sentMessageIDs( | ||
| text: String?, | ||
| timeout: TimeInterval, | ||
| changes: Topic<Void>, | ||
| linkTimeout: TimeInterval = sentMessageLinkWaitTimeout, | ||
| backstopInterval: TimeInterval = databaseTickBackstopInterval, | ||
| querySentMessageIDs: @escaping @Sendable () throws -> [SentMessageID] | ||
| ) async throws -> [SentMessageID] { | ||
| let startedAt = Date() | ||
| let timeoutDeadline = startedAt.addingTimeInterval(timeout) | ||
| let linkDeadline = startedAt.addingTimeInterval(linkTimeout) | ||
| let expectedNewMessageIDCount = text.map { max($0.linkCount, 1) } ?? 1 | ||
|
|
||
| return try await waitForDatabaseResult( | ||
| changes: changes, | ||
| backstopInterval: backstopInterval, | ||
| query: { | ||
| try querySentMessageIDs() | ||
| }, | ||
| evaluate: { sentMessageIDs in | ||
| let now = Date() | ||
| if sentMessageIDs.count == expectedNewMessageIDCount { | ||
| return .finished(sentMessageIDs) | ||
| } | ||
| if text != nil, !sentMessageIDs.isEmpty, now >= linkDeadline { | ||
| return .finished(sentMessageIDs) | ||
| } | ||
| if now >= timeoutDeadline { | ||
| throw ErrorMessage("timed out waiting for sent messages") | ||
| } | ||
|
|
||
| let wakeDeadline: Date | ||
| if text != nil, !sentMessageIDs.isEmpty { | ||
| wakeDeadline = min(timeoutDeadline, linkDeadline) | ||
| } else { | ||
| wakeDeadline = timeoutDeadline | ||
| } | ||
| return .waitingUntil(wakeDeadline) | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| static func sentThreadIDs( | ||
| timeout: TimeInterval, | ||
| changes: Topic<Void>, | ||
| backstopInterval: TimeInterval = databaseTickBackstopInterval, | ||
| querySentThreadIDs: @escaping @Sendable () throws -> [String?] | ||
| ) async throws -> [String?] { | ||
| let deadline = Date().addingTimeInterval(timeout) | ||
|
|
||
| return try await waitForDatabaseResult( | ||
| changes: changes, | ||
| backstopInterval: backstopInterval, | ||
| query: { | ||
| try querySentThreadIDs() | ||
| }, | ||
| evaluate: { threadIDs in | ||
| if !threadIDs.contains(nil) || Date() >= deadline { | ||
| return .finished(threadIDs) | ||
| } | ||
| return .waitingUntil(deadline) | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| static func loadedAttachment( | ||
| messageID: String, | ||
| timeout: TimeInterval, | ||
| changes: Topic<Void>, | ||
| backstopInterval: TimeInterval = databaseTickBackstopInterval, | ||
| minimumRequeryInterval: TimeInterval = loadedAttachmentMinimumRequeryInterval, | ||
| loadMessage: @escaping @Sendable () async throws -> PlatformSDK.Message?, | ||
| terminalAttachmentFailureState: @escaping @Sendable () async throws -> Attachment.IMFileTransferState? | ||
| ) async throws -> PlatformSDK.Message { | ||
| let deadline = Date().addingTimeInterval(timeout) | ||
| var isFirstRead = true | ||
|
|
||
| return try await waitForDatabaseResult( | ||
| changes: changes, | ||
| backstopInterval: backstopInterval, | ||
| minimumRequeryInterval: minimumRequeryInterval, | ||
| query: { | ||
| try await loadMessage() | ||
| .orThrow(ErrorMessage("Could not find message \(messageID)")) | ||
| }, | ||
| evaluate: { message in | ||
| let attachments = message.attachments ?? [] | ||
| if isFirstRead { | ||
| guard !attachments.isEmpty else { | ||
| throw ErrorMessage("Message \(messageID) has no attachments") | ||
| } | ||
| isFirstRead = false | ||
| } | ||
| if !attachments.isEmpty, !attachments.contains(where: { $0.loading == true }) { | ||
| return .finished(message) | ||
| } | ||
|
|
||
| if let failureState = try await terminalAttachmentFailureState() { | ||
| throw ErrorMessage("Attachment in message \(messageID) failed to load (transfer state: \(failureState.rawValue))") | ||
| } | ||
|
|
||
| guard Date() < deadline else { | ||
| throw ErrorMessage("Timed out waiting for attachment in message \(messageID) to load") | ||
| } | ||
|
|
||
| return .waitingUntil(deadline) | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| private static func waitForDatabaseResult<T>( | ||
| changes: Topic<Void>, | ||
| backstopInterval: TimeInterval, | ||
| minimumRequeryInterval: TimeInterval = 0, | ||
| query: @escaping @Sendable () async throws -> T, | ||
| evaluate: (T) async throws -> WaitResult<T> | ||
| ) async throws -> T { | ||
| while true { | ||
| let changeStream = changes.subscribe() | ||
| let result = try await query() | ||
| switch try await evaluate(result) { | ||
| case let .finished(value): | ||
| return value | ||
| case let .waitingUntil(deadline): | ||
| let earliestNextQuery = Date().addingTimeInterval(minimumRequeryInterval) | ||
| try await waitForChange(on: changeStream, until: deadline, backstopInterval: backstopInterval) | ||
| try await waitUntil(earliestNextQuery, cappedAt: deadline) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static func waitForChange(on stream: AsyncStream<Void>, until deadline: Date, backstopInterval: TimeInterval) async throws { | ||
| let remainingTime = deadline.timeIntervalSinceNow | ||
| guard remainingTime > 0 else { return } | ||
|
|
||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| let sleepTime = min(remainingTime, backstopInterval) | ||
|
|
||
| try await withThrowingTaskGroup(of: Void.self) { group in | ||
| group.addTask { | ||
| var iterator = stream.makeAsyncIterator() | ||
| _ = await iterator.next() | ||
| } | ||
| group.addTask { | ||
| try await Task.sleep(forTimeInterval: sleepTime) | ||
| } | ||
|
|
||
| defer { group.cancelAll() } | ||
| _ = try await group.next() | ||
| } | ||
| } | ||
|
|
||
| private static func waitUntil(_ date: Date, cappedAt deadline: Date) async throws { | ||
| let sleepUntil = min(date, deadline) | ||
| let remainingTime = sleepUntil.timeIntervalSinceNow | ||
| guard remainingTime > 0 else { return } | ||
| try await Task.sleep(forTimeInterval: remainingTime) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Subscription leak when query succeeds without waiting.
When
evaluatereturns.finishedon the first query attempt, the subscription created at line 134 is never iterated—waitForChangeis skipped. SinceAsyncStream.onTerminationonly fires when the stream is iterated, finished, or the iterating task is cancelled, the continuation remains inTopic.subscriptionsindefinitely.Over time, these dangling subscriptions accumulate: each
broadcast()willyieldto orphaned continuations with.unboundedbuffering, causing unbounded memory growth.Proposed fix: Wrap stream in RAII-style cleanup
Introduce a small wrapper that ensures the stream is consumed/cancelled on scope exit:
Alternatively, add explicit unsubscribe support to
Topic(e.g.,subscribe() -> (stream, unsubscribe: () -> Void)).🤖 Prompt for AI Agents