Skip to content

Migrating modification of Accounts to Entity layer#527

Merged
allouis merged 2 commits intomainfrom
ap-1071-account-entity-update
Apr 15, 2025
Merged

Migrating modification of Accounts to Entity layer#527
allouis merged 2 commits intomainfrom
ap-1071-account-entity-update

Conversation

@allouis
Copy link
Collaborator

@allouis allouis commented Apr 15, 2025

ref https://linear.app/ghost/issue/AP-1071

These are some building blocks for updating an Accounts profile fields

allouis added 2 commits April 15, 2025 14:07
ref https://linear.app/ghost/issue/AP-1071

This allows us to move away from the `updateAccount` implementation in
AccountService which writes directly to the DB and then emits an
`account.updated` event. Instead we can use the entity system and follow the
existing patterns
ref https://linear.app/ghost/issue/AP-1071

This gives us a way to modify the profile fields of an Account entity so that
we can later save them and have the Update activity sent to federated servers.
@coderabbitai
Copy link

coderabbitai bot commented Apr 15, 2025

Walkthrough

This change introduces a new event-driven mechanism for handling account profile updates. A new AccountUpdatedEvent class is added to encapsulate updated Account instances and provide a standardized event name. The Account entity is refactored to make profile fields (name, bio, avatarUrl, bannerImageUrl) private, with public getters and an updateProfile method that allows partial updates using a new ProfileUpdateParams interface. The KnexAccountRepository class now includes an asynchronous save method that updates existing accounts in the database and emits the AccountUpdatedEvent upon successful update. Integration and unit tests are added to verify the correct behavior of profile updates and event emission. The FediverseBridge class is extended to listen for AccountUpdatedEvent, generating and sending ActivityPub Update activities to followers when internal accounts are updated.

Suggested reviewers

  • vershwal

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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

@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: 0

🧹 Nitpick comments (4)
src/account/account.repository.knex.integration.test.ts (2)

215-218: Consider testing partial updates.

The test only verifies updating both name and bio. Consider also testing scenarios where only a subset of profile fields are updated to ensure partial updates work correctly.

- accountEntity.updateProfile({
-     name: 'Updated Name',
-     bio: 'Updated Bio',
- });

+ // Test partial update
+ accountEntity.updateProfile({
+     name: 'Updated Name',
+ });
+ 
+ // Later verify only name was updated
+ expect(updatedAccount.name).toBe('Updated Name');
+ expect(updatedAccount.bio).toBe(account.bio);

229-231: Consider verifying event content more thoroughly.

You're checking that the event contains the account entity, but not verifying the actual updated values within the account. Consider expanding this to validate the content of the account within the event.

// Verify that the event contains the account
const event = emitSpy.mock.calls[0][1] as AccountUpdatedEvent;
expect(event.getAccount()).toBe(accountEntity);
+ expect(event.getAccount().name).toBe('Updated Name');
+ expect(event.getAccount().bio).toBe('Updated Bio');
src/account/account.entity.ts (2)

101-117: Consider validating input in updateProfile method.

The updateProfile method currently accepts any values without validation. Consider adding basic validation to ensure data quality.

updateProfile(params: ProfileUpdateParams): void {
    if (params.name !== undefined) {
+       // Optional validation for name (e.g., length, format)
        this._name = params.name;
    }

    if (params.bio !== undefined) {
+       // Optional validation for bio (e.g., length)
        this._bio = params.bio;
    }

    if (params.avatarUrl !== undefined) {
+       // Optional validation for avatarUrl (e.g., valid URL format if not null)
        this._avatarUrl = params.avatarUrl;
    }

    if (params.bannerImageUrl !== undefined) {
+       // Optional validation for bannerImageUrl (e.g., valid URL format if not null)
        this._bannerImageUrl = params.bannerImageUrl;
    }
}

58-62: Consider grouping field initializations.

The initialization of private fields is separate from their declaration. Consider initializing these fields directly in the declaration for better readability and to avoid potential issues if initialization is missed.

-private _name: string | null;
-private _bio: string | null;
-private _avatarUrl: URL | null;
-private _bannerImageUrl: URL | null;
+private _name: string | null = null;
+private _bio: string | null = null;
+private _avatarUrl: URL | null = null;
+private _bannerImageUrl: URL | null = null;

