2020-12-23 11:35:49 +01:00
|
|
|
// Copyright (c) Umbraco.
|
|
|
|
|
// See LICENSE for more details.
|
|
|
|
|
|
2018-06-29 19:52:40 +02:00
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Threading;
|
2020-12-17 17:06:51 +00:00
|
|
|
using Microsoft.Extensions.Logging;
|
2018-06-29 19:52:40 +02:00
|
|
|
using NUnit.Framework;
|
2021-02-09 10:22:42 +01:00
|
|
|
using Umbraco.Cms.Core.Models;
|
|
|
|
|
using Umbraco.Cms.Core.Services;
|
v10 SQLite support + distributed locking abstractions (#11922)
* Created Persistence.SQLite project skeleton.
* SQLite database initialization
* Various changes and hacks to make things work.
* WIP integration tests
* Fix thread safety tests
* Fix tests that relied on tie breaker sorting.
Spent a fair amount of time looking for a less lazy fix but gave up.
* Convert right join to left join ContentTypeRepository.PerformGetByQuery
SQLite doesn't support right join
* Fix test Can_Generate_Delete_SubQuery_Statement
Worth noting that NPoco.DatabaseTypes.SQLiteDatabaseType doesn't override
EscapeSqlIdentifier so NPoco will escape with [].
SQLite docs say > "A keyword enclosed in square brackets is an identifier.
This is not standard SQL.
This quoting mechanism is used by MS Access and SQL Server and is
included in SQLite for compatibility."
Also could have updated SqliteSyntaxProvider to match npoco but
decided against it.
* Fixes for paginated custom order by
* Fix tests broken by lack of unique indexes.
* Fix SqlServerTableByTableTest tests.
These tests didn't actually do anything as the tables already exist so schema creator just returned.
Did however point out that the default implementation for DoesTableExist just returns false so added a default naive implementation.
* Fix ValidateLoginSession - SelectTop must come later
* dry up database cleanup
* Fix up db migration tests.
We can't drop pk in sqlite without recreating table.
Test looks to be testing that add column works as intended which we can test.
* Prevent schema creation errors.
* SQLite ignore lock tests, WAL back on.
* Fix package schema tests
* Fix NPocoFetchTests - case sensitivity not under test
* Fix AdvancedMigrationTests (where possible)
Migrations probably need a good look later.
Maybe nuke old migrations and only support moving to v10 from v9.
If we do that can do some cleanup.
* Cleanup test database configuration
* Run integration tests against SQLite on build agent.
* Drop MS.Data.SQLite
System.Data.SQLite was quicker to roll out due to more CLR type mapping
* YAML
* Skip Umbraco.Tests.Integration.SqlCe
* Drop SqlServerTableByTable tests.
Until this week they did nothing anyway as they with NewSchemaPerTest
so the tests all passed as CreateTable was no op (already exists).
Also all of the tables are created in an empty database by SchemaValidationTest.cs
DatabaseSchemaCreation_Produces_DatabaseSchemaResult_With_Zero_Errors
* Might aswell run against macOS also.
* Copy azure pipelines task header layout
* Delete SQLCe projects
* Remove SQL CE specific code.
* Remove SQL CE NuSpec, template params, build script setup
* Delete umbraco-netcore-only.sln
* Add SkipTests solution configuration and use for codeql
* Remove reference to deleted nuspec file.
* Refactor ConnectionStrings WRT DataDirectory placeholder & ProviderName.
At this point you can try out SQLite support by setting the following
in appsettings.json and then completing the install process.
"ConnectionStrings": {
"umbracoDbDSN": "Data Source=|DataDirectory|/umbraco.sqlite",
"umbracoDbDSN_ProviderName": "System.Data.SQLite"
},
Not currently possible via installer UI without provider name pre-set in
configuration.
* Switch to Microsoft.Data.Sqlite
Some gross hacks but will be good to find out if this works
with apple silicon.
* Enable selection of SQLite via installer UI (also quick install)
* Remove SqlServerDbProviderFactoryCreator to cleanup a TODO
* Move SQL Server support to its own class library
* Add persistence dependencies to Umbraco.CMS metapackage
* Bugfix packages delete query
Created invalid query for SQLite.
* Try out cypress tests Linux + SQLite
* Prevent cypress test artifact upload failure on attempt 2+
* LocalDb bugfixes
* Drop redundant enum
* Move SqlClient constant
* Misc whitespace
* Remove IsSqlCe extension (TODO: drop non 9->10 migrations later).
* Umbraco.Persistence.* -> Umbraco.Cms.Persistence.*
* Display quick install defaults and per provider default database name.
* Misc remove old comment
* little re-arrange
* Remove almost all usages of IsSqlite extension.
* visual adjustments
* Custom Database Configuration is last step and should then say Install.
* use text instead of disabled inputs
* move legend, rename to Install
* Update SqlMainDomLock to work without distributed locks.
* Added IDistributedLockingMechanism interface and in memory impl.
* Drop locking from ISqlSyntaxProvider & wire up scope to abstraction.
* Added SqlServerDistributedLockingMechanism
* Move distributed locking interfaces and exceptions to Core + xmldocs.
* Fix tests, Misc cleanup, Add SQL distributed locking integration tests
* Provide mechanism to specify DistributedLockingMechanism in config
(even if added by composer)
* Nomplementation -> NoImplementation
* Fix misleading comment
* Integration tests use SqlServerDistributedLockingMechanism when possible
* Handle up-gradable locks SqlServerDistributedLockingMechanism.
TODO: InMemoryDistributedLockingMechanism.
Note: Nuked SqlServerDistributedLockingMechanismTests, will still sleep
at night.
Is covered by Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.LockTests
* Make tests pass for InMemoryDistributedLockingMechanism, pretty hacky.
* Tweak constraints on WithCollectionBuilder so i can drop bad constructor
* Added SqliteDistributedLockingMechanism
* Dropped InMemoryDistributedMechanism + magic
InMemoryDistributedMechanism was pretty rubbish and now we have
a decent implementation for SQLite as we no longer block readers
see 8d1f42b.
Also drop the CollectionBuilder setup, instead do the same as we do
for syntax providers etc, it's more automagical so we never require an
explicit selection although we are allowing for it.
However keeping the optional IUmbracoBuilder constructor param for
CollectionBuilders as it's extremely useful.
* Fix quick install "" database name.
* Hide Database Configuration section when a connection string is pre-set.
Doesn't seem worth it to extract db name from connection string.
* Ensure wal test 2+
* Fix logging inconsistencies.
* Ensure in transaction when obtaining locks + no-op the SQLite read lock.
There's no point in running the query just to make a single test pass.
* Fix installer database display names
* Allow SQLite shared cache without losing deferred transactions
* Opt into shared cache for new SQLite databases + fix filename
* Fix misc inconsistency in .gitignore
* Prefer our interceptor interface
* Restore DEBUG_DATABASES code OnConnectionOpened in case it's used.
* Back to private cache.
* Added retry strategy for SQLite + refactor out SQL server specific stuff
* Fix SQL server tests.
* Misc - Orphaned comment, incorrect casing.
* InMemory SQLite test database & turn shared cache back on everywhere.
Co-authored-by: Niels Lyngsø <niels.lyngso@gmail.com>
2022-03-11 16:14:20 +00:00
|
|
|
using Umbraco.Cms.Infrastructure.Persistence;
|
2023-09-12 14:16:27 +02:00
|
|
|
using Umbraco.Cms.Tests.Common.Attributes;
|
2021-02-10 14:45:44 +01:00
|
|
|
using Umbraco.Cms.Tests.Common.Builders;
|
|
|
|
|
using Umbraco.Cms.Tests.Common.Testing;
|
2021-02-11 08:30:27 +01:00
|
|
|
using Umbraco.Cms.Tests.Integration.Testing;
|
2021-03-09 12:45:51 +11:00
|
|
|
using Umbraco.Extensions;
|
2021-02-09 10:22:42 +01:00
|
|
|
using Constants = Umbraco.Cms.Core.Constants;
|
2022-04-26 10:22:37 +01:00
|
|
|
using IScope = Umbraco.Cms.Infrastructure.Scoping.IScope;
|
|
|
|
|
|
2021-02-11 08:30:27 +01:00
|
|
|
namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Services
|
2018-06-29 19:52:40 +02:00
|
|
|
{
|
|
|
|
|
// these tests tend to fail from time to time esp. on VSTS
|
|
|
|
|
//
|
|
|
|
|
// read
|
|
|
|
|
// Lock Time-out: https://technet.microsoft.com/en-us/library/ms172402.aspx?f=255&MSPPError=-2147217396
|
|
|
|
|
// http://support.x-tensive.com/question/5242/strange-locking-exceptions-with-sqlserverce
|
|
|
|
|
// http://debuggingblog.com/wp/2009/05/07/high-cpu-usage-and-windows-forms-application-hang-with-sqlce-database-and-the-sqlcelocktimeoutexception/
|
|
|
|
|
//
|
|
|
|
|
// tried to increase it via connection string or via SET LOCK_TIMEOUT
|
|
|
|
|
// but still, the test fails on VSTS in most cases, so now ignoring it,
|
|
|
|
|
// as I could not figure out _why_ and it does not look like we are
|
|
|
|
|
// causing it, getting into __sysObjects locks, no idea why
|
|
|
|
|
[TestFixture]
|
2020-12-17 17:06:51 +00:00
|
|
|
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, Logger = UmbracoTestOptions.Logger.Console)]
|
2020-10-21 13:54:22 +02:00
|
|
|
public class ThreadSafetyServiceTest : UmbracoIntegrationTest
|
2018-06-29 19:52:40 +02:00
|
|
|
{
|
2020-10-21 13:54:22 +02:00
|
|
|
private IContentService ContentService => GetRequiredService<IContentService>();
|
2020-12-23 11:35:49 +01:00
|
|
|
|
2020-10-21 13:54:22 +02:00
|
|
|
private IMediaService MediaService => GetRequiredService<IMediaService>();
|
2020-12-23 11:35:49 +01:00
|
|
|
|
2020-10-21 13:54:22 +02:00
|
|
|
private IContentTypeService ContentTypeService => GetRequiredService<IContentTypeService>();
|
|
|
|
|
|
|
|
|
|
[SetUp]
|
|
|
|
|
public void SetUp()
|
2018-06-29 19:52:40 +02:00
|
|
|
{
|
|
|
|
|
CreateTestData();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private const int MaxThreadCount = 20;
|
|
|
|
|
|
|
|
|
|
private void Save(ContentService service, IContent content)
|
|
|
|
|
{
|
2020-12-23 11:35:49 +01:00
|
|
|
using (IScope scope = ScopeProvider.CreateScope())
|
2018-06-29 19:52:40 +02:00
|
|
|
{
|
v10 SQLite support + distributed locking abstractions (#11922)
* Created Persistence.SQLite project skeleton.
* SQLite database initialization
* Various changes and hacks to make things work.
* WIP integration tests
* Fix thread safety tests
* Fix tests that relied on tie breaker sorting.
Spent a fair amount of time looking for a less lazy fix but gave up.
* Convert right join to left join ContentTypeRepository.PerformGetByQuery
SQLite doesn't support right join
* Fix test Can_Generate_Delete_SubQuery_Statement
Worth noting that NPoco.DatabaseTypes.SQLiteDatabaseType doesn't override
EscapeSqlIdentifier so NPoco will escape with [].
SQLite docs say > "A keyword enclosed in square brackets is an identifier.
This is not standard SQL.
This quoting mechanism is used by MS Access and SQL Server and is
included in SQLite for compatibility."
Also could have updated SqliteSyntaxProvider to match npoco but
decided against it.
* Fixes for paginated custom order by
* Fix tests broken by lack of unique indexes.
* Fix SqlServerTableByTableTest tests.
These tests didn't actually do anything as the tables already exist so schema creator just returned.
Did however point out that the default implementation for DoesTableExist just returns false so added a default naive implementation.
* Fix ValidateLoginSession - SelectTop must come later
* dry up database cleanup
* Fix up db migration tests.
We can't drop pk in sqlite without recreating table.
Test looks to be testing that add column works as intended which we can test.
* Prevent schema creation errors.
* SQLite ignore lock tests, WAL back on.
* Fix package schema tests
* Fix NPocoFetchTests - case sensitivity not under test
* Fix AdvancedMigrationTests (where possible)
Migrations probably need a good look later.
Maybe nuke old migrations and only support moving to v10 from v9.
If we do that can do some cleanup.
* Cleanup test database configuration
* Run integration tests against SQLite on build agent.
* Drop MS.Data.SQLite
System.Data.SQLite was quicker to roll out due to more CLR type mapping
* YAML
* Skip Umbraco.Tests.Integration.SqlCe
* Drop SqlServerTableByTable tests.
Until this week they did nothing anyway as they with NewSchemaPerTest
so the tests all passed as CreateTable was no op (already exists).
Also all of the tables are created in an empty database by SchemaValidationTest.cs
DatabaseSchemaCreation_Produces_DatabaseSchemaResult_With_Zero_Errors
* Might aswell run against macOS also.
* Copy azure pipelines task header layout
* Delete SQLCe projects
* Remove SQL CE specific code.
* Remove SQL CE NuSpec, template params, build script setup
* Delete umbraco-netcore-only.sln
* Add SkipTests solution configuration and use for codeql
* Remove reference to deleted nuspec file.
* Refactor ConnectionStrings WRT DataDirectory placeholder & ProviderName.
At this point you can try out SQLite support by setting the following
in appsettings.json and then completing the install process.
"ConnectionStrings": {
"umbracoDbDSN": "Data Source=|DataDirectory|/umbraco.sqlite",
"umbracoDbDSN_ProviderName": "System.Data.SQLite"
},
Not currently possible via installer UI without provider name pre-set in
configuration.
* Switch to Microsoft.Data.Sqlite
Some gross hacks but will be good to find out if this works
with apple silicon.
* Enable selection of SQLite via installer UI (also quick install)
* Remove SqlServerDbProviderFactoryCreator to cleanup a TODO
* Move SQL Server support to its own class library
* Add persistence dependencies to Umbraco.CMS metapackage
* Bugfix packages delete query
Created invalid query for SQLite.
* Try out cypress tests Linux + SQLite
* Prevent cypress test artifact upload failure on attempt 2+
* LocalDb bugfixes
* Drop redundant enum
* Move SqlClient constant
* Misc whitespace
* Remove IsSqlCe extension (TODO: drop non 9->10 migrations later).
* Umbraco.Persistence.* -> Umbraco.Cms.Persistence.*
* Display quick install defaults and per provider default database name.
* Misc remove old comment
* little re-arrange
* Remove almost all usages of IsSqlite extension.
* visual adjustments
* Custom Database Configuration is last step and should then say Install.
* use text instead of disabled inputs
* move legend, rename to Install
* Update SqlMainDomLock to work without distributed locks.
* Added IDistributedLockingMechanism interface and in memory impl.
* Drop locking from ISqlSyntaxProvider & wire up scope to abstraction.
* Added SqlServerDistributedLockingMechanism
* Move distributed locking interfaces and exceptions to Core + xmldocs.
* Fix tests, Misc cleanup, Add SQL distributed locking integration tests
* Provide mechanism to specify DistributedLockingMechanism in config
(even if added by composer)
* Nomplementation -> NoImplementation
* Fix misleading comment
* Integration tests use SqlServerDistributedLockingMechanism when possible
* Handle up-gradable locks SqlServerDistributedLockingMechanism.
TODO: InMemoryDistributedLockingMechanism.
Note: Nuked SqlServerDistributedLockingMechanismTests, will still sleep
at night.
Is covered by Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.LockTests
* Make tests pass for InMemoryDistributedLockingMechanism, pretty hacky.
* Tweak constraints on WithCollectionBuilder so i can drop bad constructor
* Added SqliteDistributedLockingMechanism
* Dropped InMemoryDistributedMechanism + magic
InMemoryDistributedMechanism was pretty rubbish and now we have
a decent implementation for SQLite as we no longer block readers
see 8d1f42b.
Also drop the CollectionBuilder setup, instead do the same as we do
for syntax providers etc, it's more automagical so we never require an
explicit selection although we are allowing for it.
However keeping the optional IUmbracoBuilder constructor param for
CollectionBuilders as it's extremely useful.
* Fix quick install "" database name.
* Hide Database Configuration section when a connection string is pre-set.
Doesn't seem worth it to extract db name from connection string.
* Ensure wal test 2+
* Fix logging inconsistencies.
* Ensure in transaction when obtaining locks + no-op the SQLite read lock.
There's no point in running the query just to make a single test pass.
* Fix installer database display names
* Allow SQLite shared cache without losing deferred transactions
* Opt into shared cache for new SQLite databases + fix filename
* Fix misc inconsistency in .gitignore
* Prefer our interceptor interface
* Restore DEBUG_DATABASES code OnConnectionOpened in case it's used.
* Back to private cache.
* Added retry strategy for SQLite + refactor out SQL server specific stuff
* Fix SQL server tests.
* Misc - Orphaned comment, incorrect casing.
* InMemory SQLite test database & turn shared cache back on everywhere.
Co-authored-by: Niels Lyngsø <niels.lyngso@gmail.com>
2022-03-11 16:14:20 +00:00
|
|
|
if (ScopeAccessor.AmbientScope.Database.DatabaseType.IsSqlServer())
|
|
|
|
|
{
|
|
|
|
|
ScopeAccessor.AmbientScope.Database.Execute("SET LOCK_TIMEOUT 60000");
|
|
|
|
|
}
|
|
|
|
|
|
2018-06-29 19:52:40 +02:00
|
|
|
service.Save(content);
|
|
|
|
|
scope.Complete();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void Save(MediaService service, IMedia media)
|
|
|
|
|
{
|
2020-12-23 11:35:49 +01:00
|
|
|
using (IScope scope = ScopeProvider.CreateScope())
|
2018-06-29 19:52:40 +02:00
|
|
|
{
|
v10 SQLite support + distributed locking abstractions (#11922)
* Created Persistence.SQLite project skeleton.
* SQLite database initialization
* Various changes and hacks to make things work.
* WIP integration tests
* Fix thread safety tests
* Fix tests that relied on tie breaker sorting.
Spent a fair amount of time looking for a less lazy fix but gave up.
* Convert right join to left join ContentTypeRepository.PerformGetByQuery
SQLite doesn't support right join
* Fix test Can_Generate_Delete_SubQuery_Statement
Worth noting that NPoco.DatabaseTypes.SQLiteDatabaseType doesn't override
EscapeSqlIdentifier so NPoco will escape with [].
SQLite docs say > "A keyword enclosed in square brackets is an identifier.
This is not standard SQL.
This quoting mechanism is used by MS Access and SQL Server and is
included in SQLite for compatibility."
Also could have updated SqliteSyntaxProvider to match npoco but
decided against it.
* Fixes for paginated custom order by
* Fix tests broken by lack of unique indexes.
* Fix SqlServerTableByTableTest tests.
These tests didn't actually do anything as the tables already exist so schema creator just returned.
Did however point out that the default implementation for DoesTableExist just returns false so added a default naive implementation.
* Fix ValidateLoginSession - SelectTop must come later
* dry up database cleanup
* Fix up db migration tests.
We can't drop pk in sqlite without recreating table.
Test looks to be testing that add column works as intended which we can test.
* Prevent schema creation errors.
* SQLite ignore lock tests, WAL back on.
* Fix package schema tests
* Fix NPocoFetchTests - case sensitivity not under test
* Fix AdvancedMigrationTests (where possible)
Migrations probably need a good look later.
Maybe nuke old migrations and only support moving to v10 from v9.
If we do that can do some cleanup.
* Cleanup test database configuration
* Run integration tests against SQLite on build agent.
* Drop MS.Data.SQLite
System.Data.SQLite was quicker to roll out due to more CLR type mapping
* YAML
* Skip Umbraco.Tests.Integration.SqlCe
* Drop SqlServerTableByTable tests.
Until this week they did nothing anyway as they with NewSchemaPerTest
so the tests all passed as CreateTable was no op (already exists).
Also all of the tables are created in an empty database by SchemaValidationTest.cs
DatabaseSchemaCreation_Produces_DatabaseSchemaResult_With_Zero_Errors
* Might aswell run against macOS also.
* Copy azure pipelines task header layout
* Delete SQLCe projects
* Remove SQL CE specific code.
* Remove SQL CE NuSpec, template params, build script setup
* Delete umbraco-netcore-only.sln
* Add SkipTests solution configuration and use for codeql
* Remove reference to deleted nuspec file.
* Refactor ConnectionStrings WRT DataDirectory placeholder & ProviderName.
At this point you can try out SQLite support by setting the following
in appsettings.json and then completing the install process.
"ConnectionStrings": {
"umbracoDbDSN": "Data Source=|DataDirectory|/umbraco.sqlite",
"umbracoDbDSN_ProviderName": "System.Data.SQLite"
},
Not currently possible via installer UI without provider name pre-set in
configuration.
* Switch to Microsoft.Data.Sqlite
Some gross hacks but will be good to find out if this works
with apple silicon.
* Enable selection of SQLite via installer UI (also quick install)
* Remove SqlServerDbProviderFactoryCreator to cleanup a TODO
* Move SQL Server support to its own class library
* Add persistence dependencies to Umbraco.CMS metapackage
* Bugfix packages delete query
Created invalid query for SQLite.
* Try out cypress tests Linux + SQLite
* Prevent cypress test artifact upload failure on attempt 2+
* LocalDb bugfixes
* Drop redundant enum
* Move SqlClient constant
* Misc whitespace
* Remove IsSqlCe extension (TODO: drop non 9->10 migrations later).
* Umbraco.Persistence.* -> Umbraco.Cms.Persistence.*
* Display quick install defaults and per provider default database name.
* Misc remove old comment
* little re-arrange
* Remove almost all usages of IsSqlite extension.
* visual adjustments
* Custom Database Configuration is last step and should then say Install.
* use text instead of disabled inputs
* move legend, rename to Install
* Update SqlMainDomLock to work without distributed locks.
* Added IDistributedLockingMechanism interface and in memory impl.
* Drop locking from ISqlSyntaxProvider & wire up scope to abstraction.
* Added SqlServerDistributedLockingMechanism
* Move distributed locking interfaces and exceptions to Core + xmldocs.
* Fix tests, Misc cleanup, Add SQL distributed locking integration tests
* Provide mechanism to specify DistributedLockingMechanism in config
(even if added by composer)
* Nomplementation -> NoImplementation
* Fix misleading comment
* Integration tests use SqlServerDistributedLockingMechanism when possible
* Handle up-gradable locks SqlServerDistributedLockingMechanism.
TODO: InMemoryDistributedLockingMechanism.
Note: Nuked SqlServerDistributedLockingMechanismTests, will still sleep
at night.
Is covered by Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.LockTests
* Make tests pass for InMemoryDistributedLockingMechanism, pretty hacky.
* Tweak constraints on WithCollectionBuilder so i can drop bad constructor
* Added SqliteDistributedLockingMechanism
* Dropped InMemoryDistributedMechanism + magic
InMemoryDistributedMechanism was pretty rubbish and now we have
a decent implementation for SQLite as we no longer block readers
see 8d1f42b.
Also drop the CollectionBuilder setup, instead do the same as we do
for syntax providers etc, it's more automagical so we never require an
explicit selection although we are allowing for it.
However keeping the optional IUmbracoBuilder constructor param for
CollectionBuilders as it's extremely useful.
* Fix quick install "" database name.
* Hide Database Configuration section when a connection string is pre-set.
Doesn't seem worth it to extract db name from connection string.
* Ensure wal test 2+
* Fix logging inconsistencies.
* Ensure in transaction when obtaining locks + no-op the SQLite read lock.
There's no point in running the query just to make a single test pass.
* Fix installer database display names
* Allow SQLite shared cache without losing deferred transactions
* Opt into shared cache for new SQLite databases + fix filename
* Fix misc inconsistency in .gitignore
* Prefer our interceptor interface
* Restore DEBUG_DATABASES code OnConnectionOpened in case it's used.
* Back to private cache.
* Added retry strategy for SQLite + refactor out SQL server specific stuff
* Fix SQL server tests.
* Misc - Orphaned comment, incorrect casing.
* InMemory SQLite test database & turn shared cache back on everywhere.
Co-authored-by: Niels Lyngsø <niels.lyngso@gmail.com>
2022-03-11 16:14:20 +00:00
|
|
|
if (ScopeAccessor.AmbientScope.Database.DatabaseType.IsSqlServer())
|
|
|
|
|
{
|
|
|
|
|
ScopeAccessor.AmbientScope.Database.Execute("SET LOCK_TIMEOUT 60000");
|
|
|
|
|
}
|
|
|
|
|
|
2018-06-29 19:52:40 +02:00
|
|
|
service.Save(media);
|
|
|
|
|
scope.Complete();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private ManualResetEventSlim TraceLocks()
|
|
|
|
|
{
|
|
|
|
|
var done = new ManualResetEventSlim(false);
|
|
|
|
|
|
|
|
|
|
// comment out to trace locks
|
|
|
|
|
return done;
|
|
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
// new Thread(() =>
|
|
|
|
|
// {
|
2018-06-29 19:52:40 +02:00
|
|
|
// using (var scope = ScopeProvider.CreateScope())
|
|
|
|
|
// while (done.IsSet == false)
|
|
|
|
|
// {
|
|
|
|
|
// var db = scope.Database;
|
|
|
|
|
// var info = db.Query<dynamic>("SELECT * FROM sys.lock_information;");
|
|
|
|
|
// Console.WriteLine("LOCKS:");
|
|
|
|
|
// foreach (var row in info)
|
|
|
|
|
// {
|
|
|
|
|
// Console.WriteLine("> " + row.request_spid + " " + row.resource_type + " " + row.resource_description + " " + row.request_mode + " " + row.resource_table + " " + row.resource_table_id + " " + row.request_status);
|
|
|
|
|
// }
|
|
|
|
|
// Thread.Sleep(50);
|
|
|
|
|
// }
|
2020-12-23 11:35:49 +01:00
|
|
|
// }).Start();
|
|
|
|
|
// return done;
|
2018-06-29 19:52:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Test]
|
2023-09-12 14:16:27 +02:00
|
|
|
[LongRunning]
|
2018-06-29 19:52:40 +02:00
|
|
|
public void Ensure_All_Threads_Execute_Successfully_Content_Service()
|
|
|
|
|
{
|
|
|
|
|
if (Environment.GetEnvironmentVariable("UMBRACO_TMP") != null)
|
2020-12-23 11:35:49 +01:00
|
|
|
{
|
2018-06-29 19:52:40 +02:00
|
|
|
Assert.Ignore("Do not run on VSTS.");
|
2020-12-23 11:35:49 +01:00
|
|
|
}
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
ILogger<ThreadSafetyServiceTest> log = GetRequiredService<ILogger<ThreadSafetyServiceTest>>();
|
2020-12-17 17:06:51 +00:00
|
|
|
|
2018-06-29 19:52:40 +02:00
|
|
|
// the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
|
2020-10-21 13:54:22 +02:00
|
|
|
var contentService = (ContentService)ContentService;
|
2018-06-29 19:52:40 +02:00
|
|
|
|
|
|
|
|
var threads = new List<Thread>();
|
|
|
|
|
var exceptions = new List<Exception>();
|
|
|
|
|
|
2020-12-17 17:06:51 +00:00
|
|
|
log.LogInformation("Starting...");
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
ManualResetEventSlim done = TraceLocks();
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
for (int i = 0; i < MaxThreadCount; i++)
|
2018-06-29 19:52:40 +02:00
|
|
|
{
|
|
|
|
|
var t = new Thread(() =>
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2021-03-09 12:45:51 +11:00
|
|
|
// NOTE: This is NULL because we have supressed the execution context flow.
|
|
|
|
|
// If we don't do that we will get various exceptions because we're trying to run concurrent threads
|
|
|
|
|
// against an ambient context which cannot be done due to the rules of scope creation and completion.
|
|
|
|
|
// But this works in v8 without the supression!? Why?
|
|
|
|
|
// In v8 the value of the AmbientScope is simply the current CallContext (i.e. AsyncLocal) Value which
|
|
|
|
|
// is not a mutable Stack like we are maintaining now. This means that for each child thread
|
|
|
|
|
// in v8, that thread will see it's own CallContext Scope value that it set and not the 'true'
|
|
|
|
|
// ambient Scope like we do now.
|
|
|
|
|
// So although the test passes in v8, there's actually some strange things occuring because Scopes
|
|
|
|
|
// are being created and disposed concurrently and out of order.
|
2021-09-14 11:32:43 +02:00
|
|
|
var currentScope = ScopeAccessor.AmbientScope;
|
2022-06-21 08:09:38 +02:00
|
|
|
log.LogInformation("[{ThreadId}] Current Scope? {CurrentScope}", Thread.CurrentThread.ManagedThreadId, currentScope?.GetDebugInfo());
|
2021-03-09 12:45:51 +11:00
|
|
|
Assert.IsNull(currentScope);
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
string name1 = "test-" + Guid.NewGuid();
|
|
|
|
|
IContent content1 = contentService.Create(name1, -1, "umbTextpage");
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2021-03-09 12:45:51 +11:00
|
|
|
log.LogInformation("[{ThreadId}] Saving content #1.", Thread.CurrentThread.ManagedThreadId);
|
2018-06-29 19:52:40 +02:00
|
|
|
Save(contentService, content1);
|
|
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
Thread.Sleep(100); // quick pause for maximum overlap!
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
string name2 = "test-" + Guid.NewGuid();
|
|
|
|
|
IContent content2 = contentService.Create(name2, -1, "umbTextpage");
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2021-03-09 12:45:51 +11:00
|
|
|
log.LogInformation("[{ThreadId}] Saving content #2.", Thread.CurrentThread.ManagedThreadId);
|
2018-06-29 19:52:40 +02:00
|
|
|
Save(contentService, content2);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception e)
|
|
|
|
|
{
|
2022-06-21 08:09:38 +02:00
|
|
|
// throw;
|
2020-12-23 11:35:49 +01:00
|
|
|
lock (exceptions)
|
|
|
|
|
{
|
|
|
|
|
exceptions.Add(e);
|
|
|
|
|
}
|
2018-06-29 19:52:40 +02:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
threads.Add(t);
|
|
|
|
|
}
|
|
|
|
|
|
2021-03-09 12:45:51 +11:00
|
|
|
// See NOTE above, we must supress flow here to be able to run concurrent threads,
|
|
|
|
|
// else the AsyncLocal value from this current context will flow to the child threads.
|
2021-03-08 12:31:17 +11:00
|
|
|
using (ExecutionContext.SuppressFlow())
|
|
|
|
|
{
|
|
|
|
|
// start all threads
|
|
|
|
|
log.LogInformation("Starting threads");
|
|
|
|
|
threads.ForEach(x => x.Start());
|
2021-09-14 11:32:43 +02:00
|
|
|
}
|
2018-06-29 19:52:40 +02:00
|
|
|
|
|
|
|
|
// wait for all to complete
|
2020-12-17 17:06:51 +00:00
|
|
|
log.LogInformation("Joining threads");
|
2018-06-29 19:52:40 +02:00
|
|
|
threads.ForEach(x => x.Join());
|
|
|
|
|
|
|
|
|
|
done.Set();
|
|
|
|
|
|
2020-12-17 17:06:51 +00:00
|
|
|
log.LogInformation("Checking exceptions");
|
2018-06-29 19:52:40 +02:00
|
|
|
if (exceptions.Count == 0)
|
|
|
|
|
{
|
2020-12-23 11:35:49 +01:00
|
|
|
// now look up all items, there should be 40!
|
|
|
|
|
IEnumerable<IContent> items = contentService.GetRootContent();
|
2018-06-29 19:52:40 +02:00
|
|
|
Assert.AreEqual(2 * MaxThreadCount, items.Count());
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
throw new Exception("Exceptions!", exceptions.First()); // rethrow the first one...
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Test]
|
2023-09-12 14:16:27 +02:00
|
|
|
[LongRunning]
|
2018-06-29 19:52:40 +02:00
|
|
|
public void Ensure_All_Threads_Execute_Successfully_Media_Service()
|
|
|
|
|
{
|
|
|
|
|
if (Environment.GetEnvironmentVariable("UMBRACO_TMP") != null)
|
2020-12-23 11:35:49 +01:00
|
|
|
{
|
2018-06-29 19:52:40 +02:00
|
|
|
Assert.Ignore("Do not run on VSTS.");
|
2020-12-23 11:35:49 +01:00
|
|
|
}
|
2020-12-17 17:06:51 +00:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
ILogger<ThreadSafetyServiceTest> log = GetRequiredService<ILogger<ThreadSafetyServiceTest>>();
|
2020-12-17 17:06:51 +00:00
|
|
|
|
2018-06-29 19:52:40 +02:00
|
|
|
// mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
|
2020-10-21 13:54:22 +02:00
|
|
|
var mediaService = (MediaService)MediaService;
|
2018-06-29 19:52:40 +02:00
|
|
|
|
|
|
|
|
var threads = new List<Thread>();
|
|
|
|
|
var exceptions = new List<Exception>();
|
|
|
|
|
|
2020-12-17 17:06:51 +00:00
|
|
|
log.LogInformation("Starting...");
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
ManualResetEventSlim done = TraceLocks();
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
for (int i = 0; i < MaxThreadCount; i++)
|
2018-06-29 19:52:40 +02:00
|
|
|
{
|
|
|
|
|
var t = new Thread(() =>
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2021-03-09 12:45:51 +11:00
|
|
|
// NOTE: This is NULL because we have supressed the execution context flow.
|
|
|
|
|
// If we don't do that we will get various exceptions because we're trying to run concurrent threads
|
|
|
|
|
// against an ambient context which cannot be done due to the rules of scope creation and completion.
|
|
|
|
|
// But this works in v8 without the supression!? Why?
|
|
|
|
|
// In v8 the value of the AmbientScope is simply the current CallContext (i.e. AsyncLocal) Value which
|
|
|
|
|
// is not a mutable Stack like we are maintaining now. This means that for each child thread
|
|
|
|
|
// in v8, that thread will see it's own CallContext Scope value that it set and not the 'true'
|
|
|
|
|
// ambient Scope like we do now.
|
|
|
|
|
// So although the test passes in v8, there's actually some strange things occuring because Scopes
|
|
|
|
|
// are being created and disposed concurrently and out of order.
|
2021-09-14 11:32:43 +02:00
|
|
|
var currentScope = ScopeAccessor.AmbientScope;
|
2022-06-21 08:09:38 +02:00
|
|
|
log.LogInformation("[{ThreadId}] Current Scope? {CurrentScope}", Thread.CurrentThread.ManagedThreadId, currentScope?.GetDebugInfo());
|
2021-03-09 12:45:51 +11:00
|
|
|
Assert.IsNull(currentScope);
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
string name1 = "test-" + Guid.NewGuid();
|
|
|
|
|
IMedia media1 = mediaService.CreateMedia(name1, -1, Constants.Conventions.MediaTypes.Folder);
|
2020-12-17 17:06:51 +00:00
|
|
|
log.LogInformation("[{0}] Saving media #1.", Thread.CurrentThread.ManagedThreadId);
|
2018-06-29 19:52:40 +02:00
|
|
|
Save(mediaService, media1);
|
|
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
Thread.Sleep(100); // quick pause for maximum overlap!
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
string name2 = "test-" + Guid.NewGuid();
|
|
|
|
|
IMedia media2 = mediaService.CreateMedia(name2, -1, Constants.Conventions.MediaTypes.Folder);
|
2020-12-17 17:06:51 +00:00
|
|
|
log.LogInformation("[{0}] Saving media #2.", Thread.CurrentThread.ManagedThreadId);
|
2018-06-29 19:52:40 +02:00
|
|
|
Save(mediaService, media2);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception e)
|
|
|
|
|
{
|
2020-12-23 11:35:49 +01:00
|
|
|
lock (exceptions)
|
|
|
|
|
{
|
|
|
|
|
exceptions.Add(e);
|
|
|
|
|
}
|
2018-06-29 19:52:40 +02:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
threads.Add(t);
|
|
|
|
|
}
|
|
|
|
|
|
2021-03-09 12:45:51 +11:00
|
|
|
// See NOTE above, we must supress flow here to be able to run concurrent threads,
|
|
|
|
|
// else the AsyncLocal value from this current context will flow to the child threads.
|
2021-03-08 12:31:17 +11:00
|
|
|
using (ExecutionContext.SuppressFlow())
|
|
|
|
|
{
|
|
|
|
|
// start all threads
|
|
|
|
|
threads.ForEach(x => x.Start());
|
|
|
|
|
}
|
2018-06-29 19:52:40 +02:00
|
|
|
|
2020-12-23 11:35:49 +01:00
|
|
|
// wait for all to complete
|
2018-06-29 19:52:40 +02:00
|
|
|
threads.ForEach(x => x.Join());
|
|
|
|
|
|
|
|
|
|
done.Set();
|
|
|
|
|
|
|
|
|
|
if (exceptions.Count == 0)
|
|
|
|
|
{
|
|
|
|
|
// now look up all items, there should be 40!
|
2020-12-23 11:35:49 +01:00
|
|
|
IEnumerable<IMedia> items = mediaService.GetRootMedia();
|
2018-06-29 19:52:40 +02:00
|
|
|
Assert.AreEqual(2 * MaxThreadCount, items.Count());
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
throw new Exception("Exceptions!", exceptions.First()); // rethrow the first one...
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void CreateTestData()
|
|
|
|
|
{
|
|
|
|
|
// Create and Save ContentType "umbTextpage" -> 1045
|
2020-12-23 11:35:49 +01:00
|
|
|
ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage");
|
2018-06-29 19:52:40 +02:00
|
|
|
contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522");
|
2020-10-21 13:54:22 +02:00
|
|
|
ContentTypeService.Save(contentType);
|
2018-06-29 19:52:40 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|