Example #1
0
        public void TestConcurrent()
        {
            var serializerRepresentation = GetSerializerRepresentation();
            var tags = new List <NamedValue <string> >
            {
                new NamedValue <string>("ChangeSet", Guid.NewGuid().ToString().ToUpperInvariant()),
            };
            var timestampUtc = DateTime.UtcNow;
            var payloadType  = typeof(byte[]).ToRepresentation();
            var metadata     = new StreamRecordMetadata(
                Guid.NewGuid().ToString().ToUpperInvariant(),
                serializerRepresentation,
                typeof(string).ToRepresentation().ToWithAndWithoutVersion(),
                payloadType.ToWithAndWithoutVersion(),
                tags,
                timestampUtc,
                timestampUtc);

            var payload        = new BinaryDescribedSerialization(payloadType, serializerRepresentation, new byte[3000000]);
            var putOp          = new StandardPutRecordOp(metadata, payload);
            var commandTimeout = TimeSpan.FromSeconds(1000);
            var listOfStreams  = Enumerable.Range(1, 10)
                                 .Select(
                _ => this.GetCreatedSqlStream(
                    commandTimeout,
                    RecordTagAssociationManagementStrategy.ExternallyManaged))
                                 .ToList();

            var times = new ConcurrentBag <TimeSpan>();

            Parallel.ForEach(listOfStreams, _ =>
            {
                var stopwatch = new Stopwatch();
                for (var idx = 0;
                     idx < 100;
                     idx++)
                {
                    stopwatch.Reset();
                    stopwatch.Start();
                    _.Execute(putOp);
                    stopwatch.Stop();
                    times.Add(stopwatch.Elapsed);
                }
            });

            var averageSeconds = times.Average(_ => _.TotalSeconds);
            var minSeconds     = times.Min(_ => _.TotalSeconds);
            var maxSeconds     = times.Max(_ => _.TotalSeconds);

            this.testOutputHelper.WriteLine(Invariant($"{nameof(averageSeconds)}: {averageSeconds}, {nameof(minSeconds)}: {minSeconds}, {nameof(maxSeconds)}: {maxSeconds}, "));
            foreach (var time in times)
            {
                this.testOutputHelper.WriteLine(time.TotalSeconds.ToString(CultureInfo.InvariantCulture));
            }
        }
        public override TryHandleRecordResult Execute(
            StandardTryHandleRecordOp operation)
        {
            operation.MustForArg(nameof(operation)).NotBeNull();

            var sqlServerLocator      = this.TryGetLocator(operation);
            var convertedRecordFilter = this.ConvertRecordFilter(operation.RecordFilter, sqlServerLocator);
            var tagIdsForEntryCsv     = this.GetIdsAddIfNecessaryTag(
                sqlServerLocator,
                operation.Tags ?? new List <NamedValue <string> >())
                                        .Select(_ => _.ToStringInvariantPreferred())
                                        .ToCsv();
            var storedProcOp = StreamSchema.Sprocs.TryHandleRecord.BuildExecuteStoredProcedureOp(
                this.Name,
                operation.Concern,
                operation.Details ?? Invariant($"Created by {nameof(StandardTryHandleRecordOp)}."),
                convertedRecordFilter,
                tagIdsForEntryCsv,
                operation.OrderRecordsBy,
                operation.MinimumInternalRecordId,
                operation.InheritRecordTags,
                operation.StreamRecordItemsToInclude);

            var sqlProtocol = this.BuildSqlOperationsProtocol(sqlServerLocator);
            var sprocResult = sqlProtocol.Execute(storedProcOp);

            int shouldHandle = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.ShouldHandle)].GetValueOfType <int>();
            int isBlocked    = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.IsBlocked)].GetValueOfType <int>();

            if (shouldHandle != 1)
            {
                return(new TryHandleRecordResult(null, isBlocked == 1));
            }

            long   internalRecordId            = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.InternalRecordId)].GetValueOfType <long>();
            int    serializerRepresentationId  = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.SerializerRepresentationId)].GetValueOfType <int>();
            int    identifierTypeWithVersionId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.IdentifierTypeWithVersionId)].GetValueOfType <int>();
            int    objectTypeWithVersionId     = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.ObjectTypeWithVersionId)].GetValueOfType <int>();
            string stringSerializedId          = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.StringSerializedId)].GetValueOfType <string>();
            string stringSerializedObject      = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.StringSerializedObject)].GetValueOfType <string>();

            byte[]   binarySerializedObject = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.BinarySerializedObject)].GetValueOfType <byte[]>();
            DateTime recordTimestampRaw     = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.RecordDateTime)].GetValueOfType <DateTime>();
            DateTime?objectTimestampRaw     = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.ObjectDateTime)].GetValueOfType <DateTime?>();
            string   recordTagIdsCsv        = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.TagIdsCsv)].GetValueOfType <string>();

            var identifiedSerializerRepresentation = this.GetSerializerRepresentationFromId(sqlServerLocator, serializerRepresentationId);
            var identifierType = this.GetTypeById(sqlServerLocator, identifierTypeWithVersionId, true);
            var objectType     = this.GetTypeById(sqlServerLocator, objectTypeWithVersionId, true);
            var tagIds         = recordTagIdsCsv?.FromCsv().Select(_ => long.Parse(_, CultureInfo.InvariantCulture)).ToList();
            var tags           = tagIds == null ? null : this.GetTagsByIds(sqlServerLocator, tagIds);

            var recordTimestamp = recordTimestampRaw.ToUtc();

            var objectTimestamp = objectTimestampRaw == null ? (DateTime?)null : objectTimestampRaw.ToUtc();

            var metadata = new StreamRecordMetadata(
                stringSerializedId,
                identifiedSerializerRepresentation.SerializerRepresentation,
                identifierType,
                objectType,
                tags,
                recordTimestamp,
                objectTimestamp);

            DescribedSerializationBase payload;

            if (operation.StreamRecordItemsToInclude == StreamRecordItemsToInclude.MetadataAndPayload)
            {
                switch (identifiedSerializerRepresentation.SerializationFormat)
                {
                case SerializationFormat.Binary:
                    payload = new BinaryDescribedSerialization(
                        objectType.WithVersion,
                        identifiedSerializerRepresentation.SerializerRepresentation,
                        binarySerializedObject);
                    break;

                case SerializationFormat.String:
                    payload = new StringDescribedSerialization(
                        objectType.WithVersion,
                        identifiedSerializerRepresentation.SerializerRepresentation,
                        stringSerializedObject);
                    break;

                default:
                    throw new NotSupportedException(
                              Invariant($"{nameof(SerializationFormat)} {identifiedSerializerRepresentation.SerializationFormat} is not supported."));
                }
            }
            else
            {
                payload = new NullDescribedSerialization(metadata.TypeRepresentationOfObject.WithVersion, metadata.SerializerRepresentation);
            }

            var record = new StreamRecord(internalRecordId, metadata, payload);
            var result = new TryHandleRecordResult(record);

            return(result);
        }
        public override StreamRecord Execute(
            StandardGetLatestRecordOp operation)
        {
            operation.MustForArg(nameof(operation)).NotBeNull();

            var sqlServerLocator      = this.TryGetLocator(operation);
            var convertedRecordFilter = this.ConvertRecordFilter(operation.RecordFilter, sqlServerLocator);

            var storedProcOp = StreamSchema.Sprocs.GetLatestRecord.BuildExecuteStoredProcedureOp(
                this.Name,
                convertedRecordFilter,
                operation.StreamRecordItemsToInclude);

            var sqlProtocol = this.BuildSqlOperationsProtocol(sqlServerLocator);
            var sprocResult = sqlProtocol.Execute(storedProcOp);

            long internalRecordId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.InternalRecordId)].GetValueOfType <long>();

            if (internalRecordId == StreamSchema.Tables.Record.NullId)
            {
                switch (operation.RecordNotFoundStrategy)
                {
                case RecordNotFoundStrategy.ReturnDefault:
                    return(null);

                case RecordNotFoundStrategy.Throw:
                    throw new InvalidOperationException(
                              Invariant(
                                  $"Expected stream {this.StreamRepresentation} to contain a matching record for {operation}, none was found and {nameof(operation.RecordNotFoundStrategy)} is '{operation.RecordNotFoundStrategy}'."));

                default:
                    throw new NotSupportedException(
                              Invariant($"{nameof(RecordNotFoundStrategy)} {operation.RecordNotFoundStrategy} is not supported."));
                }
            }

            int    serializerRepresentationId  = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.SerializerRepresentationId)].GetValueOfType <int>();
            int    identifierTypeWithVersionId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.IdentifierTypeWithVersionId)].GetValueOfType <int>();
            int    objectTypeWithVersionId     = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.ObjectTypeWithVersionId)].GetValueOfType <int>();
            string stringSerializedId          = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.StringSerializedId)].GetValueOfType <string>();
            string stringSerializedObject      = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.StringSerializedObject)].GetValueOfType <string>();

            byte[]   binarySerializedObject = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.BinarySerializedObject)].GetValueOfType <byte[]>();
            DateTime recordTimestampRaw     = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.RecordDateTime)].GetValueOfType <DateTime>();
            DateTime?objectTimestampRaw     = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.ObjectDateTime)].GetValueOfType <DateTime?>();
            string   tagIdsCsv = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.TagIdsCsv)].GetValueOfType <string>();

            var identifiedSerializerRepresentation = this.GetSerializerRepresentationFromId(sqlServerLocator, serializerRepresentationId);
            var identifierType = this.GetTypeById(sqlServerLocator, identifierTypeWithVersionId, true);
            var objectType     = this.GetTypeById(sqlServerLocator, objectTypeWithVersionId, true);
            var tagIds         = tagIdsCsv?.FromCsv().Select(_ => long.Parse(_, CultureInfo.InvariantCulture)).ToList();
            var tags           = tagIds == null ? null : this.GetTagsByIds(sqlServerLocator, tagIds);

            var recordTimestamp = recordTimestampRaw.ToUtc();

            var objectTimestamp = objectTimestampRaw == null ? (DateTime?)null : objectTimestampRaw.ToUtc();

            var metadata = new StreamRecordMetadata(
                stringSerializedId,
                identifiedSerializerRepresentation.SerializerRepresentation,
                identifierType,
                objectType,
                tags,
                recordTimestamp,
                objectTimestamp);

            DescribedSerializationBase payload;

            if (operation.StreamRecordItemsToInclude == StreamRecordItemsToInclude.MetadataAndPayload)
            {
                switch (identifiedSerializerRepresentation.SerializationFormat)
                {
                case SerializationFormat.Binary:
                    payload = new BinaryDescribedSerialization(
                        objectType.WithVersion,
                        identifiedSerializerRepresentation.SerializerRepresentation,
                        binarySerializedObject);
                    break;

                case SerializationFormat.String:
                    payload = new StringDescribedSerialization(
                        objectType.WithVersion,
                        identifiedSerializerRepresentation.SerializerRepresentation,
                        stringSerializedObject);
                    break;

                default:
                    throw new NotSupportedException(
                              Invariant($"{nameof(SerializationFormat)} {identifiedSerializerRepresentation.SerializationFormat} is not supported."));
                }
            }
            else
            {
                payload = new NullDescribedSerialization(metadata.TypeRepresentationOfObject.WithVersion, metadata.SerializerRepresentation);
            }

            var result = new StreamRecord(internalRecordId, metadata, payload);

            return(result);
        }