Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(j-s): Rollback subpoena entry if we get an error while creating it #16155

Closed
wants to merge 3 commits into from

Conversation

unakb
Copy link
Member

@unakb unakb commented Sep 25, 2024

What

Handle police creation errors by rolling back a transaction so we don't flood the db with failed subpoenas

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Enhanced subpoena creation process to support database transactions, improving data integrity during operations.
  • Bug Fixes

    • Improved atomicity of subpoena creation and updates, ensuring all operations succeed or fail together.

@unakb unakb requested a review from a team as a code owner September 25, 2024 13:40
Copy link
Contributor

coderabbitai bot commented Sep 25, 2024

Walkthrough

The changes involve modifications to the SubpoenaService class, specifically the createSubpoena and update methods. The createSubpoena method now accepts an additional transaction parameter to facilitate the creation of subpoenas within a database transaction. The update method has been refactored to ensure that both the creation of the subpoena and the update of its associated record are wrapped in a Sequelize transaction, allowing for atomic execution and improved data integrity.

Changes

File Change Summary
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts Updated createSubpoena method to accept a transaction parameter. Refactored update method to wrap operations in a transaction.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • oddsson

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1726e51 and 3a8aa02.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Sep 25, 2024

Codecov Report

Attention: Patch coverage is 0% with 7 lines in your changes missing coverage. Please review.

Project coverage is 36.59%. Comparing base (59391dd) to head (3a8aa02).
Report is 78 commits behind head on main.

Files with missing lines Patch % Lines
...ckend/src/app/modules/subpoena/subpoena.service.ts 0.00% 7 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16155      +/-   ##
==========================================
- Coverage   36.64%   36.59%   -0.06%     
==========================================
  Files        6769     6770       +1     
  Lines      139435   139652     +217     
  Branches    39656    39713      +57     
==========================================
+ Hits        51100    51109       +9     
- Misses      88335    88543     +208     
Flag Coverage Δ
judicial-system-backend 54.81% <0.00%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...ckend/src/app/modules/subpoena/subpoena.service.ts 0.00% <0.00%> (ø)

... and 10 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 59391dd...3a8aa02. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Sep 25, 2024

Datadog Report

Branch report: j-s/subpoena-transaction
Commit report: b56aadd
Test service: judicial-system-backend

✅ 0 Failed, 21271 Passed, 0 Skipped, 20m 2.73s Total Time
➡️ Test Sessions change in coverage: 1 no change

Copy link
Member

@gudjong gudjong left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A minor fix needed to trigger rollback in case of failure.

if (!createdSubpoena) {
this.logger.error('Failed to create subpoena file for police')
return { delivered: false }
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not absolutely sure, but I don't think this will rollback the transaction. I think you need to throw an exception for that.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked the documentation and my understanding is correct. You need to throw to trigger a rollback. The catch clause below returns the right delivered status so that should be fine.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok weird because I tried it locally and it rolled back! I'll try again tomorrow to confirm but I can always add in an exception just in case

Copy link
Member

@gudjong gudjong Sep 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hér er skjölunin fyrir þetta:

try {
  const transaction = await sequelize.transaction();
  const user = await User.findOne(..., { transaction });
  await user.update(..., { transaction });
  await transaction.commit();
} catch(err) {
  await transaction.rollback();
}
try {
  await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no arguments
  const user = await User.findOne(..., {transaction});
  await user.update(..., {transaction});
  // Committed
} catch(err) {
  // Rolled back
  console.error(err);
}

Þú getur annað hvort búið til transaction og séð sjálf um commit og rollback, eða sent callback inn í transaction fallið og látið transaction fallið sjá um commit og rollback. Til að fallið geti rollbackað callbackið er það væntanlega með try/catch utan um callbackið og þess vegna þarf throw.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aa ok ég veit af hverju þetta virkaði þegar ég prófaði locally - af því þá var createsubpoena kallið að kasta exception ekki skila villu eða tómu svari þannig ég datt ekkert inn í if(!created)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Í rauninni gæti ég bara tekið þessa if setningu alveg út, er að kasta exceptions ef eitthvað klikkar í lögreglukallinu þannig þetta er eiginlega unreachable kóði

Copy link
Member

@gudjong gudjong left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, one suggestion.

defendant: Defendant,
transaction: Transaction,
): Promise<Subpoena> {
return await this.subpoenaModel.create(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't have to await here, so you may consider removing the await.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done ✔️

@unakb unakb added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Sep 26, 2024
@kodiakhq kodiakhq bot removed the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Sep 27, 2024
Copy link
Contributor

kodiakhq bot commented Sep 27, 2024

This PR currently has a merge conflict. Please resolve this and then re-add the automerge label.

@unakb unakb added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Oct 3, 2024
Copy link
Contributor

kodiakhq bot commented Oct 3, 2024

This PR currently has a merge conflict. Please resolve this and then re-add the automerge label.

@kodiakhq kodiakhq bot removed the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Oct 3, 2024
@unakb unakb closed this Oct 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants