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

Bugfix/cache logic #78

Merged
merged 5 commits into from
Dec 12, 2023
Merged

Bugfix/cache logic #78

merged 5 commits into from
Dec 12, 2023

Conversation

maerki
Copy link
Contributor

@maerki maerki commented Dec 11, 2023

Summary by CodeRabbit

  • New Features

    • Enhanced logging capabilities for better diagnostics and performance monitoring.
    • Introduced a new method to customize cache policies for network requests.
  • Improvements

    • Updated caching logic to include additional parameters for more precise cache management.
    • Improved request preparation process to ensure optimal use of caching strategies.
  • Refactor

    • Modified internal networking logic to streamline data task completion and error handling processes.

Copy link

coderabbitai bot commented Dec 11, 2023

Walkthrough

The recent updates to the UBFoundation networking components focus on enhancing logging capabilities, refining cache policy handling, and improving the way requests are prepared and utilized. These changes include the introduction of a new logging structure, adjustments to method signatures to accommodate new parameters, and the modification of request cache policies to align with protocol standards.

Changes

File Path Change Summary
.../AutoRefreshCacheLogic.swift & .../BaseCachingLogic.swift Introduced a new logging structure and updated method signatures to include new parameters.
.../CachingLogic.swift Added a new method to the UBCachingLogic protocol for request modification.
.../UBURLRequest.swift Modified the init method to use a different cache policy.
.../UBURLSession+Delegate.swift & .../UBURLSession.swift Updated logic for task completion and cache usage, including the modification of request parameters before task creation.

🐇✨
In the land of code, where the data streams flow,
A rabbit hopped in, with updates in tow.
Cache policies tweaked, and logs now unfurled,
A swift network dance, through the digital world. 🌐🐾
✨🐇

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 X ?


Tips

Chat with CodeRabbit Bot (@coderabbitai)

  • If you reply to a review comment from CodeRabbit, the bot will automatically respond.
  • To engage with CodeRabbit bot directly around the specific lines of code in the PR, mention @coderabbitai in your review comment
  • Note: Review comments are made on code diffs or files, not on the PR overview.
  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Note: For conversation with the bot, please use the review comments on code diffs or files.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

Copy link

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 1 Code Smell

No Coverage information No Coverage information
0.0% 0.0% Duplication

Copy link

github-actions bot commented Dec 11, 2023

Unit Test Results

    1 files  ±0      3 suites  ±0   1m 50s ⏱️ ±0s
164 tests ±0  163 ✔️ ±0  0 💤 ±0  1 ❌ ±0 

For more details on these failures, see this check.

Results for commit 48f4a00. ± Comparison against base commit 48f4a00.

♻️ This comment has been updated with latest results.

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.

Review Status

Actionable comments generated: 3

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between e01e253 and 583a006.
Files selected for processing (6)
  • Sources/UBFoundation/Networking/AutoRefreshCacheLogic.swift (6 hunks)
  • Sources/UBFoundation/Networking/BaseCachingLogic.swift (2 hunks)
  • Sources/UBFoundation/Networking/CachingLogic.swift (2 hunks)
  • Sources/UBFoundation/Networking/UBURLRequest.swift (1 hunks)
  • Sources/UBFoundation/Networking/UBURLSession+Delegate.swift (1 hunks)
  • Sources/UBFoundation/Networking/UBURLSession.swift (2 hunks)
Additional comments: 12
Sources/UBFoundation/Networking/AutoRefreshCacheLogic.swift (5)
  • 11-14: The addition of the Log struct is a good encapsulation of logging functionality and its usage is correctly guarded by availability checks for iOS 14.0 and watchOS 7.0.

  • 35-53: The conditional logging statements added to the scheduleRefreshCronJob function are well-placed and provide valuable information for debugging. The use of availability checks ensures backward compatibility.

  • 87-100: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [67-97]

