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

Added persistence helpers to the jobs service #22246

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

9larsons
Copy link
Contributor

@9larsons 9larsons commented Feb 19, 2025

ref https://linear.app/ghost/issue/ENG-2027/

The email analytics job has had a one-off/custom implementation of using the jobs table to persist started_at and finished_at timestamps for the analytics jobs. This would be helpful for other scheduled/recurring jobs, so this adds helper fns to the JobsService to do so.

The intent is for an entry in the jobs table to simply hold the last started/finished times so we don't need to schedule a random time on Ghost boot. This ensures jobs are run daily, etc, in the event of frequent reboots.

This also expands the unit test coverage to ~95% for the job manager lib.

ref https://linear.app/ghost/issue/ENG-2027/

The email analytics job has had a one-off/custom implementation of using the jobs table to persist `started_at` and `finished_at` timestamps for the analytics jobs. This would be helpful for other scheduled/recurring jobs, so this adds helper fns to the JobsService to do so.

The intent is for an entry in the `jobs` table to simply hold the last started/finished times so we don't need to schedule a random time on Ghost boot. This ensures jobs are run daily, etc, in the event of frequent reboots.
Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

Walkthrough

The changes introduce new asynchronous methods in both the JobManager and JobsRepository classes to improve the handling of job data, timestamps, and statuses. In the JobManager, methods are added to fetch job data, retrieve the last job run timestamp, update job timestamps, and set job statuses. Similarly, the JobsRepository now supports operations for retrieving the last run timestamp, managing job timestamps with proper error handling for incorrect fields, and updating the status of a job. Additionally, the test suite has been updated to validate the new functionalities and error conditions, ensuring that the changes work as intended in various scenarios.

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cee2b99 and ac23645.

📒 Files selected for processing (3)
  • ghost/job-manager/lib/JobManager.js (1 hunks)
  • ghost/job-manager/lib/JobsRepository.js (2 hunks)
  • ghost/job-manager/test/job-manager.test.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Ghost-CLI tests
  • GitHub Check: Database tests (Node 20.11.1, sqlite3)
  • GitHub Check: Database tests (Node 22.13.1, mysql8)
  • GitHub Check: Database tests (Node 20.11.1, mysql8)
  • GitHub Check: Regression tests (Node 20.11.1, sqlite3)
  • GitHub Check: Database tests (Node 18.12.1, mysql8)
  • GitHub Check: Regression tests (Node 20.11.1, mysql8)
🔇 Additional comments (9)
ghost/job-manager/test/job-manager.test.js (3)

740-851: Solid test coverage for persistent job data.

Overall, the tests in this range comprehensively verify the behavior of:

  • getLastJobRunTimestamp()
  • setJobTimestamp()
  • setJobStatus()

They cover both success and error scenarios, ensuring a well-rounded validation of job timestamps and statuses.


852-951: Good repository test organization.

The test cases for getQueuedJobs, delete, and addQueuedJob thoroughly check default/custom limits, error handling, and transaction usage. This ensures reliability and correctness when managing queued jobs.


952-1016: Robust error handling tests.

These tests effectively confirm:

  • Worker messages without a custom handler
  • Domain event dispatch
  • Promise rejections for both single job and “all jobs” in-flight

They help guarantee the JobManager can gracefully handle errors and signal failures correctly.

ghost/job-manager/lib/JobsRepository.js (2)

3-3: Import usage is appropriate.

The import of IncorrectUsageError is well-placed for validating timestamp fields.


136-145: Neat retrieval of last run timestamp.

The getLastRunTimestamp method correctly returns finished_at if available, otherwise falling back to started_at. Good clarity for “latest” run detection.

ghost/job-manager/lib/JobManager.js (4)

477-481: Helper to retrieve job data.

getJobData is straightforward, returning early if no repository is present.


489-499: Timestamp retrieval integration.

getLastJobRunTimestamp neatly delegates to the repository. Looks good for confirming the last known completion or start time.


501-512: Timestamp assignment logic is clear.

setJobTimestamp does a no-op if the repository is absent to avoid runtime errors in ephemeral environments. This aligns with the intended fallback behavior.


514-524: Clean status update delegation.

setJobStatus similarly delegates, enabling flexible job status tracking. With the repository fix for ID usage, this logic works nicely.

Comment on lines +147 to +166
/**
* Updates or creates a job's timestamp
* @param {string} name - The name of the job
* @param {'started_at'|'finished_at'} field - The timestamp field to update
* @param {Date} date - The timestamp value
*/
async setTimestamp(name, field, date) {
if (field !== 'started_at' && field !== 'finished_at') {
throw new IncorrectUsageError({
message: `Invalid timestamp field "${field}". Must be either "started_at" or "finished_at"`
});
}

const job = await this.read(name);
if (!job) {
await this.add({name, [field]: date});
} else {
await this.update(name, {[field]: date});
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Likely ID mismatch in update calls.

In setTimestamp, the update function expects the job's ID, but the code calls this.update(name, {…}). It should instead call this.update(job.id, {…}) to ensure the existing job is updated correctly. Otherwise, the edit will target an invalid ID.

- await this.update(name, {[field]: date});
+ await this.update(job.id, {[field]: date});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* Updates or creates a job's timestamp
* @param {string} name - The name of the job
* @param {'started_at'|'finished_at'} field - The timestamp field to update
* @param {Date} date - The timestamp value
*/
async setTimestamp(name, field, date) {
if (field !== 'started_at' && field !== 'finished_at') {
throw new IncorrectUsageError({
message: `Invalid timestamp field "${field}". Must be either "started_at" or "finished_at"`
});
}
const job = await this.read(name);
if (!job) {
await this.add({name, [field]: date});
} else {
await this.update(name, {[field]: date});
}
}
/**
* Updates or creates a job's timestamp
* @param {string} name - The name of the job
* @param {'started_at'|'finished_at'} field - The timestamp field to update
* @param {Date} date - The timestamp value
*/
async setTimestamp(name, field, date) {
if (field !== 'started_at' && field !== 'finished_at') {
throw new IncorrectUsageError({
message: `Invalid timestamp field "${field}". Must be either "started_at" or "finished_at"`
});
}
const job = await this.read(name);
if (!job) {
await this.add({ name, [field]: date });
} else {
await this.update(job.id, { [field]: date });
}
}

Comment on lines +168 to +180
/**
* Updates or creates a job's status
* @param {string} name - The name of the job
* @param {string} status - The status to set
*/
async setStatus(name, status) {
const job = await this.read(name);
if (!job) {
await this.add({name, status});
} else {
await this.update(name, {status});
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Same ID mismatch in setStatus method.

Similar to setTimestamp, passing name to this.update is incorrect. It should pass the found job's ID, or updates will fail.

- await this.update(name, {status});
+ await this.update(job.id, {status});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* Updates or creates a job's status
* @param {string} name - The name of the job
* @param {string} status - The status to set
*/
async setStatus(name, status) {
const job = await this.read(name);
if (!job) {
await this.add({name, status});
} else {
await this.update(name, {status});
}
}
/**
* Updates or creates a job's status
* @param {string} name - The name of the job
* @param {string} status - The status to set
*/
async setStatus(name, status) {
const job = await this.read(name);
if (!job) {
await this.add({name, status});
} else {
await this.update(job.id, {status});
}
}

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.

1 participant