Example #1
0
        public void BuildTimestampsAsIso8601Strings(Type type)
        {
            var builder = new SchemaBuilder(temporalBehavior: TemporalBehavior.Iso8601);
            var schema  = Assert.IsType <StringSchema>(builder.BuildSchema(type));

            Assert.Null(schema.LogicalType);
        }
Example #2
0
        public void BuildTimestampsAsMillisecondsFromEpoch(Type type)
        {
            var builder = new SchemaBuilder(temporalBehavior: TemporalBehavior.EpochMilliseconds);
            var schema  = Assert.IsType <LongSchema>(builder.BuildSchema(type));

            Assert.IsType <MillisecondTimestampLogicalType>(schema.LogicalType);
        }
        public void BuildsTimestampsAsMillisecondsFromEpoch(Type type)
        {
            var builder = new SchemaBuilder(SchemaBuilder.CreateCaseBuilders(TemporalBehavior.EpochMilliseconds));
            var schema  = builder.BuildSchema(type) as LongSchema;

            Assert.NotNull(schema);
            Assert.IsType <MillisecondTimestampLogicalType>(schema.LogicalType);
        }
        public void BuildsTimestampsAsIso8601Strings(Type type)
        {
            var builder = new SchemaBuilder(SchemaBuilder.CreateCaseBuilders(TemporalBehavior.Iso8601));
            var schema  = builder.BuildSchema(type) as StringSchema;

            Assert.NotNull(schema);
            Assert.Null(schema.LogicalType);
        }
        /// <summary>
        /// Serialize a message. (See <see cref="IAsyncSerializer{T}.SerializeAsync(T, SerializationContext)" />.)
        /// </summary>
        public virtual async Task <byte[]> SerializeAsync(T data, SerializationContext context)
        {
            var serialize = await(_cache.GetOrAdd(SubjectNameBuilder(context), async subject =>
            {
                int id;
                Action <T, Stream> @delegate;

                try
                {
                    var existing = await _resolve(subject).ConfigureAwait(false);
                    var schema   = SchemaReader.Read(existing.SchemaString);

                    @delegate = SerializerBuilder.BuildDelegate <T>(schema);
                    id        = existing.Id;
                }
                catch (Exception e) when(RegisterAutomatically && (
                                             (e is SchemaRegistryException sre && sre.ErrorCode == 40401) ||
                                             (e is AggregateException a && a.InnerExceptions.All(i =>
                                                                                                 i is UnsupportedSchemaException ||
                                                                                                 i is UnsupportedTypeException
                                                                                                 ))
                                             ))
                {
                    var schema = SchemaBuilder.BuildSchema <T>();
                    var json   = SchemaWriter.Write(schema);

                    @delegate = SerializerBuilder.BuildDelegate <T>(schema);
                    id        = await _register(subject, json).ConfigureAwait(false);
                }

                var bytes = BitConverter.GetBytes(id);

                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(bytes);
                }

                return(value =>
                {
                    var stream = new MemoryStream();

                    using (stream)
                    {
                        stream.WriteByte(0x00);
                        stream.Write(bytes, 0, bytes.Length);

                        @delegate(value, stream);
                    }

                    return stream.ToArray();
                });
            })).ConfigureAwait(false);

            return(serialize(data));
        }
        public void Ensure_Schema_IsCorrect()
        {
            // arrange
            var schema = SchemaBuilder.BuildSchema();

            // act
            string schemaSDL = schema.ToString();

            // assert
            Snapshot.Match(schemaSDL);
        }
