Ejemplo n.º 1
0
        public void PostEntry(HttpEntityManager manager, int expectedVersion, bool requireMaster, string stream)
        {
            manager.ReadTextRequestAsync(
                (man, body) =>
            {
                var events = new Event[0];
                try
                {
                    events = AutoEventConverter.SmartParse(body, manager.RequestCodec);
                }
                catch (Exception ex)
                {
                    SendBadRequest(manager, ex.Message);
                }
                if (events.IsEmpty())
                {
                    SendBadRequest(manager, "Write request body invalid.");
                    return;
                }

                var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                      manager,
                                                      Format.WriteEventsCompleted,
                                                      (a, m) => Configure.WriteEventsCompleted(a, m, stream));
                var corrId = Guid.NewGuid();
                var msg    = new ClientMessage.WriteEvents(corrId, corrId, envelope, requireMaster,
                                                           stream, expectedVersion, events, manager.User);
                Publish(msg);
            },
                e => Log.Debug("Error while reading request (POST entry): {0}.", e.Message));
        }
Ejemplo n.º 2
0
        private void OnPostGossipRequestRead(HttpEntityManager manager, string body)
        {
            var clusterInfoDto = manager.RequestCodec.From <ClusterInfoDto>(body);

            if (clusterInfoDto == null)
            {
                var msg = string.Format(
                    "Received as POST invalid ClusterInfo from [{0}]. Content-Type: {1}, Body:\n{2}.",
                    manager.RequestedUrl, manager.RequestCodec.ContentType, body);
                Log.Error("Received as POST invalid ClusterInfo from [{requestedUrl}]. Content-Type: {contentType}.",
                          manager.RequestedUrl, manager.RequestCodec.ContentType);
                Log.Error("Received as POST invalid ClusterInfo from [{requestedUrl}]. Body: {body}.",
                          manager.RequestedUrl, body);
                SendBadRequest(manager, msg);
                return;
            }

            var sendToHttpEnvelope = new SendToHttpEnvelope(_networkSendQueue,
                                                            manager,
                                                            Format.SendGossip,
                                                            (e, m) => Configure.Ok(e.ResponseCodec.ContentType));
            var serverEndPoint = TryGetServerEndPoint(clusterInfoDto);

            Publish(new GossipMessage.GossipReceived(sendToHttpEnvelope, new ClusterInfo(clusterInfoDto),
                                                     serverEndPoint));
        }
Ejemplo n.º 3
0
        private void DeleteStream(HttpEntityManager manager, UriTemplateMatch match)
        {
            var stream = match.BoundVariables["stream"];

            if (stream.IsEmptyString())
            {
                SendBadRequest(manager, string.Format("Invalid stream name '{0}'", stream));
                return;
            }
            int expectedVersion;

            if (!GetExpectedVersion(manager, out expectedVersion))
            {
                SendBadRequest(manager, string.Format("{0} header in wrong format.", SystemHeaders.ExpectedVersion));
                return;
            }
            bool requireMaster;

            if (!GetRequireMaster(manager, out requireMaster))
            {
                SendBadRequest(manager, string.Format("{0} header in wrong format.", SystemHeaders.RequireMaster));
                return;
            }
            if (!requireMaster && _httpForwarder.ForwardRequest(manager))
            {
                return;
            }
            var envelope = new SendToHttpEnvelope(_networkSendQueue, manager, Format.DeleteStreamCompleted, Configure.DeleteStreamCompleted);
            var corrId   = Guid.NewGuid();

            Publish(new ClientMessage.DeleteStream(corrId, corrId, envelope, requireMaster, stream, expectedVersion, manager.User));
        }
Ejemplo n.º 4
0
        private void ProjectionsPost(HttpEntity http, UriTemplateMatch match, ProjectionMode mode, string name)
        {
            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.Updated>(
                http, DefaultFormatter, (codec, message) =>
            {
                var localPath = string.Format("/projection/{0}", message.Name);
                var url       = MakeUrl(match, localPath);
                return(new ResponseConfiguration(
                           201, "Created", codec.ContentType, new KeyValuePair <string, string>("Location", url)));
            }, ErrorsEnvelope(http));

            http.Manager.ReadRequestAsync(
                (o, s) =>
            {
                ProjectionManagementMessage.Post postMessage;
                string handlerType = match.BoundVariables["type"] ?? "JS";
                if ((mode == ProjectionMode.OneTime || mode == ProjectionMode.AdHoc) &&
                    string.IsNullOrEmpty(name))
                {
                    postMessage = new ProjectionManagementMessage.Post(
                        envelope, mode, Guid.NewGuid().ToString("D"), handlerType, s, enabled: true);
                }
                else
                {
                    postMessage = new ProjectionManagementMessage.Post(
                        envelope, mode, name, handlerType, s, enabled: true);
                }
                Publish(postMessage);
            }, Console.WriteLine);
        }
