71443b7d26f84a75941abdc1df2762fec4dced14.svn-base
9.11 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#include "impl/async_query.hpp"
#include "impl/realm_coordinator.hpp"
#include "results.hpp"
using namespace realm;
using namespace realm::_impl;
AsyncQuery::AsyncQuery(Results& target)
: m_target_results(&target)
, m_realm(target.get_realm().shared_from_this())
, m_sort(target.get_sort())
, m_sg_version(Realm::Internal::get_shared_group(*m_realm).get_version_of_current_transaction())
{
Query q = target.get_query();
m_query_handover = Realm::Internal::get_shared_group(*m_realm).export_for_handover(q, MutableSourcePayload::Move);
}
AsyncQuery::~AsyncQuery()
{
// unregister() may have been called from a different thread than we're being
// destroyed on, so we need to synchronize access to the interesting fields
// modified there
std::lock_guard<std::mutex> lock(m_target_mutex);
m_realm = nullptr;
}
size_t AsyncQuery::add_callback(std::function<void (std::exception_ptr)> callback)
{
m_realm->verify_thread();
auto next_token = [=] {
size_t token = 0;
for (auto& callback : m_callbacks) {
if (token <= callback.token) {
token = callback.token + 1;
}
}
return token;
};
std::lock_guard<std::mutex> lock(m_callback_mutex);
auto token = next_token();
m_callbacks.push_back({std::move(callback), token, -1ULL});
if (m_callback_index == npos) { // Don't need to wake up if we're already sending notifications
Realm::Internal::get_coordinator(*m_realm).send_commit_notifications();
m_have_callbacks = true;
}
return token;
}
void AsyncQuery::remove_callback(size_t token)
{
Callback old;
{
std::lock_guard<std::mutex> lock(m_callback_mutex);
REALM_ASSERT(m_error || m_callbacks.size() > 0);
auto it = find_if(begin(m_callbacks), end(m_callbacks),
[=](const auto& c) { return c.token == token; });
// We should only fail to find the callback if it was removed due to an error
REALM_ASSERT(m_error || it != end(m_callbacks));
if (it == end(m_callbacks)) {
return;
}
size_t idx = distance(begin(m_callbacks), it);
if (m_callback_index != npos && m_callback_index >= idx) {
--m_callback_index;
}
old = std::move(*it);
m_callbacks.erase(it);
m_have_callbacks = !m_callbacks.empty();
}
}
void AsyncQuery::unregister() noexcept
{
std::lock_guard<std::mutex> lock(m_target_mutex);
m_target_results = nullptr;
m_realm = nullptr;
}
void AsyncQuery::release_query() noexcept
{
{
std::lock_guard<std::mutex> lock(m_target_mutex);
REALM_ASSERT(!m_realm && !m_target_results);
}
m_query = nullptr;
}
bool AsyncQuery::is_alive() const noexcept
{
std::lock_guard<std::mutex> lock(m_target_mutex);
return m_target_results != nullptr;
}
// Most of the inter-thread synchronization for run(), prepare_handover(),
// attach_to(), detach(), release_query() and deliver() is done by
// RealmCoordinator external to this code, which has some potentially
// non-obvious results on which members are and are not safe to use without
// holding a lock.
//
// attach_to(), detach(), run(), prepare_handover(), and release_query() are
// all only ever called on a single thread. call_callbacks() and deliver() are
// called on the same thread. Calls to prepare_handover() and deliver() are
// guarded by a lock.
//
// In total, this means that the safe data flow is as follows:
// - prepare_handover(), attach_to(), detach() and release_query() can read
// members written by each other
// - deliver() can read members written to in prepare_handover(), deliver(),
// and call_callbacks()
// - call_callbacks() and read members written to in deliver()
//
// Separately from this data flow for the query results, all uses of
// m_target_results, m_callbacks, and m_callback_index must be done with the
// appropriate mutex held to avoid race conditions when the Results object is
// destroyed while the background work is running, and to allow removing
// callbacks from any thread.
void AsyncQuery::run()
{
REALM_ASSERT(m_sg);
{
std::lock_guard<std::mutex> target_lock(m_target_mutex);
// Don't run the query if the results aren't actually going to be used
if (!m_target_results || (!m_have_callbacks && !m_target_results->wants_background_updates())) {
return;
}
}
REALM_ASSERT(!m_tv.is_attached());
// If we've run previously, check if we need to rerun
if (m_initial_run_complete) {
// Make an empty tableview from the query to get the table version, since
// Query doesn't expose it
if (m_query->find_all(0, 0, 0).sync_if_needed() == m_handed_over_table_version) {
return;
}
}
m_tv = m_query->find_all();
if (m_sort) {
m_tv.sort(m_sort.columnIndices, m_sort.ascending);
}
}
void AsyncQuery::prepare_handover()
{
m_sg_version = m_sg->get_version_of_current_transaction();
if (!m_tv.is_attached()) {
return;
}
REALM_ASSERT(m_tv.is_in_sync());
m_initial_run_complete = true;
m_handed_over_table_version = m_tv.sync_if_needed();
m_tv_handover = m_sg->export_for_handover(m_tv, MutableSourcePayload::Move);
// detach the TableView as we won't need it again and keeping it around
// makes advance_read() much more expensive
m_tv = TableView();
}
bool AsyncQuery::deliver(SharedGroup& sg, std::exception_ptr err)
{
if (!is_for_current_thread()) {
return false;
}
std::lock_guard<std::mutex> target_lock(m_target_mutex);
// Target results being null here indicates that it was destroyed while we
// were in the process of advancing the Realm version and preparing for
// delivery, i.e. it was destroyed from the "wrong" thread
if (!m_target_results) {
return false;
}
// We can get called before the query has actually had the chance to run if
// we're added immediately before a different set of async results are
// delivered
if (!m_initial_run_complete && !err) {
return false;
}
if (err) {
m_error = err;
return m_have_callbacks;
}
REALM_ASSERT(!m_query_handover);
auto realm_sg_version = Realm::Internal::get_shared_group(*m_realm).get_version_of_current_transaction();
if (m_sg_version != realm_sg_version) {
// Realm version can be newer if a commit was made on our thread or the
// user manually called refresh(), or older if a commit was made on a
// different thread and we ran *really* fast in between the check for
// if the shared group has changed and when we pick up async results
return false;
}
if (m_tv_handover) {
m_tv_handover->version = m_sg_version;
Results::Internal::set_table_view(*m_target_results,
std::move(*sg.import_from_handover(std::move(m_tv_handover))));
m_delivered_table_version = m_handed_over_table_version;
}
REALM_ASSERT(!m_tv_handover);
return m_have_callbacks;
}
void AsyncQuery::call_callbacks()
{
REALM_ASSERT(is_for_current_thread());
while (auto fn = next_callback()) {
fn(m_error);
}
if (m_error) {
// Remove all the callbacks as we never need to call anything ever again
// after delivering an error
std::lock_guard<std::mutex> callback_lock(m_callback_mutex);
m_callbacks.clear();
}
}
std::function<void (std::exception_ptr)> AsyncQuery::next_callback()
{
std::lock_guard<std::mutex> callback_lock(m_callback_mutex);
for (++m_callback_index; m_callback_index < m_callbacks.size(); ++m_callback_index) {
auto& callback = m_callbacks[m_callback_index];
if (m_error || callback.delivered_version != m_delivered_table_version) {
callback.delivered_version = m_delivered_table_version;
return callback.fn;
}
}
m_callback_index = npos;
return nullptr;
}
void AsyncQuery::attach_to(realm::SharedGroup& sg)
{
REALM_ASSERT(!m_sg);
REALM_ASSERT(m_query_handover);
m_query = sg.import_from_handover(std::move(m_query_handover));
m_sg = &sg;
}
void AsyncQuery::detatch()
{
REALM_ASSERT(m_sg);
REALM_ASSERT(m_query);
REALM_ASSERT(!m_tv.is_attached());
m_query_handover = m_sg->export_for_handover(*m_query, MutableSourcePayload::Move);
m_sg = nullptr;
m_query = nullptr;
}