mirror of
https://github.com/outline/outline.git
synced 2026-11-27 07:58:51 +03:00
* fix: Make count-based limit checks reliable under concurrency Limits enforced by counting rows before an insert could be exceeded by requests that ran at the same time, as each one read the same count before any of them had written. Add a LockHelper that takes a Postgres advisory lock for the remainder of the transaction, and use it to serialize the check for webhook subscriptions, team domains, share subscriptions and pins. The counts now also run on the transaction so they include rows written earlier in the same request. * Remove excessive tests * Also guard simultaneous row removal
71 lines
2.0 KiB
TypeScript
71 lines
2.0 KiB
TypeScript
import fractionalIndex from "fractional-index";
|
|
import type { WhereOptions } from "sequelize";
|
|
import { Sequelize, Op } from "sequelize";
|
|
import type { User } from "@server/models";
|
|
import { Pin } from "@server/models";
|
|
import type { APIContext } from "@server/types";
|
|
|
|
type Props = {
|
|
/** The request context */
|
|
ctx: APIContext;
|
|
/** The user creating the pin */
|
|
user: User;
|
|
/** The document to pin */
|
|
documentId: string;
|
|
/** The collection to pin the document in. If no collection is provided then it will be pinned to home */
|
|
collectionId?: string | null;
|
|
/** The index to pin the document at. If no index is provided then it will be pinned to the end of the collection */
|
|
index?: string;
|
|
};
|
|
|
|
/**
|
|
* This command creates a "pinned" document via the pin relation. A document can
|
|
* be pinned to a collection or to the home screen.
|
|
*
|
|
* @param Props The properties of the pin to create
|
|
* @returns Pin The pin that was created
|
|
*/
|
|
export default async function pinCreator({
|
|
ctx,
|
|
user,
|
|
documentId,
|
|
collectionId,
|
|
...rest
|
|
}: Props): Promise<Pin> {
|
|
let { index } = rest;
|
|
const { transaction } = ctx.context;
|
|
const where: WhereOptions<Pin> = {
|
|
teamId: user.teamId,
|
|
...(collectionId ? { collectionId } : { collectionId: { [Op.is]: null } }),
|
|
};
|
|
|
|
if (!index) {
|
|
const pins = await Pin.findAll({
|
|
where,
|
|
attributes: ["id", "index", "updatedAt"],
|
|
transaction,
|
|
limit: 1,
|
|
order: [
|
|
// using LC_COLLATE:"C" because we need byte order to drive the sorting
|
|
// find only the last pin so we can create an index after it
|
|
Sequelize.literal('"pin"."index" collate "C" DESC'),
|
|
["updatedAt", "ASC"],
|
|
],
|
|
});
|
|
|
|
// create a pin at the end of the list
|
|
index = fractionalIndex(pins.length ? pins[0].index : null, null);
|
|
}
|
|
|
|
const [pin] = await Pin.findOrCreateWithCtx(ctx, {
|
|
where: {
|
|
collectionId: collectionId ?? null,
|
|
documentId,
|
|
teamId: user.teamId,
|
|
},
|
|
defaults: { index, createdById: user.id },
|
|
});
|
|
|
|
return pin;
|
|
}
|