Пример #1
0
        public ServiceBusConnectionContext(IServiceBusHost host, CancellationToken cancellationToken)
        {
            _host             = host;
            CancellationToken = cancellationToken;

            _payloadCache = new PayloadCache();
        }
        public async Task <IActionResult> CreatePayload([FromBody, Required] CreatePayloadRequest request)
        {
            var envelope = await _blueprintConverter.Decode(request.Encoded);

            var firstBlueprint = FirstBlueprintOrDefault(envelope);

            if (firstBlueprint == null)
            {
                return(BadRequest("A blueprint book must contain at least one blueprint"));
            }

            var hash    = Hash.Compute(request.Encoded);
            var payload = new Payload(
                hash,
                _blueprintConverter.ParseType(envelope.Entity.Item),
                _blueprintConverter.DecodeGameVersion(envelope.Entity.Version),
                request.Encoded);

            var cache = new PayloadCache();

            cache.TryAdd(envelope, payload);

            await cache.EnsureInitializedGraph(envelope);

            await _buildService.SavePayloadGraph(hash, cache.Values);

            return(Ok(new CreatePayloadResult
            {
                Payload = payload.ToViewModel(Url, envelope, cache),
                ExtractedSlug = await _slugService.Validate(TryValidateModel, envelope.Entity.Label?.ToSlug(), User.GetUserId()),
            }));
        }
Пример #3
0
        /// <summary>
        /// Either adds a new payload, or updates an existing payload
        /// </summary>
        /// <param name="addFactory">The payload factory called if the payload is not present</param>
        /// <param name="updateFactory">The payload factory called if the payload already exists</param>
        /// <typeparam name="T">The payload type</typeparam>
        /// <returns></returns>
        public virtual T AddOrUpdatePayload <T>(PayloadFactory <T> addFactory, UpdatePayloadFactory <T> updateFactory)
            where T : class
        {
            if (this is T context)
            {
                return(context);
            }

            return(PayloadCache.AddOrUpdatePayload(addFactory, updateFactory));
        }
Пример #4
0
        /// <summary>
        /// Get or add a payload to the context, using the provided payload factory.
        /// </summary>
        /// <param name="payloadFactory">The payload factory, which is only invoked if the payload is not present.</param>
        /// <typeparam name="T">The payload type</typeparam>
        /// <returns></returns>
        public virtual T GetOrAddPayload <T>(PayloadFactory <T> payloadFactory)
            where T : class
        {
            if (this is T context)
            {
                return(context);
            }

            return(PayloadCache.GetOrAddPayload(payloadFactory));
        }
        public ConsumerJobContext(ConsumeContext <TInput> context)
            : base(context)
        {
            _context = context;

            _cancellationTokenSource = new CancellationTokenSource();
            _payloadCache            = new PayloadCache();

            JobId      = NewId.NextGuid();
            _stopwatch = Stopwatch.StartNew();
        }
Пример #6
0
        /// <summary>
        /// Attempts to get the specified payload type
        /// </summary>
        /// <param name="payload"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public virtual bool TryGetPayload <T>(out T payload)
            where T : class
        {
            if (this is T context)
            {
                payload = context;
                return(true);
            }

            return(PayloadCache.TryGetPayload(out payload));
        }
Пример #7
0
        public RabbitMqConnectionContext(IConnection connection, RabbitMqHostSettings hostSettings, CancellationToken cancellationToken)
        {
            _connection   = connection;
            _hostSettings = hostSettings;
            _payloadCache = new PayloadCache();

            _completed     = new TaskCompletionSource <bool>();
            _tokenSource   = new CancellationTokenSource();
            _registration  = cancellationToken.Register(OnCancellationRequested);
            _taskScheduler = new QueuedTaskScheduler(TaskScheduler.Default, 1);

            connection.ConnectionShutdown += OnConnectionShutdown;
        }
