Skip to content

Commit

Permalink
all tests pass
Browse files Browse the repository at this point in the history
  • Loading branch information
pvh committed Jul 24, 2024
1 parent 2963205 commit a64500f
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 62 deletions.
35 changes: 2 additions & 33 deletions packages/automerge-repo/src/DocHandle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,9 @@ export class DocHandle<T> extends EventEmitter<DocHandleEvents<T>> {
on: {
REQUEST: "requesting",
DOC_READY: "ready",
AWAIT_NETWORK: "awaitingNetwork",
},
after: { [delay]: "unavailable" },
},
awaitingNetwork: {
on: {
DOC_READY: "ready",
NETWORK_READY: "requesting"
},
},
requesting: {
on: {
DOC_UNAVAILABLE: "unavailable",
Expand Down Expand Up @@ -429,17 +422,6 @@ export class DocHandle<T> extends EventEmitter<DocHandleEvents<T>> {
if (this.#state === "loading") this.#machine.send({ type: REQUEST })
}

/** @hidden */
awaitNetwork() {
if (this.#state === "loading") this.#machine.send({ type: AWAIT_NETWORK })
}

/** @hidden */
networkReady() {
if (this.#state === "awaitingNetwork")
this.#machine.send({ type: NETWORK_READY })
}

/** Called by the repo when the document is deleted. */
delete() {
this.#machine.send({ type: DELETE })
Expand Down Expand Up @@ -554,8 +536,6 @@ export const HandleState = {
IDLE: "idle",
/** We are waiting for storage to finish loading */
LOADING: "loading",
/** We are waiting for the network to be come ready */
AWAITING_NETWORK: "awaitingNetwork",
/** We are waiting for someone in the network to respond to a sync request */
REQUESTING: "requesting",
/** The document is available */
Expand All @@ -567,15 +547,8 @@ export const HandleState = {
} as const
export type HandleState = (typeof HandleState)[keyof typeof HandleState]

export const {
IDLE,
LOADING,
AWAITING_NETWORK,
REQUESTING,
READY,
DELETED,
UNAVAILABLE,
} = HandleState
export const { IDLE, LOADING, REQUESTING, READY, DELETED, UNAVAILABLE } =
HandleState

// context

Expand All @@ -598,14 +571,10 @@ type DocHandleEvent<T> =
| { type: typeof TIMEOUT }
| { type: typeof DELETE }
| { type: typeof DOC_UNAVAILABLE }
| { type: typeof AWAIT_NETWORK }
| { type: typeof NETWORK_READY }

const FIND = "FIND"
const REQUEST = "REQUEST"
const DOC_READY = "DOC_READY"
const AWAIT_NETWORK = "AWAIT_NETWORK"
const NETWORK_READY = "NETWORK_READY"
const UPDATE = "UPDATE"
const DELETE = "DELETE"
const TIMEOUT = "TIMEOUT"
Expand Down
42 changes: 17 additions & 25 deletions packages/automerge-repo/src/Repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { SyncStatePayload } from "./synchronizer/Synchronizer.js"
import type { AnyDocumentId, DocumentId, PeerId } from "./types.js"

function randomPeerId() {
return "peer-" + Math.random().toString(36).slice(4) as PeerId
return ("peer-" + Math.random().toString(36).slice(4)) as PeerId
}

/** A Repo is a collection of documents with networking, syncing, and storage capabilities. */
Expand Down Expand Up @@ -88,9 +88,7 @@ export class Repo extends EventEmitter<RepoEvents> {
}: DocHandleEncodedChangePayload<any>) => {
void storageSubsystem.saveDoc(handle.documentId, doc)
}
handle.on("heads-changed",
throttle(saveFn, this.saveDebounceRate)
)
handle.on("heads-changed", throttle(saveFn, this.saveDebounceRate))
}

handle.on("unavailable", () => {
Expand All @@ -100,18 +98,6 @@ export class Repo extends EventEmitter<RepoEvents> {
})
})

if (!this.networkSubsystem.isReady()) {
handle.awaitNetwork()
this.networkSubsystem
.whenReady()
.then(() => {
handle.networkReady()
})
.catch(err => {
this.#log("error waiting for network", { err })
})
}

// Register the document with the synchronizer. This advertises our interest in the document.
this.#synchronizer.addDocument(handle.documentId)
})
Expand Down Expand Up @@ -316,7 +302,7 @@ export class Repo extends EventEmitter<RepoEvents> {

/** Returns an existing handle if we have it; creates one otherwise. */
#getHandle<T>({
documentId
documentId,
}: {
/** The documentId of the handle to look up or create */
documentId: DocumentId /** If we know we're creating a new document, specify this so we can have access to it immediately */
Expand Down Expand Up @@ -354,7 +340,7 @@ export class Repo extends EventEmitter<RepoEvents> {
// Generate a new UUID and store it in the buffer
const { documentId } = parseAutomergeUrl(generateAutomergeUrl())
const handle = this.#getHandle<T>({
documentId
documentId,
}) as DocHandle<T>

this.emit("document", { handle })
Expand All @@ -365,10 +351,10 @@ export class Repo extends EventEmitter<RepoEvents> {
nextDoc = Automerge.from(initialValue)
} else {
nextDoc = Automerge.emptyChange(Automerge.init())
}
}
return nextDoc
})

