Files
bitchat/bitchatTests/LocationNotesManagerTests.swift
T
jackandjack d783e8cc24 Fix location notes and mesh notice correctness bugs (#1963)
* Fix location notes and mesh notice correctness bugs

- Scope BoardStore orphan tombstone eviction by (postID, authorSigningKey) and isOrphan so an attacker cannot evict a genuine author's matched tombstone and resurrect deleted mesh notices; use saturating arithmetic on deletedAt retention.
- Suppress postArrivals when a newly ingested board post is immediately evicted by per-author or global quota.
- Filter expired board posts in BoardManager, UnifiedNotices, and ContentHeaderView, and add BoardStore.pruneExpired() on notice/feed appear.
- Fix merged delete of bridged geo notices: tag NIP-09 deletions with geohash, retract the bridged event locally via LocationNotesPool.retractEvent, and fall back to deleting matching own bridged notes after relaunch.
- Normalize/validate geohash in BoardManager.createPost, gate live Nostr bridging on LocationNotesSettings.enabled and activationAllowed, and clear bridgedEventIDs on panic wipe.
- Track bounded author-scoped pending NIP-09 deletions in LocationNotesManager so kind-5 deletions arriving before kind-1/kind-7 backfill suppress matching-author events; persist local deletes in deletedEventIDs across refresh and tag with note.geohash.
- Guard LocationNotesManager subscribe callbacks by subscriptionID, clear reactionMetaByEventID on refresh, and gate send/sendFeedPost/toggleReaction/delete/postDrop on network activationAllowed when not uplinked via BLE gateway.
- Hold NearbyNotesCounter active in PlacesTabView so the Location Notes card and building header indicator show live counts, and mark geohash board alerts seen when opening Location Notes or Place Feed.

* Fix Periphery assign-only warning and make async board tests deterministic

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
2026-11-28 15:15:39 -10:00

729 lines
28 KiB
Swift

import Testing
import Combine
import Foundation
@testable import bitchat
@MainActor
struct LocationNotesManagerTests {
@Test
func subscribeWithoutRelays_setsNoRelaysState() {
var subscribeCalled = false
let deps = LocationNotesDependencies(
relayLookup: { _, _ in [] },
subscribe: { _, _, _, _, _ in
subscribeCalled = true
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { Date() }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
#expect(subscribeCalled == false)
#expect(manager.state == .noRelays)
#expect(manager.initialLoadComplete)
#expect(manager.errorMessage == String(localized: "location_notes.error.no_relays"))
}
@Test
func noRelays_resubscribesWhenDirectoryRefreshes() async throws {
var relays: [String] = []
var subscribeCount = 0
let directorySubject = PassthroughSubject<Void, Never>()
let deps = LocationNotesDependencies(
relayLookup: { _, _ in relays },
subscribe: { _, _, _, _, _ in
subscribeCount += 1
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { Date() },
relayDirectoryUpdates: directorySubject.eraseToAnyPublisher()
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
#expect(manager.state == .noRelays)
#expect(subscribeCount == 0)
// Directory loads later (e.g. remote fetch finished after Tor came up).
relays = ["wss://relay.one"]
directorySubject.send(())
let deadline = Date().addingTimeInterval(1.0)
while manager.state == .noRelays && Date() < deadline {
try await Task.sleep(nanoseconds: 10_000_000)
}
#expect(subscribeCount == 1)
#expect(manager.state == .loading)
#expect(manager.errorMessage == nil)
}
@Test
func sendWithoutRelays_surfacesNoRelaysError() {
var sendCalled = false
let deps = LocationNotesDependencies(
relayLookup: { _, _ in [] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { _, _ in sendCalled = true },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
manager.send(content: "hello", nickname: "tester")
#expect(sendCalled == false)
#expect(manager.state == .noRelays)
#expect(manager.errorMessage == String(localized: "location_notes.error.no_relays"))
}
@Test func subscribeUsesGeoRelaysAndAppendsNotes() throws {
var relaysCaptured: [String] = []
var storedHandler: ((NostrEvent) -> Void)?
var storedEOSE: (() -> Void)?
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { filter, id, relays, handler, eose in
#expect(filter.kinds == [1, 7, 5])
#expect(!id.isEmpty)
relaysCaptured = relays
storedHandler = handler
storedEOSE = eose
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
#expect(relaysCaptured == ["wss://relay.one"])
#expect(manager.state == .loading)
let identity = try NostrIdentity.generate()
let event = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: Date(),
kind: .textNote,
tags: [["g", "u4pruydq"]],
content: "hi"
)
let signed = try event.sign(with: identity.schnorrSigningKey())
storedHandler?(signed)
storedEOSE?()
#expect(manager.state == .ready)
#expect(manager.notes.count == 1)
#expect(manager.notes.first?.content == "hi")
}
@Test
func refreshAndCancel_manageSubscriptions() {
var subscribeIDs: [String] = []
var unsubscribedIDs: [String] = []
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, id, _, _, _ in
subscribeIDs.append(id)
},
unsubscribe: { id in
unsubscribedIDs.append(id)
},
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { Date() }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
manager.refresh()
manager.cancel()
#expect(subscribeIDs.count == 2)
#expect(unsubscribedIDs.count == 2)
#expect(manager.state == .idle)
#expect(manager.errorMessage == nil)
}
@Test
func send_successCreatesLocalEchoAndClearsError() throws {
var sentEvents: [NostrEvent] = []
let identity = try NostrIdentity.generate()
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { event, _ in
sentEvents.append(event)
},
deriveIdentity: { _ in identity },
now: { Date(timeIntervalSince1970: 123_456) }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
manager.send(content: " hello note ", nickname: "Builder")
#expect(sentEvents.count == 1)
#expect(manager.state == .ready)
#expect(manager.errorMessage == nil)
#expect(manager.notes.first?.content == "hello note")
#expect(manager.notes.first?.displayName.hasPrefix("Builder#") == true)
}
@Test
func send_failureFormatsErrorMessageAndClearErrorRemovesIt() {
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
manager.send(content: "hello", nickname: "Builder")
#expect(manager.errorMessage?.isEmpty == false)
manager.clearError()
#expect(manager.errorMessage == nil)
}
@Test
func ingestDropsExpiredNotesAndKeepsUnexpiredOnes() throws {
var storedHandler: ((NostrEvent) -> Void)?
let now = Date(timeIntervalSince1970: 1_700_000_000)
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in
storedHandler = handler
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { now }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let identity = try NostrIdentity.generate()
let expired = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: now.addingTimeInterval(-3600),
kind: .textNote,
tags: [["g", "u4pruydq"], ["expiration", String(Int(now.timeIntervalSince1970) - 60)]],
content: "gone"
)
storedHandler?(try expired.sign(with: identity.schnorrSigningKey()))
let live = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: now.addingTimeInterval(-3600),
kind: .textNote,
tags: [["g", "u4pruydq"], ["expiration", String(Int(now.timeIntervalSince1970) + 3600)]],
content: "still here"
)
storedHandler?(try live.sign(with: identity.schnorrSigningKey()))
#expect(manager.notes.count == 1)
#expect(manager.notes.first?.content == "still here")
#expect(manager.notes.first?.expiresAt == Date(timeIntervalSince1970: TimeInterval(Int(now.timeIntervalSince1970) + 3600)))
}
/// created_at is author-chosen: a note dated 2100 used to sort above
/// every real note forever and survive the newest-first memory cap.
@Test
func ingestClampsFutureDatedNotesToTheBoardSkew() throws {
var storedHandler: ((NostrEvent) -> Void)?
let start = Date(timeIntervalSince1970: 1_700_000_000)
var currentNow = start
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in
storedHandler = handler
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { currentNow }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let identity = try NostrIdentity.generate()
let skew = TimeInterval(BoardStore.Limits.clockSkewMs) / 1000
// Within the board's skew allowance the author's timestamp is kept,
// so a bridged copy of a board post still dedupes against the post.
let slightlyAhead = start.addingTimeInterval(30 * 60)
let bridged = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: slightlyAhead,
kind: .textNote,
tags: [["g", "u4pruydq"]],
content: "bridged"
)
storedHandler?(try bridged.sign(with: identity.schnorrSigningKey()))
#expect(manager.notes.first(where: { $0.content == "bridged" })?.createdAt == slightlyAhead)
// Far-future timestamps are clamped to the edge of that allowance.
let futureDated = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: Date(timeIntervalSince1970: 4_102_444_800), // 2100-01-01
kind: .textNote,
tags: [["g", "u4pruydq"]],
content: "pinned"
)
storedHandler?(try futureDated.sign(with: identity.schnorrSigningKey()))
#expect(manager.notes.first(where: { $0.content == "pinned" })?.createdAt == start.addingTimeInterval(skew))
// Once local time passes that edge, newer notes sort above it.
currentNow = start.addingTimeInterval(skew + 120)
let later = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: start.addingTimeInterval(skew + 60),
kind: .textNote,
tags: [["g", "u4pruydq"]],
content: "later"
)
storedHandler?(try later.sign(with: identity.schnorrSigningKey()))
#expect(manager.notes.map(\.content) == ["later", "pinned", "bridged"])
}
@Test
func postDrop_sendsExpiringNoteToGeoRelays() throws {
var sentEvents: [NostrEvent] = []
let now = Date(timeIntervalSince1970: 1_700_000_000)
let identity = try NostrIdentity.generate()
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { event, _ in sentEvents.append(event) },
deriveIdentity: { _ in identity },
now: { now }
)
let posted = LocationNotesManager.postDrop(
content: " the coffee here is great ",
nickname: "scout",
geohash: "u4pruydq",
dependencies: deps
)
#expect(posted)
#expect(sentEvents.count == 1)
let event = try #require(sentEvents.first)
#expect(event.kind == NostrProtocol.EventKind.textNote.rawValue)
#expect(event.content == "the coffee here is great")
#expect(event.tags.contains(["g", "u4pruydq"]))
let expiration = event.tags.first { $0.first == "expiration" }?.last
let expected = Int(now.addingTimeInterval(TransportConfig.locationDropExpirySeconds).timeIntervalSince1970)
#expect(expiration == String(expected))
}
@Test
func postDrop_failsWithoutRelays() {
let deps = LocationNotesDependencies(
relayLookup: { _, _ in [] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
#expect(!LocationNotesManager.postDrop(content: "hi", nickname: "x", geohash: "u4pruydq", dependencies: deps))
}
@Test
func pruneExpiredNotes_dropsNotesWhoseExpiryPassed() throws {
var storedHandler: ((NostrEvent) -> Void)?
var currentNow = Date(timeIntervalSince1970: 1_700_000_000)
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in
storedHandler = handler
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { currentNow }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let identity = try NostrIdentity.generate()
let note = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: currentNow,
kind: .textNote,
tags: [["g", "u4pruydq"], ["expiration", String(Int(currentNow.timeIntervalSince1970) + 60)]],
content: "short lived"
)
storedHandler?(try note.sign(with: identity.schnorrSigningKey()))
#expect(manager.notes.count == 1)
currentNow = currentNow.addingTimeInterval(120)
manager.pruneExpiredNotes()
#expect(manager.notes.isEmpty)
}
@Test
func eoseWithoutConnectedRelays_showsConnectingInsteadOfEmpty() {
var storedEOSE: (() -> Void)?
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, eose in storedEOSE = eose },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
deps.anyRelayConnected = { _ in false }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
storedEOSE?()
#expect(manager.state == .connecting)
#expect(manager.initialLoadComplete)
}
@Test
func eoseWithConnectedRelayAndNoNotes_isReadyEmpty() {
var storedEOSE: (() -> Void)?
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, eose in storedEOSE = eose },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
deps.anyRelayConnected = { _ in true }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
storedEOSE?()
#expect(manager.state == .ready)
}
@Test
func connectingState_retriesOnceARelayComesUp() {
var storedEOSE: (() -> Void)?
var subscribeCount = 0
var relayUp = false
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, eose in
subscribeCount += 1
storedEOSE = eose
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
deps.anyRelayConnected = { _ in relayUp }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
#expect(subscribeCount == 1)
storedEOSE?()
#expect(manager.state == .connecting)
// Relay still down: no retry.
manager.retryIfRelaysAvailable(relays: ["wss://relay.one"])
#expect(subscribeCount == 1)
// Relay up: re-subscribes for a fresh initial fetch.
relayUp = true
manager.retryIfRelaysAvailable(relays: ["wss://relay.one"])
#expect(subscribeCount == 2)
#expect(manager.state == .loading)
}
@Test @MainActor
func networkBecameAvailable_refreshesConnectingNotesImmediately() async {
var subscribeCount = 0
var storedEOSE: (() -> Void)?
let networkAvailable = PassthroughSubject<Void, Never>()
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.geo"] },
subscribe: { _, _, _, _, eose in
subscribeCount += 1
storedEOSE = eose
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
deps.anyRelayConnected = { _ in false }
deps.networkBecameAvailable = { networkAvailable.eraseToAnyPublisher() }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
#expect(subscribeCount == 1)
storedEOSE?()
#expect(manager.state == .connecting)
// Network returns online: manager refreshes immediately without waiting for poll.
networkAvailable.send(())
for _ in 0..<5 {
await Task.yield()
}
#expect(subscribeCount == 2)
#expect(manager.state == .loading)
}
@Test
func inboundDeletionArrivingBeforeNote_suppressesMatchingAuthorOnly() throws {
var storedHandler: ((NostrEvent) -> Void)?
let now = Date(timeIntervalSince1970: 1_700_000_000)
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in storedHandler = handler },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { now }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let author = try NostrIdentity.generate()
let attacker = try NostrIdentity.generate()
let deletedNote = try NostrProtocol.createGeohashTextNote(
content: "retracted",
geohash: "u4pruydq",
senderIdentity: author,
createdAt: now.addingTimeInterval(-60)
)
let keptNote = try NostrProtocol.createGeohashTextNote(
content: "forged delete target",
geohash: "u4pruydq",
senderIdentity: author,
createdAt: now.addingTimeInterval(-30)
)
// Relay delivers newer kind-5 deletions BEFORE older kind-1 notes.
let genuineDelete = try NostrProtocol.createDeleteEvent(
ofEventID: deletedNote.id,
senderIdentity: author,
geohash: "u4pruydq"
)
let forgedDelete = try NostrProtocol.createDeleteEvent(
ofEventID: keptNote.id,
senderIdentity: attacker,
geohash: "u4pruydq"
)
storedHandler?(genuineDelete)
storedHandler?(forgedDelete)
// Now older kind-1 notes arrive in backfill.
storedHandler?(deletedNote)
storedHandler?(keptNote)
#expect(manager.notes.map(\.id) == [keptNote.id.lowercased()])
}
@Test
func inboundDeletionArrivingBeforeReaction_suppressesMatchingAuthorOnly() throws {
var storedHandler: ((NostrEvent) -> Void)?
let now = Date(timeIntervalSince1970: 1_700_000_000)
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in storedHandler = handler },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { now }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let author = try NostrIdentity.generate()
let reactor = try NostrIdentity.generate()
let attacker = try NostrIdentity.generate()
let note = try NostrProtocol.createGeohashTextNote(
content: "hello",
geohash: "u4pruydq",
senderIdentity: author,
createdAt: now.addingTimeInterval(-120)
)
let removedReaction = try NostrProtocol.createGeohashReactionEvent(
emoji: "🔥",
targetEventID: note.id,
targetAuthorPubkey: author.publicKeyHex,
geohash: "u4pruydq",
senderIdentity: reactor,
createdAt: now.addingTimeInterval(-60)
)
let keptReaction = try NostrProtocol.createGeohashReactionEvent(
emoji: "👍",
targetEventID: note.id,
targetAuthorPubkey: author.publicKeyHex,
geohash: "u4pruydq",
senderIdentity: reactor,
createdAt: now.addingTimeInterval(-50)
)
// Deliver kind-5 deletions before the kind-7 reactions arrive.
storedHandler?(try NostrProtocol.createDeleteEvent(ofEventID: removedReaction.id, senderIdentity: reactor, geohash: "u4pruydq"))
storedHandler?(try NostrProtocol.createDeleteEvent(ofEventID: keptReaction.id, senderIdentity: attacker, geohash: "u4pruydq"))
storedHandler?(note)
storedHandler?(removedReaction)
storedHandler?(keptReaction)
let reactions = manager.reactions(forNoteID: note.id)
#expect(reactions.map(\.emoji) == ["👍"])
}
@Test
func localDelete_survivesRefreshAndTagsNoteGeohash() throws {
var storedHandler: ((NostrEvent) -> Void)?
var sentEvents: [NostrEvent] = []
let identity = try NostrIdentity.generate()
let neighbor = try #require(Geohash.neighbors(of: "u4pruydq").first)
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in storedHandler = handler },
unsubscribe: { _ in },
sendEvent: { event, _ in sentEvents.append(event) },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { Date(timeIntervalSince1970: 1_700_000_000) }
)
deps.publicIdentity = { identity }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let noteEvent = try NostrProtocol.createGeohashTextNote(
content: "neighbor note",
geohash: neighbor,
senderIdentity: identity,
createdAt: Date(timeIntervalSince1970: 1_700_000_000)
)
storedHandler?(noteEvent)
let note = try #require(manager.notes.first)
#expect(manager.delete(note: note))
#expect(manager.notes.isEmpty)
// Deletion event must tag the note's own geohash (neighbor).
let deletion = try #require(sentEvents.first { $0.kind == NostrProtocol.EventKind.deletion.rawValue })
#expect(deletion.tags.contains(["g", neighbor]))
// Refreshing and replaying the deleted event must not resurrect it.
manager.refresh()
storedHandler?(noteEvent)
#expect(manager.notes.isEmpty)
}
@Test
func staleSubscriptionCallbacks_areIgnoredAfterRefreshAndCancel() throws {
var handlers: [(NostrEvent) -> Void] = []
var eoses: [() -> Void] = []
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, eose in
handlers.append(handler)
if let eose { eoses.append(eose) }
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date(timeIntervalSince1970: 1_700_000_000) }
)
deps.anyRelayConnected = { _ in false }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
manager.refresh()
#expect(handlers.count == 2)
#expect(eoses.count == 2)
// Firing the first subscription's stale EOSE must not mark the second subscription loaded/connecting.
eoses[0]()
#expect(!manager.initialLoadComplete)
#expect(manager.state == .loading)
// Cancelling must ignore late events from the cancelled subscription.
manager.cancel()
let identity = try NostrIdentity.generate()
let lateEvent = try NostrProtocol.createGeohashTextNote(
content: "late",
geohash: "u4pruydq",
senderIdentity: identity
)
handlers[1](lateEvent)
#expect(manager.notes.isEmpty)
#expect(manager.state == .idle)
}
@Test
func sendAndPostDrop_failWhenActivationDisallowed() throws {
var sendCalled = false
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { _, _ in sendCalled = true },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { Date(timeIntervalSince1970: 1_700_000_000) }
)
deps.activationAllowed = { false }
#expect(!LocationNotesManager.postDrop(content: "offline drop", nickname: "alice", geohash: "u4pruydq", dependencies: deps))
#expect(!sendCalled)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
manager.send(content: "offline note", nickname: "alice")
#expect(!sendCalled)
#expect(manager.notes.isEmpty)
#expect(manager.errorMessage != nil)
#expect(!manager.sendFeedPost(content: "offline feed post", nickname: "alice"))
#expect(!sendCalled)
#expect(manager.notes.isEmpty)
}
@Test
func poolRetractEvent_removesBridgedNoteFromCoveringManagers() throws {
var storedHandler: ((NostrEvent) -> Void)?
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in storedHandler = handler },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date(timeIntervalSince1970: 1_700_000_000) }
)
let pool = LocationNotesPool(makeManager: { LocationNotesManager(geohash: $0, dependencies: deps) })
let manager = pool.acquire("u4pruydq")
let identity = try NostrIdentity.generate()
let bridged = try NostrProtocol.createGeohashTextNote(
content: "bridged notice",
geohash: "u4pruydq",
senderIdentity: identity,
createdAt: Date(timeIntervalSince1970: 1_700_000_000)
)
storedHandler?(bridged)
#expect(manager.notes.count == 1)
pool.retractEvent(id: bridged.id, geohash: "u4pruydq")
#expect(manager.notes.isEmpty)
// Replaying the retracted event must not resurrect it.
storedHandler?(bridged)
#expect(manager.notes.isEmpty)
pool.release(manager)
}
private enum TestError: Error {
case shouldNotDerive
}
}