Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Implement revert of invalid mutations

Hakan Shehu26933fdbd925
diff --git a/apps/desktop/src/main/data/workspace/migrations.ts b/apps/desktop/src/main/data/workspace/migrations.ts
index b6a3d9ac..c895ef3d 100644
--- a/apps/desktop/src/main/data/workspace/migrations.ts
+++ b/apps/desktop/src/main/data/workspace/migrations.ts
@@ -131,6 +131,7 @@ const createMessagesTable: Migration = {
.addColumn('created_by', 'text', (col) => col.notNull())
.addColumn('updated_at', 'text')
.addColumn('updated_by', 'text')
+ .addColumn('deleted_at', 'text')
.addColumn('version', 'integer')
.execute();
},
@@ -148,6 +149,7 @@ const createMessageReactionsTable: Migration = {
.addColumn('reaction', 'text', (col) => col.notNull())
.addColumn('root_id', 'text', (col) => col.notNull())
.addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('deleted_at', 'text')
.addColumn('version', 'integer', (col) => col.notNull())
.addPrimaryKeyConstraint('message_reactions_pkey', [
'message_id',
@@ -201,6 +203,7 @@ const createFilesTable: Migration = {
.addColumn('created_by', 'text', (col) => col.notNull())
.addColumn('updated_at', 'text')
.addColumn('updated_by', 'text')
+ .addColumn('deleted_at', 'text')
.addColumn('status', 'integer', (col) => col.notNull())
.addColumn('version', 'integer')
.execute();
diff --git a/apps/desktop/src/main/data/workspace/schema.ts b/apps/desktop/src/main/data/workspace/schema.ts
index dbf37604..53ec6cd7 100644
--- a/apps/desktop/src/main/data/workspace/schema.ts
+++ b/apps/desktop/src/main/data/workspace/schema.ts
@@ -108,6 +108,7 @@ interface MessageTable {
created_by: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
updated_by: ColumnType<string | null, string | null, string | null>;
+ deleted_at: ColumnType<string | null, never, string | null>;
version: ColumnType<bigint, bigint, bigint>;
}
@@ -121,6 +122,7 @@ interface MessageReactionTable {
reaction: ColumnType<string, string, string>;
root_id: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
+ deleted_at: ColumnType<string | null, never, string | null>;
version: ColumnType<bigint, bigint, bigint>;
}
@@ -157,6 +159,7 @@ interface FileTable {
created_by: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
updated_by: ColumnType<string | null, string | null, string | null>;
+ deleted_at: ColumnType<string | null, never, string | null>;
status: ColumnType<FileStatus, FileStatus, FileStatus>;
version: ColumnType<bigint, bigint, bigint>;
}
diff --git a/apps/desktop/src/main/jobs/revert-invalid-mutations.ts b/apps/desktop/src/main/jobs/revert-invalid-mutations.ts
new file mode 100644
index 00000000..ccfe9f92
--- /dev/null
+++ b/apps/desktop/src/main/jobs/revert-invalid-mutations.ts
@@ -0,0 +1,93 @@
+import { entryService } from '@/main/services/entry-service';
+import { fileService } from '@/main/services/file-service';
+import { messageService } from '@/main/services/message-service';
+import { createDebugger } from '@/main/debugger';
+import { databaseService } from '@/main/data/database-service';
+import { JobHandler } from '@/main/jobs';
+import { mapMutation } from '@/main/utils';
+
+export type RevertInvalidMutationsInput = {
+ type: 'revert_invalid_mutations';
+ userId: string;
+};
+
+declare module '@/main/jobs' {
+ interface JobMap {
+ revert_invalid_mutations: {
+ input: RevertInvalidMutationsInput;
+ };
+ }
+}
+
+export class RevertInvalidMutationsJobHandler
+ implements JobHandler<RevertInvalidMutationsInput>
+{
+ public triggerDebounce = 100;
+ public interval = 1000 * 60 * 5;
+
+ private readonly debug = createDebugger('job:revert-invalid-mutations');
+
+ public async handleJob(input: RevertInvalidMutationsInput) {
+ this.debug(`Reverting invalid mutations for user ${input.userId}`);
+
+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(
+ input.userId
+ );
+
+ const invalidMutations = await workspaceDatabase
+ .selectFrom('mutations')
+ .selectAll()
+ .where('retries', '>=', 10)
+ .execute();
+
+ if (invalidMutations.length === 0) {
+ this.debug(
+ `No invalid mutations found for user ${input.userId}, skipping`
+ );
+ return;
+ }
+
+ for (const mutationRow of invalidMutations) {
+ const mutation = mapMutation(mutationRow);
+
+ if (mutation.type === 'create_file') {
+ await fileService.revertFileCreation(input.userId, mutation.id);
+ } else if (mutation.type === 'delete_file') {
+ await fileService.revertFileDeletion(input.userId, mutation.id);
+ } else if (mutation.type === 'apply_create_transaction') {
+ await entryService.revertCreateTransaction(input.userId, mutation.data);
+ } else if (mutation.type === 'apply_update_transaction') {
+ await entryService.revertUpdateTransaction(input.userId, mutation.data);
+ } else if (mutation.type === 'apply_delete_transaction') {
+ await entryService.revertDeleteTransaction(input.userId, mutation.data);
+ } else if (mutation.type === 'create_message') {
+ await messageService.revertMessageCreation(
+ input.userId,
+ mutation.data.id
+ );
+ } else if (mutation.type === 'delete_message') {
+ await messageService.revertMessageDeletion(
+ input.userId,
+ mutation.data.id
+ );
+ } else if (mutation.type === 'create_message_reaction') {
+ await messageService.revertMessageReactionCreation(
+ input.userId,
+ mutation.data
+ );
+ } else if (mutation.type === 'delete_message_reaction') {
+ await messageService.revertMessageReactionDeletion(
+ input.userId,
+ mutation.data
+ );
+ }
+ }
+
+ const mutationIds = invalidMutations.map((m) => m.id);
+
+ await workspaceDatabase
+ .deleteFrom('mutations')
+ .where('id', 'in', mutationIds)
+ .execute();
+ }
+}
diff --git a/apps/desktop/src/main/jobs/revert-invalid-transactions.ts b/apps/desktop/src/main/jobs/revert-invalid-transactions.ts
deleted file mode 100644
index 6ee899e4..00000000
--- a/apps/desktop/src/main/jobs/revert-invalid-transactions.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-// import { entryService } from '@/main/services/entry-service';
-// import { createDebugger } from '@/main/debugger';
-// import { databaseService } from '@/main/data/database-service';
-// import { JobHandler } from '@/main/jobs';
-// import { mapTransaction } from '@/main/utils';
-
-// export type RevertInvalidTransactionsInput = {
-// type: 'revert_invalid_transactions';
-// userId: string;
-// };
-
-// declare module '@/main/jobs' {
-// interface JobMap {
-// revert_invalid_transactions: {
-// input: RevertInvalidTransactionsInput;
-// };
-// }
-// }
-
-// export class RevertInvalidTransactionsJobHandler
-// implements JobHandler<RevertInvalidTransactionsInput>
-// {
-// public triggerDebounce = 100;
-// public interval = 1000 * 60 * 5;
-
-// private readonly debug = createDebugger('job:revert-invalid-transactions');
-
-// public async handleJob(input: RevertInvalidTransactionsInput) {
-// this.debug(`Reverting invalid transactions for user ${input.userId}`);
-
-// const workspaceDatabase = await databaseService.getWorkspaceDatabase(
-// input.userId
-// );
-
-// const invalidTransactions = await workspaceDatabase
-// .selectFrom('transactions')
-// .selectAll()
-// .where('status', '=', 'pending')
-// .where('retry_count', '>=', 10)
-// .execute();
-
-// if (invalidTransactions.length === 0) {
-// this.debug(
-// `No invalid transactions found for user ${input.userId}, skipping`
-// );
-// return;
-// }
-
-// for (const transactionRow of invalidTransactions) {
-// const transaction = mapTransaction(transactionRow);
-
-// if (transaction.operation === 'create') {
-// await entryService.revertCreateTransaction(input.userId, transaction);
-// } else if (transaction.operation === 'update') {
-// await entryService.revertUpdateTransaction(input.userId, transaction);
-// } else if (transaction.operation === 'delete') {
-// await entryService.revertDeleteTransaction(input.userId, transaction);
-// }
-// }
-// }
-// }
diff --git a/apps/desktop/src/main/mutations/files/file-delete.ts b/apps/desktop/src/main/mutations/files/file-delete.ts
index f8de1f5c..a08a4b14 100644
--- a/apps/desktop/src/main/mutations/files/file-delete.ts
+++ b/apps/desktop/src/main/mutations/files/file-delete.ts
@@ -39,7 +39,13 @@ export class FileDeleteMutationHandler
};
await workspaceDatabase.transaction().execute(async (tx) => {
- await tx.deleteFrom('files').where('id', '=', input.fileId).execute();
+ await tx
+ .updateTable('files')
+ .set({
+ deleted_at: deletedAt,
+ })
+ .where('id', '=', input.fileId)
+ .execute();
await tx
.insertInto('mutations')
diff --git a/apps/desktop/src/main/mutations/messages/message-delete.ts b/apps/desktop/src/main/mutations/messages/message-delete.ts
index 62362621..2fdbf2cc 100644
--- a/apps/desktop/src/main/mutations/messages/message-delete.ts
+++ b/apps/desktop/src/main/mutations/messages/message-delete.ts
@@ -40,7 +40,10 @@ export class MessageDeleteMutationHandler
await workspaceDatabase.transaction().execute(async (tx) => {
await tx
- .deleteFrom('messages')
+ .updateTable('messages')
+ .set({
+ deleted_at: deletedAt,
+ })
.where('id', '=', input.messageId)
.execute();
diff --git a/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts b/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts
index aeeea4d0..a6007332 100644
--- a/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts
+++ b/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts
@@ -41,11 +41,14 @@ export class MessageReactionDeleteMutationHandler
.transaction()
.execute(async (trx) => {
const deletedMessageReaction = await trx
- .deleteFrom('message_reactions')
+ .updateTable('message_reactions')
+ .returningAll()
+ .set({
+ deleted_at: new Date().toISOString(),
+ })
.where('message_id', '=', input.messageId)
.where('collaborator_id', '=', input.userId)
.where('reaction', '=', input.reaction)
- .returningAll()
.executeTakeFirst();
if (!deletedMessageReaction) {
diff --git a/apps/desktop/src/main/queries/files/file-get.ts b/apps/desktop/src/main/queries/files/file-get.ts
index 3d9ff0fb..56940d4c 100644
--- a/apps/desktop/src/main/queries/files/file-get.ts
+++ b/apps/desktop/src/main/queries/files/file-get.ts
@@ -97,6 +97,7 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
'f.created_by',
'f.updated_at',
'f.updated_by',
+ 'f.deleted_at',
'f.status',
'f.version',
'fs.download_status',
@@ -105,9 +106,10 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
'fs.upload_progress',
])
.where('f.id', '=', input.id)
+ .where('f.deleted_at', 'is', null)
.executeTakeFirst();
- if (!file) {
+ if (!file || file.deleted_at) {
return null;
}
diff --git a/apps/desktop/src/main/queries/files/file-list.ts b/apps/desktop/src/main/queries/files/file-list.ts
index f0d04106..34c6eb96 100644
--- a/apps/desktop/src/main/queries/files/file-list.ts
+++ b/apps/desktop/src/main/queries/files/file-list.ts
@@ -113,6 +113,7 @@ export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
'f.created_by',
'f.updated_at',
'f.updated_by',
+ 'f.deleted_at',
'f.status',
'f.version',
'fs.download_status',
@@ -121,6 +122,7 @@ export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
'fs.upload_progress',
])
.where('f.parent_id', '=', input.parentId)
+ .where('f.deleted_at', 'is', null)
.orderBy('f.id', 'asc')
.limit(input.count)
.offset(offset)
diff --git a/apps/desktop/src/main/queries/messages/message-list.ts b/apps/desktop/src/main/queries/messages/message-list.ts
index 4430f313..716ee08a 100644
--- a/apps/desktop/src/main/queries/messages/message-list.ts
+++ b/apps/desktop/src/main/queries/messages/message-list.ts
@@ -100,6 +100,7 @@ export class MessageListQueryHandler
.selectFrom('messages')
.selectAll()
.where('parent_id', '=', input.conversationId)
+ .where('deleted_at', 'is', null)
.orderBy('id', 'desc')
.limit(input.count)
.offset(offset)
diff --git a/apps/desktop/src/main/queries/messages/message-reactions-get.ts b/apps/desktop/src/main/queries/messages/message-reactions-get.ts
index 8ba8c302..03b18495 100644
--- a/apps/desktop/src/main/queries/messages/message-reactions-get.ts
+++ b/apps/desktop/src/main/queries/messages/message-reactions-get.ts
@@ -86,7 +86,7 @@ export class MessageReactionsGetQueryHandler
ELSE 0
END) as reacted
FROM message_reactions
- WHERE message_id = ${input.messageId}
+ WHERE message_id = ${input.messageId} AND deleted_at IS NULL
GROUP BY reaction
`.execute(workspaceDatabase);
diff --git a/apps/desktop/src/main/scheduler.ts b/apps/desktop/src/main/scheduler.ts
index 548b2ee6..a7fc7373 100644
--- a/apps/desktop/src/main/scheduler.ts
+++ b/apps/desktop/src/main/scheduler.ts
@@ -8,7 +8,7 @@ import { JobHandler, JobInput, JobMap } from '@/main/jobs';
import { SyncServersJobHandler } from '@/main/jobs/sync-servers';
import { SyncAccountJobHandler } from '@/main/jobs/sync-account';
import { InitSynchronizersJobHandler } from '@/main/jobs/init-synchronizers';
-// import { RevertInvalidTransactionsJobHandler } from '@/main/jobs/revert-invalid-transactions';
+import { RevertInvalidMutationsJobHandler } from '@/main/jobs/revert-invalid-mutations';
import { SyncPendingMutationsJobHandler } from '@/main/jobs/sync-pending-mutations';
import { SyncDeletedTokensJobHandler } from '@/main/jobs/sync-deleted-tokens';
import { ConnectSocketJobHandler } from '@/main/jobs/connect-socket';
@@ -26,7 +26,7 @@ export const jobHandlerMap: JobHandlerMap = {
sync_servers: new SyncServersJobHandler(),
sync_account: new SyncAccountJobHandler(),
init_synchronizers: new InitSynchronizersJobHandler(),
- // revert_invalid_transactions: new RevertInvalidTransactionsJobHandler(),
+ revert_invalid_mutations: new RevertInvalidMutationsJobHandler(),
sync_pending_mutations: new SyncPendingMutationsJobHandler(),
sync_deleted_tokens: new SyncDeletedTokensJobHandler(),
connect_socket: new ConnectSocketJobHandler(),
@@ -239,10 +239,10 @@ class Scheduler {
userId,
});
- // this.schedule({
- // type: 'revert_invalid_transactions',
- // userId,
- // });
+ this.schedule({
+ type: 'revert_invalid_mutations',
+ userId,
+ });
this.schedule({
type: 'init_synchronizers',
@@ -294,12 +294,12 @@ class Scheduler {
return true;
}
- // if (
- // state.input.type === 'revert_invalid_transactions' &&
- // state.input.userId === userId
- // ) {
- // return true;
- // }
+ if (
+ state.input.type === 'revert_invalid_mutations' &&
+ state.input.userId === userId
+ ) {
+ return true;
+ }
if (state.input.type === 'upload_files' && state.input.userId === userId) {
return true;
diff --git a/apps/desktop/src/main/services/entry-service.ts b/apps/desktop/src/main/services/entry-service.ts
index 6f3f455f..28040f36 100644
--- a/apps/desktop/src/main/services/entry-service.ts
+++ b/apps/desktop/src/main/services/entry-service.ts
@@ -308,6 +308,7 @@ class EntryService {
if (!updatedEntry) {
return { updatedEntry: undefined };
}
+
const createdTransaction = await trx
.insertInto('entry_transactions')
.returningAll()
@@ -432,16 +433,6 @@ class EntryService {
return { deletedEntry: undefined };
}
- await trx
- .deleteFrom('entry_transactions')
- .where('entry_id', '=', entryId)
- .execute();
-
- await trx
- .deleteFrom('collaborations')
- .where('entry_id', '=', entryId)
- .execute();
-
await trx.deleteFrom('texts').where('id', '=', entryId).execute();
const createdTransaction = await trx
@@ -518,234 +509,6 @@ class EntryService {
}
}
- public async replaceTransactions(
- userId: string,
- entryId: string,
- transactions: SyncEntryTransactionData[],
- transactionCursor: bigint
- ): Promise<boolean> {
- for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryReplaceTransactions(
- userId,
- entryId,
- transactions,
- transactionCursor
- );
-
- if (result !== null) {
- return result;
- }
- }
-
- return false;
- }
-
- public async tryReplaceTransactions(
- userId: string,
- entryId: string,
- transactions: SyncEntryTransactionData[],
- transactionCursor: bigint
- ): Promise<boolean | null> {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const firstTransaction = transactions[0];
- if (!firstTransaction || firstTransaction.operation !== 'create') {
- return false;
- }
-
- if (transactionCursor < BigInt(firstTransaction.version)) {
- return false;
- }
-
- const lastTransaction = transactions[transactions.length - 1];
- if (!lastTransaction) {
- return false;
- }
-
- const ydoc = new YDoc();
- for (const transaction of transactions) {
- if (transaction.operation === 'delete') {
- await this.applyServerDeleteTransaction(userId, transaction);
- return true;
- }
-
- ydoc.applyUpdate(transaction.data);
- }
-
- const attributes = ydoc.getAttributes<EntryAttributes>();
- const model = registry.getModel(attributes.type);
- if (!model) {
- return false;
- }
-
- const attributesJson = JSON.stringify(attributes);
- const text = model.getText(entryId, attributes);
-
- const existingEntry = await workspaceDatabase
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', entryId)
- .executeTakeFirst();
-
- if (existingEntry) {
- const updatedEntry = await workspaceDatabase
- .transaction()
- .execute(async (trx) => {
- const updatedEntry = await trx
- .updateTable('entries')
- .returningAll()
- .set({
- attributes: attributesJson,
- updated_at:
- firstTransaction.id !== lastTransaction.id
- ? lastTransaction.createdAt
- : null,
- updated_by:
- firstTransaction.id !== lastTransaction.id
- ? lastTransaction.createdBy
- : null,
- transaction_id: lastTransaction.id,
- })
- .where('id', '=', entryId)
- .where('transaction_id', '=', existingEntry.transaction_id)
- .executeTakeFirst();
-
- if (!updatedEntry) {
- return undefined;
- }
-
- await trx
- .deleteFrom('entry_transactions')
- .where('entry_id', '=', entryId)
- .execute();
-
- await trx
- .insertInto('entry_transactions')
- .values(
- transactions.map((t) => ({
- id: t.id,
- entry_id: t.entryId,
- root_id: t.rootId,
- operation: t.operation,
- data:
- t.operation !== 'delete' && t.data
- ? decodeState(t.data)
- : null,
- created_at: t.createdAt,
- created_by: t.createdBy,
- retry_count: 0,
- status: 'synced',
- version: BigInt(t.version),
- server_created_at: t.serverCreatedAt,
- }))
- )
- .execute();
-
- if (text !== undefined) {
- await trx.deleteFrom('texts').where('id', '=', entryId).execute();
- }
-
- if (text) {
- await trx
- .insertInto('texts')
- .values({ id: entryId, name: text.name, text: text.text })
- .execute();
- }
- });
-
- if (updatedEntry) {
- eventBus.publish({
- type: 'entry_updated',
- userId,
- entry: mapEntry(updatedEntry),
- });
-
- return true;
- }
-
- return null;
- }
-
- const createdEntry = await workspaceDatabase
- .transaction()
- .execute(async (trx) => {
- const createdEntry = await trx
- .insertInto('entries')
- .returningAll()
- .values({
- id: entryId,
- root_id: firstTransaction.rootId,
- attributes: attributesJson,
- created_at: firstTransaction.createdAt,
- created_by: firstTransaction.createdBy,
- updated_at:
- firstTransaction.id !== lastTransaction.id
- ? lastTransaction.createdAt
- : null,
- updated_by:
- firstTransaction.id !== lastTransaction.id
- ? lastTransaction.createdBy
- : null,
- transaction_id: lastTransaction.id,
- })
- .onConflict((b) => b.doNothing())
- .executeTakeFirst();
-
- if (!createdEntry) {
- return undefined;
- }
-
- await trx
- .deleteFrom('entry_transactions')
- .where('entry_id', '=', entryId)
- .execute();
-
- await trx
- .insertInto('entry_transactions')
- .values(
- transactions.map((t) => ({
- id: t.id,
- entry_id: t.entryId,
- root_id: t.rootId,
- operation: t.operation,
- data:
- t.operation !== 'delete' && t.data ? decodeState(t.data) : null,
- created_at: t.createdAt,
- created_by: t.createdBy,
- retry_count: 0,
- status: 'synced',
- version: BigInt(t.version),
- server_created_at: t.serverCreatedAt,
- }))
- )
- .execute();
-
- if (text !== undefined) {
- await trx.deleteFrom('texts').where('id', '=', entryId).execute();
- }
-
- if (text) {
- await trx
- .insertInto('texts')
- .values({ id: entryId, name: text.name, text: text.text })
- .execute();
- }
- });
-
- if (createdEntry) {
- eventBus.publish({
- type: 'entry_created',
- userId,
- entry: mapEntry(createdEntry),
- });
-
- return true;
- }
-
- return null;
- }
-
private async applyServerCreateTransaction(
userId: string,
transaction: SyncCreateEntryTransactionData
@@ -904,11 +667,6 @@ class EntryService {
return;
}
- const model = registry.getModel(transaction.entryId);
- if (!model) {
- return;
- }
-
const previousTransactions = await workspaceDatabase
.selectFrom('entry_transactions')
.selectAll()
@@ -926,6 +684,12 @@ class EntryService {
ydoc.applyUpdate(transaction.data);
const attributes = ydoc.getAttributes<EntryAttributes>();
+
+ const model = registry.getModel(attributes.type);
+ if (!model) {
+ return;
+ }
+
const text = model.getText(transaction.entryId, attributes);
const { updatedEntry } = await workspaceDatabase
@@ -1008,45 +772,45 @@ class EntryService {
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
- const entry = await workspaceDatabase
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', transaction.entryId)
- .executeTakeFirst();
+ const { deletedEntry } = await workspaceDatabase
+ .transaction()
+ .execute(async (trx) => {
+ const deletedEntry = await trx
+ .deleteFrom('entries')
+ .returningAll()
+ .where('id', '=', transaction.entryId)
+ .executeTakeFirst();
- if (!entry) {
- return;
- }
+ await trx
+ .deleteFrom('entry_transactions')
+ .where('entry_id', '=', transaction.entryId)
+ .execute();
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .deleteFrom('entries')
- .where('id', '=', transaction.entryId)
- .execute();
- await trx
- .deleteFrom('entry_transactions')
- .where('entry_id', '=', transaction.entryId)
- .execute();
+ await trx
+ .deleteFrom('entry_interactions')
+ .where('entry_id', '=', transaction.entryId)
+ .execute();
- await trx
- .deleteFrom('collaborations')
- .where('entry_id', '=', transaction.entryId)
- .execute();
+ await trx
+ .deleteFrom('texts')
+ .where('id', '=', transaction.entryId)
+ .execute();
- await trx
- .deleteFrom('texts')
- .where('id', '=', transaction.entryId)
- .execute();
- });
+ return { deletedEntry };
+ });
this.debug(
- `Deleted entry ${entry.id} with type ${entry.type} with transaction ${transaction.id}`
+ `Deleted entry ${transaction.entryId} with transaction ${transaction.id}`
);
+ if (!deletedEntry) {
+ return;
+ }
+
eventBus.publish({
type: 'entry_deleted',
userId,
- entry: mapEntry(entry),
+ entry: mapEntry(deletedEntry),
});
}
@@ -1089,9 +853,14 @@ class EntryService {
.execute();
await tx
- .deleteFrom('collaborations')
+ .deleteFrom('entry_interactions')
.where('entry_id', '=', transaction.entryId)
.execute();
+
+ await tx
+ .deleteFrom('texts')
+ .where('id', '=', transaction.entryId)
+ .execute();
});
eventBus.publish({
@@ -1128,6 +897,22 @@ class EntryService {
.executeTakeFirst();
if (!entry) {
+ // Make sure we don't have any data left behind
+ await workspaceDatabase
+ .deleteFrom('entry_transactions')
+ .where('id', '=', transaction.id)
+ .execute();
+
+ await workspaceDatabase
+ .deleteFrom('entry_interactions')
+ .where('entry_id', '=', transaction.entryId)
+ .execute();
+
+ await workspaceDatabase
+ .deleteFrom('texts')
+ .where('id', '=', transaction.entryId)
+ .execute();
+
return true;
}
@@ -1228,10 +1013,108 @@ class EntryService {
return;
}
- await workspaceDatabase
- .deleteFrom('entry_transactions')
- .where('id', '=', transaction.id)
+ const previousTransactions = await workspaceDatabase
+ .selectFrom('entry_transactions')
+ .selectAll()
+ .where('entry_id', '=', transaction.entryId)
+ .orderBy('id', 'asc')
.execute();
+
+ const ydoc = new YDoc();
+
+ let lastTransaction: SelectEntryTransaction | undefined;
+ for (const previousTransaction of previousTransactions) {
+ if (previousTransaction.id === transaction.id) {
+ continue;
+ }
+
+ if (previousTransaction.data) {
+ ydoc.applyUpdate(previousTransaction.data);
+ }
+
+ lastTransaction = previousTransaction;
+ }
+
+ if (!lastTransaction) {
+ return true;
+ }
+
+ const attributes = ydoc.getAttributes<EntryAttributes>();
+ const model = registry.getModel(attributes.type);
+ if (!model) {
+ return true;
+ }
+
+ const text = model.getText(transaction.entryId, attributes);
+
+ const createdEntry = await workspaceDatabase
+ .transaction()
+ .execute(async (trx) => {
+ const createdEntry = await trx
+ .insertInto('entries')
+ .returningAll()
+ .values({
+ id: transaction.entryId,
+ root_id: transaction.rootId,
+ created_at: lastTransaction.created_at,
+ created_by: lastTransaction.created_by,
+ attributes: JSON.stringify(attributes),
+ updated_at: lastTransaction.created_at,
+ updated_by: lastTransaction.created_by,
+ transaction_id: lastTransaction.id,
+ })
+ .onConflict((b) =>
+ b
+ .columns(['id'])
+ .doUpdateSet({
+ attributes: JSON.stringify(attributes),
+ updated_at: lastTransaction.created_at,
+ updated_by: lastTransaction.created_by,
+ transaction_id: lastTransaction.id,
+ })
+ .where('transaction_id', '=', transaction.id)
+ )
+ .executeTakeFirst();
+
+ if (!createdEntry) {
+ return undefined;
+ }
+
+ await trx
+ .deleteFrom('entry_transactions')
+ .where('id', '=', transaction.id)
+ .execute();
+
+ if (text !== undefined) {
+ await trx
+ .deleteFrom('texts')
+ .where('id', '=', transaction.entryId)
+ .execute();
+ }
+
+ if (text) {
+ await trx
+ .insertInto('texts')
+ .values({
+ id: transaction.entryId,
+ name: text.name,
+ text: text.text,
+ })
+ .execute();
+ }
+ });
+
+ if (createdEntry) {
+ eventBus.publish({
+ type: 'entry_created',
+ userId,
+ entry: mapEntry(createdEntry),
+ });
+
+ return true;
+ }
+
+ return false;
}
public async syncServerEntryInteraction(
diff --git a/apps/desktop/src/main/services/file-service.ts b/apps/desktop/src/main/services/file-service.ts
index d0a44381..d7e97c47 100644
--- a/apps/desktop/src/main/services/file-service.ts
+++ b/apps/desktop/src/main/services/file-service.ts
@@ -626,6 +626,71 @@ class FileService {
`Server file interaction for file ${fileInteraction.fileId} has been synced`
);
}
+
+ public async revertFileCreation(userId: string, fileId: string) {
+ const workspaceDatabase =
+ await databaseService.getWorkspaceDatabase(userId);
+
+ const deletedFile = await workspaceDatabase
+ .deleteFrom('files')
+ .returningAll()
+ .where('id', '=', fileId)
+ .executeTakeFirst();
+
+ if (!deletedFile) {
+ return;
+ }
+
+ await workspaceDatabase
+ .deleteFrom('file_states')
+ .returningAll()
+ .where('file_id', '=', fileId)
+ .executeTakeFirst();
+
+ await workspaceDatabase
+ .deleteFrom('file_interactions')
+ .where('file_id', '=', fileId)
+ .execute();
+
+ const filePath = path.join(
+ getWorkspaceFilesDirectoryPath(userId),
+ `${fileId}${deletedFile.extension}`
+ );
+
+ if (fs.existsSync(filePath)) {
+ fs.rmSync(filePath, { force: true });
+ }
+
+ eventBus.publish({
+ type: 'file_deleted',
+ userId,
+ file: mapFile(deletedFile),
+ });
+ }
+
+ public async revertFileDeletion(userId: string, fileId: string) {
+ const workspaceDatabase =
+ await databaseService.getWorkspaceDatabase(userId);
+
+ const deletedFile = await workspaceDatabase
+ .updateTable('files')
+ .returningAll()
+ .set({
+ deleted_at: null,
+ })
+ .where('id', '=', fileId)
+ .executeTakeFirst();
+
+ if (!deletedFile) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'file_created',
+ userId,
+ file: mapFile(deletedFile),
+ });
+ }
}
export const fileService = new FileService();
diff --git a/apps/desktop/src/main/services/message-service.ts b/apps/desktop/src/main/services/message-service.ts
index f43a6b98..e9f96490 100644
--- a/apps/desktop/src/main/services/message-service.ts
+++ b/apps/desktop/src/main/services/message-service.ts
@@ -1,10 +1,13 @@
import {
+ CreateMessageReactionMutationData,
+ DeleteMessageReactionMutationData,
extractText,
SyncMessageData,
SyncMessageInteractionData,
SyncMessageReactionData,
} from '@colanode/core';
+import { fileService } from '@/main/services/file-service';
import {
mapMessage,
mapMessageInteraction,
@@ -283,6 +286,126 @@ class MessageService {
`Server message interaction for message ${messageInteraction.messageId} has been synced`
);
}
+
+ public async revertMessageCreation(userId: string, messageId: string) {
+ const workspaceDatabase =
+ await databaseService.getWorkspaceDatabase(userId);
+
+ const deletedMessage = await workspaceDatabase
+ .deleteFrom('messages')
+ .returningAll()
+ .where('id', '=', messageId)
+ .executeTakeFirst();
+
+ if (!deletedMessage) {
+ return;
+ }
+
+ await workspaceDatabase
+ .deleteFrom('message_reactions')
+ .where('message_id', '=', messageId)
+ .execute();
+
+ await workspaceDatabase
+ .deleteFrom('message_interactions')
+ .where('message_id', '=', messageId)
+ .execute();
+
+ eventBus.publish({
+ type: 'message_deleted',
+ userId,
+ message: mapMessage(deletedMessage),
+ });
+
+ const files = await workspaceDatabase
+ .selectFrom('files')
+ .selectAll()
+ .where('parent_id', '=', messageId)
+ .execute();
+
+ for (const file of files) {
+ await fileService.revertFileCreation(userId, file.id);
+ }
+ }
+
+ public async revertMessageDeletion(userId: string, messageId: string) {
+ const workspaceDatabase =
+ await databaseService.getWorkspaceDatabase(userId);
+
+ const deletedMessage = await workspaceDatabase
+ .updateTable('messages')
+ .returningAll()
+ .set({
+ deleted_at: null,
+ })
+ .where('id', '=', messageId)
+ .executeTakeFirst();
+
+ if (!deletedMessage) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'message_created',
+ userId,
+ message: mapMessage(deletedMessage),
+ });
+ }
+
+ public async revertMessageReactionCreation(
+ userId: string,
+ messageReaction: CreateMessageReactionMutationData
+ ) {
+ const workspaceDatabase =
+ await databaseService.getWorkspaceDatabase(userId);
+
+ const deletedMessageReaction = await workspaceDatabase
+ .deleteFrom('message_reactions')
+ .returningAll()
+ .where('message_id', '=', messageReaction.messageId)
+ .where('collaborator_id', '=', userId)
+ .where('reaction', '=', messageReaction.reaction)
+ .executeTakeFirst();
+
+ if (!deletedMessageReaction) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'message_reaction_deleted',
+ userId,
+ messageReaction: mapMessageReaction(deletedMessageReaction),
+ });
+ }
+
+ public async revertMessageReactionDeletion(
+ userId: string,
+ messageReaction: DeleteMessageReactionMutationData
+ ) {
+ const workspaceDatabase =
+ await databaseService.getWorkspaceDatabase(userId);
+
+ const createdMessageReaction = await workspaceDatabase
+ .updateTable('message_reactions')
+ .returningAll()
+ .set({
+ deleted_at: null,
+ })
+ .where('message_id', '=', messageReaction.messageId)
+ .where('collaborator_id', '=', userId)
+ .where('reaction', '=', messageReaction.reaction)
+ .executeTakeFirst();
+
+ if (!createdMessageReaction) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'message_reaction_created',
+ userId,
+ messageReaction: mapMessageReaction(createdMessageReaction),
+ });
+ }
}
export const messageService = new MessageService();