fix(mobile/ios): replace push watermark with durable cursor state

Co-authored-by: npub1tquskdu6yc4h8l7xxtceculxw600grekeq0xg2ukqfrwl7vrzg3quz3gmp <58390b379a262b73ffc632f19c73e6769ef40f36c81e642b960246eff9831222@buzz.block.builderlab.xyz>
Signed-off-by: npub1tquskdu6yc4h8l7xxtceculxw600grekeq0xg2ukqfrwl7vrzg3quz3gmp <58390b379a262b73ffc632f19c73e6769ef40f36c81e642b960246eff9831222@buzz.block.builderlab.xyz>
Co-authored-by: Cursor <noreply@cursor.com>
Ai-assisted: true
This commit is contained in:
npub1tquskdu6yc4h8l7xxtceculxw600grekeq0xg2ukqfrwl7vrzg3quz3gmp
2026-07-27 19:54:44 -07:00
parent a7e2283537
commit c02ed4f436
5 changed files with 428 additions and 158 deletions

View File

@@ -0,0 +1,223 @@
import Darwin
import Foundation
public enum PushConsumptionStateError: Error, Equatable {
case lockFailed(Int32)
}
public struct PushEventPosition: Codable, Equatable, Comparable, Sendable {
public let createdAt: Int
public let id: String
enum CodingKeys: String, CodingKey {
case createdAt = "created_at"
case id
}
public init(createdAt: Int, id: String) {
self.createdAt = createdAt
self.id = id
}
public static func < (lhs: PushEventPosition, rhs: PushEventPosition) -> Bool {
lhs.createdAt == rhs.createdAt ? lhs.id < rhs.id : lhs.createdAt < rhs.createdAt
}
}
public struct PushOriginState: Codable, Equatable, Sendable {
public let cursor: PushEventPosition?
public let delivered: [PushEventPosition]
public init(cursor: PushEventPosition? = nil, delivered: [PushEventPosition] = []) {
self.cursor = cursor
self.delivered = delivered
}
public func contains(eventID: String) -> Bool {
delivered.contains { $0.id == eventID }
}
public func consuming(
_ position: PushEventPosition,
deliveredLimit: Int = PushConsumptionState.maximumDeliveredPerOrigin
) -> PushOriginState {
let nextCursor = max(cursor ?? position, position)
var byID = Dictionary(uniqueKeysWithValues: delivered.map { ($0.id, $0) })
byID[position.id] = position
let bounded = byID.values
.filter { $0.createdAt >= nextCursor.createdAt }
.sorted()
.suffix(deliveredLimit)
return PushOriginState(cursor: nextCursor, delivered: Array(bounded))
}
}
public struct PushConsumptionState: Codable, Equatable, Sendable {
public static let version = 1
public static let maximumDeliveredPerOrigin = 64
public static let allowedFutureSkewSeconds = 300
public var origins: [String: PushOriginState]
private let storedVersion: Int
enum CodingKeys: String, CodingKey {
case storedVersion = "version"
case origins
}
public init(origins: [String: PushOriginState] = [:]) {
storedVersion = Self.version
self.origins = origins
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let decodedVersion = try container.decode(Int.self, forKey: .storedVersion)
guard decodedVersion == Self.version else {
throw DecodingError.dataCorruptedError(
forKey: .storedVersion,
in: container,
debugDescription: "Unsupported push consumption state version \(decodedVersion)"
)
}
storedVersion = decodedVersion
origins = try container.decode([String: PushOriginState].self, forKey: .origins)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(storedVersion, forKey: .storedVersion)
try container.encode(origins, forKey: .origins)
}
public func state(for origin: String) -> PushOriginState {
origins[origin] ?? PushOriginState()
}
public func querySince(for origin: String, now: Int = Int(Date().timeIntervalSince1970)) -> Int? {
guard let timestamp = origins[origin]?.cursor?.createdAt else { return nil }
return min(timestamp, now)
}
public func hasConsumed(eventID: String, for origin: String) -> Bool {
state(for: origin).contains(eventID: eventID)
}
public func canSelect(
_ position: PushEventPosition,
for origin: String,
now: Int = Int(Date().timeIntervalSince1970),
allowedFutureSkew: Int = allowedFutureSkewSeconds
) -> Bool {
let originState = state(for: origin)
return position.createdAt <= now + allowedFutureSkew
&& position.createdAt >= (originState.cursor?.createdAt ?? position.createdAt)
&& !originState.contains(eventID: position.id)
}
public mutating func consume(
_ position: PushEventPosition,
for origin: String,
deliveredLimit: Int = maximumDeliveredPerOrigin
) {
origins[origin] = state(for: origin).consuming(position, deliveredLimit: deliveredLimit)
}
public mutating func removeInactiveOrigins(_ activeOrigins: Set<String>) {
origins = origins.filter { activeOrigins.contains($0.key) }
}
}
public protocol PushConsumptionStateLocking: Sendable {
func withExclusiveLock<T>(_ body: () throws -> T) throws -> T
}
public protocol PushConsumptionStatePersisting: Sendable {
func read() throws -> Data?
func write(_ data: Data) throws
}
public struct PushFileLock: PushConsumptionStateLocking {
private let url: URL
public init(url: URL) {
self.url = url
}
public func withExclusiveLock<T>(_ body: () throws -> T) throws -> T {
let descriptor = open(url.path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)
guard descriptor >= 0 else { throw PushConsumptionStateError.lockFailed(errno) }
defer { close(descriptor) }
guard flock(descriptor, LOCK_EX) == 0 else {
throw PushConsumptionStateError.lockFailed(errno)
}
defer { flock(descriptor, LOCK_UN) }
return try body()
}
}
public struct PushFilePersistence: PushConsumptionStatePersisting {
private let url: URL
public init(url: URL) {
self.url = url
}
public func read() throws -> Data? {
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
return try Data(contentsOf: url)
}
public func write(_ data: Data) throws {
try data.write(to: url, options: [.atomic])
}
}
public final class PushConsumptionStateStore: @unchecked Sendable {
private let lock: any PushConsumptionStateLocking
private let persistence: any PushConsumptionStatePersisting
private let encoder: JSONEncoder
private let decoder: JSONDecoder
public init(
lock: any PushConsumptionStateLocking,
persistence: any PushConsumptionStatePersisting
) {
self.lock = lock
self.persistence = persistence
encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
decoder = JSONDecoder()
}
public convenience init(containerURL: URL) {
self.init(
lock: PushFileLock(url: containerURL.appendingPathComponent("push-consumption-state.lock")),
persistence: PushFilePersistence(
url: containerURL.appendingPathComponent("push-consumption-state.json")
)
)
}
public func read() throws -> PushConsumptionState {
try lock.withExclusiveLock { try loadUnlocked() }
}
@discardableResult
public func update(
_ body: (inout PushConsumptionState) throws -> Void
) throws -> PushConsumptionState {
try lock.withExclusiveLock {
var state = try loadUnlocked()
try body(&state)
try persistence.write(encoder.encode(state))
return state
}
}
private func loadUnlocked() throws -> PushConsumptionState {
guard let data = try persistence.read() else { return PushConsumptionState() }
return try decoder.decode(PushConsumptionState.self, from: data)
}
}

