예제 #1
0
        /// <summary>
        /// Compares this activity to other activity and returns list of changed properties.
        /// </summary>
        /// <param name="Other">Other activity to compare to.</param>
        /// <returns>Bit mask information about which properties are different.</returns>
        public ActivityChange CompareChangeTo(NeighborActivity Other)
        {
            ActivityChange res = base.CompareChangeTo(Other);

            if (!ByteArrayComparer.Equals(this.PrimaryServerId, Other.PrimaryServerId))
            {
                res |= ActivityChange.PrimaryServerId;
            }

            return(res);
        }
        /// <summary>
        /// Compares this activity to other activity and returns list of changed properties.
        /// </summary>
        /// <param name="Other">Other activity to compare to.</param>
        /// <returns>Bit mask information about which properties are different.</returns>
        public ActivityChange CompareChangeTo(ActivityBase Other)
        {
            ActivityChange res = ActivityChange.None;

            SemVer thisVersion  = new SemVer(this.Version);
            SemVer otherVersion = new SemVer(Other.Version);

            if (!thisVersion.Equals(otherVersion))
            {
                res |= ActivityChange.Version;
            }

            if (this.ActivityId != Other.ActivityId)
            {
                res |= ActivityChange.ActivityId;
            }

            if (!ByteArrayComparer.Equals(this.OwnerIdentityId, Other.OwnerIdentityId))
            {
                res |= ActivityChange.OwnerIdentityId;
            }

            if (!ByteArrayComparer.Equals(this.OwnerPublicKey, Other.OwnerPublicKey))
            {
                res |= ActivityChange.OwnerPublicKey;
            }

            if (!ByteArrayComparer.Equals(this.OwnerProfileServerId, Other.OwnerProfileServerId))
            {
                res |= ActivityChange.OwnerProfileServerId;
            }

            if (!ByteArrayComparer.Equals(this.OwnerProfileServerIpAddress, Other.OwnerProfileServerIpAddress))
            {
                res |= ActivityChange.OwnerProfileServerIpAddress;
            }

            if (this.OwnerProfileServerPrimaryPort != Other.OwnerProfileServerPrimaryPort)
            {
                res |= ActivityChange.OwnerProfileServerPrimaryPort;
            }

            if (this.Type != Other.Type)
            {
                res |= ActivityChange.Type;
            }

            if (this.LocationLatitude != Other.LocationLatitude)
            {
                res |= ActivityChange.LocationLatitude;
            }

            if (this.LocationLongitude != Other.LocationLongitude)
            {
                res |= ActivityChange.LocationLongitude;
            }

            if (this.PrecisionRadius != Other.PrecisionRadius)
            {
                res |= ActivityChange.PrecisionRadius;
            }

            if (this.StartTime != Other.StartTime)
            {
                res |= ActivityChange.StartTime;
            }

            if (this.ExpirationTime != Other.ExpirationTime)
            {
                res |= ActivityChange.ExpirationTime;
            }

            if (this.ExtraData != Other.ExtraData)
            {
                res |= ActivityChange.ExtraData;
            }

            return(res);
        }