Example #7
0
        /// <inheritdoc />
        public virtual async Task <byte[]> SerializeAsync(T data, SerializationContext context)
        {
            var subject = SubjectNameBuilder(context);

            Task <Func <T, byte[]> > task;

            lock (cache)
            {
                if (!cache.TryGetValue(subject, out task) || task.IsFaulted)
                {
                    cache[subject] = task = ((Func <string, Task <Func <T, byte[]> > >)(async subject =>
                    {
                        switch (RegisterAutomatically)
                        {
                        case AutomaticRegistrationBehavior.Always:
                            var schema = SchemaBuilder.BuildSchema <T>();
                            var id = await RegistryClient.RegisterSchemaAsync(subject, new Schema(SchemaWriter.Write(schema), SchemaType.Avro)).ConfigureAwait(false);

                            return(Build(id, schema));

                        case AutomaticRegistrationBehavior.Never:
                            var registration = await RegistryClient.GetLatestSchemaAsync(subject).ConfigureAwait(false);

                            if (registration.SchemaType != SchemaType.Avro)
                            {
                                throw new UnsupportedSchemaException(null, $"The latest schema with subject {subject} is not an Avro schema.");
                            }

                            return(Build(registration.Id, SchemaReader.Read(registration.SchemaString)));

                        default:
                            throw new ArgumentOutOfRangeException(nameof(RegisterAutomatically));
                        }
                    }))(subject);
                }
            }

            var serialize = await task.ConfigureAwait(false);

            if (data == null && TombstoneBehavior != TombstoneBehavior.None)
            {
                if (context.Component == MessageComponentType.Value || TombstoneBehavior != TombstoneBehavior.Strict)
                {
                    return(null);
                }
            }

            return(serialize(data));
        }
Example #8
0
        protected Schema CreateSchema()
        {
            var type = ((IClrTypeOptions)this).ResolveType();

            var builder = new SchemaBuilder(
                enumBehavior: EnumBehavior,
                nullableReferenceTypeBehavior: NullableReferences,
                temporalBehavior: TemporalBehavior);

            try
            {
                return(builder.BuildSchema(type));
            }
            catch (UnsupportedTypeException inner)
            {
                throw new ProgramException(message: $"Failed to create a schema for {type}: The type is not supported by the resolver.", inner: inner);
            }
        }
Example #9
0
        /// <summary>
        /// Serialize a message. (See <see cref="IAsyncSerializer{T}.SerializeAsync(T, SerializationContext)" />.)
        /// </summary>
        public virtual async Task <byte[]> SerializeAsync(T data, SerializationContext context)
        {
            var subject = SubjectNameBuilder(context);

            Task <Func <T, byte[]> > task;

            lock (_cache)
            {
                if (!_cache.TryGetValue(subject, out task) || task.IsFaulted)
                {
                    _cache[subject] = task = ((Func <string, Task <Func <T, byte[]> > >)(async subject =>
                    {
                        switch (RegisterAutomatically)
                        {
                        case AutomaticRegistrationBehavior.Always:
                            var schema = SchemaBuilder.BuildSchema <T>();
                            var id = await _register(subject, SchemaWriter.Write(schema)).ConfigureAwait(false);

                            return(Build(id, schema));

                        case AutomaticRegistrationBehavior.Never:
                            var existing = await _resolve(subject).ConfigureAwait(false);

                            return(Build(existing.Id, SchemaReader.Read(existing.SchemaString)));

                        default:
                            throw new ArgumentOutOfRangeException(nameof(RegisterAutomatically));
                        }
                    }))(subject);
                }
            }

            var serialize = await task.ConfigureAwait(false);

            if (data == null && TombstoneBehavior != TombstoneBehavior.None)
            {
                if (context.Component == MessageComponentType.Value || TombstoneBehavior != TombstoneBehavior.Strict)
                {
                    return(null);
                }
            }

            return(serialize(data));
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDataServices(Configuration);
            services.AddDomainServices();

            //services.AddInMemorySubscriptionProvider();

            Schema schema = SchemaBuilder.BuildSchema();

            services.AddGraphQL(schema.MakeExecutable(c =>
                                                      c.UseDefaultPipeline(new QueryExecutionOptions
            {
#if DEBUG
                TracingPreference       = TracingPreference.Always,
                IncludeExceptionDetails = true
#endif
            })
                                                      .AddCustomErrorFilters()));
            services.AddInMemorySubscriptionProvider();
        }
