aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/traccar/session/cache/CacheManager.java
blob: 064e5672f999a5af5013ac06a33e293739d59380 (plain)
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
 * Copyright 2022 - 2023 Anton Tananaev (anton@traccar.org)
 *
 * 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.
 */
package org.traccar.session.cache;

import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import org.traccar.broadcast.BroadcastInterface;
import org.traccar.broadcast.BroadcastService;
import org.traccar.config.Config;
import org.traccar.model.Attribute;
import org.traccar.model.BaseModel;
import org.traccar.model.Calendar;
import org.traccar.model.Device;
import org.traccar.model.Driver;
import org.traccar.model.Geofence;
import org.traccar.model.Group;
import org.traccar.model.GroupedModel;
import org.traccar.model.Maintenance;
import org.traccar.model.Notification;
import org.traccar.model.ObjectOperation;
import org.traccar.model.Permission;
import org.traccar.model.Position;
import org.traccar.model.Schedulable;
import org.traccar.model.Server;
import org.traccar.model.User;
import org.traccar.storage.Storage;
import org.traccar.storage.StorageException;
import org.traccar.storage.query.Columns;
import org.traccar.storage.query.Condition;
import org.traccar.storage.query.Request;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

@Singleton
public class CacheManager implements BroadcastInterface {

    private static final Set<Class<? extends BaseModel>> GROUPED_CLASSES =
            Set.of(Attribute.class, Driver.class, Geofence.class, Maintenance.class, Notification.class);

    private final Config config;
    private final Storage storage;
    private final BroadcastService broadcastService;

    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    private final CacheGraph graph = new CacheGraph();

    private Server server;
    private final Map<Long, Position> devicePositions = new HashMap<>();
    private final Map<Long, AtomicInteger> deviceReferences = new HashMap<>();

    @Inject
    public CacheManager(Config config, Storage storage, BroadcastService broadcastService) throws StorageException {
        this.config = config;
        this.storage = storage;
        this.broadcastService = broadcastService;
        server = storage.getObject(Server.class, new Request(new Columns.All()));
        broadcastService.registerListener(this);
    }

    @Override
    public String toString() {
        return graph.toString();
    }

    public Config getConfig() {
        return config;
    }

    public <T extends BaseModel> T getObject(Class<T> clazz, long id) {
        try {
            lock.readLock().lock();
            return graph.getObject(clazz, id);
        } finally {
            lock.readLock().unlock();
        }
    }

    public <T extends BaseModel> Set<T> getDeviceObjects(long deviceId, Class<T> clazz) {
        try {
            lock.readLock().lock();
            return graph.getObjects(Device.class, deviceId, clazz, Set.of(Group.class), true)
                    .collect(Collectors.toUnmodifiableSet());
        } finally {
            lock.readLock().unlock();
        }
    }

    public Position getPosition(long deviceId) {
        try {
            lock.readLock().lock();
            return devicePositions.get(deviceId);
        } finally {
            lock.readLock().unlock();
        }
    }

    public Server getServer() {
        try {
            lock.readLock().lock();
            return server;
        } finally {
            lock.readLock().unlock();
        }
    }

    public Set<User> getNotificationUsers(long notificationId, long deviceId) {
        try {
            lock.readLock().lock();
            Set<User> deviceUsers = getDeviceObjects(deviceId, User.class);
            return graph.getObjects(Notification.class, notificationId, User.class, Set.of(), false)
                    .filter(deviceUsers::contains)
                    .collect(Collectors.toUnmodifiableSet());
        } finally {
            lock.readLock().unlock();
        }
    }

    public Set<Notification> getDeviceNotifications(long deviceId) {
        try {
            lock.readLock().lock();
            var direct = graph.getObjects(Device.class, deviceId, Notification.class, Set.of(Group.class), true)
                    .map(BaseModel::getId)
                    .collect(Collectors.toUnmodifiableSet());
            return graph.getObjects(Device.class, deviceId, Notification.class, Set.of(Group.class, User.class), true)
                    .filter(notification -> notification.getAlways() || direct.contains(notification.getId()))
                    .collect(Collectors.toUnmodifiableSet());
        } finally {
            lock.readLock().unlock();
        }
    }