Ejemplo n.º 5
0
        private void OnStopScavenge(HttpEntityManager entity, UriTemplateMatch match)
        {
            var scavengeId = match.BoundVariables["scavengeId"];

            Log.Info("Stopping scavenge because /admin/scavenge/{scavengeId} DELETE request has been received.", scavengeId);

            var envelope = new SendToHttpEnvelope(_networkSendQueue, entity, (e, message) =>
            {
                var completed = message as ClientMessage.ScavengeDatabaseResponse;
                return(e.ResponseCodec.To(completed?.ScavengeId));
            },
                                                  (e, message) =>
            {
                var completed = message as ClientMessage.ScavengeDatabaseResponse;
                switch (completed?.Result)
                {
                case ClientMessage.ScavengeDatabaseResponse.ScavengeResult.Stopped:
                    return(Configure.Ok(e.ResponseCodec.ContentType));

                case ClientMessage.ScavengeDatabaseResponse.ScavengeResult.Unauthorized:
                    return(Configure.Unauthorized());

                case ClientMessage.ScavengeDatabaseResponse.ScavengeResult.InvalidScavengeId:
                    return(Configure.NotFound());

                default:
                    return(Configure.InternalServerError());
                }
            }
                                                  );

            Publish(new ClientMessage.StopDatabaseScavenge(envelope, Guid.Empty, entity.User, scavengeId));
        }
Ejemplo n.º 6
0
        private void OnProjectionsReadEvents(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
            {
                return;
            }

            var envelope = new SendToHttpEnvelope <FeedReaderMessage.FeedPage>(
                _networkSendQueue, http, FeedPageFormatter, FeedPageConfigurator, ErrorsEnvelope(http));

            http.ReadTextRequestAsync(
                (o, body) => {
                var bodyParsed   = body.ParseJson <ReadEventsBody>();
                var fromPosition = CheckpointTag.FromJson(
                    new JTokenReader(bodyParsed.Position), new ProjectionVersion(0, 0, 0));


                Publish(
                    new FeedReaderMessage.ReadPage(
                        Guid.NewGuid(),
                        envelope,
                        http.User,
                        bodyParsed.Query,
                        fromPosition.Tag,
                        bodyParsed.MaxEvents ?? 10));
            },
                x => Log.DebugException(x, "Read Request Body Failed."));
        }
Ejemplo n.º 7
0
        private void OnProjectionConfigPut(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
            {
                return;
            }

            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.Updated>(
                _networkSendQueue, http, DefaultFormatter, OkResponseConfigurator, ErrorsEnvelope(http));

            http.ReadTextRequestAsync(
                (o, s) => {
                var config = http.RequestCodec.From <ProjectionConfigData>(s);
                if (config == null)
                {
                    SendBadRequest(o, "Failed to parse the projection config");
                    return;
                }

                var message = new ProjectionManagementMessage.Command.UpdateConfig(
                    envelope, match.BoundVariables["name"], config.EmitEnabled, config.TrackEmittedStreams,
                    config.CheckpointAfterMs, config.CheckpointHandledThreshold,
                    config.CheckpointUnhandledBytesThreshold, config.PendingEventsThreshold,
                    config.MaxWriteBatchLength, config.MaxAllowedWritesInFlight, GetRunAs(http, match));
                Publish(message);
            }, ex => Log.Debug("Failed to update projection configuration. Error: {e}", ex));
        }
Ejemplo n.º 8
0
        private void OnGetFreshStats(HttpEntityManager entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                  entity,
                                                  Format.GetFreshStatsCompleted,
                                                  Configure.GetFreshStatsCompleted);

            var statPath     = match.BoundVariables["statPath"];
            var statSelector = GetStatSelector(statPath);

            bool useMetadata;

            if (!bool.TryParse(match.QueryParameters["metadata"], out useMetadata))
            {
                useMetadata = false;
            }

            bool useGrouping;

            if (!bool.TryParse(match.QueryParameters["group"], out useGrouping))
            {
                useGrouping = true;
            }

            if (!useGrouping && !string.IsNullOrEmpty(statPath))
            {
                SendBadRequest(entity, "Dynamic stats selection works only with grouping enabled");
                return;
            }

            Publish(new MonitoringMessage.GetFreshStats(envelope, statSelector, useMetadata, useGrouping));
        }
