Example #1
0
 /// <exception cref="ArgumentException"/>
 public PartitionedStorage(
     IServiceProvider provider,
     ITypeEncoder typeEncoder,
     IDiagnosticContext diagnosticContext)
 {
     this.keyType           = typeEncoder.Encode(typeof(TKey)) ?? throw NotSupportedTypeException(typeof(TKey));
     this.valueType         = typeEncoder.Encode(typeof(TValue)) ?? throw NotSupportedTypeException(typeof(TValue));
     this.backedStorage     = provider.GetService <IPartitionedStorageProvider <TValue> >() ?? throw ImproperlyConfiguredException();
     this.keyConverter      = provider.GetService <IValueConverter <TKey> >() ?? throw ImproperlyConfiguredException();
     this.valueConverter    = provider.GetService <IValueConverter <TValue> >() ?? throw ImproperlyConfiguredException();
     this.diagnosticContext = diagnosticContext;
 }
Example #2
0
 /// <exception cref="NotSupportedException"/>
 protected Storage(
     IValueConverter <TKey> keyConverter,
     IValueConverter <TValue> valueConverter,
     IStorageProvider <TValue> backedStorage,
     ITypeEncoder typeEncoder,
     IDiagnosticContext diagnosticContext)
 {
     this.KeyType           = typeEncoder.Encode(typeof(TKey)) ?? throw NotSupportedTypeException(typeof(TKey));
     this.ValueType         = typeEncoder.Encode(typeof(TValue)) ?? throw NotSupportedTypeException(typeof(TValue));
     this.KeyConverter      = keyConverter;
     this.ValueConverter    = valueConverter;
     this.backedStorage     = backedStorage;
     this.diagnosticContext = diagnosticContext;
 }
        public async Task <object> Request(object message, CancellationToken token)
        {
            var attempt  = 1;
            var strategy = options.ResponsePoll;

            var messageName = typeEncoder.Encode(message.GetType())
                              ?? throw new NotSupportedException($"Not supported  message type '{message.GetType()}'.");
            var messageId = message.GetSha1();

            await Publish((TMessage)message, token);

            await Task.Delay(strategy.DelayTime(attempt), token);

            while (true)
            {
                logger.LogDebug("Message({MessageName}/{MessageId}) polling: {Attempt} begins.", messageName, messageId, attempt);

                if (await FindOneResponded(messageId, token) is Some <MongoRecord>(var responded))
                {
                    logger.LogInformation("Message({MessageName}/{MessageId}) polling: {Attempt} ends with {status}.", messageName, messageId, attempt, responded.Status);

                    if (responded.Status == HandlingStatus.Succeeded)
                    {
                        return((TResponse)responded.Response !);
                    }

                    if (responded.Status == HandlingStatus.Failed)
                    {
                        converter.ConvertFrom((ExceptionModel)responded.Response !) !.Throw();
                    }

                    throw new MessageContractException($"Not expected status {responded.Status}.");
                }

                logger.LogInformation("Message({MessageName}/{MessageId}) polling: {Attempt} ends without response.", messageName, messageId, attempt);

                attempt++;
                if (!strategy.CanRetry(attempt))
                {
                    logger.LogInformation("Message({MessageName}/{MessageId}) polling: {Attempt} won't proceed.", messageName, messageId, attempt);
                    break;
                }

                await Task.Delay(strategy.DelayTime(attempt), token);
            }

            throw new MessageDeferredException("No response from server in defined amount of time.");
        }
        /// <summary>
        ///     Delegates <paramref name="message"/> handling to remote WEB server.
        /// </summary>
        public async Task <TResponse> DelegateHandling <TResponse>(IMessage <TResponse> message, CancellationToken token)
        {
            var messageType       = message.GetType();
            var requestSerializer = factory.Create(messageType);

            var requestStream = new MemoryStream();
            await requestSerializer.SerializeObject(requestStream, message, token);

            requestStream.Position = 0;

            var messageName = typeEncoder.Encode(messageType);

            var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Post, "")
            {
                Headers = { { HeaderNames.MessageName, messageName } },
                Content = new StreamContent(requestStream)
            }, token);

            var responseSerializer = factory.Create(typeof(TResponse));
            var responseStream     = await response.Content.ReadAsStreamAsync(token);

            var responseObject = (TResponse)await responseSerializer.DeserializeObject(responseStream, token);

            return(responseObject !);
        }
Example #5
0
        public virtual string Serialize(object value)
        {
            lock (_lock)
            {
                for (var i = 0; i < encoders.Count; i++)
                {
                    try
                    {
                        ITypeEncoder encoder = encoders[i];
                        if (!encoder.IsSupport(value.GetType()))
                        {
                            continue;
                        }

                        return(encoder.Encode(value));
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            throw new NotSupportedException(string.Format("Unsupported type, this value \"{0}\" cannot be serialized",
                                                          value));
        }
Example #6
0
        public virtual string Serialize(object value)
        {
            lock (_lock)
            {
                for (int i = 0; i < _encoders.Count; i++)
                {
                    try
                    {
                        ITypeEncoder encoder = _encoders[i];
                        if (!encoder.IsSupport(value.GetType()))
                        {
                            continue;
                        }

                        return(encoder.Encode(value));
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                }
            }

            throw new NotSupportedException($"Unsupported type, this value \"{value}\" cannot be serialized");
        }
        /// <summary>
        ///     Converts <paramref name="exception"/> into <see cref="ExceptionModel"/>.
        /// </summary>
        public ExceptionModel?ConvertTo(Exception?exception)
        {
            if (exception == null)
            {
                return(null);
            }

            var type = exception.GetType();

            if (exception is not MessageException && !options.Value.ExposedExceptions.Any(x => x.IsAssignableFrom(type)))
            {
                return(ConvertTo(new MessageFailedException((Exception)null !)));
            }

            var typeName = typeEncoder.Encode(type) ?? throw NotSupportedTypeException(type);

            return(new ExceptionModel {
                Type = typeName, Message = exception.Message, InnerException = ConvertTo(exception.InnerException)
            });
        }
Example #8
0
        public virtual string Serialize(object value)
        {
            lock (_lock)
            {
                for (int i = 0; i < encoders.Count; i++)
                {
                    try
                    {
                        ITypeEncoder encoder = encoders[i];
                        if (!encoder.IsSupport(value.GetType()))
                        {
                            continue;
                        }

                        return(encoder.Encode(value));
                    }
                    catch (Exception) { }
                }
            }
            throw new NotSupportedException();
        }