handle.doneLoading()
return handle
}
Expand Down Expand Up @@ -438,7 +424,7 @@ export class Repo extends EventEmitter<RepoEvents> {
const handle = this.#getHandle<T>({
documentId,
}) as DocHandle<T>

// Try to load from disk
if (this.storageSubsystem) {
void this.storageSubsystem.loadDoc(handle.documentId).then(loadedDoc => {
Expand All @@ -447,15 +433,21 @@ export class Repo extends EventEmitter<RepoEvents> {
handle.update(() => loadedDoc as Automerge.Doc<T>)
handle.doneLoading()
} else {
handle.request()
this.networkSubsystem
.whenReady()
.then(() => {
handle.request()
})
.catch(err => {
this.#log("error waiting for network", { err })
})
this.emit("document", { handle })
}
})

} else {
handle.request()
this.emit("document", { handle })
}

this.emit("document", { handle })
return handle
}

Expand Down
5 changes: 4 additions & 1 deletion packages/automerge-repo/src/network/NetworkSubsystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,10 @@ export class NetworkSubsystem extends EventEmitter<NetworkSubsystemEvents> {
}

isReady = () => {
return this.#readyAdapterCount === this.#adapters.length
return (
this.#adapters.length === 0 ||
this.#readyAdapterCount === this.#adapters.length
)
}

whenReady = async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ export class CollectionSynchronizer extends Synchronizer {
*/
async receiveMessage(message: DocMessage) {
log(
`onSyncMessage: ${message.senderId}, ${message.documentId}, ${
"data" in message ? message.data.byteLength + "bytes" : ""
`onSyncMessage: ${message.senderId}, ${message.documentId}, ${"data" in message ? message.data.byteLength + "bytes" : ""
}`
)

Expand Down
8 changes: 7 additions & 1 deletion packages/automerge-repo/test/Repo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,11 @@ describe("Repo", () => {
it("doesn't find a document that doesn't exist", async () => {
const { repo } = setup()
const handle = repo.find<TestDoc>(generateAutomergeUrl())
assert.equal(handle.isReady(), false)

await handle.whenReady(["ready", "unavailable"])

assert.equal(handle.isReady(), false)
assert.equal(handle.state, "unavailable")
const doc = await handle.doc()
assert.equal(doc, undefined)
})
Expand All @@ -221,6 +224,7 @@ describe("Repo", () => {
handle.on("unavailable", () => {
wasUnavailable = true
})

await pause(50)
assert.equal(wasUnavailable, false)

Expand Down Expand Up @@ -400,6 +404,8 @@ describe("Repo", () => {
d.count = 1
})

await repo.flush()

for (let i = 0; i < 3; i++) {
const repo2 = new Repo({
storage,
Expand Down

0 comments on commit a64500f

Please sign in to comment.