Skip to content

Commit

Permalink
Prevent re-applying locally defined commits #90
Browse files Browse the repository at this point in the history
  • Loading branch information
joepio committed Sep 20, 2021
1 parent 80d793c commit 850dd84
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
7 changes: 6 additions & 1 deletion lib/src/commit.ts
Expand Up @@ -173,13 +173,17 @@ export function parseAndApply(jsonAdObjStr: string, store: Store) {
jsonAdObj[urls.properties.commit.destroy];
// const createdAt = jsonAdObj[urls.properties.commit.createdAt];
// const signer = jsonAdObj[urls.properties.commit.signer];
// const signature = jsonAdObj[urls.properties.commit.signature];
const signature = jsonAdObj[urls.properties.commit.signature];

let resource = store.resources.get(subject);

// If the resource doesn't exist in the store, create the resource
if (resource == undefined) {
resource = new Resource(subject);
} else {
if (resource.appliedCommitSignatures.has(signature)) {
return;
}
}

set &&
Expand All @@ -197,6 +201,7 @@ export function parseAndApply(jsonAdObjStr: string, store: Store) {
store.removeResource(subject);
return;
} else {
resource.appliedCommitSignatures.add(signature);
store.addResource(resource);
}
}
11 changes: 10 additions & 1 deletion lib/src/resource.ts
Expand Up @@ -42,6 +42,11 @@ export class Resource {
new: boolean;
private status: ResourceStatus;
private commitBuilder: CommitBuilder;
/**
* Every commit that has been applied should be stored here, which prevents
* applying the same commit twice
*/
appliedCommitSignatures: Set<string>;

constructor(subject: string, newResource?: boolean) {
if (subject == undefined) {
Expand All @@ -50,6 +55,7 @@ export class Resource {
this.new = newResource ? true : false;
this.subject = subject;
this.propvals = new Map();
this.appliedCommitSignatures = new Set();
this.commitBuilder = new CommitBuilder(subject);
}

Expand Down Expand Up @@ -191,11 +197,14 @@ export class Resource {
// Clean up the commitBuilder, but save a backup if the server does not apply the commit.
const oldCommitBuilder = this.commitBuilder;
this.commitBuilder = new CommitBuilder(this.getSubject());
this.status == ResourceStatus.ready;
const commit = await oldCommitBuilder.sign(agent.privateKey, agent.subject);
// Add the signature to the list of applied ones, to prevent applying it again when the server
this.appliedCommitSignatures.add(commit.signature);
// Instantly (optimistically) save for local usage
// Doing this early is essential for having a snappy UX in the document editor
store.addResource(this);
// TODO: Check if all required props are there
const commit = await oldCommitBuilder.sign(agent.privateKey, agent.subject);
const endpoint = new URL(this.getSubject()).origin + `/commit`;
try {
this.commitError = null;
Expand Down

0 comments on commit 850dd84

Please sign in to comment.