Ejemplo n.º 9
0
        private void OnProjectionCommandEnable(HttpEntity http, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.Updated>(
                http, DefaultFormatter, OkResponseConfigurator, ErrorsEnvelope(http));

            Publish(new ProjectionManagementMessage.Enable(envelope, match.BoundVariables["name"]));
        }
Ejemplo n.º 10
0
        private void OnProjectionQueryGet(HttpEntity http, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.ProjectionQuery>(
                http, QueryFormatter, QueryConfigurator, ErrorsEnvelope(http));

            Publish(new ProjectionManagementMessage.GetQuery(envelope, match.BoundVariables["name"]));
        }
        private void OnGetFreshStats(HttpEntityManager entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                  entity,
                                                  Format.GetFreshStatsCompleted,
                                                  Configure.GetFreshStatsCompleted);

            var statPath = match.BoundVariables["statPath"];
            var statSelector = GetStatSelector(statPath);

            bool useMetadata;
            if (!bool.TryParse(match.QueryParameters["metadata"], out useMetadata))
                useMetadata = false;

            bool useGrouping;
            if (!bool.TryParse(match.QueryParameters["group"], out useGrouping))
                useGrouping = true;

            if (!useGrouping && !string.IsNullOrEmpty(statPath))
            {
                SendBadRequest(entity, "Dynamic stats selection works only with grouping enabled");
                return;
            }
             
            Publish(new MonitoringMessage.GetFreshStats(envelope, statSelector, useMetadata, useGrouping));
        }
Ejemplo n.º 12
0
        private void OnPostScavenge(HttpEntityManager entity)
        {
            int startFromChunk = 0;


            var envelope = new SendToHttpEnvelope(_networkSendQueue, entity, (e, message) => {
                var completed = message as ClientMessage.ScavengeDatabaseResponse;
                return(e.ResponseCodec.To(new ScavengeResultDto(completed?.ScavengeId)));
            },
                                                  (e, message) => {
                var completed = message as ClientMessage.ScavengeDatabaseResponse;
                switch (completed?.Result)
                {
                case ClientMessage.ScavengeDatabaseResponse.ScavengeResult.Started:
                    return(Configure.Ok(e.ResponseCodec.ContentType));

                case ClientMessage.ScavengeDatabaseResponse.ScavengeResult.InProgress:
                    return(Configure.BadRequest());

                case ClientMessage.ScavengeDatabaseResponse.ScavengeResult.Unauthorized:
                    return(Configure.Unauthorized());

                default:
                    return(Configure.InternalServerError());
                }
            }
                                                  );

            Publish(new ClientMessage.ScavengeDatabase(envelope, Guid.Empty, entity.User, startFromChunk, 1));
        }
Ejemplo n.º 13
0
 private void OnGetFreshStats(HttpEntityManager entity)
 {
     var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                           entity,
                                           Format.GetFreshStatsCompleted,
                                           Configure.GetFreshStatsCompleted);
 }
Ejemplo n.º 14
0
        private void OnGetGossip(HttpEntityManager entity, UriTemplateMatch match)
        {
            var sendToHttpEnvelope = new SendToHttpEnvelope(
                _networkSendQueue, entity, Format.SendPublicGossip,
                (e, m) => Configure.Ok(e.ResponseCodec.ContentType, Helper.UTF8NoBom, null, null, false));

            Publish(new GossipMessage.ClientGossip(sendToHttpEnvelope));
        }
Ejemplo n.º 15
0
 private void OnGetTcpConnectionStats(HttpEntityManager entity, UriTemplateMatch match)
 {
     var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                           entity,
                                           Format.GetFreshTcpConnectionStatsCompleted,
                                           Configure.GetFreshTcpConnectionStatsCompleted);
     Publish(new MonitoringMessage.GetFreshTcpConnectionStats(envelope));
 }
Ejemplo n.º 16
0
        private void OnGetGossip(HttpEntityManager entity, UriTemplateMatch match)
        {
            var sendToHttpEnvelope = new SendToHttpEnvelope(
                _networkSendQueue, entity, Format.SendGossip,
                (e, m) => Configure.Ok(e.ResponseCodec.ContentType, Helper.UTF8NoBom, null, null, false));

            Publish(new GossipMessage.GossipReceived(sendToHttpEnvelope, new ClusterInfo(new MemberInfo[0]), null));
        }
Ejemplo n.º 17
0
        private void OnGetTcpConnectionStats(HttpEntityManager entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                  entity,
                                                  Format.GetFreshTcpConnectionStatsCompleted,
                                                  Configure.GetFreshTcpConnectionStatsCompleted);

            Publish(new MonitoringMessage.GetFreshTcpConnectionStats(envelope));
        }
