Skip to content

Commit

Permalink
restore abortcontroller support
Browse files Browse the repository at this point in the history
  • Loading branch information
pvh committed Jan 7, 2025
1 parent f4258e6 commit d568155
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
12 changes: 9 additions & 3 deletions packages/automerge-repo/src/Repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ export class Repo extends EventEmitter<RepoEvents> {
options: AbortOptions = {}
): FindProgress<T> {
const { signal } = options
const abortPromise = abortable(signal)
const documentId = interpretAsDocumentId(id)

// Check cache first - return plain FindStep for terminal states
Expand Down Expand Up @@ -451,22 +452,27 @@ export class Repo extends EventEmitter<RepoEvents> {
const handle = that.#getHandle<T>({ documentId })
yield { state: "loading", progress: 25, handle }

const loadedDoc = await (that.storageSubsystem
const loadingPromise = await (that.storageSubsystem
? that.storageSubsystem.loadDoc(handle.documentId)
: Promise.resolve(null))

const loadedDoc = await Promise.race([loadingPromise, abortPromise])

if (loadedDoc) {
handle.update(() => loadedDoc as Automerge.Doc<T>)
handle.doneLoading()
yield { state: "loading", progress: 50, handle }
} else {
await that.networkSubsystem.whenReady()
await Promise.race([that.networkSubsystem.whenReady(), abortPromise])
handle.request()
yield { state: "loading", progress: 75, handle }
}

that.#registerHandleWithSubsystems(handle)
await handle.whenReady([READY, UNAVAILABLE, DELETED])
await Promise.race([
handle.whenReady([READY, UNAVAILABLE, DELETED]),
abortPromise,
])

if (handle.state === UNAVAILABLE) {
throw new Error(`Document ${id} is unavailable`)
Expand Down
5 changes: 2 additions & 3 deletions packages/automerge-repo/test/Repo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1459,13 +1459,12 @@ describe("Repo.find() abort behavior", () => {
it("can abort while waiting for ready state", async () => {
// Create a repo with no network adapters so document can't become ready
const repo = new Repo()
const handle = repo.create()
const url = handle.url
const url = generateAutomergeUrl()

const controller = new AbortController()

// Start find and abort after a moment
const findPromise = repo.find(handle.url, { signal: controller.signal })
const findPromise = repo.find(url, { signal: controller.signal })
controller.abort()

await expect(findPromise).rejects.toThrow("Operation aborted")
Expand Down

0 comments on commit d568155

Please sign in to comment.