constructor(
    public readonly id: number | null,
    uuid: string | null,
    public readonly username: string,
    name: string | null,
    bio: string | null,
    avatarUrl: URL | null,
    bannerImageUrl: URL | null,
    private readonly site: AccountSite | null,
    apId: URL | null,
    url: URL | null,
    apFollowers: URL | null,
) {
    super(id);

    this._name = name;
    this._bio = bio;
    this._avatarUrl = avatarUrl;
    this._bannerImageUrl = bannerImageUrl;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 66f3051 and 08276b3.

📒 Files selected for processing (6)
  • src/account/account-updated.event.ts (1 hunks)
  • src/account/account.entity.ts (2 hunks)
  • src/account/account.entity.unit.test.ts (1 hunks)
  • src/account/account.repository.knex.integration.test.ts (3 hunks)
  • src/account/account.repository.knex.ts (2 hunks)
  • src/activitypub/fediverse-bridge.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/activitypub/fediverse-bridge.ts (1)
src/account/account-updated.event.ts (1)
  • AccountUpdatedEvent (3-13)
src/account/account.repository.knex.integration.test.ts (4)
src/core/events.ts (1)
  • AsyncEvents (3-17)
src/account/account.repository.knex.ts (1)
  • KnexAccountRepository (9-142)
src/account/account.entity.ts (1)
  • Account (32-188)
src/account/account-updated.event.ts (1)
  • AccountUpdatedEvent (3-13)
src/account/account.repository.knex.ts (2)
src/account/account.entity.ts (1)
  • Account (32-188)
src/account/account-updated.event.ts (1)
  • AccountUpdatedEvent (3-13)
🔇 Additional comments (11)
src/account/account-updated.event.ts (1)

1-13: Clean implementation for the new event class.

This is a well-structured event class that encapsulates the updated Account instance. The static getName() method provides a central place to define the event name, improving maintainability.

The implementation follows good practices by:

  1. Using a private readonly field for immutability
  2. Providing a getter method for encapsulation
  3. Following the existing event pattern in the codebase
src/account/account.repository.knex.ts (2)

6-6: LGTM!

The import is correctly added to support the new event emission.


15-35:

Details

❓ Verification inconclusive

Well-structured implementation for account updates.

The new save method correctly:

  1. Handles existing accounts only (with a clear error for new accounts)
  2. Updates the database with the account's current property values
  3. Emits the AccountUpdatedEvent after the database update is complete

The method uses the getters introduced in the Account entity, maintaining proper encapsulation.


🏁 Script executed:

#!/bin/bash
# Verify if there are existing uses of account updates that should be migrated to this new method
rg -A 2 "UPDATE.*accounts" --glob "*.ts" | grep -v "save(account"

Length of output: 67


Account Update Save Method Verified – Manual Check Advised

The updated save method in src/account/account.repository.knex.ts correctly handles account updates by:

  • Throwing an error for new accounts.
  • Performing the update on the accounts table with the current property values.
  • Emitting an AccountUpdatedEvent after the update.

A verification script was run to locate other direct update calls to the accounts table in TypeScript files. No extra occurrences were identified. However, since the script’s output was empty, please manually verify that no direct update queries exist elsewhere in the codebase.

src/account/account.entity.unit.test.ts (1)

71-247: Comprehensive test coverage for profile updates.

The tests are thorough and well-structured, covering:

  • Individual field updates (name, bio, avatarUrl, bannerImageUrl)
  • Multiple field updates in a single operation
  • Setting values to null

Each test properly verifies that:

  1. The specified fields are updated correctly
  2. Unspecified fields remain unchanged

This testing approach ensures the updateProfile method works as expected across various scenarios.

src/activitypub/fediverse-bridge.ts (3)

5-5: LGTM!

The import is correctly added for the new event handling.


17-20: Good event registration pattern.

The event handler registration follows the existing pattern in the code, maintaining consistency.


83-111:

Details

✅ Verification successful

Well-implemented event handler with proper checks.

The new handler correctly:

  1. Extracts the account from the event
  2. Verifies it's an internal account (early return if not)
  3. Creates and sends an ActivityPub Update activity to the account's followers

The implementation properly uses the entity's properties (apId and apFollowers) rather than string URLs, aligning with the entity encapsulation changes.


🏁 Script executed:

#!/bin/bash
# Verify that both event handlers (old and new) are being used and that there's no duplication
rg -A 2 "account\.updated" --glob "*.ts" | grep -v "AccountUpdatedEvent"

Length of output: 1713


Event Handler Update Verified – Code Looks Good

The new event handler in src/activitypub/fediverse-bridge.ts is implemented correctly:

  • It extracts the account from the event and exits early if the account isn’t internal.
  • It builds and broadcasts an ActivityPub Update using the account’s encapsulated properties (apId and apFollowers).
  • Global database update and activity sending are handled as expected.
  • Our grep-check confirms that the account.updated event is registered only once across the codebase, indicating there’s no duplication.

Note: Please verify that the event listener binding (this.events.on('account.updated', this.handleAccountUpdate.bind(this));) correctly points to the new handler—either directly or via a proper alias to handleAccountUpdatedEvent.

src/account/account.repository.knex.integration.test.ts (1)

187-240: Well-structured integration test with good logical flow.

This integration test effectively validates the new account profile update functionality. The test follows a clear structure:

  1. Sets up the repository and spies on events
  2. Retrieves an existing account and creates an entity
  3. Updates profile fields with the new updateProfile method
  4. Verifies both event emission and database updates

The test provides good coverage for the core functionality, validating both the event emission and persistence aspects.

src/account/account.entity.ts (3)

25-30: Good use of optional properties for partial updates.

The ProfileUpdateParams interface effectively uses TypeScript's optional properties to allow partial updates to the account profile, which is a clean approach for supporting selective field updates.


38-41: Good encapsulation of profile fields.

Converting the profile fields from public properties to private fields with public getters improves encapsulation, making the Account entity more maintainable by controlling how these fields can be modified.


85-99: Clean implementation of getters.

The getters for the profile fields are clean and straightforward, following best practices for encapsulation.


export class AccountUpdatedEvent {
static getName(): string {
return 'account.updated.event';
Copy link
Member

Choose a reason for hiding this comment

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

This could just be account.updated, but I think it would contradict the current event. Maybe something to clean up later?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah exactly, that name is already taken so I went with this - it's abstracted away in this method so easy to change later

return this._bannerImageUrl;
}

updateProfile(params: ProfileUpdateParams): void {
Copy link
Member

Choose a reason for hiding this comment

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

Do we need to add username here? Or maybe that's coming as part of other changes(custom handles)?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah that will come as part of the username change work

async save(account: Account): Promise<void> {
if (account.isNew) {
throw new Error(
'Saving of new Accounts has not been implemented yet.',
Copy link
Member

Choose a reason for hiding this comment

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

We can rename this method to update and use it only for this purpose, and have a different implementation for save. My thinking is that this method is updating the account and sending update event.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Our repository pattern uses a single save even for both update and saves, this means that callers of the code don't need to know if the entity they have a reference to is new or not.

We could change this if you think it's worth it but I think it needs to be part of a larger discussion and the PostRepository would need to be updated too

Copy link
Member

Choose a reason for hiding this comment

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

In that case, it’s fine. I get that the single save method simplifies things in PostRepository, we can keep the same patter here.

Copy link
Collaborator Author

@allouis allouis left a comment

Choose a reason for hiding this comment

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

There is a bug in github so my replies have all come as comments as part of a review @vershwal


export class AccountUpdatedEvent {
static getName(): string {
return 'account.updated.event';
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah exactly, that name is already taken so I went with this - it's abstracted away in this method so easy to change later

return this._bannerImageUrl;
}

updateProfile(params: ProfileUpdateParams): void {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah that will come as part of the username change work

async save(account: Account): Promise<void> {
if (account.isNew) {
throw new Error(
'Saving of new Accounts has not been implemented yet.',
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Our repository pattern uses a single save even for both update and saves, this means that callers of the code don't need to know if the entity they have a reference to is new or not.

We could change this if you think it's worth it but I think it needs to be part of a larger discussion and the PostRepository would need to be updated too

@allouis allouis merged commit ff2637d into main Apr 15, 2025
6 checks passed
@allouis allouis deleted the ap-1071-account-entity-update branch April 15, 2025 08:07
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