Skip to content

Commit

Permalink
feat(logservice): add LogService and its Crdt
Browse files Browse the repository at this point in the history
  • Loading branch information
cedricenclos committed Sep 10, 2018
1 parent a4a4979 commit 612af67
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/doc/LogCrdt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { State, StateVector } from '../sync'
import { StateVectorOrder } from '../sync/StateVector'
import { LogState } from './LogsService'

export class LogCrdt {
private id: number
private state: StateVector
private share: boolean

constructor(id: number, state: LogState) {
this.id = id
this.share = state.share
this.state = new StateVector(state.vector)
}

merge(other: LogCrdt) {
const res = this.state.compareTo(other.state)
if (res === StateVectorOrder.INFERIOR) {
this.share = other.share
this.state = other.state
} else if (res === StateVectorOrder.CONCURRENT) {
this.share = this.share && other.share
this.state.maxPairwise(other.state)
}
}

setShare(newShare: boolean) {
this.share = newShare
if (this.state.get(this.id)) {
this.state.set(this.id, this.state.get(this.id) + 1)
} else {
this.state.set(this.id, 0)
}
}

get isShared(): boolean {
return this.share
}
}
22 changes: 22 additions & 0 deletions src/doc/LogsService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { LogCrdt } from './LogCrdt'

export interface LogState {
share: boolean
vector?: Map<number, number>
}

export class LogsService {
private crdt: LogCrdt

constructor(id: number, state: LogState) {
this.crdt = new LogCrdt(id, state)
}

public handleLocalLogState(share: boolean): void {
this.crdt.setShare(share)
}

public handleRemoteLogState(otherCrdt: LogCrdt): void {
this.crdt.merge(otherCrdt)
}
}

0 comments on commit 612af67

Please sign in to comment.