Example #11
0
        protected Schema CreateSchema()
        {
            var type = this.ResolveType();

            var resolver = new DataContractResolver(
                resolveReferenceTypesAsNullable: NullableReferences,
                resolveUnderlyingEnumTypes: EnumsAsIntegers
                );

            var builder = new SchemaBuilder(TemporalBehavior, resolver);

            try
            {
                return(builder.BuildSchema(type));
            }
            catch (UnsupportedTypeException inner)
            {
                throw new ProgramException(message: $"Failed to create a schema for {type}: The type is not supported by the resolver.", inner: inner);
            }
        }
Example #12
0
        /// <exception cref="UnsupportedTypeException">
        /// Thrown when <typeparamref name="T" /> is incompatible with the retrieved schema.
        /// </exception>
        /// <inheritdoc />
        public async Task <ISerializer <T> > Build <T>(
            string subject,
            AutomaticRegistrationBehavior registerAutomatically = AutomaticRegistrationBehavior.Never,
            TombstoneBehavior tombstoneBehavior = TombstoneBehavior.None)
        {
            switch (registerAutomatically)
            {
            case AutomaticRegistrationBehavior.Always:
                var json = SchemaWriter.Write(SchemaBuilder.BuildSchema <T>());
                var id   = await RegistryClient.RegisterSchemaAsync(subject, new Schema(json, SchemaType.Avro)).ConfigureAwait(false);

                return(Build <T>(id, json, tombstoneBehavior));

            case AutomaticRegistrationBehavior.Never:
                var existing = await RegistryClient.GetLatestSchemaAsync(subject).ConfigureAwait(false);

                return(Build <T>(existing.Id, existing.SchemaString, tombstoneBehavior));

            default:
                throw new ArgumentOutOfRangeException(nameof(registerAutomatically));
            }
        }
Example #13
0
        /// <summary>
        /// Builds a serializer for a specific schema.
        /// </summary>
        /// <param name="subject">
        /// The subject of the schema that should be used to serialize data. The latest version of
        /// the subject will be resolved.
        /// </param>
        /// <param name="registerAutomatically">
        /// Whether to automatically register a schema that matches <typeparamref name="T" /> if
        /// one does not already exist.
        /// </param>
        /// <exception cref="AggregateException">
        /// Thrown when the type is incompatible with the retrieved schema or a matching schema
        /// cannot be generated.
        /// </exception>
        public async Task <ISerializer <T> > Build <T>(string subject, bool registerAutomatically = false)
        {
            try
            {
                var schema = await RegistryClient.GetLatestSchemaAsync(subject);

                return(Build <T>(schema.Id, schema.SchemaString));
            }
            catch (Exception e) when(registerAutomatically && (
                                         (e is SchemaRegistryException sre && sre.ErrorCode == 40401) ||
                                         (e is AggregateException a && a.InnerExceptions.All(i =>
                                                                                             i is UnsupportedSchemaException ||
                                                                                             i is UnsupportedTypeException
                                                                                             ))
                                         ))
            {
                var schema = SchemaBuilder.BuildSchema <T>();
                var json   = SchemaWriter.Write(schema);

                var id = await RegistryClient.RegisterSchemaAsync(subject, json);

                return(Build <T>(id, json));
            }
        }
Example #14
0
 public void RegisterResource <T>(string resourceName)
 {
     Schemas.Add(resourceName, SchemaBuilder.BuildSchema <T>());
     Types.Add(resourceName, typeof(T));
 }
Example #15
0
 private static Schema BuildSchema(IEnumerable <Type> types, ITypeMapper typeMapper)
 {
     return(SchemaBuilder.BuildSchema(types, typeMapper));
 }
Example #16
0
        public void BuildArrays(Type type, Type inner)
        {
            var schema = Assert.IsType <ArraySchema>(builder.BuildSchema(type));

            Assert.IsType(inner, schema.Item);
            Assert.Null(schema.LogicalType);
        }
        public void BuildsArrays(Type type, Type inner)
        {
            var schema = Builder.BuildSchema(type) as ArraySchema;

            Assert.NotNull(schema);
            Assert.IsType(inner, schema.Item);
            Assert.Null(schema.LogicalType);
        }