Skip to content

Commit 409086d

Browse files
Merge branch 'develop' into feature/box-selection
2 parents 15c7180 + fe75ff1 commit 409086d

File tree

13 files changed

+416
-16
lines changed

13 files changed

+416
-16
lines changed

docs/source/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Welcome to Apollon's documentation!
1818
user/getting-started
1919
user/api
2020
user/uml-model-helpers
21+
user/realtime-collaboration
2122

2223
.. toctree::
2324
:caption: Contributor Guide
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
.. _realtime-collaboration:
2+
3+
################
4+
Realtime Collaboration
5+
################
6+
7+
Apollon supports realtime collaboration by emitting patches when a model is changed, and importing
8+
patches potentially emitted by other Apollon clients. Patches follow the `RFC 6902`_ standard (i.e. `JSON Patch`_),
9+
so they can be applied to Apollon diagrams in any desired language.
10+
11+
.. code-block:: typescript
12+
13+
// This method subscribes to model change patches.
14+
// The callback is called whenever a patch is emitted.
15+
editor.subscribeToModelChangePatches(callback: (patch: Patch) => void): number;
16+
17+
// This method unsubscribes from model change patches.
18+
// The subscriptionId is the return value of the subscribeToModelChangePatches method.
19+
editor.unsubscribeFromModelChangePatches(subscriptionId: number): void;
20+
21+
// This method imports a patch. This can be used to
22+
// apply patches emitted by other Apollon clients.
23+
editor.importPatch(patch: Patch): void;
24+
25+
Apollon client takes care of detecting conflicts between clients and resolving them. There is no need for
26+
users to manually implement any reconcilliation mechanism. The only requirements to ensure a convergent state
27+
between all Apollon clients are as follows:
28+
29+
- Apply all patches on all clients in the same order,
30+
- Apply all patches on all clients, including patches emitted by the same client.
31+
32+
This means, if client A emits patch P1 and client B emits patch P2, both clients must then apply P1 and P2 in the same order (using `importPatch()`). The order can be picked by the server, but it needs to be the same for all clients. This means client A should also receive P1, although it has emitted P1 itself. Similarly client B should receive P2, although it has emitted P2 itself.
33+
34+
Apollon clients sign the patches they emit and treat receiving their own patches as confirmation that the patch has been applied and ordered with patches from other clients. They also optimize based on this assumption, to recognize when they are ahead of the rest of the clients on some part of the state: when client A applies the effects of patch P1 locally, its state is ahead until other clients have also applied patch P1, so client A can safely ignore other effects on that same part of the state (as it will get overwritten by patch P1 anyway).
35+
36+
================
37+
Displaying Remote Users
38+
================
39+
40+
In realtime collaboration, it can be useful to display activities of other users active in the collaboration session within the diagram editor. Apollon provides methods to display other users' selections:
41+
42+
.. code-block:: typescript
43+
44+
// This method selects or deselects elements
45+
// on part of a given remote user with given name and color.
46+
// Provide the ids of the elements the remote user
47+
// has selected/deselected.
48+
editor.remoteSelect(
49+
selectorName: string,
50+
selectorColor: string,
51+
select: string[],
52+
deselect?: string[]
53+
): void;
54+
55+
// This method clears the list of remote users displayed
56+
// on the diagram editor, except allowed users.
57+
// Use this in case some users disconnect from the collaboration session.
58+
pruneRemoteSelectors(
59+
allowedSelectors: {
60+
name: string;
61+
color: string;
62+
}[]
63+
): void;
64+
65+
.. _RFC 6902: https://tools.ietf.org/html/rfc6902
66+
.. _JSON Patch: http://jsonpatch.com/

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@ls1intum/apollon",
3-
"version": "3.3.7",
3+
"version": "3.3.9",
44
"description": "A UML diagram editor.",
55
"keywords": [],
66
"homepage": "https://github.com/ls1intum/apollon#readme",

