RLMSyncSession.mm 6.76 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 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.
//
////////////////////////////////////////////////////////////////////////////

#import "RLMSyncSession_Private.hpp"

#import "RLMSyncConfiguration_Private.hpp"
#import "RLMSyncUser_Private.hpp"
23
#import "RLMSyncUtil_Private.hpp"
24
25
26
27
#import "sync/sync_session.hpp"

using namespace realm;

28
29
30
31
32
33
34
@interface RLMSyncErrorActionToken () {
@public
    std::string _originalPath;
    BOOL _isValid;
}
@end

35
36
37
38
39
40
41
42
43
44
45
46
47
@interface RLMProgressNotificationToken() {
    uint64_t _token;
    std::weak_ptr<SyncSession> _session;
}
@end

@implementation RLMProgressNotificationToken

- (void)suppressNextNotification {
    // No-op, but implemented in case this token is passed to
    // `-[RLMRealm commitWriteTransactionWithoutNotifying:]`.
}

48
- (void)invalidate {
49
50
51
52
53
54
55
56
57
58
59
    if (auto session = _session.lock()) {
        session->unregister_progress_notifier(_token);
        _session.reset();
        _token = 0;
    }
}

- (void)dealloc {
    if (_token != 0) {
        NSLog(@"RLMProgressNotificationToken released without unregistering a notification. "
              @"You must hold on to the RLMProgressNotificationToken and call "
60
              @"-[RLMProgressNotificationToken invalidate] when you no longer wish to receive "
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
              @"progress update notifications.");
    }
}

- (nullable instancetype)initWithTokenValue:(uint64_t)token
                                    session:(std::shared_ptr<SyncSession>)session {
    if (token == 0) {
        return nil;
    }
    if (self = [super init]) {
        _token = token;
        _session = session;
        return self;
    }
    return nil;
}

@end

@interface RLMSyncSession ()
@property (class, nonatomic, readonly) dispatch_queue_t notificationsQueue;
@end

@implementation RLMSyncSession

+ (dispatch_queue_t)notificationsQueue {
    static dispatch_queue_t queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue = dispatch_queue_create("io.realm.sync.sessionsNotificationQueue", DISPATCH_QUEUE_SERIAL);
    });
    return queue;
}

- (instancetype)initWithSyncSession:(std::shared_ptr<SyncSession>)session {
    if (self = [super init]) {
        _session = session;
        return self;
    }
    return nil;
}

- (RLMSyncConfiguration *)configuration {
    if (auto session = _session.lock()) {
        if (session->state() != SyncSession::PublicState::Error) {
            return [[RLMSyncConfiguration alloc] initWithRawConfig:session->config()];
        }
    }
    return nil;
}

- (NSURL *)realmURL {
    if (auto session = _session.lock()) {
        if (auto url = session->full_realm_url()) {
            return [NSURL URLWithString:@(url->c_str())];
        }
    }
    return nil;
}

- (RLMSyncUser *)parentUser {
    if (auto session = _session.lock()) {
        if (session->state() != SyncSession::PublicState::Error) {
            return [[RLMSyncUser alloc] initWithSyncUser:session->user()];
        }
    }
    return nil;
}

- (RLMSyncSessionState)state {
    if (auto session = _session.lock()) {
        if (session->state() == SyncSession::PublicState::Inactive) {
            return RLMSyncSessionStateInactive;
        }
        if (session->state() != SyncSession::PublicState::Error) {
            return RLMSyncSessionStateActive;
        }
    }
    return RLMSyncSessionStateInvalid;
}

142
- (BOOL)waitForUploadCompletionOnQueue:(dispatch_queue_t)queue callback:(void(^)(NSError *))callback {
143
144
145
146
147
    if (auto session = _session.lock()) {
        if (session->state() == SyncSession::PublicState::Error) {
            return NO;
        }
        queue = queue ?: dispatch_get_main_queue();
148
149
150
151
152
        session->wait_for_upload_completion([=](std::error_code err) {
            NSError *error = (err == std::error_code{}) ? nil : make_sync_error(err);
            dispatch_async(queue, ^{
                callback(error);
            });
153
154
155
156
157
158
        });
        return YES;
    }
    return NO;
}

159
- (BOOL)waitForDownloadCompletionOnQueue:(dispatch_queue_t)queue callback:(void(^)(NSError *))callback {
160
161
162
163
164
    if (auto session = _session.lock()) {
        if (session->state() == SyncSession::PublicState::Error) {
            return NO;
        }
        queue = queue ?: dispatch_get_main_queue();
165
166
167
168
169
        session->wait_for_download_completion([=](std::error_code err) {
            NSError *error = (err == std::error_code{}) ? nil : make_sync_error(err);
            dispatch_async(queue, ^{
                callback(error);
            });
170
171
172
173
174
175
176
        });
        return YES;
    }
    return NO;
}

- (RLMProgressNotificationToken *)addProgressNotificationForDirection:(RLMSyncProgressDirection)direction
177
                                                                 mode:(RLMSyncProgressMode)mode
178
179
180
181
182
183
184
185
186
                                                                block:(RLMProgressNotificationBlock)block {
    if (auto session = _session.lock()) {
        if (session->state() == SyncSession::PublicState::Error) {
            return nil;
        }
        dispatch_queue_t queue = RLMSyncSession.notificationsQueue;
        auto notifier_direction = (direction == RLMSyncProgressDirectionUpload
                                   ? SyncSession::NotifierType::upload
                                   : SyncSession::NotifierType::download);
187
        bool is_streaming = (mode == RLMSyncProgressModeReportIndefinitely);
188
189
190
191
192
193
194
195
196
197
        uint64_t token = session->register_progress_notifier([=](uint64_t transferred, uint64_t transferrable) {
            dispatch_async(queue, ^{
                block((NSUInteger)transferred, (NSUInteger)transferrable);
            });
        }, notifier_direction, is_streaming);
        return [[RLMProgressNotificationToken alloc] initWithTokenValue:token session:std::move(session)];
    }
    return nil;
}

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
+ (void)immediatelyHandleError:(RLMSyncErrorActionToken *)token {
    if (!token->_isValid) {
        return;
    }
    token->_isValid = NO;
    SyncManager::shared().immediately_run_file_actions(std::move(token->_originalPath));
}

@end

// MARK: - Error action token

@implementation RLMSyncErrorActionToken

- (instancetype)initWithOriginalPath:(std::string)originalPath {
    if (self = [super init]) {
        _isValid = YES;
        _originalPath = std::move(originalPath);
        return self;
    }
    return nil;
}

221
@end