Files
Tom Moor f95761dddf perf: Use FOR NO KEY UPDATE where locked rows are only updated (#14559)
* perf: Use FOR NO KEY UPDATE where locked rows are only updated

Rows that other tables reference by foreign key are now locked with
FOR NO KEY UPDATE when the transaction only updates or soft-deletes
them, so concurrent inserts that reference the row are not blocked.

* test: Collaborative save does not wait for foreign key inserts
2026-11-12 18:54:37 -05:00

161 lines
3.6 KiB
TypeScript

import { cloneDeep, uniq } from "es-toolkit/compat";
import type {
Attributes,
CreationAttributes,
FindOrCreateOptions,
InferAttributes,
InferCreationAttributes,
InstanceDestroyOptions,
} from "sequelize";
import {
AfterCreate,
AfterDestroy,
BelongsTo,
Column,
DataType,
ForeignKey,
Table,
} from "sequelize-typescript";
import { createContext } from "@server/context";
import type { APIContext } from "@server/types";
import Comment from "./Comment";
import User from "./User";
import IdModel from "./base/IdModel";
import Length from "./validators/Length";
@Table({ tableName: "reactions", modelName: "reaction" })
class Reaction extends IdModel<
InferAttributes<Reaction>,
Partial<InferCreationAttributes<Reaction>>
> {
@Length({
max: 50,
msg: `emoji must be 50 characters or less`,
})
@Column(DataType.STRING)
emoji: string;
// associations
@BelongsTo(() => User)
user: User;
@ForeignKey(() => User)
@Column(DataType.UUID)
userId: string;
@BelongsTo(() => Comment)
comment: Comment;
@ForeignKey(() => Comment)
@Column(DataType.UUID)
commentId: string;
@AfterCreate
public static async addReactionToCommentCache(
model: Reaction,
ctx: APIContext["context"] &
FindOrCreateOptions<Attributes<Reaction>, CreationAttributes<Reaction>>
) {
const { transaction } = ctx;
const lock = transaction
? {
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
}
: undefined;
const comment = await Comment.findByPk(model.commentId, {
transaction,
lock,
});
if (!comment) {
return;
}
const reactions = cloneDeep(comment.reactions) ?? [];
const reaction = reactions.find((r) => r.emoji === model.emoji);
if (!reaction) {
reactions.push({ emoji: model.emoji, userIds: [model.userId] });
} else {
reaction.userIds = uniq([...reaction.userIds, model.userId]);
}
comment.reactions = reactions;
// Pass only the fields needed in APIContext; otherwise sequelize props will be overwritten.
const context = createContext({
user: ctx.auth.user,
authType: ctx.auth.type,
...ctx,
});
await comment.saveWithCtx(
context,
{
fields: ["reactions"],
silent: true,
},
{ name: "add_reaction", data: { emoji: model.emoji } }
);
}
@AfterDestroy
public static async removeReactionFromCommentCache(
model: Reaction,
ctx: APIContext["context"] & InstanceDestroyOptions
) {
const { transaction } = ctx;
const lock = transaction
? {
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
}
: undefined;
const comment = await Comment.findByPk(model.commentId, {
transaction,
lock,
});
if (!comment) {
return;
}
let reactions = cloneDeep(comment.reactions) ?? [];
const reaction = reactions.find((r) => r.emoji === model.emoji);
if (reaction) {
reaction.userIds = reaction.userIds.filter((id) => id !== model.userId);
if (reaction.userIds.length === 0) {
reactions = reactions.filter((r) => r.emoji !== model.emoji);
}
}
comment.reactions = reactions;
// Pass only the fields needed in APIContext; otherwise sequelize props will be overwritten.
const context = createContext({
user: ctx.auth.user,
authType: ctx.auth.type,
...ctx,
});
await comment.saveWithCtx(
context,
{
fields: ["reactions"],
silent: true,
},
{ name: "remove_reaction", data: { emoji: model.emoji } }
);
}
}
export default Reaction;