    public void addDevice(long deviceId) throws Exception {
        try {
            lock.writeLock().lock();
            if (deviceReferences.computeIfAbsent(deviceId, k -> new AtomicInteger()).getAndIncrement() <= 0) {
                Device device = storage.getObject(Device.class, new Request(
                        new Columns.All(), new Condition.Equals("id", deviceId)));
                graph.addObject(device);
                initializeCache(device);
                if (device.getPositionId() > 0) {
                    devicePositions.put(deviceId, storage.getObject(Position.class, new Request(
                            new Columns.All(), new Condition.Equals("id", device.getPositionId()))));
                }
            }
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void removeDevice(long deviceId) {
        try {
            lock.writeLock().lock();
            if (deviceReferences.computeIfAbsent(deviceId, k -> new AtomicInteger()).incrementAndGet() <= 0) {
                graph.removeObject(Device.class, deviceId);
                devicePositions.remove(deviceId);
                deviceReferences.remove(deviceId);
            }
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void updatePosition(Position position) {
        try {
            lock.writeLock().lock();
            if (deviceReferences.containsKey(position.getDeviceId())) {
                devicePositions.put(position.getDeviceId(), position);
            }
        } finally {
            lock.writeLock().unlock();
        }
    }

    @Override
    public <T extends BaseModel> void invalidateObject(
            boolean local, Class<T> clazz, long id, ObjectOperation operation) throws Exception {
        if (local) {
            broadcastService.invalidateObject(true, clazz, id, operation);
        }

        if (operation == ObjectOperation.DELETE) {
            graph.removeObject(clazz, id);
        }
        if (operation != ObjectOperation.UPDATE) {
            return;
        }

        if (clazz.equals(Server.class)) {
            server = storage.getObject(Server.class, new Request(new Columns.All()));
            return;
        }

        var after = storage.getObject(clazz, new Request(new Columns.All(), new Condition.Equals("id", id)));
        if (after == null) {
            return;
        }
        var before = getObject(after.getClass(), after.getId());
        if (before == null) {
            return;
        }

        if (after instanceof GroupedModel) {
            long beforeGroupId = ((GroupedModel) before).getGroupId();
            long afterGroupId = ((GroupedModel) after).getGroupId();
            if (beforeGroupId != afterGroupId) {
                if (beforeGroupId > 0) {
                    invalidatePermission(clazz, id, Group.class, beforeGroupId, false);
                }
                if (afterGroupId > 0) {
                    invalidatePermission(clazz, id, Group.class, afterGroupId, true);
                }
            }
        } else if (after instanceof Schedulable) {
            long beforeCalendarId = ((Schedulable) before).getCalendarId();
            long afterCalendarId = ((Schedulable) after).getCalendarId();
            if (beforeCalendarId != afterCalendarId) {
                if (beforeCalendarId > 0) {
                    invalidatePermission(clazz, id, Calendar.class, beforeCalendarId, false);
                }
                if (afterCalendarId > 0) {
                    invalidatePermission(clazz, id, Calendar.class, afterCalendarId, true);
                }
            }
            // TODO handle notification always change
        }

        graph.updateObject(after);
    }

    @Override
    public <T1 extends BaseModel, T2 extends BaseModel> void invalidatePermission(
            boolean local, Class<T1> clazz1, long id1, Class<T2> clazz2, long id2, boolean link) throws Exception {
        if (local) {
            broadcastService.invalidatePermission(true, clazz1, id1, clazz2, id2, link);
        }

        if (clazz1.equals(User.class) && GroupedModel.class.isAssignableFrom(clazz2)) {
            invalidatePermission(clazz2, id2, clazz1, id1, link);
        } else {
            invalidatePermission(clazz1, id1, clazz2, id2, link);
        }
    }

    private <T1 extends BaseModel, T2 extends BaseModel> void invalidatePermission(
            Class<T1> fromClass, long fromId, Class<T2> toClass, long toId, boolean link) throws Exception {

        boolean groupLink = GroupedModel.class.isAssignableFrom(fromClass) && toClass.equals(Group.class);
        boolean calendarLink = Schedulable.class.isAssignableFrom(fromClass) && toClass.equals(Calendar.class);
        boolean userLink = fromClass.equals(User.class) && toClass.equals(Notification.class);

        boolean groupedLinks = GroupedModel.class.isAssignableFrom(fromClass)
                && (GROUPED_CLASSES.contains(toClass) || toClass.equals(User.class));

        if (!groupLink && !calendarLink && !userLink && !groupedLinks) {
            return;
        }

        if (link) {
            BaseModel object = storage.getObject(toClass, new Request(
                    new Columns.All(), new Condition.Equals("id", toId)));
            if (!graph.addLink(fromClass, fromId, object)) {
                initializeCache(object);
            }
        } else {
            graph.removeLink(fromClass, fromId, toClass, toId);
        }
    }

    private void initializeCache(BaseModel object) throws Exception {
        if (object instanceof User) {
            for (Permission permission : storage.getPermissions(User.class, Notification.class)) {
                if (permission.getOwnerId() == object.getId()) {
                    invalidatePermission(
                            permission.getOwnerClass(), permission.getOwnerId(),
                            permission.getPropertyClass(), permission.getPropertyId(), true);
                }
            }
        } else {
            if (object instanceof GroupedModel) {
                long groupId = ((GroupedModel) object).getGroupId();
                if (groupId > 0) {
                    invalidatePermission(object.getClass(), object.getId(), Group.class, groupId, true);
                }

                for (Permission permission : storage.getPermissions(User.class, object.getClass())) {
                    if (permission.getPropertyId() == object.getId()) {
                        invalidatePermission(
                                object.getClass(), object.getId(), User.class, permission.getOwnerId(), true);
                    }
                }

                for (Class<? extends BaseModel> clazz : GROUPED_CLASSES) {
                    for (Permission permission : storage.getPermissions(object.getClass(), clazz)) {
                        if (permission.getOwnerId() == object.getId()) {
                            invalidatePermission(
                                    object.getClass(), object.getId(), clazz, permission.getPropertyId(), true);
                        }
                    }
                }
            }

            if (object instanceof Schedulable) {
                long calendarId = ((Schedulable) object).getCalendarId();
                if (calendarId > 0) {
                    invalidatePermission(object.getClass(), object.getId(), Calendar.class, calendarId, true);
                }
            }
        }
    }

}