Skip to content

Commit

Permalink
short-links: Wrap short_id creation into a transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
clbn committed Jan 19, 2022
1 parent 8f220e2 commit 6554ea0
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions app/support/DbAdapter/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,19 @@ const postsTrait = (superClass) =>
// https://github.com/knex/knex/issues/2622
toTSVector(preparedPayload.body).replace(/\?/g, '\\?'),
);
const [postId] = await this.database('posts').returning('uid').insert(preparedPayload);

// Create a short Id for this post
await this.createPostShortId(postId);
const postId = await this.database.transaction(async (trx) => {
// Lock post_short_ids table to prevent any updates
await trx.raw('lock table post_short_ids in share row exclusive mode');

// Create post
const [postId] = await trx('posts').insert(preparedPayload).returning('uid');

// Create a short ID for this post
await this.createPostShortId(trx, postId);

return postId;
});

// Update backlinks in the post body
await this.updateBacklinks(payload.body, postId);
Expand Down Expand Up @@ -408,23 +417,23 @@ const postsTrait = (superClass) =>
return this.getUsersByIds(adminIds);
}

async createPostShortId(longId) {
async createPostShortId(trx, longId) {
let length = config.postShortIds.initialLength;

for (; ; length++) {
// eslint-disable-next-line no-await-in-loop
if (await this.createPostShortIdForLength(longId, length)) {
if (await this.createPostShortIdForLength(trx, longId, length)) {
return;
}
}
}

async createPostShortIdForLength(longId, length) {
async createPostShortIdForLength(trx, longId, length) {
for (let i = 0; i < config.postShortIds.maxAttempts; i++) {
const shortId = this.getDecentRandomString(length);

// eslint-disable-next-line no-await-in-loop
const res = await this.database('post_short_ids')
const res = await trx('post_short_ids')
.insert({ short_id: shortId, long_id: longId })
.returning('short_id');

Expand Down

0 comments on commit 6554ea0

Please sign in to comment.