View File

@@ -1,51 +0,0 @@
import Foundation
public enum PushWatermark {
/// Nostr permits modest clock drift, but an authenticated author must not
/// be able to pin notification queries arbitrarily far into the future.
public static let allowedFutureSkewSeconds = 300
public static let keyPrefix = "buzz.push.watermark."
public static func key(communityID: String) -> String {
keyPrefix + communityID
}
public static func persistedTimestamp(
eventTimestamp: Int,
now: Int = Int(Date().timeIntervalSince1970),
allowedFutureSkew: Int = allowedFutureSkewSeconds
) -> Int {
min(eventTimestamp, now + allowedFutureSkew)
}
public static func isAcceptable(
eventTimestamp: Int,
now: Int = Int(Date().timeIntervalSince1970),
allowedFutureSkew: Int = allowedFutureSkewSeconds
) -> Bool {
eventTimestamp <= now + allowedFutureSkew
}
public static func queryTimestamp(
storedWatermark: Int,
now: Int = Int(Date().timeIntervalSince1970)
) -> Int {
min(storedWatermark, now)
}
/// Nostr `since` is inclusive. Keeping the watermark itself allows a later
/// event created in the same second to remain queryable.
public static func querySince(watermark: Int) -> Int? {
watermark > 0 ? watermark : nil
}
public static func staleKeys(
in storedKeys: [String],
activeCommunityIDs: Set<String>
) -> [String] {
storedKeys.filter { key in
guard key.hasPrefix(keyPrefix) else { return false }
return !activeCommunityIDs.contains(String(key.dropFirst(keyPrefix.count)))
}
}
}

