コード例 #1
0
ファイル: ConnectionState.cs プロジェクト: thoemmi/ravendb
        public void Send(DocumentChangeNotification documentChangeNotification)
        {
            var value = new { Value = documentChangeNotification, Type = "DocumentChangeNotification" };

            if (watchAllDocuments > 0)
            {
                Enqueue(value);
                return;
            }

            if (matchingDocuments.Contains(documentChangeNotification.Id))
            {
                Enqueue(value);
                return;
            }

            var hasPrefix = matchingDocumentPrefixes.Any(x => documentChangeNotification.Id.StartsWith(x, StringComparison.InvariantCultureIgnoreCase));

            if (hasPrefix == false)
            {
                return;
            }

            Enqueue(value);
        }
コード例 #2
0
        void HandleIDeviceMessages(DocumentChangeNotification change)
        {
            switch (change.Type)
            {
            case DocumentChangeTypes.Delete:
            {
                OnDeviceRemoved(new DeviceRemovedEventArgs(change.Id));
            }
            break;

            case DocumentChangeTypes.Put:
            {
                using (var session = _documentStore.OpenSession(DatabaseName))
                {
                    var device = session.Load <IDevice>(change.Id);
                    if (devices.ContainsKey(change.Id))
                    {
                        OnDeviceChanged(new DeviceEventArgs(device));
                    }
                    else
                    {
                        OnDeviceAdded(new DeviceEventArgs(device));
                    }
                }
            }
            break;

            default:
                Console.WriteLine(change.Type.ToString() + " received.");
                break;
            }
        }
コード例 #3
0
 void HandleUnknownMessage(DocumentChangeNotification change)
 {
     if (change.Type == DocumentChangeTypes.Delete)
     {
         if (!LocalCaching ? updatesInProgress.ContainsKey(change.Id) : activitiesCache.ContainsKey(change.Id))
         {
             OnActivityRemoved(new ActivityRemovedEventArgs(change.Id));
         }
         if (!LocalCaching ? updatesInProgress.ContainsKey(change.Id) : usersCache.ContainsKey(change.Id))
         {
             OnUserRemoved(new UserRemovedEventArgs(change.Id));     //special as they are not kept in store, but in memory
         }
         if (devices.ContainsKey(change.Id))
         {
             OnDeviceRemoved(new DeviceRemovedEventArgs(change.Id));
         }
         if (!LocalCaching ? updatesInProgress.ContainsKey(change.Id) : resourcesCache.ContainsKey(change.Id))
         {
             OnResourceRemoved(new ResourceRemovedEventArgs(change.Id));
         }
         if (!LocalCaching ? updatesInProgress.ContainsKey(change.Id) : notificationsCache.ContainsKey(change.Id))
         {
             OnNotificationRemoved(new NotificationRemovedEventArgs(change.Id));
         }
     }
 }
