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

В веб-сервер добавлена возможность работы с данными форм. #1476

Merged
merged 3 commits into from
Dec 13, 2024

Conversation

akpaevj
Copy link
Contributor

@akpaevj akpaevj commented Dec 6, 2024

Доработка по #1473. В веб-сервер добавлена возможность работы с данными форм в контексте запроса

Breaking changes: изменен тип значения у значений хедеров. Теперь это коллекция строк, а не примитивный тип

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced FormCollectionWrapper and FormFileCollectionWrapper classes for enhanced handling of form data and files.
    • Added FormFileWrapper to manage individual file uploads.
    • New StringValuesWrapper class to facilitate handling multiple string values in HTTP headers.
  • Enhancements

    • Updated HttpRequestWrapper to include a Form property for easy access to form data.
    • Improved handling of HTTP headers in HeaderDictionaryWrapper to support multiple values.
  • Bug Fixes

    • Simplified property initializations in several classes for improved readability and maintenance.
  • Refactor

    • Code simplifications using target-typed new expressions across various wrapper classes.
    • Streamlined property implementations in HttpResponseWrapper and WebSocketAcceptContextWrapper for clarity.

Copy link

coderabbitai bot commented Dec 6, 2024

Warning

Rate limit exceeded

@akpaevj has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 15 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 62f1394 and 320db59.

📒 Files selected for processing (8)
  • src/OneScript.Web.Server/CookieOptionsWrapper.cs (4 hunks)
  • src/OneScript.Web.Server/FormCollectionWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/FormFileCollectionWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/HttpRequestWrapper.cs (8 hunks)
  • src/OneScript.Web.Server/HttpResponseWrapper.cs (2 hunks)
  • src/OneScript.Web.Server/WebSockets/WebSocketAcceptContextWrapper.cs (3 hunks)
  • src/OneScript.Web.Server/WebSockets/WebSocketReceiveResultWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/WebSockets/WebSocketWrapper.cs (4 hunks)

Walkthrough

The changes introduced in this pull request consist of several new classes and modifications to existing classes within the OneScript.Web.Server namespace. New classes such as FormCollectionWrapper, FormFileCollectionWrapper, and FormFileWrapper are designed to handle form data and files in a structured manner. Additionally, the HeaderDictionaryWrapper class has been updated to support multiple string values for HTTP headers. The HttpRequestWrapper and HttpResponseWrapper classes have also been modified for improved syntax and functionality. Lastly, a new StringValuesWrapper class has been added to enhance the handling of string values.

Changes

File Change Summary
src/OneScript.Web.Server/FormCollectionWrapper.cs Added FormCollectionWrapper class with methods for handling form data, including Retrieve, Count, Keys, and GetEnumerator. Overridden IsIndexed property.
src/OneScript.Web.Server/FormFileCollectionWrapper.cs Added FormFileCollectionWrapper class for managing form files, with methods like Retrieve and Count. Overridden GetEnumerator.
src/OneScript.Web.Server/FormFileWrapper.cs Added FormFileWrapper class to wrap IFormFile, exposing properties like ContentType, FileName, and methods for file access.
src/OneScript.Web.Server/HeaderDictionaryWrapper.cs Updated properties to return StringValuesWrapper instead of string, modified GetIndexedValue method to return StringValuesWrapper.
src/OneScript.Web.Server/HttpRequestWrapper.cs Added Form property to access form data; simplified syntax for Body, Cookies, and Headers properties.
src/OneScript.Web.Server/HttpResponseWrapper.cs Simplified Body property getter using target-typed new.
src/OneScript.Web.Server/StringValuesWrapper.cs Introduced StringValuesWrapper class with methods and implicit conversion operators for handling StringValues.
src/OneScript.Web.Server/WebSockets/WebSocketAcceptContextWrapper.cs Simplified initialization and casting in WebSocketAcceptContextWrapper, maintaining existing functionality.

Possibly related PRs