src/main/components/store/model-store.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export const createReduxStore = (
5050
patcher &&
5151
createPatcherReducer<UMLModel, ModelState>(patcher, {
5252
transform: (model) => ModelState.fromModel(model) as ModelState,
53+
transformInverse: (state) => ModelState.toModel(state),
5354
merge,
5455
});
5556

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import { Patch } from './patcher-types';
2+
import { Operation, ReplaceOperation } from 'fast-json-patch';
3+
4+
/**
5+
* A signed replace operation is a replace operation with an additional hash property.
6+
* This enables tracing the origin of a replace operation.
7+
*/
8+
export type SignedReplaceOperation = ReplaceOperation<any> & { hash: string };
9+
10+
/**
11+
* A signed operation is either a replace operation with a hash property or any other operation.
12+
* The hash property is used to verify the origin of a replace operation.
13+
* Only replace operations need a hash property.
14+
*/
15+
export type SignedOperation = Exclude<Operation, ReplaceOperation<any>> | SignedReplaceOperation;
16+
17+
/**
18+
* A signed patch is a patch where all replace operations are signed, i.e.
19+
* all the replace operations have a hash allowing for tracing their origin.
20+
*/
21+
export type SignedPatch = SignedOperation[];
22+
23+
/**
24+
* @param operation
25+
* @returns true if the operation is a replace operation, false otherwise
26+
*/
27+
export function isReplaceOperation(operation: Operation): operation is ReplaceOperation<any> {
28+
return operation.op === 'replace';
29+
}
30+
31+
/**
32+
* @param operation
33+
* @returns true if the operation is a signed operation, false otherwise. A signed operation is either
34+
* a replace operation with a hash property or any other operation.
35+
*/
36+
export function isSignedOperation(operation: Operation): operation is SignedOperation {
37+
return !isReplaceOperation(operation) || 'hash' in operation;
38+
}
39+
40+
/**
41+
* A patch verifier enables otpimisitc discard of incomging changes.It can be used to sign
42+
* each operation (or opeerations of each patch) and track them. If the server broadcasts changes
43+
* of the same scope (e.g. the same path) before re-broadcasting that particular change, the client
44+
* can safely discard the change as it will (optimistically) be overridden when the server re-broadcasts
45+
* the tracked change.
46+
*
47+
* This greatly helps with stuttering issues due to clients constantly re-applying changes they have
48+
* already applied locally but in a different order. See
49+
* [**this issue**](https://github.com/ls1intum/Apollon_standalone/pull/70) for more details.
50+
*/
51+
export class PatchVerifier {
52+
private waitlist: { [address: string]: string } = {};
53+
54+
/**
55+
* Signs an operation and tracks it. Only replace operations are signed and tracked.
56+
* @param operation
57+
* @returns The signed version of the operation (to be sent to the server)
58+
*/
59+
public signOperation(operation: Operation): SignedOperation {
60+
if (isReplaceOperation(operation)) {
61+
const hash = Math.random().toString(36).substring(2, 15);
62+
const path = operation.path;
63+
this.waitlist[path] = hash;
64+
65+
return { ...operation, hash };
66+
} else {
67+
return operation;
68+
}
69+
}
70+
71+
/**
72+
* Signs all operations inside the patch.
73+
* @param patch
74+
* @returns the signed patch (to be sent to the server)
75+
*/
76+
public sign(patch: Patch): SignedPatch {
77+
return patch.map((op) => this.signOperation(op));
78+
}
79+
80+
/**
81+
* Checks whether the operation should be applied or should it be optimisitcally discarded.
82+
* - If the operation is not a replace operation, it is always applied.
83+
* - If the operation is a replace operation but it is not signed, it is always applied.
84+
* - If the operation is a signed replace operation and no other operation with the same path is tracked,
85+
* it will be applied.
86+
* - Otherwise it will be discarded.
87+
*
88+
* If it receives an operation that is already tracked, it will be discarded, and the
89+
* operation will be untracked (so following operations on the same path will be applied).
90+
*
91+
* @param operation
92+
* @returns true if the operation should be applied, false if it should be discarded.
93+
*/
94+
public isVerifiedOperation(operation: Operation): boolean {
95+
if (isReplaceOperation(operation) && isSignedOperation(operation) && operation.path in this.waitlist) {
96+
if (this.waitlist[operation.path] === operation.hash) {
97+
delete this.waitlist[operation.path];
98+
}
99+
100+
return false;
101+
} else {
102+
return true;
103+
}
104+
}
105+
106+
/**
107+
* Filters an incoming patch, only leaving the operations that should be applied.
108+
* @param patch
109+
* @returns a patch with operations that should be applied.
110+
*/
111+
public verified(patch: Patch): Patch {
112+
return patch.filter((op) => this.isVerifiedOperation(op));
113+
}
114+
}

src/main/services/patcher/patcher-reducer.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ export type PatcherReducerOptions<T, U = T> = {
1212
*/
1313
transform?: (state: T) => U;
1414

15+
/**
16+
* Transforms the state before applying the patch. This is useful
17+
* when the internal store schema differs from the schema exposed to the outside.
18+
* @param state The state in the internal schema.
19+
* @returns The state in the external schema.
20+
*/
21+
transformInverse?: (state: U) => T;
22+
1523
/**
1624
* Merges the old state with the new state. This is useful when naive strategies
1725
* like `Object.assign` would trigger unwanted side-effects and more context-aware merging
@@ -25,6 +33,7 @@ export type PatcherReducerOptions<T, U = T> = {
2533

2634
const _DefaultOptions = {
2735
transform: (state: any) => state,
36+
transformInverse: (state: any) => state,
2837
merge: (oldState: any, newState: any) => ({ ...oldState, ...newState }),
2938
};
3039

@@ -39,14 +48,17 @@ export function createPatcherReducer<T, U = T>(
3948
options: PatcherReducerOptions<T, U> = _DefaultOptions,
4049
): Reducer<U> {
4150
const transform = options.transform || _DefaultOptions.transform;
51+
const transformInverse = options.transformInverse || _DefaultOptions.transformInverse;
4252
const merge = options.merge || _DefaultOptions.merge;
4353

44-
return (state = {} as U, action) => {
54+
return (state, action) => {
4555
const { type, payload } = action;
4656
if (type === PatcherActionTypes.PATCH) {
47-
const res = transform(patcher.patch(payload));
57+
const res = patcher.patch(payload, transformInverse(state as U));
4858

49-
return merge(state, res);
59+
if (res.patched) {
60+
return merge((state ?? {}) as U, transform(res.result));
61+
}
5062
}
5163

5264
return state;
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { call, debounce, delay, put, select, take } from 'redux-saga/effects';
2+
import { SagaIterator } from 'redux-saga';
3+
4+
import { run } from '../../utils/actions/sagas';
5+
import { PatcherActionTypes } from './patcher-types';
6+
import { ModelState } from '../../components/store/model-state';
7+
import { UMLContainerRepository } from '../uml-container/uml-container-repository';
8+
import { UMLElement } from '../uml-element/uml-element';
9+
import { UMLRelationship } from '../uml-relationship/uml-relationship';
10+
import { recalc } from '../uml-relationship/uml-relationship-saga';
11+
import { render } from '../layouter/layouter';
12+
13+
/**
14+
* Fixes the layout of the diagram after importing a patch.
15+
*/
16+
export function* PatchLayouter(): SagaIterator {
17+
yield run([patchLayout]);
18+
}
19+
20+
export function* patchLayout(): SagaIterator {
21+
yield debounce(100, PatcherActionTypes.PATCH, recalculateLayouts);
22+
}
23+
24+
function* recalculateLayouts(): SagaIterator {
25+
const { elements }: ModelState = yield select();
26+
27+
const ids = Object.values(elements)
28+
.filter((x) => !x.owner)
29+
.map((x) => x.id);
30+
31+
if (!ids.length) {
32+
return;
33+
}
34+
35+
yield put(UMLContainerRepository.append(ids));
36+
37+
for (const id of Object.keys(elements)) {
38+
yield delay(0);
39+
if (UMLElement.isUMLElement(elements[id])) {
40+
yield call(render, id);
41+
}
42+
43+
if (UMLRelationship.isUMLRelationship(elements[id]) && !elements[id].isManuallyLayouted) {
44+
yield call(recalc, id);
45+
}
46+
}
47+
}

src/main/services/patcher/patcher.ts

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { buffer, debounceTime, filter, map, merge, Observable, Subject, Subscrip
33

44
import { compare } from './compare';
55
import { Patch, PatchListener } from './patcher-types';
6+
import { PatchVerifier, SignedPatch } from './patch-verifier';
67

78
/**
89
* Compares two objects and returns the difference
@@ -26,7 +27,7 @@ export interface PatcherOptions<T> {
2627

2728
const _DefaultOptions = {
2829
diff: compare,
29-
maxFrequency: 25,
30+
maxFrequency: 60,
3031
};
3132

3233
/**
@@ -40,6 +41,7 @@ export class Patcher<T> {
4041
private continuousRouter = new Subject<Patch>();
4142
private continuousPatchObservable: Observable<Patch>;
4243
private observable: Observable<Patch>;
44+
private verifier = new PatchVerifier();
4345
readonly options: PatcherOptions<T>;
4446

4547
/**
@@ -52,6 +54,13 @@ export class Patcher<T> {
5254
maxFrequency: options.maxFrequency || _DefaultOptions.maxFrequency,
5355
};
5456

57+
// TODO: Double check the correctness of this code.
58+
// there are guard rails for handling multiple patches per tick
59+
// or filtering out empty patches, but they are only
60+
// applied to the total observable. If a consumer subscribes
61+
// to discrete patches, for example, they won't get these
62+
// guard rails. This is a potential bug.
63+
5564
//
5665
// throttle continuous patches to handle back-pressure. note that
5766
// unlike discrete changes, it is ok to miss some continuous changes.
@@ -108,22 +117,27 @@ export class Patcher<T> {
108117
/**
109118
* Applies a patch to the object. Will NOT notify subscribers.
110119
* @param patch The patch to apply.
111-
* @returns The new state of the object.
120+
* @returns The whether the state should change, and the new state of the object.
112121
*/
113-
patch(patch: Patch): T {
122+
patch(patch: Patch | SignedPatch, state?: T): { patched: boolean; result: T } {
114123
this.validate();
115124

116-
if (patch && patch.length > 0) {
117-
this._snapshot = patch.reduce((state, p, index) => {
125+
const verified = this.verifier.verified(patch);
126+
this._snapshot = state ?? this._snapshot;
127+
128+
if (verified && verified.length > 0) {
129+
this._snapshot = verified.reduce((state, p, index) => {
118130
try {
119131
return applyReducer(state, p, index);
120132
} catch {
121133
return state;
122134
}
123135
}, this.snapshot);
136+
137+
return { patched: true, result: this.snapshot };
124138
}
125139

126-
return this.snapshot;
140+
return { patched: false, result: this.snapshot };
127141
}
128142

129143
/**
@@ -185,7 +199,7 @@ export class Patcher<T> {
185199

186200
if (patch && patch.length) {
187201
const router = discreteChange ? this.discreteRouter : this.continuousRouter;
188-
router.next(patch);
202+
router.next(this.verifier.sign(patch));
189203
}
190204
}
191205

0 commit comments

Comments
 (0)