コード例 #4
0
        private void OnSystemDocumentChange(DocumentChangeNotification notification)
        {
            if (!notification.Key.Equals(Constants.Replication.DocumentReplicationConfiguration, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (_log.IsInfoEnabled)
            {
                _log.Info("System document change detected. Starting and stopping outgoing replication threads.");
            }

            //prevent reconnecting to a destination that we shouldn't in case we have flaky network
            _reconnectQueue.Clear();

            foreach (var instance in _outgoing)
            {
                instance.Failed -= OnOutgoingSendingFailed;
                instance.SuccessfulTwoWaysCommunication -= OnOutgoingSendingSucceeded;
                instance.Dispose();
            }

            _outgoing.Clear();
            _outgoingFailureInfo.Clear();

            InitializeOutgoingReplications();

            InitializeResolvers();

            if (_log.IsInfoEnabled)
            {
                _log.Info($"Replication configuration was changed: {notification.Key}");
            }
        }
コード例 #5
0
 public void Send(DocumentChangeNotification documentChangeNotification)
 {
     OnDocumentChangeNotification(this, documentChangeNotification);
     foreach (var connectionState in connections)
     {
         connectionState.Value.Send(documentChangeNotification);
     }
 }
コード例 #6
0
        public void Send(DocumentChangeNotification documentChangeNotification)
        {
            var onOnDocumentChangeNotification = OnDocumentChangeNotification;

            if (onOnDocumentChangeNotification != null)
            {
                onOnDocumentChangeNotification(documentChangeNotification);
            }
        }
コード例 #7
0
        protected override void HandleDocumentChange(DocumentChangeNotification notification)
        {
            if (HandleAllDocs == false && Collections.Contains(notification.CollectionName) == false && _referencedCollections.Contains(notification.CollectionName) == false)
            {
                return;
            }

            _mre.Set();
        }
コード例 #8
0
        public void Should_get_independent_notification_subscriptions()
        {
            using (var store = NewRemoteDocumentStore())
            {
                using (IDocumentSession session = store.OpenSession())
                {
                    session.Store(new TestDocument {
                        Name = "Name"
                    });
                    session.SaveChanges();
                }

                DocumentChangeNotification notification1 = null;
                var         resetEvent1   = new ManualResetEvent(false);
                IDisposable subscription1 = store.Changes()
                                            .Task.Result
                                            .ForDocument("TestDocuments/1").Task.Result
                                            .Subscribe(d =>
                {
                    notification1 = d;
                    resetEvent1.Set();
                });
                using (IDocumentSession session = store.OpenSession())
                {
                    var doc = session.Load <TestDocument>("TestDocuments/1");
                    doc.Name = "NewName1";
                    session.SaveChanges();
                }

                Assert.True(resetEvent1.WaitOne(5000));
                Assert.NotNull(notification1);

                subscription1.Dispose();

                DocumentChangeNotification notification2 = null;
                var         resetEvent2   = new ManualResetEvent(false);
                IDisposable subscription2 = store.Changes().Task.Result
                                            .ForDocument("TestDocuments/1").Task.Result
                                            .Subscribe(d =>
                {
                    notification2 = d;
                    resetEvent2.Set();
                });

                using (IDocumentSession session = store.OpenSession())
                {
                    var doc = session.Load <TestDocument>("TestDocuments/1");
                    doc.Name = "NewName2";
                    session.SaveChanges();
                }

                Assert.True(resetEvent2.WaitOne(500));
                Assert.NotNull(notification2);

                subscription2.Dispose();
            }
        }
コード例 #9
0
 private void OnDocumentChange(DocumentChangeNotification notification)
 {
     if (IncomingReplicationHandler.IsIncomingReplicationThread &&
         notification.Type != DocumentChangeTypes.DeleteOnTombstoneReplication)
     {
         return;
     }
     _waitForChanges.Set();
 }
コード例 #10
0
        public void RaiseNotifications(DocumentChangeNotification documentChangeNotification)
        {
            OnDocumentChange?.Invoke(documentChangeNotification);

            foreach (var connection in Connections)
            {
                connection.Value.SendDocumentChanges(documentChangeNotification);
            }
        }
コード例 #11
0
        public void RaiseNotifications(DocumentChangeNotification obj, RavenJObject metadata)
        {
            Database.TransportState.Send(obj);
            var onDocumentChange = OnDocumentChange;

            if (onDocumentChange != null)
            {
                onDocumentChange(Database, obj, metadata);
            }
        }
コード例 #12
0
        private static void SendNotification(DocumentChangeNotification notification, string key, Action action)
        {
            if (notification.Id == null)
            {
                return;
            }

            if (string.Equals(key, notification.Id, StringComparison.OrdinalIgnoreCase))
            {
                action();
            }
        }
コード例 #13
0
ファイル: ConnectionState.cs プロジェクト: xinix00/ravendb
        public void Send(DocumentChangeNotification documentChangeNotification)
        {
            var value = new { Value = documentChangeNotification, Type = "DocumentChangeNotification" };

            if (watchAllDocuments > 0)
            {
                Enqueue(value);
                return;
            }

            if (documentChangeNotification.Id != null && matchingDocuments.Contains(documentChangeNotification.Id))
            {
                Enqueue(value);
                return;
            }

            var hasPrefix = documentChangeNotification.Id != null && matchingDocumentPrefixes
                            .Any(x => documentChangeNotification.Id.StartsWith(x, StringComparison.InvariantCultureIgnoreCase));

            if (hasPrefix)
            {
                Enqueue(value);
                return;
            }

            var hasCollection = documentChangeNotification.CollectionName != null && matchingDocumentsInCollection
                                .Any(x => string.Equals(x, documentChangeNotification.CollectionName, StringComparison.InvariantCultureIgnoreCase));

            if (hasCollection)
            {
                Enqueue(value);
                return;
            }

            var hasType = documentChangeNotification.TypeName != null && matchingDocumentsOfType
                          .Any(x => string.Equals(x, documentChangeNotification.TypeName, StringComparison.InvariantCultureIgnoreCase));

            if (hasType)
            {
                Enqueue(value);
                return;
            }

            if (documentChangeNotification.Id != null || documentChangeNotification.CollectionName != null || documentChangeNotification.TypeName != null)
            {
                return;
            }

            Enqueue(value);
        }
コード例 #14
0
        private bool DocumentChangedByOtherUser(DocumentChangeNotification change)
        {
            if (_savesCount == 0)
            {
                return(true);
            }
            if (change.Etag.Restarts != _localEtag.Restarts)
            {
                return(true);
            }

            var numberOfServerChanges = change.Etag.Changes - _localEtag.Changes;

            return(numberOfServerChanges > _savesCount);
        }
コード例 #15
0
 private void HandleChangeNotification(DocumentChangeNotification notification)
 {
     if (notification.Name.Equals(DocumentKey, StringComparison.InvariantCulture))
     {
         if (notification.Type == DocumentChangeTypes.Put && notification.Etag != Etag)
         {
             ApplicationModel.Current.AddNotification(
                 new Notification("Document " + Key + " was changed on the server"));
         }
         else if (notification.Type == DocumentChangeTypes.Delete)
         {
             ApplicationModel.Current.AddNotification(
                 new Notification("Document " + Key + " was deleted on the server"));
         }
     }
 }
コード例 #16
0
        public void SendDocumentChanges(DocumentChangeNotification notification)
        {
            if (_watchAllDocuments > 0)
            {
                Send(notification);
                return;
            }

            if (notification.Key != null && _matchingDocuments.Contains(notification.Key))
            {
                Send(notification);
                return;
            }

            var hasPrefix = notification.Key != null && _matchingDocumentPrefixes
                            .Any(x => notification.Key.StartsWith(x, StringComparison.OrdinalIgnoreCase));

            if (hasPrefix)
            {
                Send(notification);
                return;
            }

            var hasCollection = notification.CollectionName != null && _matchingDocumentsInCollection
                                .Any(x => string.Equals(x, notification.CollectionName, StringComparison.OrdinalIgnoreCase));

            if (hasCollection)
            {
                Send(notification);
                return;
            }

            var hasType = notification.TypeName != null && _matchingDocumentsOfType
                          .Any(x => string.Equals(x, notification.TypeName, StringComparison.OrdinalIgnoreCase));

            if (hasType)
            {
                Send(notification);
                return;
            }

            if (notification.Key == null && notification.CollectionName == null && notification.TypeName == null)
            {
                Send(notification);
            }
        }
コード例 #17
0
        private void DocumentChangedOnServer(DocumentChangeNotification change)
        {
            var shouldRefresh = MessageBox.Show(
                "Document was changed on the server. Would like to refresh?",
                "Alert", MessageBoxButtons.YesNo
                ) == DialogResult.Yes;

            if (shouldRefresh)
            {
                _session.Advanced.Refresh(_category);
                this.Invoke((MethodInvoker) delegate
                {
                    NameTextbox.Text        = _category.Name;
                    DescriptionTextbox.Text = _category.Description;
                });
            }
        }
コード例 #18
0
        private void OnDocumentChange(DocumentDatabase db, DocumentChangeNotification notification, RavenJObject doc)
        {
            var docId = notification.Id;

            if (docId == null)
            {
                return;
            }

            if (docId.StartsWith(Constants.IndexReplacePrefix, StringComparison.OrdinalIgnoreCase) == false)
            {
                return;
            }

            if (notification.Type != DocumentChangeTypes.Put)
            {
                return;
            }

            var replaceIndexName = docId.Substring(Constants.IndexReplacePrefix.Length);
            var instance         = Database.IndexStorage.GetIndexInstance(replaceIndexName);

            if (instance == null)
            {
                return;
            }

            var indexDefinition = Database.Indexes.GetIndexDefinition(replaceIndexName);

            if (indexDefinition == null)
            {
                return;
            }

            var indexToAdd = new IndexToAdd
            {
                Name       = replaceIndexName,
                Definition = indexDefinition,
                Priority   = instance.Priority,
            };

            SetIndexReplaceInfo(replaceIndexName, indexToAdd);

            StartReplicatingSideBySideIndexAsync(indexToAdd);
        }
コード例 #19
0
        private void HandleSystemDocumentChange(DocumentChangeNotification notification)
        {
            if (ShouldReloadConfiguration(notification.Key))
            {
                foreach (var replication in Replications)
                {
                    replication.Dispose();
                }

                Replications.Clear();
                LoadConfigurations();

                if (_logger.IsInfoEnabled)
                {
                    _logger.Info($"Replication configuration was changed: {notification.Key}");
                }
            }
        }
コード例 #20
0
        void HandleIUserMessages(DocumentChangeNotification change)
        {
            switch (change.Type)
            {
            case DocumentChangeTypes.Delete:
            {
                OnUserRemoved(new UserRemovedEventArgs(change.Id));
            }
            break;

            case DocumentChangeTypes.Put:
            {
                using (var session = _documentStore.OpenSession(DatabaseName))
                {
                    var user = session.Load <IUser>(change.Id);

                    if (!LocalCaching ? updatesInProgress.ContainsKey(change.Id) : usersCache.ContainsKey(change.Id))
                    {
                        OnUserChanged(new UserEventArgs(user));
                    }
                    else
                    {
                        OnUserAdded(new UserEventArgs(user));
                    }

                    if (!LocalCaching)
                    {
                        updatesInProgress.TryRemove(change.Id, out dump);
                    }
                }
            }
            break;

            default:
                Console.WriteLine(change.Type.ToString() + " received.");
                break;
            }
        }
コード例 #21
0
        void HandleIResourceMessages(DocumentChangeNotification change)
        {
            switch (change.Type)
            {
            case DocumentChangeTypes.Delete:
            {
                OnResourceRemoved(new ResourceRemovedEventArgs(change.Id));
            }
            break;

            case DocumentChangeTypes.Put:
            {
                using (var session = _documentStore.OpenSession("activitysystem"))
                {
                    var resource = session.Load <IResource>(change.Id);
                    if (!LocalCaching ? updatesInProgress.ContainsKey(change.Id) : resourcesCache.ContainsKey(change.Id))
                    {
                        OnResourceChanged(new ResourceEventArgs(resource));
                    }
                    else
                    {
                        OnResourceAdded(new ResourceEventArgs(resource));
                    }

                    if (!LocalCaching)
                    {
                        updatesInProgress.TryRemove(change.Id, out dump);
                    }
                }
            }
            break;

            default:
                Console.WriteLine(change.Type.ToString() + " received.");
                break;
            }
        }
コード例 #22
0
        private void Send(DocumentChangeNotification notification)
        {
            var value = new DynamicJsonValue
            {
                ["Type"]  = "DocumentChangeNotification",
                ["Value"] = new DynamicJsonValue
                {
                    [nameof(DocumentChangeNotification.Type)]           = notification.Type.ToString(),
                    [nameof(DocumentChangeNotification.Key)]            = notification.Key,
                    [nameof(DocumentChangeNotification.CollectionName)] = notification.CollectionName,
                    [nameof(DocumentChangeNotification.TypeName)]       = notification.TypeName,
                    [nameof(DocumentChangeNotification.Etag)]           = notification.Etag,
                },
            };

            if (_disposeToken.IsCancellationRequested == false)
            {
                _sendQueue.Enqueue(new NotificationValue
                {
                    ValueToSend = value,
                    AllowSkip   = true
                });
            }
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: kijanawoodard/RavenConf
            public void Work(DocumentChangeNotification change)
            {
                if (change.Type != DocumentChangeTypes.Put) return;

                using (var session = _store.OpenSession())
                {
                    var slip = session.Load<RoutingSlip>(change.Id);
                    var ok = slip.Steps.Any() && slip.Steps[0] == Step;
                    if (!ok) return;

                    Thread.Sleep(Program.WorkerSleep);

                    var task = session.Load<QuadTask>(slip.TaskId);
                    var result = task.NumberToQuadruple * 4;
                    slip.Results.Add(Step, result);

                    Console.WriteLine("Quadruple {0} is just {1}", task.NumberToQuadruple, result);
                    slip.CompleteStep();

                    session.Advanced.Evict(task);
                    session.SaveChanges();
                }
            }
コード例 #24
0
        public PutResult Put(string key, Etag etag, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation)
        {
            WorkContext.MetricsCounters.DocsPerSecond.Mark();
            key = string.IsNullOrWhiteSpace(key) ? Guid.NewGuid().ToString() : key.Trim();
            RemoveReservedProperties(document);
            RemoveMetadataReservedProperties(metadata);
            Etag newEtag = Etag.Empty;

            using (Database.DocumentLock.Lock())
            {
                TransactionalStorage.Batch(actions =>
                {
                    if (key.EndsWith("/"))
                    {
                        key += GetNextIdentityValueWithoutOverwritingOnExistingDocuments(key, actions);
                    }
                    AssertPutOperationNotVetoed(key, metadata, document, transactionInformation);
                    if (transactionInformation == null)
                    {
                        if (Database.InFlightTransactionalState.IsModified(key))
                        {
                            throw new ConcurrencyException("PUT attempted on : " + key +
                                                           " while it is being locked by another transaction");
                        }

                        Database.PutTriggers.Apply(trigger => trigger.OnPut(key, document, metadata, null));

                        var addDocumentResult = actions.Documents.AddDocument(key, etag, document, metadata);
                        newEtag = addDocumentResult.Etag;

                        Database.Indexes.CheckReferenceBecauseOfDocumentUpdate(key, actions);
                        metadata[Constants.LastModified] = addDocumentResult.SavedAt;
                        metadata.EnsureSnapshot(
                            "Metadata was written to the database, cannot modify the document after it was written (changes won't show up in the db). Did you forget to call CreateSnapshot() to get a clean copy?");
                        document.EnsureSnapshot(
                            "Document was written to the database, cannot modify the document after it was written (changes won't show up in the db). Did you forget to call CreateSnapshot() to get a clean copy?");

                        actions.AfterStorageCommitBeforeWorkNotifications(new JsonDocument
                        {
                            Metadata            = metadata,
                            Key                 = key,
                            DataAsJson          = document,
                            Etag                = newEtag,
                            LastModified        = addDocumentResult.SavedAt,
                            SkipDeleteFromIndex = addDocumentResult.Updated == false
                        }, documents => Database.Prefetcher.AfterStorageCommitBeforeWorkNotifications(PrefetchingUser.Indexer, documents));

                        if (addDocumentResult.Updated)
                        {
                            Database.Prefetcher.AfterUpdate(key, addDocumentResult.PrevEtag);
                        }

                        Database.PutTriggers.Apply(trigger => trigger.AfterPut(key, document, metadata, newEtag, null));

                        TransactionalStorage
                        .ExecuteImmediatelyOrRegisterForSynchronization(() =>
                        {
                            Database.PutTriggers.Apply(trigger => trigger.AfterCommit(key, document, metadata, newEtag));

                            var newDocumentChangeNotification =
                                new DocumentChangeNotification
                            {
                                Id             = key,
                                Type           = DocumentChangeTypes.Put,
                                TypeName       = metadata.Value <string>(Constants.RavenClrType),
                                CollectionName = metadata.Value <string>(Constants.RavenEntityName),
                                Etag           = newEtag
                            };

                            Database.Notifications.RaiseNotifications(newDocumentChangeNotification, metadata);
                        });

                        WorkContext.ShouldNotifyAboutWork(() => "PUT " + key);
                    }
                    else
                    {
                        var doc = actions.Documents.DocumentMetadataByKey(key);
                        newEtag = Database.InFlightTransactionalState.AddDocumentInTransaction(key, etag, document, metadata,
                                                                                               transactionInformation,
                                                                                               doc == null
                                                                                          ? Etag.Empty
                                                                                          : doc.Etag,
                                                                                               UuidGenerator);
                    }
                });

                Log.Debug("Put document {0} with etag {1}", key, newEtag);
                return(new PutResult
                {
                    Key = key,
                    ETag = newEtag
                });
            }
        }
コード例 #25
0
 private void OnNext(DocumentChangeNotification documentChangeNotification)
 {
     latestEtag = Etag.Max(documentChangeNotification.Etag, latestEtag);
     signal.Set();
 }
コード例 #26
0
 private bool DocumentChangedByOtherUser(DocumentChangeNotification change)
 {
     return(!_saving);
 }
コード例 #27
0
 public void Send(DocumentChangeNotification documentChangeNotification)
 {
     OnDocumentChangeNotification?.Invoke(documentChangeNotification);
 }
コード例 #28
0
 public void AddAfterCommitNotification(DocumentChangeNotification notification)
 {
     _afterCommitNotifications.Add(notification);
 }