File: dbretrievalengine.cpp

package info (click to toggle)
classified-ads 0.13-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 6,772 kB
  • sloc: cpp: 34,291; tcl: 1,175; xml: 64; makefile: 40
file content (215 lines) | stat: -rw-r--r-- 9,246 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*  -*-C++-*- -*-coding: utf-8-unix;-*-
  Classified Ads is Copyright (c) Antti Järvinen 2013-2017.

  This file is part of Classified Ads.

  Classified Ads is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  Classified Ads is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with Classified Ads; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "dbretrievalengine.h"
#include "../log.h"
#include "../controller.h"
#include "../datamodel/model.h"
#include "node.h"
#include "connection.h"
#include "protocol_message_formatter.h"

/**
 * How often to repeat query to connected nodes to keep db up-to-date
 */
static const int KNetworkQueryRepeatIntervalSeconds ( 15 * 60 ) ;
 
DbRecordRetrievalEngine::DbRecordRetrievalEngine(Controller* aController,
                                                 Model& aModel) :
    QTimer(aController),
    iController(aController),
    iModel(aModel),
    iNowRunning(false) {
    LOG_STR("DbRecordRetrievalEngine::DbRecordRetrievalEngine") ;
    connect(this, SIGNAL(timeout()), this, SLOT(run()));
}

DbRecordRetrievalEngine::~DbRecordRetrievalEngine() {
    LOG_STR("DbRecordRetrievalEngine::~DbRecordRetrievalEngine out") ;
}


// very simple algorithm here: for each newly-connected node
// send every query that we have in stock. query.iListOfNodes contains
// book-keeping about nodes that already have been sent the
// query that is kept in query.iTerms. 
void DbRecordRetrievalEngine::run() {
    if ( iNowRunning == false ) {
        iNowRunning = true ;
        iModel.lock() ;
        if ( iSearchTerms.size() > 0 &&
             iNodesSuccessfullyConnected.size() > 0 ) {
            // spam each connected node with all searches that we have pending:
            for ( int i = iSearchTerms.size()-1 ; i >= 0 ; i-- ) {
                DlQueueItem& query ( iSearchTerms[i] ) ; 
                foreach ( const Hash& connectedNode, iNodesSuccessfullyConnected ) {
                    if ( query.iListOfNodes.contains(connectedNode) == false ) {
                        sendQueryToNode(query.iTerms, 
                                        connectedNode) ; 
                        query.iListOfNodes.append(connectedNode) ; 
                        query.iTimeOfLastRefresh = QDateTime::currentDateTimeUtc() ; 
                    }
                }
            }
        } // if ( iSearchTerms.size() > 0 ) 
        iNodesSuccessfullyConnected.clear() ; 

        // 2nd stage: if there are queries where iTimeOfLastRefresh 
        // is long time ago, repeat the queries
        for ( int i = iSearchTerms.size()-1 ; i >= 0 ; i-- ) {
            DlQueueItem& query ( iSearchTerms[i] ) ; 
            QDateTime currentTime ( QDateTime::currentDateTimeUtc() ) ; 
            QLOG_STR("Repeating db query because time is up") ; 
            if ( query.iTimeOfLastRefresh.secsTo(currentTime) >
                 KNetworkQueryRepeatIntervalSeconds ) {
                // query needs to be repeated
                foreach ( const Hash& connectedNode, query.iListOfNodes) {
                    if ( iModel.nodeModel().isNodeAlreadyConnected(connectedNode) ) {
                        sendQueryToNode(query.iTerms, 
                                        connectedNode) ; 
                    }
                }
                query.iTimeOfLastRefresh = QDateTime::currentDateTimeUtc() ; 
            }
        }
        iModel.unlock() ;
        iNowRunning = false ;
    }
}


void DbRecordRetrievalEngine::nodeConnectionAttemptStatus(Connection::ConnectionState aStatus,
                                                          const Hash aHashOfAttemptedNode ) {
    LOG_STR2("DbRecordRetrievalEngine::nodeConnectionAttemptStatus %d in", aStatus) ;
    LOG_STR2("DbRecordRetrievalEngine::nodeConnectionAttemptStatus %s ", qPrintable(aHashOfAttemptedNode.toString())) ;
    // use model to lock our own resources too..
    iModel.lock() ;
    for ( int i = 0 ; i < iNodeCandidatesToTryQuery.size() ; i++ ) {
        if ( iNodeCandidatesToTryQuery[i] == aHashOfAttemptedNode ) {
            if ( aStatus == Connection::Open ) {
                if ( ! iNodesSuccessfullyConnected.contains(aHashOfAttemptedNode) ) {
                    iNodesSuccessfullyConnected.append(aHashOfAttemptedNode) ;
                }
            } else {
                if ( ! iNodesFailurefullyConnected.contains(aHashOfAttemptedNode) ) {
                    iNodesFailurefullyConnected.append(aHashOfAttemptedNode) ;
                }
            }
            break ;
        }
    }
    iModel.unlock() ;
    // so just add the hash into 1 of our internal arrays, run() will pick up
    // the items from list and try to do something clever
}