The modifications to the cachedResponseNextRefreshDate function to include referenceDate in the calculation of responseDate and to consider the connection end date in the backoffDate calculation are logical and enhance the accuracy of the refresh scheduling.

  • 119-120: The update to the hasProposedCachedResponse function to pass a referenceDate to scheduleRefreshCronJob is a sensible change that aligns with the PR's goal of improving cache refresh logic.

  • 136-138: The addition of the nonModifiedResponse parameter and the corresponding logic in the hasUsed function is a good enhancement that supports the PR's objectives to improve caching logic.

Sources/UBFoundation/Networking/BaseCachingLogic.swift (1)
  • 276-278: The hasUsed method signature has been updated to include a new nonModifiedResponse parameter. Verify that all subclasses overriding this method have been updated accordingly to prevent runtime issues.

#!/bin/bash
# Correct the pattern to search for subclasses of UBBaseCachingLogic and check if they override the hasUsed method.
ast-grep --lang swift --pattern $'class $_: UBBaseCachingLogic {
  $$$
  override func hasUsed($$$) {
    $$$
  }
  $$$
}'
Sources/UBFoundation/Networking/CachingLogic.swift (2)
  • 38-43: The addition of prepareRequest to the UBCachingLogic protocol will require all conforming types to implement this new method. Ensure that all types that conform to UBCachingLogic have been updated to include an implementation of prepareRequest.

#!/bin/bash
# Search for all types that conform to `UBCachingLogic` and check if they implement `prepareRequest`.
ast-grep --lang swift --pattern $'class $_: UBCachingLogic { $$$ }'
* 82-83: The `hasUsed` method signature in the `UBCachingLogic` protocol has been updated to include a new parameter `nonModifiedResponse`. Ensure that all types that conform to `UBCachingLogic` have been updated to match the new method signature.




---

<!--Monologue:
Thought 1: The shell script was intended to find all classes that conform to the `UBCachingLogic` protocol and check if they implement the updated `hasUsed` method.
Reflect 1: The script did not produce any output, which means it either did not find any classes conforming to `UBCachingLogic` or the `hasUsed` method was not found within those classes.
Resolution 1: Since the script exited with code 1, it indicates an error occurred during execution. This could be due to a syntax error, a problem with the pattern used in `ast-grep`, or an issue with the `rg` command.
-->

<!--Monologue:
Thought 2: The lack of output could mean that there are no conforming types implementing the method, or it could be a false negative due to an error in the script.
Reflect 2: The script's failure to produce output is not conclusive evidence that the codebase is correct or incorrect.
Resolution 2: I should generate a new script to verify the presence of the `hasUsed` method in classes conforming to `UBCachingLogic`.
-->

<!--Monologue:
Thought 3: The original review comment asked to ensure that all types conforming to `UBCachingLogic` have been updated to match the new method signature.
Reflect 3: Without output from the script, I cannot confirm whether this has been done.
Resolution 3: I need to perform a new search to verify the implementation of the `hasUsed` method in conforming types.
-->

<!--Monologue:
Thought 4: The script used `ast-grep` to find classes conforming to `UBCachingLogic` and then piped the output to `rg` to search for `hasUsed`.
Reflect 4: The error could be in the `ast-grep` command or the `rg` command.
Resolution 4: I should check the `ast-grep` command for correctness and ensure it's capable of finding the conforming classes.
-->

<!--Monologue:
Thought 5: The `ast-grep` command is supposed to find classes conforming to `UBCachingLogic`, but it might not be finding any matches.
Reflect 5: The pattern used in `ast-grep` might be too restrictive or incorrect.
Resolution 5: I should adjust the `ast-grep` pattern to be more inclusive or correct any errors.
-->

<!--Monologue:
Thought 6: The `rg` command is used to filter the output of `ast-grep` for the presence of `hasUsed`.
Reflect 6: If `ast-grep` did not produce any output, `rg` would not have anything to filter, leading to an empty result.
Resolution 6: I should first ensure `ast-grep` produces output before worrying about the `rg` command.
-->

<!--Monologue:
Thought 7: I need to generate a new script to verify the implementation of the `hasUsed` method in classes conforming to `UBCachingLogic`.
Reflect 7: I should use a different approach to ensure that the script works correctly and produces the necessary output.
Resolution 7: I will write a new script that checks for the implementation of the `hasUsed` method in any class, not just those directly conforming to `UBCachingLogic`, as subclasses could also be affected.
-->

