Esempio n. 1
0
        public async Task <ReminderTableData> ReadRows(GrainReference grainRef)
        {
            var keys = await GetAllKeysFromGrainReferenceAsync(grainRef.ToKeyString());

            var values = (await Database.StringGetAsync(keys))
                         .Select(x => JsonSerializer.Deserialize <RedisReminderTableData>(x))
                         .Select(y => new ReminderEntry
            {
                GrainRef     = _converter.GetGrainFromKeyString(y.GrainId),
                Period       = TimeSpan.FromMilliseconds(y.Period),
                ReminderName = y.ReminderName,
                ETag         = y.Version.ToString(),
                StartAt      = y.StartTime,
            });

            return(new ReminderTableData(values));
        }
        internal async Task ReadEdgeStateAsync(GrainReference grainReference, EdgeState edgeState)
        {
            var graphElementGrain = grainReference.AsReference <IGraphElementGrain>();

            var readExpression = $"g.E('{grainReference.ToKeyString()}')";

            var feedOptions = new FeedOptions
            {
                MaxItemCount = 1,
                PartitionKey = new PartitionKey(graphElementGrain.GetGraphPartition())
            };

            var readQuery = client.CreateGremlinQuery <CosmosDbEdge>(graph, readExpression, feedOptions, GraphSONMode.Normal);
            var response  = await readQuery.ExecuteNextAsync <CosmosDbEdge>();

            log.Info($"CosmosDB: Read Edge State: Request Charge: {response.RequestCharge}");

            var edge = response.FirstOrDefault();

            if (edge == null)
            {
                return;
            }

            edgeState.Persisted = true;

            var inV  = grainReferenceConverter.GetGrainFromKeyString(edge.InVertexId.ToString());
            var outV = grainReferenceConverter.GetGrainFromKeyString(edge.OutVertexId.ToString());

            inV.BindGrainReference(grainFactory);
            outV.BindGrainReference(grainFactory);

            edgeState.SetInVertex(inV.AsReference <IVertex>());
            edgeState.SetOutVertex(outV.AsReference <IVertex>());

            foreach (var property in edge.GetProperties())
            {
                if (property.Key[0] == '@' || property.Key == "partition")
                {
                    continue;
                }

                edgeState[property.Key] = property.Value.ToString();
            }
        }
 public ReminderEntry ToEntry(IGrainReferenceConverter grainReferenceConverter)
 {
     return(new ReminderEntry
     {
         ETag = Etag,
         GrainRef = grainReferenceConverter.GetGrainFromKeyString(GrainId),
         Period = Period,
         ReminderName = ReminderName,
         StartAt = StartAt
     });
 }
        private ReminderEntry ParseRecord(Record record)
        {
            var entry = new ReminderEntry();

            entry.ETag         = record.generation.ToString();
            entry.GrainRef     = _grainReferenceConverter.GetGrainFromKeyString((string)record.bins["grainref"]);
            entry.Period       = new TimeSpan((long)record.bins["period"]);
            entry.ReminderName = (string)record.bins["name"];
            entry.StartAt      = DateTime.FromBinary((long)record.bins["startat"]);
            return(entry);
        }
Esempio n. 5
0
        protected override TInterface DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var key   = context.Reader.ReadString();
            var refer = _grainReferenceConverter.GetGrainFromKeyString(key);

            if (refer != null)
            {
                refer.BindGrainReference(_grainFactory);
                return(refer.AsReference <TInterface>());
            }

            return(null);
        }
        private ReminderEntry ConvertToEntry(string reminderValue)
        {
            string[] segments = JsonConvert.DeserializeObject <string[]>(reminderValue);

            return(new ReminderEntry
            {
                GrainRef = _grainReferenceConverter.GetGrainFromKeyString(segments[1]),
                ReminderName = segments[2],
                ETag = segments[3],
                StartAt = DateTime.Parse(segments[4], null, DateTimeStyles.RoundtripKind),
                Period = TimeSpan.Parse(segments[5]),
            });
        }
Esempio n. 7
0
        /// <summary>
        /// Maps the specified converter.
        /// </summary>
        /// <param name="converter">The converter.</param>
        /// <param name="src">The source.</param>
        /// <param name="dst">The DST.</param>
        /// <returns></returns>
        internal static ReminderEntry Map(
            IGrainReferenceConverter converter,
            OrleansEFReminder src,
            ReminderEntry dst = null
            )
        {
            dst = dst ?? new ReminderEntry();

            dst.ETag         = src.ETag;
            dst.GrainRef     = converter.GetGrainFromKeyString(src.GrainId);
            dst.Period       = TimeSpan.FromMilliseconds(src.Period);
            dst.ReminderName = src.ReminderName;
            dst.StartAt      = src.StartTime;

            return(dst);
        }
Esempio n. 8
0
            internal static ReminderEntry GetReminderEntry(IDataRecord record, IGrainReferenceConverter grainReferenceConverter)
            {
                //Having non-null field, GrainId, means with the query filter options, an entry was found.
                string grainId = record.GetValueOrDefault <string>(nameof(Columns.GrainId));

                if (grainId != null)
                {
                    return(new ReminderEntry
                    {
                        GrainRef = grainReferenceConverter.GetGrainFromKeyString(grainId),
                        ReminderName = record.GetValue <string>(nameof(Columns.ReminderName)),
                        StartAt = record.GetValue <DateTime>(nameof(Columns.StartTime)),
                        Period = TimeSpan.FromMilliseconds(record.GetValue <int>(nameof(Columns.Period))),
                        ETag = GetVersion(record).ToString()
                    });
                }
                return(null);
            }
