Skip to content

Commit

Permalink
Fix report remote heads test
Browse files Browse the repository at this point in the history
  • Loading branch information
paulsonnentag committed Nov 6, 2023
1 parent 6eb0484 commit e66305d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
26 changes: 24 additions & 2 deletions packages/automerge-repo/src/DocHandle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,12 +338,27 @@ export class DocHandle<T> //
* @hidden
*/
setSyncState(peerId: PeerId, syncState: A.SyncState): void {
const previousSyncState = this.#syncStates[peerId]

this.#syncStates[peerId] = syncState
const { theirHeads, sharedHeads } = syncState

if (
syncState.theirHeads &&
(!previousSyncState ||
!previousSyncState.theirHeads ||
!arraysEqual(previousSyncState.theirHeads, syncState.theirHeads))
) {
this.emit("remote-heads", { peerId, heads: syncState.theirHeads })
}

this.emit("sync-state", { peerId, syncState })
}

getRemoteHeads(peerId: PeerId): A.Heads | undefined {
return this.#syncStates[peerId].theirHeads
}

/** `setSyncStates` is called by the repo when the doc is loaded initially
* @hidden
*/
Expand Down Expand Up @@ -507,9 +522,8 @@ export interface DocHandleOutboundEphemeralMessagePayload<T> {
}

export interface DocHandleRemoteHeadsPayload {
remote: PeerId
peerId: PeerId
heads: A.Heads
received: Date
}

export interface DocHandleSyncStatePayload {
Expand Down Expand Up @@ -654,3 +668,11 @@ const {
AWAIT_NETWORK,
NETWORK_READY,
} = Event

function arraysEqual<T>(a: T[], b: T[]): boolean {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false
}
return true
}
18 changes: 8 additions & 10 deletions packages/automerge-repo/test/Repo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -789,10 +789,10 @@ describe("Repo", () => {

const nextRemoteHeadsPromise = new Promise<{
peerId: PeerId
syncState: A.SyncState
heads: A.Heads
}>(resolve => {
handle.on("sync-state", ({ peerId, syncState }) => {
resolve({ peerId, syncState })
handle.on("remote-heads", ({ peerId, heads }) => {
resolve({ peerId, heads })
})
})

Expand All @@ -816,14 +816,12 @@ describe("Repo", () => {

const nextRemoteHeads = await nextRemoteHeadsPromise
assert.deepStrictEqual(nextRemoteHeads.peerId, "charlie")
assert.deepStrictEqual(nextRemoteHeads.syncState, charlieHeads)
assert.deepStrictEqual(nextRemoteHeads.heads, charlieHeads)

assert.deepStrictEqual(handle.getSyncState("charlie" as PeerId), {
charlie: {
heads: A.getHeads(charlieHandle.docSync()),
received: nextRemoteHeads.received,
},
})
assert.deepStrictEqual(
handle.getRemoteHeads("charlie" as PeerId),
A.getHeads(charlieHandle.docSync())
)
})
})

Expand Down

0 comments on commit e66305d

Please sign in to comment.