<!--Monologue:
Thought 8: The new script should use `ast-grep` to find the `hasUsed` method in any class, and then I can manually verify if those classes are related to `UBCachingLogic`.
Reflect 8: This approach will give me a broader search result, which I can then narrow down.
Resolution 8: I will generate a new script using `ast-grep` to search for the `hasUsed` method in any class.
-->

```shell
#!/bin/bash
# Search for the `hasUsed` method in any class to verify if it matches the updated signature.
ast-grep --lang swift --pattern $'class $_ { $$$ hasUsed($_, $_, $_, $_, $_) { $$$ } $$$ }'

The above script will search for the hasUsed method with the updated signature in any class. If the method is found, it will indicate that the class has implemented the updated method signature. If no results are found, it could mean that no classes have implemented the method, or there may be an issue with the script.

Sources/UBFoundation/Networking/UBURLSession+Delegate.swift (1)
  • 115-119: The hasUsed method call has been updated to include an additional parameter nonModifiedResponse. Ensure that all implementations of the UBCachingLogic protocol and calls to hasUsed are updated to handle this new parameter correctly.

The verification scripts aimed to check the correct implementation of the hasUsed method in extensions of the UBCachingLogic protocol and to ensure that calls to hasUsed pass the new nonModifiedResponse parameter correctly. The first script encountered a parsing error, indicating an issue with the pattern syntax used to search for protocol extensions. However, the second script successfully identified a call to hasUsed with the new parameter in UBURLSession+Delegate.swift.

Given this information, we can conclude that the call to hasUsed in UBURLSession+Delegate.swift is updated to include the new nonModifiedResponse parameter as intended. However, we cannot confirm whether all implementations of the UBCachingLogic protocol have been updated accordingly due to the error in the first script.

Final review comment:

The hasUsed method call in UBURLSession+Delegate.swift correctly includes the new nonModifiedResponse parameter. However, due to a script error, we could not verify if all implementations of the UBCachingLogic protocol are updated to handle this new parameter. Please ensure that all relevant protocol conformances are checked and updated if necessary.

Sources/UBFoundation/Networking/UBURLSession.swift (3)
  • 43-48: The modification to the createTask function to prepare the request using cachingLogic?.prepareRequest(&request) before creating a data task is consistent with the PR objectives and enhances the request preparation process.

  • 90-96: The update to the dataTaskCompleted function to include the cachedResponse and nonModifiedResponse parameters in the sessionDelegate.cachingLogic?.hasUsed call aligns with the PR objectives to enhance caching logic.

  • 43-48: Verify that the UBCachingLogic protocol and all conforming classes have been updated to include the new prepareRequest and hasUsed method signatures with the correct parameters.

Also applies to: 90-96


#!/bin/bash
# Correct the ast-grep pattern to search for the updated method signatures in the UBCachingLogic protocol and any conforming classes.
ast-grep --lang swift --pattern $'protocol UBCachingLogic {
  $$$
  prepareRequest($_) {
    $$$
  }
  $$$
  hasUsed($_, $_, $_, $_, $_) {
    $$$
  }
  $$$
}'
# Additionally, search for the updated method signatures in any extensions conforming to UBCachingLogic.
ast-grep --lang swift --pattern $'extension $_: UBCachingLogic {
  $$$
  prepareRequest($_) {
    $$$
  }
  $$$
  hasUsed($_, $_, $_, $_, $_) {
    $$$
  }
  $$$
}'

Comment on lines +43 to +45
public func prepareRequest(_ request: inout URLRequest) {
request.cachePolicy = .reloadIgnoringLocalCacheData
}
Copy link

Choose a reason for hiding this comment

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

The new prepareRequest method correctly sets the cachePolicy to .reloadIgnoringLocalCacheData. Ensure that the implications of this change in caching behavior are well-documented and communicated to consumers of the UBBaseCachingLogic class.

Comment on lines +115 to +117
if !ubDataTask.flags.contains(.refresh) {
ubDataTask.dataTaskCompleted(data: cached.data, response: cached.response as? HTTPURLResponse, error: collectedData.error ?? error, info: info)
}
Copy link

Choose a reason for hiding this comment

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

The new condition checks if the .refresh flag is not contained in ubDataTask.flags before completing the task with cached data. This change appears to be part of the caching logic bugfix. Ensure that this new behavior is documented and tested to confirm that it works as intended and does not introduce regressions.


The conditional check for the .refresh flag before completing the task with cached data is aligned with the PR's objective to fix caching logic. However, due to a script error, I couldn't verify if this behavior is covered by tests. Please ensure that this logic is well-documented and tested to prevent regressions.


The conditional check for the .refresh flag before completing the task with cached data is consistent with the PR's caching logic bugfix. However, the absence of script output prevents verification of test coverage for this new behavior. It is important to ensure that this logic is thoroughly tested to avoid regressions.

  • Please confirm that tests covering the new .refresh flag condition are present and adequately address the changes made.

Comment on lines 93 to 98
/// - method: The HTTP Method to use. Default to GET.
/// - timeoutInterval: The timeout interval for the request. The default is 60.0.
public init(url: URL, method: UBHTTPMethod = .get, timeoutInterval: TimeInterval = 60.0) {
self.init(request: URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: timeoutInterval))
self.init(request: URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: timeoutInterval))
httpMethod = method
}
Copy link

Choose a reason for hiding this comment

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

💡 NOTE
Codebase verification is a beta feature.

The verification script has identified multiple instances in the codebase where UBURLRequest is used. Given the change to the default cache policy, it is recommended to audit these specific instances to ensure that the new default behavior does not introduce regressions or unexpected behavior. The instances found are in various source and test files, and each should be reviewed to confirm that the new cache policy is suitable or to make necessary adjustments.

  • Audit all instances of UBURLRequest found in the output to ensure compatibility with the new default cache policy .useProtocolCachePolicy.
Analysis chain

The change to the default cache policy in the UBURLRequest initializer from .reloadIgnoringCacheData to .useProtocolCachePolicy is a significant alteration to the caching behavior. Ensure that all usages of UBURLRequest throughout the codebase have been audited to confirm that this new default behavior does not introduce any regressions or unexpected behavior, especially in cases where the previous default cache policy was implicitly relied upon.


Given the absence of results from the script, it's not possible to confirm that the change to the default cache policy in UBURLRequest will not affect existing code. A broader search is recommended to ensure that all instances of UBURLRequest initialization are accounted for and reviewed for potential impacts due to the change in cache policy.


The absence of results from the broader search pattern still does not provide confirmation that the change to the default cache policy in UBURLRequest is safe. A different approach is needed to verify the usage of UBURLRequest throughout the codebase.

Copy link
Contributor Author

@maerki maerki left a comment

Choose a reason for hiding this comment

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

Zusammenfassung der Änderungen:

  • Logger mit traces für Scheduling
  • Backoff immer basierend auf Date(), wenn der Task ein "refresh" ist
  • CachePolicy nicht beim Erstellen vom UBURLRequest setzen, sondern für alle Requests von der CachingLogic. Problem sind sonst alle UBURLRequest, die mit einem URLRequest initialisiert werden und nicht mit einer URL, dass dann auch die Refreshs aus dem Cache kommen können. Hat da wohl einfach eine Abstraktionsebene zuviel, aber das ist ein anderes Thema.
  • Completion-Handler erneut aufrufen, wenn ein Refresh mit einem Not-Modified endete
  • Refresh-Scheduling basierend auf Not-Modified Headers. Sollte nicht so relevant sein, da Date() als Referenz verwendet wird, aber falls in den Headers z.B. ein neuer Backoff-Internval gesetzt wäre, würde dieses für die Logik verwendet werden.

@maerki maerki merged commit 48f4a00 into main Dec 12, 2023
3 of 5 checks passed
@maerki maerki deleted the bugfix/cache-logic branch December 12, 2023 05:51
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