Пример #8
0
        public InMemorySendContext(T message, CancellationToken cancellationToken = default(CancellationToken))
        {
            CancellationToken = cancellationToken;

            _payloadCache = new PayloadCache();

            _headers = new InMemorySendHeaders();

            Message   = message;
            MessageId = NewId.NextGuid();

            Durable = true;
        }
Пример #9
0
        public ServiceBusSendContextImpl(T message, CancellationToken cancellationToken)
        {
            _payloadCache = new PayloadCache();
            _payloadCache.GetOrAddPayload <ServiceBusSendContext <T> >(() => this);

            Headers = new ServiceBusSendHeaders();

            Message            = message;
            _cancellationToken = cancellationToken;

            MessageId = NewId.NextGuid();

            Durable = true;
        }
Пример #10
0
        protected BaseReceiveContext(Uri inputAddress, bool redelivered, IReceiveObserver receiveObserver)
        {
            _receiveTimer = Stopwatch.StartNew();

            _payloadCache = new PayloadCache();

            InputAddress     = inputAddress;
            Redelivered      = redelivered;
            _receiveObserver = receiveObserver;

            _cancellationTokenSource = new CancellationTokenSource();

            _headers = new Lazy <Headers>(() => new JsonHeaders(HeaderProvider));

            _contentType = new Lazy <ContentType>(GetContentType);

            _pendingTasks = new List <Task>();
        }
Пример #11
0
        public RabbitMqModelContext(ConnectionContext connectionContext, IModel model, CancellationToken cancellationToken)
        {
            _connectionContext = connectionContext;
            _model             = model;

            _payloadCache  = new PayloadCache();
            _published     = new ConcurrentDictionary <ulong, PendingPublish>();
            _taskScheduler = new QueuedTaskScheduler(TaskScheduler.Default, 1);

            _tokenSource  = new CancellationTokenSource();
            _registration = cancellationToken.Register(OnCancellationRequested);

            _model.ModelShutdown += OnModelShutdown;
            _model.BasicAcks     += OnBasicAcks;
            _model.BasicNacks    += OnBasicNacks;
            _model.BasicReturn   += OnBasicReturn;
            _model.ConfirmSelect();
        }
Пример #12
0
        public void BasicTest()
        {
            IPayloadCache p = new PayloadCache();

            p.GetOrAddPayload(() => new Item("bob"));

            Item i;

            Assert.That(p.TryGetPayload(out i), Is.True);

            var p2 = p.CreateScope();

            p.GetOrAddPayload(() => new Item2("bill"));

            Item2 i2;

            Assert.That(p2.TryGetPayload(out i2), Is.False);
            Item i1;

            Assert.That(p2.TryGetPayload(out i1), Is.True);
        }
        public RabbitMqSendContextImpl(IBasicProperties basicProperties, T message, SendSettings sendSettings,
                                       CancellationToken cancellationToken,
                                       string routingKey = "")
        {
            CancellationToken = cancellationToken;

            _payloadCache = new PayloadCache();

            // provide access to the extended settings for RabbitMQ developers
            _payloadCache.GetOrAddPayload <RabbitMqSendContext <T> >(() => this);
            _payloadCache.GetOrAddPayload <RabbitMqSendContext>(() => this);

            Headers         = new RabbitMqSendHeaders(basicProperties);
            BasicProperties = basicProperties;
            Message         = message;
            Exchange        = sendSettings.ExchangeName;
            RoutingKey      = routingKey;

            MessageId = NewId.NextGuid();

            Durable = true;
        }
        public async Task <IActionResult> GetDetails([Required] Hash hash, [FromQuery(Name = "include_children")] bool includeChildren = false)
        {
            var payload = await _dbContext.Payloads.AsNoTracking()
                          .Where(v => v.Hash == hash)
                          .FirstOrDefaultAsync();

            if (payload == null)
            {
                return(NotFound());
            }

            var envelope = await _blueprintConverter.Decode(payload.Encoded);

            PayloadCache?payloadGraph = null;

            if (includeChildren)
            {
                payloadGraph = new PayloadCache();
                payloadGraph.TryAdd(envelope, payload);
                await payloadGraph.EnsureInitializedGraph(envelope);
            }

            return(Ok(payload.ToViewModel(Url, envelope, payloadGraph)));
        }
