Skip to content

Commit

Permalink
Use Ulid instead of Guid for better PERF
Browse files Browse the repository at this point in the history
  • Loading branch information
hishamco committed Oct 4, 2024
1 parent 027711f commit fc191b3
Show file tree
Hide file tree
Showing 39 changed files with 55 additions and 53 deletions.
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
<PackageVersion Include="StyleCop.Analyzers" Version="1.1.118" />
<PackageVersion Include="System.Linq.Async" Version="6.0.1" />
<PackageVersion Include="System.IO.Hashing" Version="8.0.0" />
<PackageVersion Include="Ulid" Version="1.3.4" />
<PackageVersion Include="xunit" Version="2.9.2" />
<PackageVersion Include="xunit.analyzers" Version="1.16.0" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ public async Task<ShellSettings> CreateTenantSettingsAsync(TenantSetupOptions se
shellSettings["TablePrefix"] = setupOptions.DatabaseTablePrefix;
shellSettings["Schema"] = setupOptions.DatabaseSchema;
shellSettings["DatabaseProvider"] = setupOptions.DatabaseProvider;
shellSettings["Secret"] = Guid.NewGuid().ToString();
shellSettings["Secret"] = Ulid.NewUlid().ToGuid().ToString();
shellSettings["RecipeName"] = setupOptions.RecipeName;
shellSettings["FeatureProfile"] = setupOptions.FeatureProfile;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public async Task<RemoteClient> CreateRemoteClientAsync(string clientName, strin

var remoteClient = new RemoteClient
{
Id = Guid.NewGuid().ToString("n"),
Id = Ulid.NewUlid().ToGuid().ToString("n"),
ClientName = clientName,
ProtectedApiKey = _dataProtector.Protect(Encoding.UTF8.GetBytes(apiKey)),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public async Task CreateRemoteInstanceAsync(string name, string url, string clie

remoteInstanceList.RemoteInstances.Add(new RemoteInstance
{
Id = Guid.NewGuid().ToString("n"),
Id = Ulid.NewUlid().ToGuid().ToString("n"),
Name = name,
Url = url,
ClientName = clientName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task<IActionResult> Create(long id, string type)
return NotFound();
}

step.Id = Guid.NewGuid().ToString("n");
step.Id = Ulid.NewUlid().ToGuid().ToString("n");

var model = new EditDeploymentPlanStepViewModel
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public IHtmlContent CachedShapeWrapper(IShape Shape)
var cache = metadata.Cache();

contentBuilder.AppendLine();
contentBuilder.AppendHtmlLine($"<!-- CACHED SHAPE: {cache.CacheId} ({Guid.NewGuid()})");
contentBuilder.AppendHtmlLine($"<!-- CACHED SHAPE: {cache.CacheId} ({Ulid.NewUlid().ToGuid()})");
contentBuilder.AppendHtmlLine($" VARY BY: {string.Join(", ", cache.Contexts)}");
contentBuilder.AppendHtmlLine($" DEPENDENCIES: {string.Join(", ", cache.Tags)}");
contentBuilder.AppendHtmlLine($" EXPIRES ON: {cache.ExpiresOn}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ public async Task<IHtmlContent> ProcessContentAsync(TagHelperOutput output, Cach
{
// No need to optimize this code as it will be used for debugging purpose.
writer.WriteLine();
writer.WriteLine($"<!-- CACHE BLOCK: {cacheContext.CacheId} ({Guid.NewGuid()})");
writer.WriteLine($"<!-- CACHE BLOCK: {cacheContext.CacheId} ({Ulid.NewUlid().ToGuid()})");
writer.WriteLine($" VARY BY: {string.Join(", ", cacheContext.Contexts)}");
writer.WriteLine($" DEPENDENCIES: {string.Join(", ", cacheContext.Tags)}");
writer.WriteLine($" EXPIRES ON: {cacheContext.ExpiresOn}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ private async Task<string> SendOnlineMessageAsync(MimeMessage message)

private static Task SendOfflineMessageAsync(MimeMessage message, string pickupDirectory)
{
var mailPath = Path.Combine(pickupDirectory, Guid.NewGuid().ToString() + EmailExtension);
var mailPath = Path.Combine(pickupDirectory, Ulid.NewUlid().ToGuid().ToString() + EmailExtension);

return message.WriteToAsync(mailPath, CancellationToken.None);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public async Task Invoke(HttpContext httpContext)
var script = $@"[{filters}].forEach(value=>{{if(!liquidFilters.includes(value)){{ liquidFilters.push(value);}}}});
[{tags}].forEach(value=>{{if(!liquidTags.includes(value)){{ liquidTags.push(value);}}}});";

_etag = Guid.NewGuid().ToString("n");
_etag = Ulid.NewUlid().ToGuid().ToString("n");
_bytes = Encoding.UTF8.GetBytes(script);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,7 @@ private static RSA GenerateRsaSecurityKey(int size)
private async Task PersistCertificateAsync(DirectoryInfo directory, X509Certificate2 certificate)
{
var password = GeneratePassword();
var path = Path.Combine(directory.FullName, Guid.NewGuid().ToString());
var path = Path.Combine(directory.FullName, Ulid.NewUlid().ToGuid().ToString());

await File.WriteAllBytesAsync(Path.ChangeExtension(path, ".pfx"), certificate.Export(X509ContentType.Pfx, password));
await File.WriteAllTextAsync(Path.ChangeExtension(path, ".pwd"), _dataProtector.Protect(password));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public async Task<ActionResult> Execute(string basePath, string fileName)

try
{
var executionId = Guid.NewGuid().ToString("n");
var executionId = Ulid.NewUlid().ToGuid().ToString("n");

await _recipeExecutor.ExecuteAsync(executionId, recipe, environment, CancellationToken.None);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public RecipeDeploymentTargetHandler(IShellHost shellHost,

public async Task ImportFromFileAsync(IFileProvider fileProvider)
{
var executionId = Guid.NewGuid().ToString("n");
var executionId = Ulid.NewUlid().ToGuid().ToString("n");
var recipeDescriptor = new RecipeDescriptor
{
FileProvider = fileProvider,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ private Task<SiteSettings> GetDefaultSettingsAsync()
{
return Task.FromResult(new SiteSettings
{
SiteSalt = Guid.NewGuid().ToString("N"),
SiteSalt = Ulid.NewUlid().ToGuid().ToString("N"),
SiteName = "My Orchard Project Application",
PageTitleFormat = "{% page_title Site.SiteName, position: \"after\", separator: \" - \" %}",
TimeZoneId = _clock.GetSystemTimeZone().TimeZoneId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ public async Task<IActionResult> Create(EditTenantViewModel model, string action
shellSettings["TablePrefix"] = model.TablePrefix;
shellSettings["Schema"] = model.Schema;
shellSettings["DatabaseProvider"] = model.DatabaseProvider;
shellSettings["Secret"] = Guid.NewGuid().ToString();
shellSettings["Secret"] = Ulid.NewUlid().ToGuid().ToString();
shellSettings["RecipeName"] = model.RecipeName;
shellSettings["FeatureProfile"] = string.Join(',', model.FeatureProfiles ?? []);

Expand Down Expand Up @@ -499,7 +499,7 @@ public async Task<IActionResult> Edit(EditTenantViewModel model)
shellSettings["Schema"] = model.Schema;
shellSettings["ConnectionString"] = model.ConnectionString;
shellSettings["RecipeName"] = model.RecipeName;
shellSettings["Secret"] = Guid.NewGuid().ToString();
shellSettings["Secret"] = Ulid.NewUlid().ToGuid().ToString();
}

await _shellHost.UpdateShellSettingsAsync(shellSettings);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public async Task<IActionResult> Create(TenantApiModel model)
shellSettings["TablePrefix"] = model.TablePrefix;
shellSettings["Schema"] = model.Schema;
shellSettings["DatabaseProvider"] = model.DatabaseProvider;
shellSettings["Secret"] = Guid.NewGuid().ToString();
shellSettings["Secret"] = Ulid.NewUlid().ToGuid().ToString();
shellSettings["RecipeName"] = model.RecipeName;
shellSettings["FeatureProfile"] = string.Join(',', model.FeatureProfiles ?? []);

Expand Down Expand Up @@ -179,7 +179,7 @@ public async Task<IActionResult> Edit(TenantApiModel model)
shellSettings["Schema"] = model.Schema;
shellSettings["ConnectionString"] = model.ConnectionString;
shellSettings["RecipeName"] = model.RecipeName;
shellSettings["Secret"] = Guid.NewGuid().ToString();
shellSettings["Secret"] = Ulid.NewUlid().ToGuid().ToString();
}

await _shellHost.UpdateShellSettingsAsync(shellSettings);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

<ItemGroup>
<PackageReference Include="NJsonSchema" />
<PackageReference Include="Ulid" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecuti
shellSettings["FeatureProfile"] = featureProfile;
}

shellSettings["Secret"] = Guid.NewGuid().ToString();
shellSettings["Secret"] = Ulid.NewUlid().ToGuid().ToString();

await ShellHost.UpdateShellSettingsAsync(shellSettings);
var reloadedSettings = ShellHost.GetSettings(shellSettings.Name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public async Task<IActionResult> Login(string returnUrl = null)
var dataProtector = _dataProtectionProvider.CreateProtector(ExternalAuthenticationsController.DefaultExternalLoginProtector)
.ToTimeLimitedDataProtector();

var token = Guid.NewGuid();
var token = Ulid.NewUlid().ToGuid();
var expiration = new TimeSpan(0, 0, 5);
var protectedToken = dataProtector.Protect(token.ToString(), _clock.UtcNow.Add(expiration));
await _distributedCache.SetAsync(token.ToString(), token.ToByteArray(), new DistributedCacheEntryOptions()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ public async Task<IActionResult> Edit(long id, string localId)
return Forbid();
}

var newLocalId = string.IsNullOrWhiteSpace(localId) ? Guid.NewGuid().ToString() : localId;
var newLocalId = string.IsNullOrWhiteSpace(localId) ? Ulid.NewUlid().ToGuid().ToString() : localId;
var availableActivities = _activityLibrary.ListActivities();
var workflowType = await _session.GetAsync<WorkflowType>(id);

Expand Down
2 changes: 1 addition & 1 deletion src/OrchardCore/OrchardCore.Abstractions/IdGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public static class IdGenerator

public static string GenerateId()
{
var guid = Guid.NewGuid().ToByteArray();
var guid = Ulid.NewUlid().ToGuid().ToByteArray();

Check failure on line 10 in src/OrchardCore/OrchardCore.Abstractions/IdGenerator.cs

View workflow job for this annotation

GitHub Actions / Build & Test (ubuntu-latest)

The name 'Ulid' does not exist in the current context

Check failure on line 10 in src/OrchardCore/OrchardCore.Abstractions/IdGenerator.cs

View workflow job for this annotation

GitHub Actions / Build & Test (ubuntu-latest)

The name 'Ulid' does not exist in the current context

Check failure on line 10 in src/OrchardCore/OrchardCore.Abstractions/IdGenerator.cs

View workflow job for this annotation

GitHub Actions / Build & Test (windows-latest)

The name 'Ulid' does not exist in the current context

Check failure on line 10 in src/OrchardCore/OrchardCore.Abstractions/IdGenerator.cs

View workflow job for this annotation

GitHub Actions / Build & Test (windows-latest)

The name 'Ulid' does not exist in the current context

return string.Create(26, guid, (buffer, guid) =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace OrchardCore.AdminMenu.Models;

public class AdminMenu
{
public string Id { get; set; } = Guid.NewGuid().ToString("n");
public string Id { get; set; } = Ulid.NewUlid().ToGuid().ToString("n");
public string Name { get; set; }
public bool Enabled { get; set; } = true;
public List<AdminNode> MenuItems { get; init; } = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace OrchardCore.AdminMenu.Models;

public class AdminNode : MenuItem
{
public string UniqueId { get; set; } = Guid.NewGuid().ToString("n");
public string UniqueId { get; set; } = Ulid.NewUlid().ToGuid().ToString("n");
public bool Enabled { get; set; } = true;

public AdminNode GetMenuItemById(string id)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ The contents of the cache block will not be cached.
// No need to optimize this code as it will be used for debugging purpose.
var debugContent = new StringWriter();
debugContent.WriteLine();
debugContent.WriteLine($"<!-- CACHE BLOCK: {cacheContext.CacheId} ({Guid.NewGuid()})");
debugContent.WriteLine($"<!-- CACHE BLOCK: {cacheContext.CacheId} ({Ulid.NewUlid().ToGuid()})");
debugContent.WriteLine($" VARY BY: {string.Join(", ", cacheContext.Contexts)}");
debugContent.WriteLine($" DEPENDENCIES: {string.Join(", ", cacheContext.Tags)}");
debugContent.WriteLine($" EXPIRES ON: {cacheContext.ExpiresOn}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class DefaultIdGenerator : IIdGenerator
public string GenerateUniqueId()
{
// Generate a base32 Guid value
var guid = Guid.NewGuid().ToByteArray();
var guid = Ulid.NewUlid().ToGuid().ToByteArray();

var hs = BitConverter.ToInt64(guid, 0);
var ls = BitConverter.ToInt64(guid, 8);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ public virtual ValueTask<ImmutableDictionary<string, string>> GetSettingsAsync(T

/// <inheritdoc/>
public virtual ValueTask<TApplication> InstantiateAsync(CancellationToken cancellationToken)
=> new(new TApplication { ApplicationId = Guid.NewGuid().ToString("n") });
=> new(new TApplication { ApplicationId = Ulid.NewUlid().ToGuid().ToString("n") });

/// <inheritdoc/>
public virtual IAsyncEnumerable<TApplication> ListAsync(int? count, int? offset, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ public virtual ValueTask<string> GetTypeAsync(TAuthorization authorization, Canc

/// <inheritdoc/>
public virtual ValueTask<TAuthorization> InstantiateAsync(CancellationToken cancellationToken)
=> new(new TAuthorization { AuthorizationId = Guid.NewGuid().ToString("n") });
=> new(new TAuthorization { AuthorizationId = Ulid.NewUlid().ToGuid().ToString("n") });

/// <inheritdoc/>
public virtual IAsyncEnumerable<TAuthorization> ListAsync(int? count, int? offset, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync(TScope scope,

/// <inheritdoc/>
public virtual ValueTask<TScope> InstantiateAsync(CancellationToken cancellationToken)
=> new(new TScope { ScopeId = Guid.NewGuid().ToString("n") });
=> new(new TScope { ScopeId = Ulid.NewUlid().ToGuid().ToString("n") });

/// <inheritdoc/>
public virtual IAsyncEnumerable<TScope> ListAsync(int? count, int? offset, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ public virtual ValueTask<string> GetTypeAsync(TToken token, CancellationToken ca

/// <inheritdoc/>
public virtual ValueTask<TToken> InstantiateAsync(CancellationToken cancellationToken)
=> new(new TToken { TokenId = Guid.NewGuid().ToString("n") });
=> new(new TToken { TokenId = Ulid.NewUlid().ToGuid().ToString("n") });

/// <inheritdoc/>
public virtual IAsyncEnumerable<TToken> ListAsync(int? count, int? offset, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public async Task<string> ExecuteAsync(string executionId, RecipeDescriptor reci
{
foreach (var descriptor in recipeStep.InnerRecipes)
{
var innerExecutionId = Guid.NewGuid().ToString();
var innerExecutionId = Ulid.NewUlid().ToGuid().ToString();
descriptor.RequireNewScope = recipeDescriptor.RequireNewScope;
await ExecuteAsync(innerExecutionId, descriptor, environment, cancellationToken);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public async Task<string> ExecuteAsync(string recipeFileName, IDataMigration mig
await _environmentProviders.OrderBy(x => x.Order)
.InvokeAsync((provider, env) => provider.PopulateEnvironmentAsync(env), environment, _logger);

var executionId = Guid.NewGuid().ToString("n");
var executionId = Ulid.NewUlid().ToGuid().ToString("n");

return await _recipeExecutor.ExecuteAsync(executionId, recipeDescriptor, environment, CancellationToken.None);
}
Expand Down
2 changes: 1 addition & 1 deletion src/OrchardCore/OrchardCore.Setup.Core/SetupService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ await scope.ServiceProvider.GetService<IShellDescriptorManager>()
return null;
}

executionId = Guid.NewGuid().ToString("n");
executionId = Ulid.NewUlid().ToGuid().ToString("n");

var recipeExecutor = shellContext.ServiceProvider.GetRequiredService<IRecipeExecutor>();
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ await _distributedCache.SetAsync(cacheKey, protectedBytes,

public async Task<string> StoreAsync(AuthenticationTicket ticket)
{
var key = Guid.NewGuid().ToString();
var key = Ulid.NewUlid().ToGuid().ToString();
var cacheKey = $"{KeyPrefix}-{key}";

try
Expand Down
6 changes: 3 additions & 3 deletions test/OrchardCore.Tests/Apis/Context/SiteContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ static SiteContext()

public virtual async Task InitializeAsync()
{
var tenantName = Guid.NewGuid().ToString("n");
var tenantName = Ulid.NewUlid().ToGuid().ToString("n");
var tablePrefix = await _tablePrefixGenerator.GeneratePrefixAsync();

var createModel = new Tenants.Models.TenantApiModel
Expand Down Expand Up @@ -83,7 +83,7 @@ public virtual async Task InitializeAsync()

if (PermissionsContext != null)
{
var permissionContextKey = Guid.NewGuid().ToString();
var permissionContextKey = Ulid.NewUlid().ToGuid().ToString();
SiteStartup.PermissionsContexts.TryAdd(permissionContextKey, PermissionsContext);
Client.DefaultRequestHeaders.Add("PermissionsContext", permissionContextKey);
}
Expand Down Expand Up @@ -114,7 +114,7 @@ await UsingTenantScopeAsync(async scope =>
var recipe = recipes
.FirstOrDefault(recipe => recipe.RecipeFileInfo.Name == recipeName && recipe.BasePath == recipePath);

var executionId = Guid.NewGuid().ToString("n");
var executionId = Ulid.NewUlid().ToGuid().ToString("n");

await recipeExecutor.ExecuteAsync(
executionId,
Expand Down
8 changes: 4 additions & 4 deletions test/OrchardCore.Tests/Data/JsonDynamicTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public void JsonDynamicValueMustConvertToNullableDouble()
[Fact]
public void JsonDynamicValueMustConvertToGuid()
{
Guid expectedValue = Guid.NewGuid();
Guid expectedValue = Ulid.NewUlid().ToGuid();
dynamic myDynamic = new JsonDynamicValue(JsonValue.Create(expectedValue));

Assert.Equal(expectedValue, (Guid)myDynamic);
Expand All @@ -149,7 +149,7 @@ public void JsonDynamicValueMustConvertToGuid()
[Fact]
public void JsonDynamicValueMustConvertToNullableGuid()
{
Guid? expectedValue = Guid.NewGuid();
Guid? expectedValue = Ulid.NewUlid().ToGuid();
dynamic myDynamic = new JsonDynamicValue(JsonValue.Create(expectedValue));

Assert.Equal(expectedValue, (Guid?)myDynamic);
Expand Down Expand Up @@ -530,7 +530,7 @@ public void JsonDynamicValueCanImplicitlyConvertToNullableDouble()
[Fact]
public void JsonDynamicValueCanImplicitlyConvertToGuid()
{
Guid expectedValue = Guid.NewGuid();
Guid expectedValue = Ulid.NewUlid().ToGuid();
dynamic myDynamic = new JsonDynamicValue(JsonValue.Create(expectedValue));

Guid value = myDynamic;
Expand All @@ -543,7 +543,7 @@ public void JsonDynamicValueCanImplicitlyConvertToGuid()
[Fact]
public void JsonDynamicValueCanImplicitlyConvertToNullableGuid()
{
Guid? expectedValue = Guid.NewGuid();
Guid? expectedValue = Ulid.NewUlid().ToGuid();
dynamic myDynamic = new JsonDynamicValue(JsonValue.Create(expectedValue));

Guid? value = myDynamic;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ private static OpenIdServerSettings CreateSettings(string authority, OpenIdServe

result.EncryptionCertificateStoreLocation = StoreLocation.LocalMachine;
result.EncryptionCertificateStoreName = StoreName.My;
result.EncryptionCertificateThumbprint = Guid.NewGuid().ToString();
result.EncryptionCertificateThumbprint = Ulid.NewUlid().ToGuid().ToString();

result.SigningCertificateStoreLocation = StoreLocation.LocalMachine;
result.SigningCertificateStoreName = StoreName.My;
result.SigningCertificateThumbprint = Guid.NewGuid().ToString();
result.SigningCertificateThumbprint = Ulid.NewUlid().ToGuid().ToString();

result.AllowAuthorizationCodeFlow = true;
result.AllowClientCredentialsFlow = true;
Expand Down
Loading

0 comments on commit fc191b3

Please sign in to comment.