Ejemplo n.º 18
0
        private void OnProjectionStateGet(HttpEntity http, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.ProjectionState>(
                http, StateFormatter, StateConfigurator, ErrorsEnvelope(http));

            Publish(
                new ProjectionManagementMessage.GetState(
                    envelope, match.BoundVariables["name"], match.BoundVariables["partition"] ?? ""));
        }
Ejemplo n.º 19
0
        private void OnGetReplicationStats(HttpEntityManager entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                  entity,
                                                  Format.GetReplicationStatsCompleted,
                                                  Configure.GetReplicationStatsCompleted);

            Publish(new ReplicationMessage.GetReplicationStats(envelope));
        }
Ejemplo n.º 20
0
        private void OnPostScavenge(HttpEntityManager entity, UriTemplateMatch match)
        {
            int startFromChunk = 0;

            var startFromChunkVariable = match.BoundVariables["startFromChunk"];

            if (startFromChunkVariable != null)
            {
                if (!int.TryParse(startFromChunkVariable, out startFromChunk) || startFromChunk < 0)
                {
                    SendBadRequest(entity, "startFromChunk must be a positive integer");
                    return;
                }
            }

            int threads = 1;

            var threadsVariable = match.BoundVariables["threads"];

            if (threadsVariable != null)
            {
                if (!int.TryParse(threadsVariable, out threads) || threads < 1)
                {
                    SendBadRequest(entity, "threads must be a 1 or above");
                    return;
                }
            }

            Log.Info("Request scavenging because /admin/scavenge?startFromChunk={chunkStartNumber}&threads={numThreads} request has been received.", startFromChunk, threads);

            var envelope = new SendToHttpEnvelope(_networkSendQueue, entity, (e, message) =>
            {
                var completed = message as ClientMessage.ScavengeDatabaseResponse;
                return(e.ResponseCodec.To(new ScavengeResultDto(completed?.ScavengeId)));
            },
                                                  (e, message) =>
            {
                var completed = message as ClientMessage.ScavengeDatabaseResponse;
                switch (completed?.Result)
                {
                case ClientMessage.ScavengeDatabaseResponse.ScavengeResult.Started:
                    return(Configure.Ok(e.ResponseCodec.ContentType));

                case ClientMessage.ScavengeDatabaseResponse.ScavengeResult.InProgress:
                    return(Configure.BadRequest());

                case ClientMessage.ScavengeDatabaseResponse.ScavengeResult.Unauthorized:
                    return(Configure.Unauthorized());

                default:
                    return(Configure.InternalServerError());
                }
            }
                                                  );

            Publish(new ClientMessage.ScavengeDatabase(envelope, Guid.Empty, entity.User, startFromChunk, threads));
        }
        public void GetFeedPage(HttpEntity entity, string stream, int start, int count)
        {
            entity.Manager.AsyncState = start;
            var envelope = new SendToHttpEnvelope(entity,
                                                  (ent, msg) => Format.Atom.ReadEventsBackwardsCompletedFeed(ent, msg, start, count),
                                                  Configure.ReadEventsFromEndCompleted);

            Publish(new ClientMessage.ReadEventsBackwards(Guid.NewGuid(), envelope, stream, start, count, resolveLinks: true));
        }
Ejemplo n.º 22
0
        private void GetStreamEvent(HttpEntityManager manager, string stream, int eventNumber,
                                    bool resolveLinkTos, bool requireMaster, EmbedLevel embed)
        {
            var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                  manager,
                                                  (args, message) => Format.EventEntry(args, message, embed),
                                                  (args, message) => Configure.EventEntry(args, message, headEvent: eventNumber == -1));
            var corrId = Guid.NewGuid();

            Publish(new ClientMessage.ReadEvent(corrId, corrId, envelope, stream, eventNumber, resolveLinkTos, requireMaster, manager.User));
        }
Ejemplo n.º 23
0
        private void OnProjectionDelete(HttpEntity http, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.Updated>(
                http, DefaultFormatter, OkResponseConfigurator, ErrorsEnvelope(http));

            Publish(
                new ProjectionManagementMessage.Delete(
                    envelope, match.BoundVariables["name"],
                    "yes".Equals(match.BoundVariables["deleteCheckpointStream"], StringComparison.OrdinalIgnoreCase),
                    "yes".Equals(match.BoundVariables["deleteStateStream"], StringComparison.OrdinalIgnoreCase)));
        }
Ejemplo n.º 24
0
        private void OnProjectionQueryPut(HttpEntity http, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.Updated>(
                http, DefaultFormatter, OkResponseConfigurator, ErrorsEnvelope(http));

            http.Manager.ReadRequestAsync(
                (o, s) =>
                this.Publish(
                    new ProjectionManagementMessage.UpdateQuery(
                        envelope, match.BoundVariables["name"], match.BoundVariables["type"], s)), Console.WriteLine);
        }