// note that this method is called via datamodel and lock is
// already on during this call -> do not try (un)locking 
// for 2nd time.
void DbRecordRetrievalEngine::startRetrieving(CaDbRecord::SearchTerms aSearchTerms) {
    if ( aSearchTerms.iFromCollection == KNullHash ) {
        return ; // can't search from unspecified collection
    }
    // lets see if our search conditions are already included
    // in at least one query already found from queue. 
    // -> spamming the network with smaller query makes no
    // sense if broader query is already underway
    foreach ( const DlQueueItem& oldQuery, iSearchTerms) {
        if ( aSearchTerms < oldQuery.iTerms ) {
            return ; // proceed no further
        }
    }

    DlQueueItem dlQueueItem ; 
    dlQueueItem.iTerms = aSearchTerms ; 
    dlQueueItem.iTimeOfLastRefresh = QDateTime::currentDateTimeUtc() ; 
    
    // as new content is added, add also candidate nodes to connection
    // wishlist:
    QList<Node *>* nodesToTry =
        iModel.nodeModel().getNodesAfterHash(aSearchTerms.iFromCollection,
                                             20, // 20 nodes
                                             300 ) ;// at most 5 hours old

    if ( nodesToTry ) {
        while ( ! nodesToTry->isEmpty() ) {
            Node* connectCandidate ( nodesToTry->takeFirst() ) ;
            // here it is possible that node is already
            // connected, in which case send query straight away
            // and don't put node into connection wishlist
            if ( iModel.nodeModel().isNodeAlreadyConnected (*connectCandidate) ) {
                sendQueryToNode(aSearchTerms, 
                                connectCandidate->nodeFingerPrint()) ; 
                // mark this node to list of nodes already spammed with this query:
                dlQueueItem.iListOfNodes.append(connectCandidate->nodeFingerPrint()) ; 
                delete connectCandidate ; 
            } else {
                // node was not already connected, put it into wishlist
                iNodeCandidatesToTryQuery.append(connectCandidate->nodeFingerPrint()) ;
                iModel.nodeModel().addNodeToConnectionWishList(connectCandidate) ;
            }
        }
        delete nodesToTry; 
    }
    iSearchTerms.append(dlQueueItem) ; 
}

void DbRecordRetrievalEngine::stopRetrieving() {
        iModel.lock() ;
        iSearchTerms.clear() ; 
        iNodeCandidatesToTryQuery.clear() ; 
        iNodesSuccessfullyConnected.clear() ; 
        iNodesFailurefullyConnected.clear() ; 
        iModel.unlock() ;
}

void DbRecordRetrievalEngine::notifyOfContentReceived(const Hash& aHashOfContent,
                                                      const ProtocolItemType aTypeOfReceivedContent ) {
    if ( aTypeOfReceivedContent == DbRecord ) {
        iModel.lock() ;
        for ( int i = iSearchTerms.size()-1 ; i >= 0 ; i-- ) {
            if ( iSearchTerms[i].iTerms.iById == aHashOfContent ) {
                iSearchTerms.removeAt(i) ; 
            }
        }
        iModel.unlock() ;
    }
}

// when this is called, datamodel must be locked
void DbRecordRetrievalEngine::sendQueryToNode(const CaDbRecord::SearchTerms& aSearchTerms, 
                                              const Hash& aNodeFingerPrint) {
    const QList <Connection *>& openConnections = iModel.getConnections() ;
    foreach ( Connection* c, openConnections ) {
        if ( c->connectionState() == Connection::Open) {
            const Node* n = c->node() ; 
            if ( n && n->nodeFingerPrint() == aNodeFingerPrint ) {
                QByteArray* serializedSearch = new QByteArray() ;
                serializedSearch->append( ProtocolMessageFormatter::dbSearchTerms(aSearchTerms)) ;
                if ( serializedSearch->size() > 0 ) {
                    c->iNextProtocolItemToSend.append(serializedSearch) ;
                } else {
                    delete serializedSearch ;
                }
                return ; 
            }
        }
    }
}