🐇 Hop, hop, hooray!
New wrappers come to play!
Forms and files, all in line,
Handling data, oh so fine!
With headers wrapped in strings so sweet,
Our web requests are now complete! 🌟


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. (Experiment)
  • @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: 1

🧹 Outside diff range and nitpick comments (3)
src/OneScript.Web.Server/FormCollectionWrapper.cs (1)

30-36: Ensure correct return type in GetIndexedValue method

In the GetIndexedValue method, while implicit conversion from StringValues to StringValuesWrapper is available, explicitly wrapping the result enhances clarity and consistency.

Suggested change:

public override StringValuesWrapper GetIndexedValue(IValue index)
{
    if (_items.TryGetValue(index.AsString(), out var result))
-       return result;
+       return new StringValuesWrapper(result);
    else
-       return StringValues.Empty;
+       return new StringValuesWrapper(StringValues.Empty);
}
src/OneScript.Web.Server/HeaderDictionaryWrapper.cs (2)

27-292: Explicitly wrap header values in StringValuesWrapper

The properties return StringValuesWrapper but are currently returning StringValues instances. While implicit conversion exists, explicitly wrapping the values improves readability.

Suggested change for each property:

[ContextProperty("Accept", CanWrite = false)]
- public StringValuesWrapper Accept => _items.Accept;
+ public StringValuesWrapper Accept => new StringValuesWrapper(_items.Accept);

307-313: Ensure correct return type in GetIndexedValue method

Similar to earlier, explicitly wrapping the result enhances clarity.

Suggested change:

public override StringValuesWrapper GetIndexedValue(IValue index)
{
    if (_items.TryGetValue(index.AsString(), out var result))
-       return result;
+       return new StringValuesWrapper(result);
    else
-       return StringValues.Empty;
+       return new StringValuesWrapper(StringValues.Empty);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0aea6cd and ba904f5.

📒 Files selected for processing (8)
  • src/OneScript.Web.Server/FormCollectionWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/FormFileCollectionWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/FormFileWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/HeaderDictionaryWrapper.cs (4 hunks)
  • src/OneScript.Web.Server/HttpRequestWrapper.cs (4 hunks)
  • src/OneScript.Web.Server/HttpResponseWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/StringValuesWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/WebSockets/WebSocketAcceptContextWrapper.cs (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/OneScript.Web.Server/HttpResponseWrapper.cs
🔇 Additional comments (8)
src/OneScript.Web.Server/StringValuesWrapper.cs (1)

1-79: Overall implementation looks good

The StringValuesWrapper class correctly wraps StringValues and provides the necessary methods and properties for indexed access and enumeration.

src/OneScript.Web.Server/FormCollectionWrapper.cs (1)

1-79: Overall implementation is correct

The FormCollectionWrapper class effectively wraps IFormCollection, providing indexed access and enumeration of form data.

src/OneScript.Web.Server/HeaderDictionaryWrapper.cs (1)

Line range hint 1-365: Updated header handling is appropriate

The modifications to handle multiple header values enhance functionality and align with HTTP standards.

src/OneScript.Web.Server/FormFileCollectionWrapper.cs (1)

1-65: Implementation is correct and follows best practices

The FormFileCollectionWrapper class properly wraps IFormFileCollection and exposes necessary methods for file retrieval and enumeration.

src/OneScript.Web.Server/FormFileWrapper.cs (1)

1-47: Well-implemented wrapper for IFormFile

The FormFileWrapper class correctly exposes the properties and methods of IFormFile, facilitating file handling in the OneScript environment.

src/OneScript.Web.Server/WebSockets/WebSocketAcceptContextWrapper.cs (1)

22-22: LGTM! Modern C# syntax improvements

The changes utilize C# 9.0 features (target-typed new) and remove redundant casts, improving code readability while maintaining the same functionality.

Let's verify the C# language version setting:

Also applies to: 32-32

✅ Verification successful

Let me verify the specific project's language version. I'll search for the project file containing WebSocketAcceptContextWrapper.cs.


Target-typed new syntax is compatible with project settings

The project uses C# 10.0 (LangVersion 10.0), which fully supports the target-typed new syntax introduced in C# 9.0. The changes are safe and aligned with the project's language version settings.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check .csproj files for language version
fd -e csproj . -x cat {} | grep -i 'LangVersion\|TargetFramework'

Length of output: 2028


Script:

#!/bin/bash
# Find the specific .csproj file for the WebSockets component
fd "OneScript.Web.Server.csproj|WebSocketAcceptContextWrapper.cs" . --type f -x dirname {} | sort | uniq

Length of output: 173


Script:

#!/bin/bash
# Check the specific project file's settings
cat ./src/OneScript.Web.Server/OneScript.Web.Server.csproj | grep -i 'LangVersion\|TargetFramework'

Length of output: 198

src/OneScript.Web.Server/HttpRequestWrapper.cs (2)

44-44: LGTM! Consistent use of modern C# syntax

The changes to use target-typed new expressions improve code readability while maintaining functionality.

Also applies to: 71-71, 74-74


136-146: Add XML documentation for the Form property

Consider adding XML documentation to maintain consistency with other properties in the class. Include description, return value details, and any relevant remarks about form content type requirements.

Here's a suggested documentation block:

+        /// <summary>
+        /// Gets the form data from the request if available.
+        /// </summary>
+        /// <returns>
+        /// FormCollectionWrapper instance if the request has form content type;
+        /// otherwise, returns null.
+        /// </returns>
         [ContextProperty("Форма", "Form", CanWrite = false)]
         public IValue Form

Let's verify the form handling implementation:

Comment on lines 31 to 35
public override IValue GetIndexedValue(IValue index)
{
var value = (int)index.AsNumber();

return ValueFactory.Create(_value[value]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add index validation to prevent exceptions in GetIndexedValue

The GetIndexedValue method currently casts the index to an integer and accesses the _value array without validating the index range. This could lead to an IndexOutOfRangeException if an invalid index is provided.

Consider adding validation to ensure the index is within the valid range:

public override IValue GetIndexedValue(IValue index)
{
    var idx = (int)index.AsNumber();
+   if (idx < 0 || idx >= _value.Count)
+       return BslNullValue.Instance; // Or throw an appropriate exception
    return ValueFactory.Create(_value[idx]);
}
📝 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
public override IValue GetIndexedValue(IValue index)
{
var value = (int)index.AsNumber();
return ValueFactory.Create(_value[value]);
public override IValue GetIndexedValue(IValue index)
{
var idx = (int)index.AsNumber();
if (idx < 0 || idx >= _value.Count)
return BslNullValue.Instance; // Or throw an appropriate exception
return ValueFactory.Create(_value[idx]);
}

src/OneScript.Web.Server/FormCollectionWrapper.cs Outdated Show resolved Hide resolved
src/OneScript.Web.Server/HttpRequestWrapper.cs Outdated Show resolved Hide resolved
src/OneScript.Web.Server/HttpRequestWrapper.cs Outdated Show resolved Hide resolved
src/OneScript.Web.Server/HttpRequestWrapper.cs Outdated Show resolved Hide resolved
@akpaevj
Copy link
Contributor Author

akpaevj commented Dec 10, 2024

Поправлю отступы и обновлю пр. Что-то непонятное

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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ba904f5 and 62f1394.

📒 Files selected for processing (6)
  • src/OneScript.Web.Server/FormCollectionWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/FormFileCollectionWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/FormFileWrapper.cs (1 hunks)
  • src/OneScript.Web.Server/HeaderDictionaryWrapper.cs (4 hunks)
  • src/OneScript.Web.Server/HttpRequestWrapper.cs (4 hunks)
  • src/OneScript.Web.Server/StringValuesWrapper.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/OneScript.Web.Server/FormFileWrapper.cs
  • src/OneScript.Web.Server/FormFileCollectionWrapper.cs
  • src/OneScript.Web.Server/FormCollectionWrapper.cs
🔇 Additional comments (3)
src/OneScript.Web.Server/StringValuesWrapper.cs (1)

31-36: Add index validation to prevent exceptions in GetIndexedValue

The GetIndexedValue method casts the index to an integer and accesses _value without validating the index range. This could lead to an IndexOutOfRangeException if an invalid index is provided.

Apply this diff to add index validation:

 public override IValue GetIndexedValue(IValue index)
 {
     var value = (int)index.AsNumber();
+    if (value < 0 || value >= _value.Count)
+        return BslNullValue.Instance; // Or throw an appropriate exception
     return ValueFactory.Create(_value[value]);
 }
src/OneScript.Web.Server/HttpRequestWrapper.cs (2)

144-144: Consider returning Undefined instead of Null

Returning BslUndefinedValue.Instance may be more appropriate than BslNullValue.Instance when the Form property is not available, aligning with the language's semantics for undefined values.

Apply this change:

     else
-        return BslNullValue.Instance;
+        return BslUndefinedValue.Instance;

44-44: Verify compatibility of target-typed new expressions

The properties Body, Cookies, and Headers use target-typed new expressions, which require C# 9.0 or later. Ensure that the project is set to use a compatible language version to prevent compilation issues.

Run the following script to check the project's language version:

Also applies to: 71-71, 74-74

✅ Verification successful

Target-typed new expressions are compatible with project settings

The project OneScript.Web.Server explicitly sets LangVersion to 10.0, which fully supports target-typed new expressions (introduced in C# 9.0). The code is safe to use this feature.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the project is set to use C# 9.0 or later.

# Test: Inspect the .csproj files for the LangVersion property. Expect: LangVersion is 9.0 or higher.
fd --type f --extension csproj | xargs grep -E '<LangVersion>(9\.0|latest)</LangVersion>'

Length of output: 91


Script:

#!/bin/bash
# Let's first check if there are any .csproj files and their content
fd --type f --extension csproj -x cat {}

Length of output: 54355

Comment on lines +307 to +312
public override StringValuesWrapper GetIndexedValue(IValue index)
{
if (_items.TryGetValue(index.AsString(), out var result))
return ValueFactory.Create(result);
return result;
else
return ValueFactory.Create();
return StringValues.Empty;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure consistent return types in GetIndexedValue

The method GetIndexedValue returns StringValuesWrapper, but it currently returns StringValues instances. While implicit conversions may handle this, it's clearer and safer to explicitly return StringValuesWrapper objects.

Apply this diff to explicitly convert the return values:

 public override StringValuesWrapper GetIndexedValue(IValue index)
 {
     if (_items.TryGetValue(index.AsString(), out var result))
-        return result;
+        return new StringValuesWrapper(result);
     else
-        return StringValues.Empty;
+        return new StringValuesWrapper(StringValues.Empty);
 }
📝 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
public override StringValuesWrapper GetIndexedValue(IValue index)
{
if (_items.TryGetValue(index.AsString(), out var result))
return ValueFactory.Create(result);
return result;
else
return ValueFactory.Create();
return StringValues.Empty;
public override StringValuesWrapper GetIndexedValue(IValue index)
{
if (_items.TryGetValue(index.AsString(), out var result))
return new StringValuesWrapper(result);
else
return new StringValuesWrapper(StringValues.Empty);

@akpaevj akpaevj requested a review from EvilBeaver December 10, 2024 18:04
@EvilBeaver
Copy link
Owner

@akpaevj LGTM. Вливать?

@akpaevj
Copy link
Contributor Author

akpaevj commented Dec 13, 2024

Да

@EvilBeaver EvilBeaver merged commit 72229c7 into EvilBeaver:develop Dec 13, 2024
2 checks passed
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.

3 participants