Ejemplo n.º 25
0
        private void OnGetFreshStats(HttpEntity entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(
                    entity,
                    Format.GetFreshStatsCompleted,
                    Configure.GetFreshStatsCompleted);

            var statPath = match.BoundVariables["statPath"];
            var statSelector = GetStatSelector(statPath);

            Publish(new MonitoringMessage.GetFreshStats(envelope, statSelector));
        }
Ejemplo n.º 26
0
        private void GetStreamEventsForward(HttpEntityManager manager, string stream, int eventNumber, int count,
                                            bool resolveLinkTos, bool requireMaster, int?etag, TimeSpan?longPollTimeout, EmbedLevel embed)
        {
            var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                  manager,
                                                  (ent, msg) => Format.GetStreamEventsForward(ent, msg, embed),
                                                  Configure.GetStreamEventsForward);
            var corrId = Guid.NewGuid();

            Publish(new ClientMessage.ReadStreamEventsForward(corrId, corrId, envelope, stream, eventNumber, count,
                                                              resolveLinkTos, requireMaster, etag, manager.User, longPollTimeout));
        }
Ejemplo n.º 27
0
        private void OnGetFreshStats(HttpEntity entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(
                entity,
                Format.GetFreshStatsCompleted,
                Configure.GetFreshStatsCompleted);

            var statPath     = match.BoundVariables["statPath"];
            var statSelector = GetStatSelector(statPath);

            Publish(new MonitoringMessage.GetFreshStats(envelope, statSelector));
        }
Ejemplo n.º 28
0
        private void OnProjectionCommandAbort(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
            {
                return;
            }

            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.Updated>(
                _networkSendQueue, http, DefaultFormatter, OkResponseConfigurator, ErrorsEnvelope(http));

            Publish(new ProjectionManagementMessage.Command.Abort(envelope, match.BoundVariables["name"], GetRunAs(http, match)));
        }
 public void GetAllBefore(HttpEntity entity, TFPos position, int count)
 {
     var envelope = new SendToHttpEnvelope(entity,
                                           Format.Atom.ReadAllEventsBackwardCompleted,
                                           Configure.ReadAllEventsBackwardCompleted);
     Publish(new ClientMessage.ReadAllEventsBackward(Guid.NewGuid(),
                                                     envelope,
                                                     position.CommitPosition,
                                                     position.PreparePosition,
                                                     count,
                                                     true));
 }
Ejemplo n.º 30
0
        private void GetStreamEventsBackward(HttpEntityManager manager, string stream, int eventNumber, int count,
                                             bool resolveLinkTos, bool requireMaster, bool headOfStream, EmbedLevel embed)
        {
            var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                  manager,
                                                  (ent, msg) =>
                                                  Format.GetStreamEventsBackward(ent, msg, embed, headOfStream),
                                                  (args, msg) => Configure.GetStreamEventsBackward(args, msg, headOfStream));
            var corrId = Guid.NewGuid();

            Publish(new ClientMessage.ReadStreamEventsBackward(corrId, corrId, envelope, stream, eventNumber, count,
                                                               resolveLinkTos, requireMaster, GetETagStreamVersion(manager), manager.User));
        }
Ejemplo n.º 31
0
        public void GetAllAfter(HttpEntity entity, TFPos position, int count)
        {
            var envelope = new SendToHttpEnvelope(entity,
                                                  Format.Atom.ReadAllEventsForwardCompleted,
                                                  Configure.ReadAllEventsForwardCompleted);

            Publish(new ClientMessage.ReadAllEventsForward(Guid.NewGuid(),
                                                           envelope,
                                                           position.CommitPosition,
                                                           position.PreparePosition,
                                                           count,
                                                           true));
        }
Ejemplo n.º 32
0
        private void OnProjectionResultGet(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
            {
                return;
            }

            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.ProjectionResult>(
                _networkSendQueue, http, ResultFormatter, ResultConfigurator, ErrorsEnvelope(http));

            Publish(
                new ProjectionManagementMessage.Command.GetResult(
                    envelope, match.BoundVariables["name"], match.BoundVariables["partition"] ?? ""));
        }
        private void GetAllSubscriptionInfo(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
            {
                return;
            }
            var envelope = new SendToHttpEnvelope(
                _networkSendQueue, http,
                (args, message) => http.ResponseCodec.To(ToSummaryDto(http, message as MonitoringMessage.GetPersistentSubscriptionStatsCompleted).ToArray()),
                (args, message) => StatsConfiguration(http, message));
            var cmd = new MonitoringMessage.GetAllPersistentSubscriptionStats(envelope);

            Publish(cmd);
        }