Пример #15
0
 public TestPipeContext()
 {
     _cache = new PayloadCache();
 }
Пример #16
0
 public SendTransformContext(SendContext <TMessage> context)
 {
     _context      = context;
     _payloadCache = new PayloadCache();
 }
Пример #17
0
        private async Task SeedBuilds(IReadOnlyCollection <SeedBlueprint> blueprints)
        {
            _logger.LogInformation("Seeding {TotalCount} builds", blueprints.Count);
            var createdCount = 0;
            var skippedCount = 0;
            var errorCount   = 0;

            foreach (var blueprint in blueprints)
            {
                var slug     = blueprint.Title.ToSlug();
                var username = blueprint.Owner.ToSlug();

                var existing = await _dbContext.Builds.FirstOrDefaultAsync(bp => bp.OwnerSlug == username && bp.Slug == slug);

                if (existing != null)
                {
                    skippedCount++;
                    _logger.LogInformation("Blueprint {Title} by {Owner} already exists", blueprint.Title, blueprint.Owner);
                    continue;
                }

                var owner = await _dbContext.Users.FirstOrDefaultAsync(u => u.UserName == username);

                if (owner == null)
                {
                    var email = Guid.NewGuid() + "@test.local.factorio.tech";

                    _logger.LogInformation("Creating user {DisplayName} / {UserName} / {Email}",
                                           blueprint.Owner, username, email);

                    owner = new User
                    {
                        DisplayName        = blueprint.Owner,
                        UserName           = username,
                        NormalizedUserName = username.ToUpperInvariant(),
                        Email           = email,
                        NormalizedEmail = email.ToUpperInvariant(),
                        EmailConfirmed  = true,
                        RegisteredAt    = SystemClock.Instance.GetCurrentInstant(),
                    };

                    _dbContext.Add(owner);
                    await _dbContext.SaveChangesAsync();
                }

                var envelope = await _blueprintConverter.Decode(blueprint.Encoded);

                var payload = new Payload(
                    Hash.Compute(blueprint.Encoded),
                    _blueprintConverter.ParseType(envelope.Entity.Item),
                    _blueprintConverter.DecodeGameVersion(envelope.Entity.Version),
                    blueprint.Encoded);

                var cache = new PayloadCache();
                cache.TryAdd(envelope, payload);

                await cache.EnsureInitializedGraph(envelope);

                await _buildService.SavePayloadGraph(payload.Hash, cache.Values);

                var tags = blueprint.Tags
                           .Select(t => t.TrimEnd('/'))
                           .Where(_buildTags.Contains)
                           .ToArray();

                var request = new BuildService.CreateRequest(
                    username,
                    slug,
                    blueprint.Title,
                    blueprint.Description,
                    tags.Any() ? tags : GetSomeRandomTags(),
                    (payload.Hash, null, null, envelope.Entity.Icons.ToGameIcons()),
                    null);

                var principal = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
                {
                    new(ClaimTypes.NameIdentifier, owner.Id.ToString()),
                }));
Пример #18
0
 public ConsumeTransformContext(ConsumeContext <TMessage> context)
 {
     _context      = context;
     _payloadCache = new PayloadCache();
 }
Пример #19
0
 /// <summary>
 /// Returns true if the payload type is included with or supported by the context type
 /// </summary>
 /// <param name="payloadType"></param>
 /// <returns></returns>
 public virtual bool HasPayloadType(Type payloadType)
 {
     return(payloadType.GetTypeInfo().IsInstanceOfType(this) || PayloadCache.HasPayloadType(payloadType));
 }