View File

@@ -0,0 +1,153 @@
import Foundation
import XCTest
@testable import BuzzPushKit
final class PushConsumptionStateTests: XCTestCase {
func testSameSecondSiblingsRemainReachable() {
var state = PushConsumptionState()
let first = PushEventPosition(createdAt: 1_000, id: "a")
let sibling = PushEventPosition(createdAt: 1_000, id: "b")
state.consume(first, for: "origin")
XCTAssertEqual(state.querySince(for: "origin", now: 2_000), 1_000)
XCTAssertFalse(state.canSelect(first, for: "origin", now: 2_000))
XCTAssertTrue(state.canSelect(sibling, for: "origin", now: 2_000))
}
func testLosingOriginIsNotConsumed() {
var state = PushConsumptionState()
state.consume(PushEventPosition(createdAt: 2_000, id: "winner"), for: "winner-origin")
XCTAssertTrue(
state.canSelect(
PushEventPosition(createdAt: 1_999, id: "loser"),
for: "loser-origin",
now: 3_000
)
)
XCTAssertNil(state.querySince(for: "loser-origin", now: 3_000))
}
func testDeliveredEventIsNeverSelectedAgainAndHistoryIsBounded() {
var state = PushConsumptionState()
for index in 0..<70 {
state.consume(
PushEventPosition(createdAt: 1_000, id: String(format: "%064x", index)),
for: "origin"
)
}
let latest = PushEventPosition(createdAt: 1_000, id: String(format: "%064x", 69))
XCTAssertFalse(state.canSelect(latest, for: "origin", now: 2_000))
XCTAssertEqual(state.state(for: "origin").delivered.count, 64)
}
func testEventOlderThanCompositeCursorIsNotSelected() {
var state = PushConsumptionState()
state.consume(PushEventPosition(createdAt: 2_000, id: "newer"), for: "origin")
XCTAssertFalse(
state.canSelect(
PushEventPosition(createdAt: 1_999, id: "older"),
for: "origin",
now: 3_000
)
)
}
func testEventBeyondAllowedFutureSkewIsNotSelected() {
let state = PushConsumptionState()
XCTAssertTrue(
state.canSelect(
PushEventPosition(createdAt: 1_300, id: "boundary"),
for: "origin",
now: 1_000,
allowedFutureSkew: 300
)
)
XCTAssertFalse(
state.canSelect(
PushEventPosition(createdAt: 1_301, id: "future"),
for: "origin",
now: 1_000,
allowedFutureSkew: 300
)
)
}
func testInterleavedWritersCannotLoseDeliveredIDOrMoveCursorBackward() throws {
let lock = TestLock()
let persistence = TestPersistence()
let storeA = PushConsumptionStateStore(lock: lock, persistence: persistence)
let storeB = PushConsumptionStateStore(lock: lock, persistence: persistence)
let writerARead = expectation(description: "writer A entered")
let letWriterAFinish = DispatchSemaphore(value: 0)
let completed = expectation(description: "writers completed")
completed.expectedFulfillmentCount = 2
DispatchQueue.global().async {
defer { completed.fulfill() }
do {
try storeA.update { state in
writerARead.fulfill()
_ = letWriterAFinish.wait(timeout: .now() + 2)
state.consume(PushEventPosition(createdAt: 2_000, id: "b"), for: "origin")
}
} catch {
XCTFail("writer A failed: \(error)")
}
}
wait(for: [writerARead], timeout: 1)
DispatchQueue.global().async {
defer { completed.fulfill() }
do {
try storeB.update { state in
state.consume(PushEventPosition(createdAt: 2_000, id: "a"), for: "origin")
}
} catch {
XCTFail("writer B failed: \(error)")
}
}
letWriterAFinish.signal()
wait(for: [completed], timeout: 3)
let state = try storeA.read().state(for: "origin")
XCTAssertEqual(state.cursor, PushEventPosition(createdAt: 2_000, id: "b"))
XCTAssertEqual(Set(state.delivered.map(\.id)), ["a", "b"])
}
func testStateFileIsVersionedAndDeterministic() throws {
let persistence = TestPersistence()
let store = PushConsumptionStateStore(lock: TestLock(), persistence: persistence)
try store.update { state in
state.consume(PushEventPosition(createdAt: 1_000, id: "event"), for: "origin")
}
let json = try XCTUnwrap(
persistence.data.flatMap {
try? JSONSerialization.jsonObject(with: $0) as? [String: Any]
})
XCTAssertEqual(json["version"] as? Int, 1)
XCTAssertNotNil(json["origins"])
}
}
private final class TestLock: PushConsumptionStateLocking, @unchecked Sendable {
private let lock = NSRecursiveLock()
func withExclusiveLock<T>(_ body: () throws -> T) throws -> T {
lock.lock()
defer { lock.unlock() }
return try body()
}
}
private final class TestPersistence: PushConsumptionStatePersisting, @unchecked Sendable {
var data: Data?
func read() throws -> Data? { data }
func write(_ data: Data) throws { self.data = data }
}