예제 #3
0
        /// <summary>
        /// Updates an existing activity in the database. Then a new neighborhood action is created to propagate the changes to the neighborhood
        /// if this is required. If the update is rejected, the action is deleted from the database and this is propagated to the neighborhood.
        /// <para>Note that the change in activity is not propagated if the client sets no propagation flag in the request, or if only the activity
        /// expiration date or its location is changed.</para>
        /// </summary>
        /// <param name="UpdateRequest">Update request received from the client.</param>
        /// <param name="Signature">Signature of the updated activity data from the client.</param>
        /// <param name="OwnerIdentityId">Network ID of the client who requested the update.</param>
        /// <param name="CloserServerId">If the result is Status.ErrorRejected, this is filled with network identifier of a neighbor server that is closer to the target location.</param>
        /// <returns>Status.Ok if the function succeeds,
        /// Status.ErrorNotFound if the activity to update does not exist,
        /// Status.ErrorRejected if the update was rejected and the client should migrate the activity to closest proximity server,
        /// Status.ErrorInvalidValue if the update attempted to change activity's type,
        /// Status.ErrorInternal otherwise.</returns>
        public async Task <Status> UpdateAndPropagateAsync(UpdateActivityRequest UpdateRequest, byte[] Signature, byte[] OwnerIdentityId, StrongBox <byte[]> CloserServerId)
        {
            log.Trace("(UpdateRequest.Activity.Id:{0},OwnerIdentityId:'{1}')", UpdateRequest.Activity.Id, OwnerIdentityId.ToHex());

            Status res = Status.ErrorInternal;

            bool success = false;
            bool signalNeighborhoodAction           = false;
            bool migrateActivity                    = false;
            ActivityInformation activityInformation = UpdateRequest.Activity;

            DatabaseLock[] lockObjects = new DatabaseLock[] { UnitOfWork.PrimaryActivityLock, UnitOfWork.FollowerLock, UnitOfWork.NeighborhoodActionLock };
            using (IDbContextTransaction transaction = await unitOfWork.BeginTransactionWithLockAsync(lockObjects))
            {
                try
                {
                    PrimaryActivity existingActivity = (await GetAsync(a => (a.ActivityId == activityInformation.Id) && (a.OwnerIdentityId == OwnerIdentityId))).FirstOrDefault();
                    if (existingActivity != null)
                    {
                        // First, we check whether the activity should be migrated to closer proximity server.
                        GpsLocation oldLocation     = existingActivity.GetLocation();
                        GpsLocation newLocation     = new GpsLocation(activityInformation.Latitude, activityInformation.Longitude);
                        bool        locationChanged = !oldLocation.Equals(newLocation);

                        bool error = false;
                        if (locationChanged)
                        {
                            List <byte[]> ignoreServerIds = new List <byte[]>(UpdateRequest.IgnoreServerIds.Select(i => i.ToByteArray()));
                            if (!await unitOfWork.NeighborRepository.IsServerNearestToLocationAsync(newLocation, ignoreServerIds, CloserServerId, ProxMessageBuilder.ActivityMigrationDistanceTolerance))
                            {
                                if (CloserServerId.Value != null)
                                {
                                    migrateActivity = true;
                                    log.Debug("Activity's new location is outside the reach of this proximity server, the activity will be deleted from the database.");
                                }
                                else
                                {
                                    error = true;
                                }
                            }
                            // else No migration needed
                        }

                        if (!error)
                        {
                            // If it should not be migrated, we update the activity in our database.
                            if (!migrateActivity)
                            {
                                SignedActivityInformation signedActivityInformation = new SignedActivityInformation()
                                {
                                    Activity  = activityInformation,
                                    Signature = ProtocolHelper.ByteArrayToByteString(Signature)
                                };

                                PrimaryActivity updatedActivity = ActivityBase.FromSignedActivityInformation <PrimaryActivity>(signedActivityInformation);
                                ActivityChange  changes         = existingActivity.CompareChangeTo(updatedActivity);

                                if ((changes & ActivityChange.Type) == 0)
                                {
                                    bool propagateChange = false;
                                    if (!UpdateRequest.NoPropagation)
                                    {
                                        // If only changes in the activity are related to location or expiration time, the activity update is not propagated to the neighborhood.
                                        propagateChange = (changes & ~(ActivityChange.LocationLatitude | ActivityChange.LocationLongitude | ActivityChange.PrecisionRadius | ActivityChange.ExpirationTime)) != 0;
                                    }

                                    existingActivity.CopyFromSignedActivityInformation(signedActivityInformation);

                                    Update(existingActivity);

                                    if (propagateChange)
                                    {
                                        // The activity has to be propagated to all our followers we create database actions that will be processed by dedicated thread.
                                        signalNeighborhoodAction = await unitOfWork.NeighborhoodActionRepository.AddActivityFollowerActionsAsync(NeighborhoodActionType.ChangeActivity, existingActivity.ActivityId, existingActivity.OwnerIdentityId);
                                    }
                                    else
                                    {
                                        log.Trace("Change of activity ID {0}, owner identity ID '{1}' won't be propagated to neighborhood.", existingActivity.ActivityId, existingActivity.OwnerIdentityId.ToHex());
                                    }

                                    await unitOfWork.SaveThrowAsync();

                                    transaction.Commit();
                                    success = true;
                                }
                                else
                                {
                                    log.Debug("Activity ID {0}, owner identity ID '{1}' attempt to change type.", activityInformation.Id, OwnerIdentityId.ToHex());
                                    res = Status.ErrorInvalidValue;
                                }
                            }
                            // else this is handled below separately, out of locked section
                        }
                        // else Internal error
                    }
                    else
                    {
                        log.Debug("Activity ID {0}, owner identity ID '{1}' does not exist.", activityInformation.Id, OwnerIdentityId.ToHex());
                        res = Status.ErrorNotFound;
                    }
                }
                catch (Exception e)
                {
                    log.Error("Exception occurred: {0}", e.ToString());
                }

                if (!success)
                {
                    log.Warn("Rolling back transaction.");
                    unitOfWork.SafeTransactionRollback(transaction);
                }

                unitOfWork.ReleaseLock(lockObjects);
            }


            if (migrateActivity)
            {
                // If activity should be migrated, we delete it from our database and inform our neighbors.
                StrongBox <bool> notFound = new StrongBox <bool>(false);
                if (await DeleteAndPropagateAsync(activityInformation.Id, OwnerIdentityId, notFound))
                {
                    if (!notFound.Value)
                    {
                        // The activity was deleted from the database and this change will be propagated to the neighborhood.
                        log.Debug("Update rejected, activity ID {0}, owner identity ID '{1}' deleted.", activityInformation.Id, OwnerIdentityId.ToHex());
                        res = Status.ErrorRejected;
                    }
                    else
                    {
                        // Activity of given ID not found among activities created by the client.
                        res = Status.ErrorNotFound;
                    }
                }
            }

            if (success)
            {
                // Send signal to neighborhood action processor to process the new series of actions.
                if (signalNeighborhoodAction)
                {
                    Network.NeighborhoodActionProcessor neighborhoodActionProcessor = (Network.NeighborhoodActionProcessor)Base.ComponentDictionary[Network.NeighborhoodActionProcessor.ComponentName];
                    neighborhoodActionProcessor.Signal();
                }

                res = Status.Ok;
            }


            log.Trace("(-):{0}", res);
            return(res);
        }