-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(logservice): add LogService and its Crdt
- Loading branch information
1 parent
a4a4979
commit 612af67
Showing
2 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |