Skip to content

Ws changes cleanup#1588

Merged
hahn-kev merged 14 commits into
developfrom
ws-changes-cleanup
May 16, 2025
Merged

Ws changes cleanup#1588
hahn-kev merged 14 commits into
developfrom
ws-changes-cleanup

Conversation

@hahn-kev

@hahn-kev hahn-kev commented Apr 9, 2025

Copy link
Copy Markdown
Collaborator

fixes #1586

Currently this fails as there's no way inside our change context to fetch a writing system by it's WsId. In order to do that I think we need to expose a new api in Harmony on IChangeContext to allow for this

@coderabbitai

coderabbitai Bot commented Apr 9, 2025

Copy link
Copy Markdown

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This change refactors the creation and updating of writing systems by removing the explicit type parameter from relevant methods and deriving it from the WritingSystem object. It also introduces validation to prevent updates to immutable properties like WsId and Type, and adds new validators and tests to enforce these constraints.

Changes

Files / Areas Change Summary
FwDataMiniLcmApi.cs, CrdtMiniLcmApi.cs, DryRunMiniLcmApi.cs, IMiniLcmWriteApi.cs Removed type parameter from CreateWritingSystem method signatures; now derives type from the WritingSystem object. Added validation to UpdateWritingSystem.
MiniLcmImport.cs, MiniLcmJsInvokable.cs, MiniLcmApiHubBase.cs, MiniLcm/SyncHelpers/WritingSystemSync.cs, CrdtProjectsService.cs, test fixtures and test files Updated calls to CreateWritingSystem to use the new signature without the type parameter.
CreateWritingSystemChange.cs, UseChangesTests.cs, MiniLcmApiFixture.cs Updated constructor and usage of CreateWritingSystemChange to remove the explicit type argument; added duplicate detection logic.
MiniLcm/Validators/JsonPatchValidator.cs, MiniLcm/Validators/WritingSystemUpdateValidator.cs, MiniLcm/Validators/MiniLcmValidators.cs Introduced new validators to prevent updates to WsId, Type, and DeletedAt via patching; registered and integrated these validators.
MiniLcm.Tests/Validators/WritingSystemUpdateValidatorTests.cs, LcmCrdt.Tests/Changes/WritingSystemChangeTests.cs Added new tests to verify validator enforcement and correct handling of writing system creation and duplication.
MiniLcm.Tests/BasicApiTestsBase.cs, MiniLcm.Tests/WritingSystemTestsBase.cs, MiniLcm.Tests/SortingTestsBase.cs, LcmCrdt.Tests/Changes/UseChangesTests.cs, FwLiteProjectSync.Tests Updated tests to use the new CreateWritingSystem signature and verify correct behavior.
MiniLcmCrdtAdapter.cs, ChangeContextHelpers.cs Added static utility for type name retrieval and a strongly-typed extension for fetching objects by type from the context.
backend/harmony Updated subproject reference to a new commit.

Assessment against linked issues

Objective Addressed Explanation
Prevent duplicate errors when two users create the same writing system (#1586)
Disallow changing WsId via UpdateWritingSystem (#1586)
Disallow changing Type via UpdateWritingSystem (#1586)
Ensure update validation is enforced before applying changes to writing systems (#1586)

Poem

In the meadow of code where the writing winds spin,
A rabbit hops in—let the cleanup begin!
No more sneaky type swaps or IDs that stray,
Validators stand guard, keeping chaos at bay.
With patches now tighter and tests hopping through,
Writing systems are safer—thanks to this crew!
🐇✨


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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

Comment thread backend/FwLite/LcmCrdt.Tests/Changes/WritingSystemChangeTests.cs Outdated
@github-actions

github-actions Bot commented May 13, 2025

Copy link
Copy Markdown
Contributor

C# Unit Tests

116 tests   116 ✅  9s ⏱️
 17 suites    0 💤
  1 files      0 ❌

Results for commit d11b26b.

♻️ This comment has been updated with latest results.

@hahn-kev hahn-kev marked this pull request as ready for review May 15, 2025 05:05

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
backend/FwLite/LcmCrdt.Tests/Changes/WritingSystemChangeTests.cs (1)

7-26: Test should be more explicit about duplicate deletion behavior

While the test correctly verifies that only one writing system remains after creating a duplicate, it would be clearer if the test name or assertion explicitly indicated that duplicates are marked as deleted rather than just not appearing.

Consider renaming the test to be more explicit about the deletion behavior:

- public async Task CreatingTheSameWritingSystemShouldResultInOnlyOne()
+ public async Task CreatingTheSameWritingSystemShouldMarkDuplicateAsDeleted()

And potentially add an assertion that verifies the deleted status if possible.

🧹 Nitpick comments (5)
backend/FwLite/LcmCrdt/Utils/ChangeContextHelpers.cs (1)

30-34: Added convenient helper method for type-safe object retrieval

This new extension method provides a cleaner, strongly-typed way to retrieve objects from the change context without needing to specify the type name string manually. It improves code readability and reduces the chance of errors.

It would be good to add inline documentation for this method given its utility.

+/// <summary>
+/// Gets all objects of type T from the change context.
+/// </summary>
+/// <typeparam name="T">The type of objects to retrieve</typeparam>
+/// <returns>An async enumerable of objects of type T</returns>
public static IAsyncEnumerable<T> GetObjectsOfType<T>(this IChangeContext context)
    where T : class, IObjectWithId
{
    return context.GetObjectsOfType<T>(MiniLcmCrdtAdapter.GetObjectTypeName(typeof(T)));
}
backend/FwLite/MiniLcm/Validators/WritingSystemUpdateValidator.cs (1)

10-18: Duplicate validation for WsId property

There's redundant validation for the WsId property - it's being checked both in this custom validation block and again on line 19 using the NoOperation extension method. Consider removing this duplicate validation to simplify the code.

-        RuleFor(u => u.Patch).Custom((document, context) =>
-        {
-            //todo pull this out to make it easy to define properties that aren't allowed to be changed
-            if (document.Operations.Any(o =>
-                    string.Equals(o.Path,
-                        $"/{nameof(WritingSystem.WsId)}",
-                        StringComparison.InvariantCultureIgnoreCase)))
-                context.AddFailure(nameof(WritingSystem.WsId), "Not allowed to update WsId");
-        });
backend/FwLite/MiniLcm/Validators/JsonPatchValidator.cs (1)

8-21: Well-implemented reusable validation rule with room for improvement

The NoOperation extension method provides a clean, reusable way to prevent modification of specific properties. However, as noted in the TODO comment, the string-based property name approach could be improved.

Consider enhancing this to use expression-based property selection for type safety:

    public static IRuleBuilderOptionsConditions<UpdateObjectInput<T>, JsonPatchDocument<T>> NoOperation<T>(
        this IRuleBuilder<UpdateObjectInput<T>, JsonPatchDocument<T>> builder,
-        string propertyName//todo handle this better
+        Expression<Func<T, object>> propertyExpression
    ) where T : class
    {
+        string propertyName = GetPropertyName(propertyExpression);
        return builder.Custom((document, context) =>
        {
            if (document.Operations.Any(o =>
                    string.Equals(o.Path,
                        $"/{propertyName}",
                        StringComparison.InvariantCultureIgnoreCase)))
                context.AddFailure(propertyName, "Not allowed to update " + propertyName);
        });
    }
+    
+    private static string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> expression)
+    {
+        if (expression.Body is MemberExpression memberExpression)
+            return memberExpression.Member.Name;
+            
+        throw new ArgumentException("Expression is not a member access", nameof(expression));
+    }

Also, consider handling nested property paths, as JSON Patch allows operations on nested properties (e.g., /address/city).

backend/FwLite/MiniLcm.Tests/Validators/WritingSystemUpdateValidatorTests.cs (1)

15-44: Good test coverage with minor gaps

The tests provide good coverage for the validator, checking both successful and failed validation scenarios. However, there are a couple of improvements that could be made:

  1. Missing test for DeletedAt property validation - the validator prevents updates to this property, but there's no test for it
  2. The assertion for the "no changes" test could be more specific about which validation rule is being triggered

Add a test for the DeletedAt property validation:

[Fact]
public void Fails_WhenTryingToUpdateDeletedAt()
{
    var update = NewUpdate();
    update.Set(ws => ws.DeletedAt, DateTimeOffset.Now);
    _validator.TestValidate(update).ShouldHaveValidationErrorFor(nameof(WritingSystem.DeletedAt));
}

And make the assertion more specific in the "no changes" test:

[Fact]
public void Fails_WhenThereAreNoChanges()
{
    var update = NewUpdate();
-    _validator.TestValidate(update).ShouldHaveAnyValidationError();
+    _validator.TestValidate(update).ShouldHaveValidationErrorFor("Patch.Operations");
}
backend/FwLite/LcmCrdt.Tests/Changes/WritingSystemChangeTests.cs (1)

38-38: Misleading comment about Type being ignored

The comment suggests that the Type is ignored by the CreateApi, but according to the implementation in FwDataMiniLcmApi.cs and CreateWritingSystemChange.cs, the Type is actually used from the WritingSystem object.

- Type = WritingSystemType.Analysis//ignored by create api
+ Type = WritingSystemType.Analysis
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between e44fffb and 8397dce.

📒 Files selected for processing (26)
  • backend/FwLite/FwDataMiniLcmBridge/Api/FwDataMiniLcmApi.cs (2 hunks)
  • backend/FwLite/FwLiteProjectSync.Tests/Fixtures/SyncFixture.cs (1 hunks)
  • backend/FwLite/FwLiteProjectSync.Tests/Sena3SyncTests.cs (1 hunks)
  • backend/FwLite/FwLiteProjectSync.Tests/SyncTests.cs (1 hunks)
  • backend/FwLite/FwLiteProjectSync/DryRunMiniLcmApi.cs (1 hunks)
  • backend/FwLite/FwLiteProjectSync/MiniLcmImport.cs (1 hunks)
  • backend/FwLite/FwLiteShared/Services/MiniLcmJsInvokable.cs (1 hunks)
  • backend/FwLite/FwLiteWeb/Hubs/MiniLcmApiHubBase.cs (1 hunks)
  • backend/FwLite/LcmCrdt.Tests/Changes/UseChangesTests.cs (1 hunks)
  • backend/FwLite/LcmCrdt.Tests/Changes/WritingSystemChangeTests.cs (1 hunks)
  • backend/FwLite/LcmCrdt.Tests/MiniLcmApiFixture.cs (1 hunks)
  • backend/FwLite/LcmCrdt/Changes/CreateWritingSystemChange.cs (4 hunks)
  • backend/FwLite/LcmCrdt/CrdtMiniLcmApi.cs (1 hunks)
  • backend/FwLite/LcmCrdt/CrdtProjectsService.cs (1 hunks)
  • backend/FwLite/LcmCrdt/Objects/MiniLcmCrdtAdapter.cs (1 hunks)
  • backend/FwLite/LcmCrdt/Utils/ChangeContextHelpers.cs (2 hunks)
  • backend/FwLite/MiniLcm.Tests/BasicApiTestsBase.cs (1 hunks)
  • backend/FwLite/MiniLcm.Tests/SortingTestsBase.cs (1 hunks)
  • backend/FwLite/MiniLcm.Tests/Validators/WritingSystemUpdateValidatorTests.cs (1 hunks)
  • backend/FwLite/MiniLcm.Tests/WritingSystemTestsBase.cs (2 hunks)
  • backend/FwLite/MiniLcm/IMiniLcmWriteApi.cs (1 hunks)
  • backend/FwLite/MiniLcm/SyncHelpers/WritingSystemSync.cs (1 hunks)
  • backend/FwLite/MiniLcm/Validators/JsonPatchValidator.cs (1 hunks)
  • backend/FwLite/MiniLcm/Validators/MiniLcmValidators.cs (3 hunks)
  • backend/FwLite/MiniLcm/Validators/WritingSystemUpdateValidator.cs (1 hunks)
  • backend/harmony (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
backend/FwLite/MiniLcm.Tests/WritingSystemTestsBase.cs (1)
backend/FwLite/MiniLcm/Models/WritingSystem.cs (1)
  • Guid (22-25)
backend/FwLite/MiniLcm/IMiniLcmWriteApi.cs (2)
backend/FwLite/FwDataMiniLcmBridge/Api/FwDataMiniLcmApi.cs (1)
  • WritingSystem (101-115)
backend/FwLite/MiniLcm/Models/WritingSystem.cs (1)
  • WritingSystem (31-45)
backend/FwLite/LcmCrdt.Tests/Changes/UseChangesTests.cs (1)
backend/FwLite/LcmCrdt/Changes/CreateWritingSystemChange.cs (1)
  • CreateWritingSystemChange (11-55)
backend/FwLite/LcmCrdt/Changes/CreateWritingSystemChange.cs (9)
backend/FwLite/MiniLcm/Models/WritingSystem.cs (2)
  • WritingSystem (31-45)
  • Guid (22-25)
backend/FwLite/LcmCrdt/Objects/MiniLcmCrdtAdapter.cs (1)
  • Guid (26-29)
backend/FwLite/LcmCrdt/Utils/ChangeContextHelpers.cs (2)
  • ValueTask (9-12)
  • ValueTask (14-18)
backend/FwLite/LcmCrdt/Changes/CreateEntryChange.cs (1)
  • ValueTask (34-44)
backend/FwLite/LcmCrdt/Changes/CreateExampleSentenceChange.cs (1)
  • ValueTask (34-46)
backend/FwLite/LcmCrdt/Changes/CreateSenseChange.cs (1)
  • ValueTask (36-49)
backend/FwLite/LcmCrdt/Changes/AddSemanticDomainChange.cs (1)
  • ValueTask (12-23)
backend/FwLite/LcmCrdt/Changes/CreatePartOfSpeechChange.cs (1)
  • ValueTask (14-17)
backend/FwLite/LcmCrdt/Changes/SetPartOfSpeechChange.cs (1)
  • ValueTask (11-29)
🔇 Additional comments (32)
backend/harmony (1)

1-1:

Details

✅ Verification successful

Submodule update for Harmony
This bump aligns the Harmony subproject with upstream changes introducing the new IChangeContext API. Please ensure the referenced commit exists in the remote and that the submodule is properly synchronized and initialized before building.

Run this script to verify the commit is present in the remote and submodule is up‐to‐date:


🏁 Script executed:

#!/bin/bash
set -e
# Get the URL for the harmony submodule
url=$(git config -f .gitmodules --get submodule.backend/harmony.url)
echo "Verifying commit 5207421436e557c6d0704dbd3e61ca9cec680960 in $url"
# Check remote for the commit
if git ls-remote "$url" | grep -q 5207421436e557c6d0704dbd3e61ca9cec680960; then
  echo "✅ Commit found in remote."
else
  echo "❌ Commit not found in remote backend/harmony!"
  exit 1
fi
# Sync and update submodule
git submodule sync backend/harmony
git submodule update --init backend/harmony
echo "Submodule backend/harmony is synchronized and updated."

Length of output: 1012


Submodule backend/harmony Verified and Updated

Commit 5207421436e557c6d0704dbd3e61ca9cec680960 was found in https://github.com/sillsdev/harmony.git, and the submodule has been synchronized and initialized successfully. Ready to merge.

backend/FwLite/FwLiteProjectSync.Tests/Fixtures/SyncFixture.cs (1)

105-105: Clean signature refactoring.

The API call has been updated to the new CreateWritingSystem signature, which no longer requires a separate type parameter since it's now derived from the WritingSystem object's Type property. This change eliminates potential inconsistencies between the explicit type parameter and the type property in the writing system object.

backend/FwLite/MiniLcm/IMiniLcmWriteApi.cs (1)

10-10: Improved API design.

The method signature has been simplified to remove the redundant WritingSystemType parameter. This is a good change as it makes the API more intuitive by deriving the type from the WritingSystem object itself, eliminating the possibility of inconsistencies between the explicit type parameter and the Type property of the object.

backend/FwLite/MiniLcm.Tests/WritingSystemTestsBase.cs (2)

26-34: Test updated to match new API signature.

The test now properly creates a WritingSystem with the type specified in the object rather than as a separate parameter, which aligns with the API change. This ensures that tests validate the new API contract correctly.


44-61: Duplicate detection test correctly updated.

The test now uses the updated API signature, explicitly setting the Type property in the WritingSystem object. The test still correctly verifies that creating a writing system with a duplicate WsId throws a DuplicateObjectException.

backend/FwLite/MiniLcm.Tests/BasicApiTestsBase.cs (1)

75-84: Test correctly implements new API signature.

The test for verifying that multiple writing systems don't have duplicate orders has been correctly updated to use the new API signature. The Type property is now set directly in the WritingSystem object rather than passed as a separate parameter.

backend/FwLite/MiniLcm/SyncHelpers/WritingSystemSync.cs (1)

63-63: LGTM! API signature update correctly implemented.

This change correctly implements the API signature update where CreateWritingSystem now accepts only the WritingSystem object and derives the type from its Type property, eliminating the need for a separate parameter.

backend/FwLite/LcmCrdt.Tests/Changes/UseChangesTests.cs (1)

114-114: LGTM! Updated constructor call aligns with new signature.

The CreateWritingSystemChange constructor call has been correctly updated to match the new signature that removes the explicit WritingSystemType parameter, relying instead on the Type property of the WritingSystem object.

backend/FwLite/FwLiteProjectSync.Tests/Sena3SyncTests.cs (1)

71-71: LGTM! API call correctly updated.

The call to _crdtApi.CreateWritingSystem has been properly updated to pass only the WritingSystem object without the explicit WritingSystemType parameter, which aligns with the refactored API.

backend/FwLite/MiniLcm.Tests/SortingTestsBase.cs (1)

40-48: LGTM! WritingSystem creation correctly includes Type property.

The API call has been properly updated to create a WritingSystem object with all necessary properties, including Type = WritingSystemType.Vernacular, which replaces the previous pattern of passing the type as a separate parameter.

backend/FwLite/LcmCrdt/CrdtProjectsService.cs (1)

209-250: LGTM! Simplified API usage by moving type information to the object

The changes to the SampleProjectData method are clean and consistent. By incorporating the Type property directly within the WritingSystem object initialization, the code now follows a more object-oriented approach, which aligns with the PR objective of exposing a new API to fetch writing systems by WsId.

backend/FwLite/FwLiteShared/Services/MiniLcmJsInvokable.cs (1)

120-122: Well-handled API evolution with backward compatibility

The implementation now forwards only the writingSystem parameter to the underlying API while maintaining the existing method signature. This is an excellent approach that preserves backward compatibility for JavaScript callers while adapting to the new underlying API design.

backend/FwLite/FwLiteProjectSync/DryRunMiniLcmApi.cs (1)

21-24: API signature updated consistently for dry run implementation

The CreateWritingSystem method has been properly updated to align with the new API signature, now accepting only the WritingSystem object. The implementation correctly references the object's Type property when creating the dry run record.

backend/FwLite/FwLiteProjectSync.Tests/SyncTests.cs (1)

418-419: Test calls updated to match new API pattern

The test code has been properly updated to use the new API pattern, embedding the writing system type within the WritingSystem object rather than passing it as a separate parameter. This ensures the tests remain functional with the updated API design.

backend/FwLite/FwLiteProjectSync/MiniLcmImport.cs (2)

106-106: Simplified API call by removing explicit type parameter

The removal of the WritingSystemType parameter from the CreateWritingSystem call aligns with the broader refactoring to simplify the API. Now the method correctly relies on the Type property that's already part of the WritingSystem object itself.


112-112: Consistent implementation for both Analysis and Vernacular writing systems

This change mirrors the same simplification made to the Analysis writing systems above, ensuring consistent implementation across both writing system types.

backend/FwLite/LcmCrdt.Tests/MiniLcmApiFixture.cs (1)

41-59:

Details

✅ Verification successful

Updated test fixture to use new CreateWritingSystem API pattern

The updated code correctly sets the Type property directly on the WritingSystem objects rather than passing it as a separate parameter. This aligns with the API changes throughout the codebase.

Note: There's a potential issue with creating two writing systems with the same WsId "en" but different types. Verify this is the intended behavior for test purposes.


🏁 Script executed:

#!/bin/bash
# Check if this pattern of duplicate WsIds is used elsewhere in tests

echo "Checking for other instances of duplicate WsIds in tests..."
rg -A 1 -B 1 'WsId = "(\w+)"' --glob="*.cs" | sort | uniq -c | sort -nr | head -10

Length of output: 1047


Duplicate WsId usage is intentional and consistent
The pattern of creating two WritingSystem instances with the same WsId = "en" but different Type values already exists in backend/FwLite/LcmCrdt/CrdtProjectsService.cs. This confirms the test fixture is mirroring the service behavior and is intended for coverage. No further changes are needed.

  • See backend/FwLite/LcmCrdt/CrdtProjectsService.cs where both Vernacular and Analysis systems share WsId = "en".
backend/FwLite/LcmCrdt/Utils/ChangeContextHelpers.cs (1)

1-2: New imports support the GetObjectsOfType extension method

These imports are necessary for the new extension method. The change correctly brings in the required namespaces.

backend/FwLite/LcmCrdt/Objects/MiniLcmCrdtAdapter.cs (1)

41-51: Good refactoring to improve code reuse

The extraction of the type name logic into a static method allows for broader reuse within the system. This is beneficial for the new GetObjectsOfType<T> extension method mentioned in the AI summary.

The existing TODO comment about potential issues with refactor renaming remains relevant. Consider using Type.FullName or a more robust type identifier mechanism to avoid potential name collisions if multiple classes with the same name exist in different namespaces.

backend/FwLite/MiniLcm/Validators/WritingSystemUpdateValidator.cs (1)

19-23: Clean and concise validator implementation

The NoOperation calls for the immutable properties and the check for non-empty operations are well-implemented. This creates a robust validation for writing system updates that properly protects critical fields from modification.

The TODO comment on line 12 has been addressed with the NoOperation extension method from JsonPatchValidator, which makes it easier to define properties that aren't allowed to be changed.

backend/FwLite/MiniLcm/Validators/MiniLcmValidators.cs (3)

14-15: Good addition of the WritingSystemUpdateValidator dependency

The addition of WritingSystemUpdateValidator as a dependency in the validator record follows the established pattern in the codebase for validator dependencies.


51-55: LGTM! Appropriate validation method implementation

The implementation of ValidateAndThrow for UpdateObjectInput<WritingSystem> correctly follows the pattern used for other model types in this file.


70-70: Properly registered the validator service

The transient registration of the WritingSystemUpdateValidator in the dependency injection container is consistent with how other validators are registered.

backend/FwLite/LcmCrdt/Changes/CreateWritingSystemChange.cs (3)

3-3: Correctly added Utils namespace import

This import is needed for the new functionality that checks for existing writing systems.


22-31: Good simplification of the constructor

Removing the explicit WritingSystemType parameter and deriving it from the WritingSystem object simplifies the API and makes it more consistent.


39-53: Well-implemented duplicate detection logic

The change from synchronous to asynchronous method properly supports querying the context for existing writing systems. The implementation sets DeletedAt for duplicates instead of throwing an exception, which aligns with the CRDT pattern of handling conflicts.

backend/FwLite/FwDataMiniLcmBridge/Api/FwDataMiniLcmApi.cs (2)

149-152: Good simplification of API method signature

Removing the explicit type parameter and deriving it from the WritingSystem object makes the API more intuitive and consistent with other implementations in the codebase.


190-190: Properly added validation for writing system updates

The addition of validation for update inputs is a good security practice that will prevent invalid updates to immutable properties like WsId and Type.

backend/FwLite/LcmCrdt.Tests/Changes/WritingSystemChangeTests.cs (1)

28-45: Good test for multi-type creation scenario

This test properly verifies that writing systems with the same WsId but different types can coexist, which is a key requirement of the feature.

backend/FwLite/LcmCrdt/CrdtMiniLcmApi.cs (3)

96-96: Improved API design by simplifying method signature.

The method signature has been improved by removing the explicit WritingSystemType parameter and instead deriving it from the WritingSystem object itself, which avoids potential inconsistencies.


100-104: Enhanced duplicate checking and error handling.

The implementation now:

  1. Uses AnyAsync to check for duplicates with both WsId and Type before adding changes
  2. Throws a more descriptive exception when duplicates are found
  3. Properly passes the writing system type from the object to the change creation
  4. Returns the created writing system with appropriate error handling

This approach is more direct and efficient than relying on database constraint exceptions.


109-109: Added validation to protect immutable properties.

Added validation for writing system updates, which prevents modifications to immutable properties like WsId and Type, enhancing data integrity.

Comment thread backend/FwLite/FwLiteWeb/Hubs/MiniLcmApiHubBase.cs Outdated
@hahn-kev hahn-kev requested a review from myieye May 15, 2025 09:08

@myieye myieye left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good to me. Nice to see that redundant ws-type parameter get cleaned up 🤠 👍

Comment thread backend/FwLite/MiniLcm/Validators/JsonPatchValidator.cs Outdated
@hahn-kev hahn-kev merged commit c5503ef into develop May 16, 2025
20 checks passed
@hahn-kev hahn-kev deleted the ws-changes-cleanup branch May 16, 2025 04:44
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.

Tighten up writing system changes

2 participants