Ejemplo n.º 34
0
        private void DeleteSubscription(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
            {
                return;
            }
            var envelope = new SendToHttpEnvelope(
                _networkSendQueue, http,
                (args, message) => http.ResponseCodec.To(message),
                (args, message) => {
                int code;
                var m = message as ClientMessage.DeletePersistentSubscriptionCompleted;
                if (m == null)
                {
                    throw new Exception("unexpected message " + message);
                }
                switch (m.Result)
                {
                case ClientMessage.DeletePersistentSubscriptionCompleted.DeletePersistentSubscriptionResult
                    .Success:
                    code = HttpStatusCode.OK;
                    break;

                case ClientMessage.DeletePersistentSubscriptionCompleted.DeletePersistentSubscriptionResult
                    .DoesNotExist:
                    code = HttpStatusCode.NotFound;
                    break;

                case ClientMessage.DeletePersistentSubscriptionCompleted.DeletePersistentSubscriptionResult
                    .AccessDenied:
                    code = HttpStatusCode.Unauthorized;
                    break;

                default:
                    code = HttpStatusCode.InternalServerError;
                    break;
                }

                return(new ResponseConfiguration(code, http.ResponseCodec.ContentType,
                                                 http.ResponseCodec.Encoding));
            });
            var groupname = match.BoundVariables["subscription"];
            var stream    = match.BoundVariables["stream"];
            var cmd       = new ClientMessage.DeletePersistentSubscription(Guid.NewGuid(), Guid.NewGuid(), envelope, stream,
                                                                           groupname, http.User);

            Publish(cmd);
        }
