Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224import Foundationimport Testing@testable import JetstreamKit
@Suite("Wire formats")struct WireFormatTests { private let v2 = JetstreamHost.v2("wss://jetstream.us-east.bsky.network") private let v1 = JetstreamHost.v1("wss://jetstream.us-east.bsky.network") private let index = JetstreamHost.v1("wss://index.tangled.network")
private func key(_ commit: JetstreamCommit) -> String { "\(commit.uri)#\(commit.rev)" }
// MARK: - Captures
@Test("A commit read over both wires of one instance decodes to the same value, minus the seq") func bothWiresDecodeEqually() throws { let overV2 = try Fixture.commits("frames-v2-bsky", on: v2) let overV1 = try Fixture.commits("frames-v1-bsky", on: v1) let legacy = Dictionary(overV1.map { (key($0), $0) }, uniquingKeysWith: { first, _ in first })
var compared = 0 for commit in overV2 { let match = try #require(legacy[key(commit)], "\(commit.uri) is missing from the legacy capture") #expect(commit.seq != nil) #expect(match.seq == nil) let withoutSeq = JetstreamCommit( seq: nil, did: commit.did, time: commit.time, witnessedAt: commit.witnessedAt, rev: commit.rev, operation: commit.operation, collection: commit.collection, rkey: commit.rkey, record: commit.record, cid: commit.cid ) #expect(match == withoutSeq) compared += 1 } #expect(compared == 20) }
/// The CID is the comparison that holds. An index stamps its own times, /// reports a backfilled record as a `create` whatever the commit was, and /// pads the base64 of `$bytes` values where Bluesky does not. @Test("The tangled index carries the same records as Bluesky") func indexMatchesBluesky() throws { let overV2 = try Fixture.commits("frames-v2-bsky", on: v2) let fromIndex = try Fixture.commits("frames-v1-index", on: index) let indexed = Dictionary(fromIndex.map { (key($0), $0) }, uniquingKeysWith: { first, _ in first })
var compared = 0 for commit in overV2 { guard let match = indexed[key(commit)] else { continue } #expect(match.cid == commit.cid) compared += 1 } #expect(compared > 0) }
@Test("Every captured frame is understood", arguments: [ ("frames-v2-bsky", JetstreamHost.v2("wss://jetstream.us-east.bsky.network")), ("frames-v1-bsky", JetstreamHost.v1("wss://jetstream.us-east.bsky.network")), ("frames-v1-index", JetstreamHost.v1("wss://index.tangled.network")), ]) func capturesDecode(name: String, host: JetstreamHost) throws { let frames = try Fixture.frames(name) #expect(!frames.isEmpty) for frame in frames { _ = try host.decode(frame) } }
@Test("Captured frames play through the client in order, every commit delivered") func capturesPlayThroughTheClient() async throws { let frames = try Fixture.frames("frames-v1-index") let transport = ScriptedJetstreamTransport([.opens(frames: frames, then: .staysOpen)]) let client = JetstreamClient(hosts: [index], filter: JetstreamFilter(collections: ["org.tangled.*"]), transport: transport)
let seen = try await client.take(1 + frames.count)
#expect(seen.first == .connected("wss://index.tangled.network", resumed: false)) let commits = seen.dropFirst().compactMap { item -> (position: JetstreamPosition, isLive: Bool)? in guard case .commit(_, let position, let isLive) = item else { return nil } return (position, isLive) } #expect(commits.count == frames.count) #expect(commits.allSatisfy { $0.position.seq == nil }) // The capture holds both replayed history and live commits. #expect(commits.contains { $0.isLive }) #expect(commits.contains { !$0.isLive }) }
// MARK: - Appendix A
@Test("A knot-hosted ticket update keeps its fields, including the editor") func legacyTicketUpdate() throws { let text = #"{"did":"did:plc:v2aguxduy4e3ketkuxsvrohh","time_us":1794158436663919,"cursor":26962473215,"kind":"commit","commit":{"rev":"3mzswc6kopt22","operation":"update","collection":"org.tangled.track.ticket","rkey":"240","record":{"$type":"org.tangled.track.ticket","body":{"$type":"org.tangled.markup.markdown","text":"SIGTERM … "},"createdAt":"2026-11-08T17:20:02Z","state":"open","targetBranch":"main","title":{"$type":"org.tangled.markup.markdown#inline","text":"fix(publish): release the lease on SIGTERM …"},"x-tngl-editor":"did:web:galena-trogon.test.pds.did.bot"},"cid":"bafyreiaoqgwrcrhxpyr7ltqaayd74o4aykjsugse6lw3fkkbyksafo27r4"}}"# guard case .event(.commit(let commit), let timeMicros, let isLive) = try v1.decode(text) else { Issue.record("expected a commit") return } #expect(commit.seq == nil) #expect(commit.did == "did:plc:v2aguxduy4e3ketkuxsvrohh") #expect(commit.time == "2026-11-08T17:20:36.663919Z") #expect(commit.operation == .update) #expect(commit.uri == "at://did:plc:v2aguxduy4e3ketkuxsvrohh/org.tangled.track.ticket/240") #expect(commit.record?["x-tngl-editor"]?.string == "did:web:galena-trogon.test.pds.did.bot") #expect(commit.cid == "bafyreiaoqgwrcrhxpyr7ltqaayd74o4aykjsugse6lw3fkkbyksafo27r4") #expect(timeMicros == 1_794_158_436_663_919) #expect(isLive) }
@Test("An index frame's refs bytes and live flag survive") func indexRefsFrame() throws { let text = #"{"did":"did:plc:3pmp47a5lygfu5j42flcyh5r","time_us":1794158449500603,"kind":"commit","commit":{"rev":"3mzswckthnm22","operation":"update","collection":"org.tangled.git.refs","rkey":"self","record":{"refs":{"$bytes":"OTUxMDU5MzliN2My"},"$type":"org.tangled.git.refs","defaultBranch":"main"},"cid":"bafyreiegsxjbmtbcbdzf6kh3jri4w25n6vgzy2i7ubxjbbmhk3loiam3mu","live":true}}"# guard case .event(.commit(let commit), _, let isLive) = try index.decode(text) else { Issue.record("expected a commit") return } #expect(commit.record?["refs"]?["$bytes"]?.string == "OTUxMDU5MzliN2My") #expect(isLive) }
// MARK: - Decoding rules
@Test("A legacy frame is live unless it says otherwise") func liveFlag() throws { guard case .event(_, _, let absent) = try v1.decode(Frame.v1Commit(live: nil)), case .event(_, _, let present) = try v1.decode(Frame.v1Commit(live: true)), case .event(_, _, let historical) = try v1.decode(Frame.v1Commit(live: false)) else { Issue.record("expected commits") return } #expect(absent) #expect(present) #expect(!historical) }
@Test("Legacy frames that aren't commits are skipped") func legacyNonCommits() throws { guard case .ignored = try v1.decode(Frame.v1Identity()) else { Issue.record("expected the identity frame to be ignored") return } }
@Test("A legacy delete has no record or CID") func legacyDelete() throws { let text = #"{"did":"did:plc:abc","time_us":1794158436663919,"kind":"commit","commit":{"rev":"3mzswc6nweq2x","operation":"delete","collection":"org.tangled.feed.star","rkey":"3mzswc6nhlktj"}}"# guard case .event(.commit(let commit), _, _) = try v1.decode(text) else { Issue.record("expected a commit") return } #expect(commit.operation == .delete) #expect(commit.record == nil) #expect(commit.cid == nil) }
@Test("Microsecond timestamps convert exactly in both directions", arguments: [ (1_794_158_436_663_919, "2026-11-08T17:20:36.663919Z"), (1_794_158_436_000_000, "2026-11-08T17:20:36.000000Z"), (1_794_158_436_000_001, "2026-11-08T17:20:36.000001Z"), (1_794_160_506_481_411, "2026-11-08T17:55:06.481411Z"), ] as [(Int64, String)]) func timeConversion(micros: Int64, text: String) { #expect(JetstreamTime.timestamp(microseconds: micros) == text) #expect(JetstreamTime.microseconds(from: text) == micros) }
@Test("Every captured v1 timestamp survives the round trip through RFC 3339") func capturedTimesRoundTrip() throws { for name in ["frames-v1-bsky", "frames-v1-index"] { for text in try Fixture.frames(name) { let micros = try LegacyJetstreamFrame.decode(text).timeMicros #expect(JetstreamTime.microseconds(from: JetstreamTime.timestamp(microseconds: micros)) == micros) } } }
// MARK: - URLs
@Test("A v2 subscription uses the XRPC path, its parameters and a seq cursor") func v2URL() throws { let filter = JetstreamFilter(collections: ["org.tangled.*"], dids: ["did:plc:abc"], kinds: [.commit]) let url = try v2.subscriptionURL(filter: filter, cursor: .seq(42)) #expect(url.absoluteString == "wss://jetstream.us-east.bsky.network/xrpc/network.bsky.jetstream.subscribeEvents?kinds=commit&collections=org.tangled.*&dids=did:plc:abc&cursor=42&maxMessageSizeBytes=4194304") #expect(v2.subprotocol == "xrpc.v1.json") }
@Test("A v1 subscription uses /subscribe, the wanted parameters and only live events") func v1URL() throws { let filter = JetstreamFilter(collections: ["org.tangled.*"], dids: ["did:plc:abc"], kinds: [.commit]) let url = try index.subscriptionURL(filter: filter, cursor: .timestamp(microseconds: 1_794_158_436_663_919)) #expect(url.absoluteString == "wss://index.tangled.network/subscribe?wantedCollections=org.tangled.*&wantedDids=did:plc:abc&wantedEventTypes=live&cursor=1794158436663919&maxMessageSizeBytes=4194304") #expect(index.subprotocol == nil) }
@Test("Limits and bad hosts are rejected on both wires") func urlValidation() { let tooMany = JetstreamFilter(collections: Array(repeating: "a.b.c", count: 101)) #expect(throws: JetstreamSubscription.ValidationError.tooManyCollections(101)) { try v2.subscriptionURL(filter: tooMany, cursor: nil) } #expect(throws: JetstreamSubscription.ValidationError.tooManyCollections(101)) { try index.subscriptionURL(filter: tooMany, cursor: nil) } #expect(throws: JetstreamSubscription.ValidationError.invalidHost("https://example.com")) { try JetstreamHost.v1("https://example.com").subscriptionURL(filter: .init(), cursor: nil) } }
// MARK: - Text form
@Test("Hosts round-trip through their text form") func hostText() { #expect(JetstreamHost("wss://a.example") == .v2("wss://a.example")) #expect(JetstreamHost("v2:wss://a.example") == .v2("wss://a.example")) #expect(JetstreamHost("v1:wss://a.example") == .v1("wss://a.example")) #expect(JetstreamHost("https://a.example") == nil) #expect(JetstreamHost("v1:") == nil) #expect(JetstreamHost("") == nil) for host in [JetstreamHost.v2("wss://a.example"), .v1("wss://b.example")] { #expect(JetstreamHost(host.description) == host) } }}