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

Improve perf of base64 encoding check on a consumer hot path #2371

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 4 additions & 21 deletions src/Confluent.SchemaRegistry/CachedSchemaRegistryClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -592,34 +592,17 @@ private bool checkSchemaMatchesFormat(string format, string schemaString)
// if a format isn't specified, then assume text is desired.
if (format == null)
{
try
{
Convert.FromBase64String(schemaString);
}
catch (Exception)
{
return true; // Base64 conversion failed, infer the schemaString format is text.
}

return false; // Base64 conversion succeeded, so infer the schamaString format is base64.
// If schemaString is not Base64, infer the schemaString format is text.
return !Utils.IsBase64String(schemaString);
}
else
{
if (format != "serialized")
{
throw new ArgumentException($"Invalid schema format was specified: {format}.");
}

try
{
Convert.FromBase64String(schemaString);
}
catch (Exception)
{
return false;
}

return true;

return Utils.IsBase64String(schemaString);
}
}

Expand Down
20 changes: 20 additions & 0 deletions src/Confluent.SchemaRegistry/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
using System.Linq;
using Confluent.Kafka;

#if NET8_0_OR_GREATER
using System.Buffers.Text;
#endif

namespace Confluent.SchemaRegistry
{
Expand Down Expand Up @@ -70,5 +73,22 @@ public static bool ListEquals<T>(IList<T> a, IList<T> b)
if (a == null || b == null) return false;
return a.SequenceEqual(b);
}

internal static bool IsBase64String(string value)
{
#if NET8_0_OR_GREATER
return Base64.IsValid(value);
#else
try
{
_ = Convert.FromBase64String(value);
return true;
}
catch (FormatException)
{
return false;
}
#endif
}
}
}