|
3 | 3 | using System.Data;
|
4 | 4 | using System.Globalization;
|
5 | 5 | using System.Linq;
|
| 6 | +using System.Threading.Tasks; |
6 | 7 | using System.Transactions;
|
7 | 8 | using Dapper;
|
8 | 9 | using Hangfire.Common;
|
@@ -463,6 +464,54 @@ public void AddToSet_WithScore_UpdatesAScore_WhenBothKeyAndValueAreExist()
|
463 | 464 | });
|
464 | 465 | }
|
465 | 466 |
|
| 467 | + [SkippableFact, CleanDatabase] |
| 468 | + public void AddToSet_DoesNotFailWithConcurrencyError_WhenRunningMultipleThreads() |
| 469 | + { |
| 470 | + if (Environment.ProcessorCount < 2) |
| 471 | + { |
| 472 | + throw new SkipException("You need to have more than 1 CPU to run the test"); |
| 473 | + } |
| 474 | + |
| 475 | + void CommitTags(PostgreSqlWriteOnlyTransaction transaction, IEnumerable<string> tags, string jobId) |
| 476 | + { |
| 477 | + //Imitating concurrency issue scenario from Hangfire.Tags library. |
| 478 | + //Details: https://github.com/frankhommers/Hangfire.PostgreSql/issues/191 |
| 479 | + |
| 480 | + foreach (var tag in tags) |
| 481 | + { |
| 482 | + var score = DateTime.Now.Ticks; |
| 483 | + |
| 484 | + transaction.AddToSet("tags", tag, score); |
| 485 | + transaction.AddToSet($"tags:{jobId}", tag, score); |
| 486 | + transaction.AddToSet($"tags:{tag}", jobId, score); |
| 487 | + } |
| 488 | + } |
| 489 | + |
| 490 | + Parallel.For(1, 1_000, i => |
| 491 | + { |
| 492 | + UseConnection(sql => |
| 493 | + { |
| 494 | + Utils.Utils.TryExecute(() => |
| 495 | + { |
| 496 | + Commit(sql, x => |
| 497 | + { |
| 498 | + int jobTypeIndex = i % 10; |
| 499 | + CommitTags(x, new[] {"my-shared-tag", $"job-type-{jobTypeIndex}"}, i.ToString()); |
| 500 | + }); |
| 501 | + }, e => |
| 502 | + { |
| 503 | + /* Account for 'duplicate key value violates unique constraint "set_key_value_key"' error |
| 504 | + * Details: https://github.com/frankhommers/Hangfire.PostgreSql/issues/191#issuecomment-872367869 |
| 505 | + * |
| 506 | + * Once AddToSet is improved to use MERGE statement, we should be able to remove |
| 507 | + * retry-policy from this unit-test. |
| 508 | + */ |
| 509 | + return e is PostgresException postgresException && postgresException.SqlState == "23505"; |
| 510 | + }); |
| 511 | + }); |
| 512 | + }); |
| 513 | + } |
| 514 | + |
466 | 515 | [Fact, CleanDatabase]
|
467 | 516 | public void RemoveFromSet_RemovesARecord_WithGivenKeyAndValue()
|
468 | 517 | {
|
|
0 commit comments