View File

@@ -1,73 +0,0 @@
import XCTest
@testable import BuzzPushKit
final class PushWatermarkTests: XCTestCase {
func testClampsFutureTimestampToAllowedClockSkew() {
XCTAssertEqual(
PushWatermark.persistedTimestamp(
eventTimestamp: 2_000,
now: 1_000,
allowedFutureSkew: 300
),
1_300
)
}
func testPreservesTimestampWithinAllowedClockSkew() {
XCTAssertEqual(
PushWatermark.persistedTimestamp(
eventTimestamp: 1_200,
now: 1_000,
allowedFutureSkew: 300
),
1_200
)
}
func testRejectsEventsBeyondAllowedClockSkew() {
XCTAssertFalse(
PushWatermark.isAcceptable(
eventTimestamp: 1_301,
now: 1_000,
allowedFutureSkew: 300
)
)
XCTAssertTrue(
PushWatermark.isAcceptable(
eventTimestamp: 1_300,
now: 1_000,
allowedFutureSkew: 300
)
)
}
func testRepairsPoisonedStoredWatermarkToCurrentTime() {
XCTAssertEqual(
PushWatermark.queryTimestamp(storedWatermark: 2_000, now: 1_000),
1_000
)
XCTAssertEqual(
PushWatermark.queryTimestamp(storedWatermark: 900, now: 1_000),
900
)
}
func testQuerySinceIsInclusiveForSameSecondEvents() {
XCTAssertEqual(PushWatermark.querySince(watermark: 1_000), 1_000)
XCTAssertNil(PushWatermark.querySince(watermark: 0))
}
func testFindsOnlyRemovedCommunityWatermarks() {
XCTAssertEqual(
PushWatermark.staleKeys(
in: [
PushWatermark.key(communityID: "kept"),
PushWatermark.key(communityID: "removed"),
"unrelated",
],
activeCommunityIDs: ["kept"]
),
[PushWatermark.key(communityID: "removed")]
)
}
}

View File

