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

Fix non-thread-safe use of Random in MultipartFormDataBinaryContent #36

Merged
merged 3 commits into from
Jun 14, 2024

Conversation

stephentoub
Copy link
Contributor

MultipartFormDataBinaryContent has a static Random instance that's being used without a lock. This locks around each access (an alternative would be to use and lazily-initialize on each access a [ThreadStatic] Random).

While fixing that, also improved a few things:

  • We don't need to create a char[] for the boundary values; the const string can be used directly.
  • For netstandard2.0, we don't need to allocate a char[]; a stackalloc'd span can be used directly.
  • For .NET, we don't need a stackalloc, either; we can use string.Create and write directly into the new string instance.
  • For .NET, we don't need a dedicated Random instance, either; we can use Random.Shared.
  • For .NET, Random allows writing into a byte span, so we don't need the byte[] allocation either and can stackalloc it.
  • For .NET, just %'ing by the string length produces as good or better code than using a manually-computed mask.

MultipartFormDataBinaryContent has a static Random instance that's being used without a lock. This locks around each access (an alternative would be to use and lazily-initialize on each access a [ThreadStatic] Random).

While fixing that, also improved a few things:
- We don't need to create a char[] for the boundary values; the const string can be used directly.
- For netstandard2.0, we don't need to allocate a char[]; a stackalloc'd span can be used directly.
- For .NET, we don't need a stackalloc, either; we can use string.Create and write directly into the new string instance.
- For .NET, we don't need a dedicated Random instance, either; we can use Random.Shared.
- For .NET, Random allows writing into a byte span, so we don't need the byte[] allocation either and can stackalloc it.
- For .NET, just %'ing by the string length produces as good or better code than using a manually-computed mask.
@KrzysztofCwalina
Copy link
Collaborator

cc: @annelo-msft

@annelo-msft
Copy link
Contributor

Adding some context regarding why Random needs to be used in a thread-safe manner: https://devblogs.microsoft.com/pfxteam/getting-random-numbers-in-a-thread-safe-way/

@trrwilson trrwilson merged commit 7cacdee into openai:main Jun 14, 2024
1 check 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.

None yet

4 participants