public async Task sets_context_bag() { var bag = new ContextBag(); var context = new Moq.Mock <IIncomingPhysicalMessageContext>(); var next = new Moq.Mock <Func <Task> >(); context.Setup(x => x.MessageId).Returns("1"); context.Setup(x => x.Message).Returns(new IncomingMessage("1", new Dictionary <string, string>(), new byte[] { })); context.Setup(x => x.Extensions).Returns(bag); next.Setup(x => x()).Throws(new Exception("test")); Assert.ThrowsAsync <Exception>(() => _rejector.Invoke(context.Object, next.Object)); next.Verify(x => x(), Moq.Times.Once); int retries; Assert.True(bag.TryGet <int>(Defaults.Retries, out retries)); Assert.AreEqual(0, retries); next.Setup(x => x()).Returns(Task.CompletedTask); await _rejector.Invoke(context.Object, next.Object); next.Verify(x => x(), Moq.Times.Exactly(2)); Assert.True(bag.TryGet <int>(Defaults.Retries, out retries)); Assert.AreEqual(1, retries); }
public void ShouldShallowCloneContextBag() { var context = new ContextBag(); context.Set("someKey", "someValue"); var testee = new SubscribeContext(new RootContext(null, null, null), typeof(object), context); testee.Extensions.Set("someKey", "updatedValue"); testee.Extensions.Set("anotherKey", "anotherValue"); string value; string anotherValue; context.TryGet("someKey", out value); Assert.AreEqual("someValue", value); Assert.IsFalse(context.TryGet("anotherKey", out anotherValue)); string updatedValue; string anotherValue2; testee.Extensions.TryGet("someKey", out updatedValue); testee.Extensions.TryGet("anotherKey", out anotherValue2); Assert.AreEqual("updatedValue", updatedValue); Assert.AreEqual("anotherValue", anotherValue2); }
public Task max_retries_no_response_needed() { var bag = new ContextBag(); var context = new Moq.Mock <IIncomingPhysicalMessageContext>(); var next = new Moq.Mock <Func <Task> >(); var errorFunc = new Moq.Mock <Func <Exception, String, Error> >(); errorFunc.Setup(x => x(Moq.It.IsAny <Exception>(), Moq.It.IsAny <string>())).Returns(new Moq.Mock <Error>().Object).Verifiable(); context.Setup(x => x.Builder.Build <Func <Exception, String, Error> >()).Returns(errorFunc.Object); context.Setup(x => x.MessageId).Returns("2"); context.Setup(x => x.Message).Returns(new IncomingMessage("2", new Dictionary <string, string>() { [Headers.MessageIntent] = MessageIntentEnum.Send.ToString(), [Defaults.RequestResponse] = "0" }, new byte[] { })); context.Setup(x => x.Extensions).Returns(bag); next.Setup(x => x()).Throws(new Exception("test")); Assert.ThrowsAsync <Exception>(() => _rejector.Invoke(context.Object, next.Object)); Assert.ThrowsAsync <Exception>(() => _rejector.Invoke(context.Object, next.Object)); Assert.ThrowsAsync <Exception>(() => _rejector.Invoke(context.Object, next.Object)); int retries; Assert.True(bag.TryGet <int>(Defaults.Retries, out retries)); Assert.AreEqual(2, retries); next.Verify(x => x(), Moq.Times.Exactly(3)); errorFunc.Verify(x => x(Moq.It.IsAny <Exception>(), Moq.It.IsAny <string>()), Moq.Times.Never); return(Task.CompletedTask); }
public Task persistence_uow_bag_stored_on_fail() { var bag = new ContextBag(); bag.Set("test", "test"); var context = new Moq.Mock <IIncomingLogicalMessageContext>(); var next = new Moq.Mock <Func <Task> >(); var builder = new Moq.Mock <IBuilder>(); var uow = new Moq.Mock <IApplicationUnitOfWork>(); builder.Setup(x => x.BuildAll <IApplicationUnitOfWork>()).Returns(new IApplicationUnitOfWork[] { uow.Object }); context.Setup(x => x.MessageId).Returns("1"); context.Setup(x => x.Message).Returns(new LogicalMessage(new NServiceBus.Unicast.Messages.MessageMetadata(typeof(object)), new object())); context.Setup(x => x.Extensions).Returns(bag); context.Setup(x => x.Builder).Returns(builder.Object); context.Setup(x => x.Headers).Returns(new Dictionary <string, string>()); context.Setup(x => x.MessageHeaders) .Returns(new Dictionary <string, string> { [Headers.MessageIntent] = MessageIntentEnum.Send.ToString() }); uow.Setup(x => x.End(null)).Throws(new Exception("test")); uow.Setup(x => x.Bag).Returns(bag); Assert.ThrowsAsync <Exception>(() => _uow.Invoke(context.Object, next.Object)); Dictionary <Type, ContextBag> holder; Assert.True(bag.TryGet("contextbags.1", out holder)); next.Verify(x => x(), Moq.Times.Once); return(Task.CompletedTask); }
static int GetConcurrency(ContextBag context) { if (!context.TryGet("NServiceBus.Persistence.Sql.Concurrency", out int concurrency)) { throw new Exception("Cannot save saga because optimistic concurrency version is missing in the context."); } return(concurrency); }
string ApplyDistributorLogic(ContextBag context) { IncomingMessage incomingMessage; return(distributorAddress != null && context.TryGet(out incomingMessage) && incomingMessage.Headers.ContainsKey(LegacyDistributorHeaders.WorkerSessionId) ? distributorAddress : sharedQueue); }
static void SetEntry(ContextBag context, Guid sagaId, Entry value) { if (context.TryGet(ContextKey, out Dictionary <Guid, Entry> entries) == false) { entries = new Dictionary <Guid, Entry>(); context.Set(ContextKey, entries); } entries[sagaId] = value; }
public void ShouldShallowCloneContextBag() { var context = new ContextBag(); context.Set("someKey", "someValue"); var testee = new SubscribeContext(new FakeRootContext(), new Type[0], context); testee.Extensions.Set("someKey", "updatedValue"); testee.Extensions.Set("anotherKey", "anotherValue"); context.TryGet("someKey", out string value); Assert.AreEqual("someValue", value); Assert.IsFalse(context.TryGet("anotherKey", out string _)); testee.Extensions.TryGet("someKey", out string updatedValue); testee.Extensions.TryGet("anotherKey", out string anotherValue2); Assert.AreEqual("updatedValue", updatedValue); Assert.AreEqual("anotherValue", anotherValue2); }
/// <summary> /// Tries to retrieve an instance of <typeparamref name="T" /> from a <see cref="ContextBag" />. /// </summary> public static bool TryGetDeliveryConstraint <T>(this ContextBag context, out T constraint) where T : DeliveryConstraint { Guard.AgainstNull(nameof(context), context); if (context.TryGet(out List <DeliveryConstraint> constraints)) { return(constraints.TryGet(out constraint)); } constraint = null; return(false); }
string ApplyDistributorLogic(ContextBag context) { IncomingMessage incomingMessage; if (distributorAddress != null && context.TryGet(out incomingMessage) && incomingMessage.Headers.ContainsKey(LegacyDistributorHeaders.WorkerSessionId)) { return(distributorAddress); } return(configuredReturnAddress); }
/// <summary> /// Retrieves an IAsyncDocumentSession from the ContextBag. If a sessionFunction exists, that will be used /// to create the session. Otherwise, retrieve the session directly from the bag. /// </summary> internal static IAsyncDocumentSession GetAsyncSession(this ContextBag contextBag) { Func <IAsyncDocumentSession> sessionFunction; contextBag.TryGet(out sessionFunction); if (sessionFunction != null) { return(sessionFunction()); } IAsyncDocumentSession session; if (contextBag.TryGet(out session)) { return(session); } throw new Exception("IAsyncDocumentSession could not be retrieved for the incoming message pipeline."); }
IAsyncDocumentSession GetSession(ContextBag context) { IncomingMessage message; if (context.TryGet(out message)) { return(sessionCreator.OpenSession(message.Headers)); } return(documentStore.OpenAsyncSession()); }
internal static IDocumentSession GetSession(this ContextBag contextBag) { IDocumentSession session; if (contextBag.TryGet(out session)) { return(session); } throw new Exception("IDocumentSession could not be retrieved for the incoming message pipeline."); }
/// <summary> /// Removes a <see cref="DeliveryConstraint" /> to a <see cref="ContextBag" />. /// </summary> public static void RemoveDeliveryConstaint(this ContextBag context, DeliveryConstraint constraint) { List <DeliveryConstraint> constraints; if (!context.TryGet(out constraints)) { return; } constraints.Remove(constraint); }
/// <summary> /// Removes a <see cref="DeliveryConstraint" /> to a <see cref="ContextBag" />. /// </summary> public static List <DeliveryConstraint> GetDeliveryConstraints(this ContextBag context) { List <DeliveryConstraint> constraints; if (context.TryGet(out constraints)) { return(constraints); } return(new List <DeliveryConstraint>()); }
/// <summary> /// Tries to retrieves an instance of <typeparamref name="T" /> from a <see cref="ContextBag" />. /// </summary> public static bool TryGetDeliveryConstraint <T>(this ContextBag context, out T constraint) where T : DeliveryConstraint { List <DeliveryConstraint> constraints; if (context.TryGet(out constraints)) { return(constraints.TryGet(out constraint)); } constraint = null; return(false); }
/// <summary> /// Removes a <see cref="DeliveryConstraint" /> from a <see cref="ContextBag" />. /// </summary> public static List <DeliveryConstraint> GetDeliveryConstraints(this ContextBag context) { Guard.AgainstNull(nameof(context), context); if (context.TryGet(out List <DeliveryConstraint> constraints)) { return(constraints); } return(new List <DeliveryConstraint>()); }
/// <summary> /// Removes a <see cref="DeliveryConstraint" /> from a <see cref="ContextBag" />. /// </summary> public static void RemoveDeliveryConstraint(this ContextBag context, DeliveryConstraint constraint) { Guard.AgainstNull(nameof(constraint), constraint); Guard.AgainstNull(nameof(context), context); if (!context.TryGet(out List <DeliveryConstraint> constraints)) { return; } constraints.Remove(constraint); }
/// <summary> /// Tries to remove an instance of <typeparamref name="T" /> from a <see cref="ContextBag" />. /// </summary> public static bool TryRemoveDeliveryConstraint <T>(this ContextBag context, out T constraint) where T : DeliveryConstraint { Guard.AgainstNull(nameof(context), context); if (context.TryGet(out List <DeliveryConstraint> constraints)) { var result = constraints.TryGet(out constraint); if (result) { constraints.Remove(constraint); } return(result); } constraint = null; return(false); }
/// <summary> /// Adds a <see cref="DeliveryConstraint" /> to a <see cref="ContextBag" />. /// </summary> public static void AddDeliveryConstraint(this ContextBag context, DeliveryConstraint constraint) { List <DeliveryConstraint> constraints; if (!context.TryGet(out constraints)) { constraints = new List <DeliveryConstraint>(); context.Set(constraints); } if (constraints.Any(c => c.GetType() == constraint.GetType())) { throw new InvalidOperationException("Constraint of type " + constraint.GetType().FullName + " already exists"); } constraints.Add(constraint); }
public Task Dispatch(TransportOperations outgoingMessages, ContextBag context) { foreach (UnicastTransportOperation transportOperation in outgoingMessages.UnicastTransportOperations) { string basePath = BaseDirectoryBuilder.BuildBasePath(transportOperation.Destination); string nativeMessageId = Guid.NewGuid().ToString(); string bodyPath = Path.Combine(basePath, ".bodies", nativeMessageId) + ".xml"; var dir = Path.GetDirectoryName(bodyPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllBytes(bodyPath, transportOperation.Message.Body); List <string> messageContents = new List <string> { bodyPath, HeaderSerializer.Serialize(transportOperation.Message.Headers) }; DirectoryBasedTransaction transaction; string messagePath = Path.Combine(basePath, nativeMessageId) + ".txt"; if (transportOperation.RequiredDispatchConsistency != DispatchConsistency.Isolated && context.TryGet(out transaction)) { transaction.Enlist(messagePath, messageContents); } else { string tempFile = Path.GetTempFileName(); //write to temp file first so an atomic move can be done //this avoids the file being locked when the receiver tries to process it File.WriteAllLines(tempFile, messageContents); File.Move(tempFile, messagePath); } } return(TaskEx.CompletedTask); }
public Task Dispatch(TransportOperations outgoingMessages, ContextBag context) { foreach (UnicastTransportOperation transportOperation in outgoingMessages.UnicastTransportOperations) { string basePath = BaseDirectoryBuilder.BuildBasePath(transportOperation.Destination); string nativeMessageId = Guid.NewGuid().ToString(); string bodyPath = Path.Combine(basePath, ".bodies", nativeMessageId) + ".xml"; var dir = Path.GetDirectoryName(bodyPath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); File.WriteAllBytes(bodyPath, transportOperation.Message.Body); List<string> messageContents = new List<string> { bodyPath, HeaderSerializer.Serialize(transportOperation.Message.Headers) }; DirectoryBasedTransaction transaction; string messagePath = Path.Combine(basePath, nativeMessageId) + ".txt"; if (transportOperation.RequiredDispatchConsistency != DispatchConsistency.Isolated && context.TryGet(out transaction)) { transaction.Enlist(messagePath, messageContents); } else { string tempFile = Path.GetTempFileName(); //write to temp file first so we can do a atomic move //this avoids the file being locked when the receiver tries to process it File.WriteAllLines(tempFile, messageContents); File.Move(tempFile, messagePath); } } return TaskEx.CompletedTask; }
public async Task Complete(IContainSagaData sagaData, SynchronizedStorageSession session, ContextBag context) { var documentSession = session.RavenSession(); documentSession.Delete(sagaData); string uniqueDocumentId; RavenJToken uniqueDocumentIdMetadata; var metadata = await documentSession.Advanced.GetMetadataForAsync(sagaData).ConfigureAwait(false); if (metadata.TryGetValue(UniqueDocIdKey, out uniqueDocumentIdMetadata)) { uniqueDocumentId = uniqueDocumentIdMetadata.Value <string>(); } else { context.TryGet(UniqueDocIdKey, out uniqueDocumentId); } if (string.IsNullOrEmpty(uniqueDocumentId)) { var uniqueDoc = await documentSession.Query <SagaUniqueIdentity>() .SingleOrDefaultAsync(d => d.SagaId == sagaData.Id) .ConfigureAwait(false); if (uniqueDoc != null) { documentSession.Delete(uniqueDoc); } } else { documentSession.Advanced.Defer(new DeleteCommandData { Key = uniqueDocumentId }); } }