Exemple #1
0
        ///<inheritdoc/>
        public override async Task PublishAsync <TIntegrationEvent>(
            TIntegrationEvent @event,
            string topic  = null,
            string prefix = null)
        {
            if (@event is null)
            {
                throw new ArgumentNullException(nameof(@event));
            }
            var topicName = GetTopicName(@event.GetType(), topic, prefix);

            if (_daprEventBusSchemaOptions.Value.UseSchemaRegistry)
            {
                // Get schema
                var schema = await _schemaRegistry.GetSchema(topicName);

                if (schema == null)
                {
                    if (!_daprEventBusSchemaOptions.Value.AddSchemaOnPublish)
                    {
                        _logger.LogError("No schema registered for {TopicName}", topicName);
                        throw new SchemaNotRegisteredException(topicName);
                    }

                    // Generate schema
                    var content = _schemaGenerator.GenerateSchema(typeof(TIntegrationEvent));
                    if (string.IsNullOrWhiteSpace(content))
                    {
                        _logger.LogError("Schema generation failed for {TopicName}", topicName);
                        throw new Exception($"Schema generation failed for {topicName}");
                    }

                    // Register schema
                    schema = new Schema
                    {
                        Topic   = topicName,
                        Content = content
                    };
                    await _schemaRegistry.AddSchema(schema);

                    _logger.LogInformation("Schema registered for {TopicName}", topicName);
                }

                // Validate message with schema
                var message = JsonSerializer.Serialize(@event, typeof(TIntegrationEvent), DaprClient.JsonSerializerOptions);
                var isValid = _schemaValidator.ValidateMessage(message, schema.Content, out var errorMessages);
                if (!isValid)
                {
                    _logger.LogError("Schema validation failed for {TopicName}", topicName);
                    foreach (var errorMessage in errorMessages)
                    {
                        _logger.LogError("Schema validation error: {ErrorMessage}", errorMessage);
                    }
                    throw new SchemaValidationException(topicName);
                }
            }

            await DaprClient.PublishEventAsync(DaprEventBusOptions.Value.PubSubName, topicName, @event);
        }
Exemple #2
0
        public async Task <IActionResult> GetSchema([FromRoute] string topic)
        {
            var schema = await _schemaRegistry.GetSchema(topic);

            if (schema == null)
            {
                return(NotFound());
            }
            return(Ok(schema));
        }