Esempio n. 9
0
            internal static ReminderEntry GetReminderEntry(IDataRecord record, IGrainReferenceConverter grainReferenceConverter)
            {
                //Having non-null field, GrainId, means with the query filter options, an entry was found.
                string grainId = record.GetValueOrDefault <string>(nameof(Columns.GrainId));

                if (grainId != null)
                {
                    return(new ReminderEntry
                    {
                        GrainRef = grainReferenceConverter.GetGrainFromKeyString(grainId),
                        ReminderName = record.GetValue <string>(nameof(Columns.ReminderName)),
                        StartAt = record.GetValue <DateTime>(nameof(Columns.StartTime)),

                        //Use the GetInt64 method instead of the generic GetValue<TValue> version to retrieve the value from the data record
                        //GetValue<int> causes an InvalidCastException with oracle data provider. See https://github.com/dotnet/orleans/issues/3561
                        Period = TimeSpan.FromMilliseconds(record.GetInt64(nameof(Columns.Period))),
                        ETag = GetVersion(record).ToString()
                    });
                }
                return(null);
            }
        public static GrainReference FromByteArray(ArraySegment <byte> Data, IGrainReferenceConverter GrainReferenceConverter)
        {
            if (Data.Count == 0)
            {
                return(null); // I actually think this never happens, because Bond simply leaves fields with default values out
            }
            var Ref = (SerializationGrainReference)BondSerializer.Deserialize(typeof(SerializationGrainReference), new ArraySegmentReaderStream(Data));

            var s = new StringBuilder();

            s.AppendFormat("{0:x16}{1:x16}{2:x16}", Ref.IdN0, Ref.IdN1, Ref.TypeCodeData);
            if (Ref.KeyExt != null)
            {
                s.Append("+");
                s.Append(Ref.KeyExt);
            }
            string IdStr = s.ToString();

            string KeyString;

            if (Ref.ObserverReferenceId != null)
            {
                KeyString = String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, IdStr, OBSERVER_ID_STR, Ref.ObserverReferenceId.ToString());
            }
            else if (Ref.SystemTargetSiloAddress != null)
            {
                KeyString = String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, IdStr, SYSTEM_TARGET_STR, Ref.SystemTargetSiloAddress);
            }
            else if (Ref.GenericArgs != null)
            {
                KeyString = String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, IdStr, GENERIC_ARGUMENTS_STR, ConvertBackToGenericArgsString(Ref.GenericArgs));
            }
            else
            {
                KeyString = String.Format("{0}={1}", GRAIN_REFERENCE_STR, IdStr);
            }

            return(GrainReferenceConverter.GetGrainFromKeyString(KeyString));
        }
        public override GrainReference Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            if (context.Reader.CurrentBsonType == BsonType.Null)
            {
                context.Reader.ReadNull();
                return(null);
            }
            EnsureBsonTypeEquals(context.Reader, BsonType.Document);
            // The MongoDB document will look like
            // { "_t": "CodeGenGrainName", _v: { grain_interface: "Fully qualified type name", grain_key: "GrainReference=..."} }
            context.Reader.ReadStartDocument();
            context.Reader.FindElement("_v");
            context.Reader.ReadStartDocument();
            var interfaceName = context.Reader.ReadString(InterfaceNameField);
            var grainKey      = context.Reader.ReadString(KeyField);

            context.Reader.ReadEndDocument();
            context.Reader.ReadEndDocument();
            if (string.IsNullOrEmpty(interfaceName) || string.IsNullOrEmpty(grainKey))
            {
                throw new InvalidOperationException(
                          $"Expected ${InterfaceNameField} and ${KeyField} fields in the document. " +
                          $"Got ${InterfaceNameField}={interfaceName}, {KeyField}={grainKey}.");
            }
            var grainReference     = _grainReferenceConverter.GetGrainFromKeyString(grainKey);
            var grainInterfaceType = LookupGrainInterfaces(interfaceName, args.NominalType)
                                     .FirstOrDefault(x => x != null);

            if (grainInterfaceType == null)
            {
                throw new InvalidOperationException(
                          $"Failed to resolve grain interface type. Serialized type was: {interfaceName}.");
            }
            var deserialize    = DeserializationMethod.MakeGenericMethod(grainInterfaceType);
            var grainInterface = deserialize.Invoke(null, new object[] { grainReference });

            return((GrainReference)grainInterface);
        }
        internal async Task ReadVertexStateAsync(GrainReference grainReference, VertexState vertexState)
        {
            var readExpression    = $"g.V('{grainReference.ToKeyString()}')";
            var graphElementGrain = grainReference.AsReference <IGraphElementGrain>();

            var feedOptions = new FeedOptions
            {
                MaxItemCount = 1,
                PartitionKey = new PartitionKey(graphElementGrain.GetGraphPartition())
            };

            var readQuery = client.CreateGremlinQuery <CosmosDbVertex>(graph, readExpression, feedOptions, GraphSONMode.Normal);

            var response = await readQuery.ExecuteNextAsync <CosmosDbVertex>();

            log.Info($"CosmosDB: Read Vertex State: Request Charge: {response.RequestCharge}");

            var vertex = response.FirstOrDefault();

            if (vertex == null)
            {
                return;
            }

            vertexState.Persisted = true;

            foreach (var edge in vertex.GetInEdges())
            {
                var edgeReference = grainReferenceConverter.GetGrainFromKeyString(edge.Id.ToString());
                edgeReference.BindGrainReference(grainFactory);

                var vertexReference = grainReferenceConverter.GetGrainFromKeyString(edge.InVertexId.ToString());
                vertexReference.BindGrainReference(grainFactory);

                vertexState.AddInEdge(edgeReference.AsReference <IEdge>(), vertexReference.AsReference <IVertex>());
            }

            foreach (var edge in vertex.GetOutEdges())
            {
                var edgeReference = grainReferenceConverter.GetGrainFromKeyString(edge.Id.ToString());
                edgeReference.BindGrainReference(grainFactory);

                var vertexReference = grainReferenceConverter.GetGrainFromKeyString(edge.InVertexId.ToString());
                vertexReference.BindGrainReference(grainFactory);

                vertexState.AddOutEdge(edgeReference.AsReference <IEdge>(), vertexReference.AsReference <IVertex>());
            }

            foreach (var property in vertex.GetVertexProperties())
            {
                if (property.Key[0] == '@' || property.Key == "partition")
                {
                    continue;
                }

                var vertexProperty = vertexState.SetProperty(property.Key, property.Value.ToString());

                try
                {
                    foreach (var subProperty in property.GetProperties())
                    {
                        if (subProperty.Key[0] == '@')
                        {
                            continue;
                        }

                        vertexProperty.SetMeta(subProperty.Key, subProperty.Value.ToString());
                    }
                }
                // BUG: The Microsoft.Azure.Graphs library throws an exception when enumerating over empty properties. How do we check or work around this?
                catch (NullReferenceException) { }
            }
        }
 public GrainReference GetGrain(byte[] key)
 {
     return(grainReferenceConverter.GetGrainFromKeyString(Encoding.UTF8.GetString(key)));
 }