Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

topologically sort changes before applying #468

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions backend/new.js
Original file line number Diff line number Diff line change
Expand Up @@ -1691,6 +1691,36 @@ function appendChange(columns, change, actorIds, changeIndexByHash) {
])
}

function topologicalSort(xs, outgoingEdges) {
const result = []
const unmarked = new Set(xs)
const tempMarks = new Set()
const stack = []
while (unmarked.size) {
const [n] = unmarked
stack.push([visit, n])
while (stack.length) {
const [f, x] = stack.pop()
f(x)
}
}
return result
function visit(n) {
if (!unmarked.has(n)) return
unmarked.delete(n)

if (tempMarks.has(n)) throw new Error("Not a DAG")

tempMarks.add(n)
stack.push([append, n])
for (const m of outgoingEdges(n)) stack.push([visit, m])
}
function append(n) {
tempMarks.delete(n)
result.push(n)
}
}

class BackendDoc {
constructor(buffer) {
this.maxOp = 0
Expand Down Expand Up @@ -1795,11 +1825,16 @@ class BackendDoc {
*/
applyChanges(changeBuffers, isLocal = false) {
// decoded change has the form { actor, seq, startOp, time, message, deps, actorIds, hash, columns, buffer }
const decodedChangesByHash = new Map()
let decodedChanges = changeBuffers.map(buffer => {
const decoded = decodeChangeColumns(buffer)
decoded.buffer = buffer
decodedChangesByHash.set(decoded.hash, decoded)
return decoded
})
// topologically sort the changes before processing, so that we process
// deps of a change before the change itself.
decodedChanges = topologicalSort(decodedChanges, (change) => change.deps.map(depHash => decodedChangesByHash.get(depHash)))

let patches = {_root: {objectId: '_root', type: 'map', props: {}}}
let docState = {
Expand Down