@@ -79,7 +79,6 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
private let session: URLSession
private let appGroupIdentifier: String?
private let keychainAccessGroup: String?
private let defaults: UserDefaults?
private let fileManager: FileManager
init(
@@ -95,20 +94,18 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
self.session = session
self.appGroupIdentifier = appGroupIdentifier
self.keychainAccessGroup = keychainAccessGroup
defaults = appGroupIdentifier.flatMap(UserDefaults.init(suiteName:))
self.fileManager = fileManager
}
func resolve(completion: @escaping (BuzzPushResolutionResult) -> Void) {
let loadedCommunities: [PushLeaseCommunity]
let loaded: (communities: [PushLeaseCommunity], store: PushConsumptionStateStore)
do {
loadedCommunities = try loadCommunities()
loaded = try loadState()
} catch {
completion(.diagnostic("Open Buzz to refresh notification subscriptions."))
return
}
removeStaleWatermarks(activeCommunityIDs: Set(loadedCommunities.map(\.id)))
let communities = loadedCommunities.filter {
let communities = loaded.communities.filter {
$0.pubkey?.isEmpty == false && loadPrivateKey(communityID: $0.id) != nil
}
guard !communities.isEmpty else {
@@ -116,13 +113,21 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
return
}
let consumptionState: PushConsumptionState
do {
consumptionState = try loaded.store.read()
} catch {
completion(.diagnostic("Buzz could not read notification history."))
return
}
let group = DispatchGroup()
let lock = NSLock()
var candidates: [Candidate] = []
var diagnostics: [String] = []
for community in communities {
group.enter()
query(community) { result in
query(community, consumptionState: consumptionState) { result in
lock.lock()
switch result {
case .candidate(let candidate): candidates.append(candidate)
@@ -146,11 +151,25 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
completion(diagnostics.sorted().first.map(BuzzPushResolutionResult.diagnostic) ?? .none)
return
}
for candidate in candidates {
self.defaults?.set(
PushWatermark.persistedTimestamp(eventTimestamp: candidate.event.createdAt),
forKey: PushWatermark.key(communityID: candidate.community.id)
)
let position = PushEventPosition(
createdAt: winner.event.createdAt,
id: winner.event.id
)
var shouldPresent = false
do {
try loaded.store.update { state in
state.removeInactiveOrigins(Set(communities.map(\.id)))
guard state.canSelect(position, for: winner.community.id) else { return }
state.consume(position, for: winner.community.id)
shouldPresent = true
}
} catch {
completion(.diagnostic("Buzz could not save notification history."))
return
}
guard shouldPresent else {
completion(.none)
return
}
completion(.notification(winner.resolution))
}
@@ -164,6 +183,7 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
private func query(
_ community: PushLeaseCommunity,
consumptionState: PushConsumptionState,
completion: @escaping (QueryResult) -> Void
) {
guard let privateKey = loadPrivateKey(communityID: community.id) else {
@@ -177,11 +197,7 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
completion(.diagnostic("Open Buzz to refresh notification subscriptions."))
return
}
let watermarkKey = PushWatermark.key(communityID: community.id)
let storedWatermark = defaults?.integer(forKey: watermarkKey) ?? 0
let watermark = PushWatermark.queryTimestamp(storedWatermark: storedWatermark)
if watermark != storedWatermark { defaults?.set(watermark, forKey: watermarkKey) }
let since = PushWatermark.querySince(watermark: watermark)
let since = consumptionState.querySince(for: community.id)
let filters = subscriptions.map { $0.filter.queryFilter(since: since, limit: 10) }
guard let body = try? JSONSerialization.data(withJSONObject: filters) else {
completion(.diagnostic("Buzz notification subscriptions are invalid."))
@@ -223,7 +239,8 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
Self.decodeResolution(
events: events,
community: community,
subscriptions: subscriptions
subscriptions: subscriptions,
consumptionState: consumptionState
)
)
}.resume()
@@ -232,14 +249,21 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
private static func decodeResolution(
events: [VerifiedNostrEvent],
community: PushLeaseCommunity,
subscriptions: [PushLeaseSubscription]
subscriptions: [PushLeaseSubscription],
consumptionState: PushConsumptionState
) -> QueryResult {
let matching = events.filter { event in
event.hasValidIDAndSignature()
&& PushWatermark.isAcceptable(eventTimestamp: event.createdAt)
&& subscriptions.contains(where: {
guard event.hasValidIDAndSignature(),
subscriptions.contains(where: {
PushLeaseMatcher.matches(event: event, subscription: $0)
})
else {
return false
}
return consumptionState.canSelect(
PushEventPosition(createdAt: event.createdAt, id: event.id),
for: community.id
)
}.sorted {
$0.createdAt == $1.createdAt ? $0.id < $1.id : $0.createdAt > $1.createdAt
}
@@ -306,16 +330,6 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
pubkey.count > 8 ? String(pubkey.prefix(8)) + "…" : pubkey
}
private func removeStaleWatermarks(activeCommunityIDs: Set<String>) {
guard let defaults else { return }
for key in PushWatermark.staleKeys(
in: Array(defaults.dictionaryRepresentation().keys),
activeCommunityIDs: activeCommunityIDs
) {
defaults.removeObject(forKey: key)
}
}
private func loadPrivateKey(communityID: String) -> String? {
var query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
@@ -334,7 +348,10 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
return String(data: data, encoding: .utf8)
}
private func loadCommunities() throws -> [PushLeaseCommunity] {
private func loadState() throws -> (
communities: [PushLeaseCommunity],
store: PushConsumptionStateStore
) {
guard let appGroupIdentifier,
let container = fileManager.containerURL(
forSecurityApplicationGroupIdentifier: appGroupIdentifier
@@ -344,7 +361,8 @@ final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
}
let snapshotURL = container.appendingPathComponent("push-communities.json")
let data = try Data(contentsOf: snapshotURL)
return try JSONDecoder().decode(PushLeaseSnapshot.self, from: data).communities
let snapshot = try JSONDecoder().decode(PushLeaseSnapshot.self, from: data)
return (snapshot.communities, PushConsumptionStateStore(containerURL: container))
}
}