Ejemplo n.º 35
0
        private void OnGetRead(HttpEntity entity, UriTemplateMatch match)
        {
            var stream = match.BoundVariables["stream"];
            var versionString = match.BoundVariables["version"];
            var resolve = match.BoundVariables["resolve"] ?? "yes";
            //TODO: reply invalid ??? if neither NO nor YES
            int version;

            if (String.IsNullOrEmpty(stream) || !Int32.TryParse(versionString, out version))
            {
                SendBadRequest(entity, "Stream must bu non-empty string and id must be integer value");
                return;
            }

            var envelope = new SendToHttpEnvelope(entity, Format.ReadEventCompleted, Configure.ReadEventCompleted);
            Publish(
                new ClientMessage.ReadEvent(
                    Guid.NewGuid(), envelope, stream, version, resolve.Equals("yes", StringComparison.OrdinalIgnoreCase)));
        }
        private void ReplayParkedMessages(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
                return;
            var envelope = new SendToHttpEnvelope(
                _networkSendQueue, http,
                (args, message) => http.ResponseCodec.To(message),
                (args, message) =>
                {
                    int code;
                    var m = message as ClientMessage.ReplayMessagesReceived;
                    if (m == null) throw new Exception("unexpected message " + message);
                    switch (m.Result)
                    {
                        case ClientMessage.ReplayMessagesReceived.ReplayMessagesReceivedResult.Success:
                            code = HttpStatusCode.OK;
                            break;
                        case ClientMessage.ReplayMessagesReceived.ReplayMessagesReceivedResult.DoesNotExist:
                            code = HttpStatusCode.NotFound;
                            break;
                        case ClientMessage.ReplayMessagesReceived.ReplayMessagesReceivedResult.AccessDenied:
                            code = HttpStatusCode.Unauthorized;
                            break;
                        default:
                            code = HttpStatusCode.InternalServerError;
                            break;
                    }

                    return new ResponseConfiguration(code, http.ResponseCodec.ContentType,
                        http.ResponseCodec.Encoding);
                });
            var groupname = match.BoundVariables["subscription"];
            var stream = match.BoundVariables["stream"];
            var cmd = new ClientMessage.ReplayAllParkedMessages(Guid.NewGuid(), Guid.NewGuid(), envelope, stream, groupname, http.User);
            Publish(cmd);
        }
        private void PutSubscription(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
                return;
            var groupname = match.BoundVariables["subscription"];
            var stream = match.BoundVariables["stream"];
            var envelope = new SendToHttpEnvelope(
                _networkSendQueue, http,
                (args, message) => http.ResponseCodec.To(message),
                (args,message) =>
                {
                    int code;
                    var m = message as ClientMessage.CreatePersistentSubscriptionCompleted;
                    if(m==null) throw new Exception("unexpected message " + message);
                    switch (m.Result)
                    {
                        case ClientMessage.CreatePersistentSubscriptionCompleted.CreatePersistentSubscriptionResult.Success:
                            code = HttpStatusCode.Created;
                            //TODO competing return uri to subscription
                            break;
                        case ClientMessage.CreatePersistentSubscriptionCompleted.CreatePersistentSubscriptionResult.AlreadyExists:
                            code = HttpStatusCode.Conflict;
                            break;
                        case ClientMessage.CreatePersistentSubscriptionCompleted.CreatePersistentSubscriptionResult.AccessDenied:
                            code = HttpStatusCode.Unauthorized;
                            break;
                        default:
                            code = HttpStatusCode.InternalServerError;
                            break;
                    }
                    return new ResponseConfiguration(code, http.ResponseCodec.ContentType,
                        http.ResponseCodec.Encoding, new KeyValuePair<string, string>("location", MakeUrl(http, "/subscriptions/" + stream + "/" + groupname)));
                });
            http.ReadTextRequestAsync(
                (o, s) =>
                {
                    var data = http.RequestCodec.From<SubscriptionConfigData>(s);

                    var config = GetConfig(data);
                    var message = new ClientMessage.CreatePersistentSubscription(Guid.NewGuid(),
                        Guid.NewGuid(),
                        envelope,
                        stream, 
                        groupname,
                        config.ResolveLinktos,
                        config.StartFrom,
                        config.MessageTimeoutMilliseconds,
                        config.ExtraStatistics,
                        config.MaxRetryCount,
                        config.BufferSize,
                        config.LiveBufferSize,
                        config.ReadBatchSize,
                        config.CheckPointAfterMilliseconds,
                        config.MinCheckPointCount,
                        config.MaxCheckPointCount,
                        config.MaxSubscriberCount,
                        CalculateNamedConsumerStrategyForOldClients(data),
                        http.User,
                        "",
                        "");
                    Publish(message);
                }, x => Log.DebugException(x, "Reply Text Content Failed."));
        }
 public void GetEntry(HttpEntity entity, string stream, int version)
 {
     var envelope = new SendToHttpEnvelope(entity, Format.Atom.ReadEventCompletedEntry, Configure.ReadEventCompleted);
     Publish(new ClientMessage.ReadEvent(Guid.NewGuid(), envelope, stream, version, true));
 }
 public void GetFeedPage(HttpEntity entity, string stream, int start, int count)
 {
     entity.Manager.AsyncState = start;
     var envelope = new SendToHttpEnvelope(entity,
                                           (ent, msg) => Format.Atom.ReadStreamEventsBackwardCompletedFeed(ent, msg, start, count),
                                           Configure.ReadStreamEventsBackwardCompleted);
     Publish(new ClientMessage.ReadStreamEventsBackward(Guid.NewGuid(), envelope, stream, start, count, resolveLinks: true));
 }
        private void CreateStreamBodyRead(HttpEntityManager manager, string body)
        {
            var entity = manager.HttpEntity;

            var create = entity.RequestCodec.From<HttpClientMessageDto.CreateStreamText>(body);
            if (create == null)
            {
                SendBadRequest(entity, "Create stream request body cannot be deserialized");
                return;
            }

            var envelope = new SendToHttpEnvelope(entity,
                                                  Format.Atom.CreateStreamCompleted,
                                                  Configure.CreateStreamCompleted);
            var msg = new ClientMessage.CreateStream(Guid.NewGuid(),
                                                     envelope,
                                                     true,
                                                     create.EventStreamId,
                                                     false,//TODO TR discover
                                                     Encoding.UTF8.GetBytes(create.Metadata ?? string.Empty));
            Publish(msg);
        }
        private void GetNextNMessages(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
                return;
            var groupname = match.BoundVariables["subscription"];
            var stream = match.BoundVariables["stream"];
            var cnt = match.BoundVariables["count"];
            var embed = GetEmbedLevel(http, match);
            int count = DefaultNumberOfMessagesToGet;
            if (!cnt.IsEmptyString() && (!int.TryParse(cnt, out count) || count > 100 || count < 1))
            {
                SendBadRequest(http, string.Format("Message count must be an integer between 1 and 100 'count' ='{0}'", count));
                return;
            }
            var envelope = new SendToHttpEnvelope(
                _networkSendQueue, http,
                (args, message) => Format.ReadNextNPersistentMessagesCompleted(http, message as ClientMessage.ReadNextNPersistentMessagesCompleted, stream, groupname, count, embed),
                (args, message) =>
                {
                    int code;
                    var m = message as ClientMessage.ReadNextNPersistentMessagesCompleted;
                    if (m == null) throw new Exception("unexpected message " + message);
                    switch (m.Result)
                    {
                        case
                            ClientMessage.ReadNextNPersistentMessagesCompleted.ReadNextNPersistentMessagesResult.Success:
                            code = HttpStatusCode.OK;
                            break;
                        case
                            ClientMessage.ReadNextNPersistentMessagesCompleted.ReadNextNPersistentMessagesResult.DoesNotExist:
                            code = HttpStatusCode.NotFound;
                            break;
                        case
                            ClientMessage.ReadNextNPersistentMessagesCompleted.ReadNextNPersistentMessagesResult.AccessDenied:
                            code = HttpStatusCode.Unauthorized;
                            break;
                        default:
                            code = HttpStatusCode.InternalServerError;
                            break;
                    }
                    return new ResponseConfiguration(code, http.ResponseCodec.ContentType,
                        http.ResponseCodec.Encoding);
                });

            var cmd = new ClientMessage.ReadNextNPersistentMessages(
                                             Guid.NewGuid(),
                                             Guid.NewGuid(),
                                             envelope,
                                             stream,
                                             groupname,
                                             count,
                                             http.User);
            Publish(cmd);
        }
        private void DeleteStreamBodyRead(HttpEntityManager manager, string body)
        {
            var entity = manager.HttpEntity;
            var stream = (string)manager.AsyncState;

            var delete = entity.RequestCodec.From<HttpClientMessageDto.DeleteStreamText>(body);
            if (delete == null)
            {
                SendBadRequest(entity, "Delete stream request body cannot be deserialized");
                return;
            }

            var envelope = new SendToHttpEnvelope(entity,
                                                  Format.Atom.DeleteStreamCompleted,
                                                  Configure.DeleteStreamCompleted);
            var msg = new ClientMessage.DeleteStream(Guid.NewGuid(),
                                                     envelope,
                                                     true,
                                                     stream,
                                                     delete.ExpectedVersion);
            Publish(msg);
        }
        private void OnPostEntryRequestRead(HttpEntityManager manager, string body)
        {
            var entity = manager.HttpEntity;
            var stream = (string)manager.AsyncState;

            var parsed = AutoEventConverter.SmartParse(body, entity.RequestCodec);
            var expectedVersion = parsed.Item1;
            var events = parsed.Item2;

            if (events == null || events.Length == 0)
            {
                SendBadRequest(entity, "Write request body invalid");
                return;
            }

            var envelope = new SendToHttpEnvelope(entity, Format.WriteEventsCompleted, Configure.WriteEventsCompleted);
            var msg = new ClientMessage.WriteEvents(Guid.NewGuid(), envelope, true, stream, expectedVersion, events);

            Publish(msg);
        }
 //SERVICE DOCUMENT
 private void OnGetServiceDocument(HttpEntity entity, UriTemplateMatch match)
 {
     var envelope = new SendToHttpEnvelope(entity, Format.Atom.ListStreamsCompletedServiceDoc, Configure.ListStreamsCompletedServiceDoc);
     Publish(new ClientMessage.ListStreams(envelope));
 }
 private void GetAllSubscriptionInfo(HttpEntityManager http, UriTemplateMatch match)
 {
     if (_httpForwarder.ForwardRequest(http))
         return;
     var envelope = new SendToHttpEnvelope(
         _networkSendQueue, http,
         (args, message) => http.ResponseCodec.To(ToSummaryDto(http, message as MonitoringMessage.GetPersistentSubscriptionStatsCompleted)),
         (args, message) => StatsConfiguration(http, message));
     var cmd = new MonitoringMessage.GetAllPersistentSubscriptionStats(envelope);
     Publish(cmd);
 }
Ejemplo n.º 46
0
 private void OnGetReplicationStats(HttpEntityManager entity, UriTemplateMatch match)
 {
     var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                           entity,
                                           Format.GetReplicationStatsCompleted,
                                           Configure.GetReplicationStatsCompleted);
     Publish(new ReplicationMessage.GetReplicationStats(envelope));
 }
 private void GetSubscriptionInfo(HttpEntityManager http, UriTemplateMatch match)
 {
     if (_httpForwarder.ForwardRequest(http))
         return;
     var stream = match.BoundVariables["stream"];
     var groupName = match.BoundVariables["subscription"];
     var envelope = new SendToHttpEnvelope(
         _networkSendQueue, http,
         (args, message) => http.ResponseCodec.To(ToDto(http, message as MonitoringMessage.GetPersistentSubscriptionStatsCompleted).FirstOrDefault()),
         (args, message) => StatsConfiguration(http, message));
     var cmd = new MonitoringMessage.GetPersistentSubscriptionStats(envelope, stream, groupName);
     Publish(cmd);
 }