|
| 1 | +package com.segment.analytics.internal; |
| 2 | + |
| 3 | +import com.google.gson.Gson; |
| 4 | +import com.google.gson.GsonBuilder; |
| 5 | +import com.segment.analytics.gson.AutoValueAdapterFactory; |
| 6 | +import com.segment.analytics.gson.ISO8601DateAdapter; |
| 7 | +import com.segment.analytics.messages.Message; |
| 8 | +import com.segment.analytics.messages.TrackMessage; |
| 9 | +import java.io.File; |
| 10 | +import java.io.IOException; |
| 11 | +import java.io.OutputStream; |
| 12 | +import java.nio.channels.Channels; |
| 13 | +import java.nio.channels.FileChannel; |
| 14 | +import java.nio.charset.StandardCharsets; |
| 15 | +import java.nio.file.StandardOpenOption; |
| 16 | +import java.util.ArrayList; |
| 17 | +import java.util.Arrays; |
| 18 | +import java.util.Collections; |
| 19 | +import java.util.Date; |
| 20 | +import java.util.List; |
| 21 | +import java.util.Objects; |
| 22 | +import java.util.concurrent.ArrayBlockingQueue; |
| 23 | +import java.util.concurrent.BlockingQueue; |
| 24 | +import java.util.concurrent.TimeUnit; |
| 25 | +import java.util.concurrent.locks.Lock; |
| 26 | +import java.util.concurrent.locks.ReentrantLock; |
| 27 | +import java.util.stream.Collectors; |
| 28 | + |
| 29 | +public class FallbackAppender { |
| 30 | + |
| 31 | + private static final int FLUSH_MS = 100; |
| 32 | + private static final int BATCH = 20; |
| 33 | + private static final int LASTMESSAGE_RETRY_MS = 10_000; |
| 34 | + private static final String PATH = "pending"; |
| 35 | + |
| 36 | + private final AnalyticsClient client; |
| 37 | + private final BlockingQueue<Message> queue; |
| 38 | + private final File file; |
| 39 | + private final Lock lock = new ReentrantLock(); |
| 40 | + private final Thread writer; |
| 41 | + private final Thread reader; |
| 42 | + private final Gson gson; |
| 43 | + |
| 44 | + private transient long lastMessage; |
| 45 | + |
| 46 | + public FallbackAppender(AnalyticsClient client) { |
| 47 | + this.client = client; |
| 48 | + this.file = new File(PATH); |
| 49 | + this.queue = new ArrayBlockingQueue<Message>(100); |
| 50 | + this.writer = new Thread(new FileWriter()); // XXX threadFactory daemon |
| 51 | + this.reader = new Thread(new FileReader()); // XXX threadFactory daemon |
| 52 | + this.gson = new GsonBuilder() |
| 53 | + .registerTypeAdapterFactory(new AutoValueAdapterFactory()) |
| 54 | + .registerTypeAdapter(Date.class, new ISO8601DateAdapter()) |
| 55 | + .create(); |
| 56 | + |
| 57 | + file.delete(); // FIXME do not remove on start |
| 58 | + |
| 59 | + this.lastMessage = System.currentTimeMillis(); |
| 60 | + this.writer.start(); |
| 61 | + this.reader.start(); |
| 62 | + } |
| 63 | + |
| 64 | + public void close() { |
| 65 | + reader.interrupt(); |
| 66 | + writer.interrupt(); |
| 67 | + } |
| 68 | + |
| 69 | + // block !!! |
| 70 | + public void add(Message msg) { |
| 71 | + try { |
| 72 | + queue.put(msg); |
| 73 | + } catch (InterruptedException e) { |
| 74 | + Thread.currentThread().interrupt(); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + class FileReader implements Runnable { |
| 79 | + @Override |
| 80 | + public void run() { |
| 81 | + while (!Thread.currentThread().isInterrupted()) { |
| 82 | + if (queue.isEmpty() && System.currentTimeMillis() - lastMessage > LASTMESSAGE_RETRY_MS) { |
| 83 | + if (file.length() == 0) { |
| 84 | + continue; |
| 85 | + } |
| 86 | + |
| 87 | + List<Message> msgs; |
| 88 | + lock.lock(); |
| 89 | + try { |
| 90 | + msgs = read(); |
| 91 | + if (msgs.isEmpty()) { |
| 92 | + continue; |
| 93 | + } |
| 94 | + // FIXME now its reading all the msgs and waits until all is processed |
| 95 | + // it will be better to work with batch and truncate the file |
| 96 | + file.delete(); |
| 97 | + } catch (IOException e) { |
| 98 | + // TODO Auto-generated catch block |
| 99 | + e.printStackTrace(); |
| 100 | + lastMessage = System.currentTimeMillis(); |
| 101 | + continue; |
| 102 | + } finally { |
| 103 | + lock.unlock(); |
| 104 | + } |
| 105 | + |
| 106 | + // FIXME batch |
| 107 | + while (!msgs.isEmpty()) { |
| 108 | + int reenqueued = 0; |
| 109 | + boolean canEnqueue = true; |
| 110 | + for (int i = msgs.size() - 1; canEnqueue && i >= 0; i--) { |
| 111 | + Message msg = msgs.get(i); |
| 112 | + canEnqueue = client.offer(msg); |
| 113 | + if (canEnqueue) { |
| 114 | + msgs.remove(i); |
| 115 | + reenqueued++; |
| 116 | + } |
| 117 | + } |
| 118 | + System.err.println("reenqueued " + reenqueued); |
| 119 | + try { |
| 120 | + Thread.sleep(1_000); |
| 121 | + } catch (InterruptedException e) { |
| 122 | + Thread.currentThread().interrupt(); |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + lastMessage = System.currentTimeMillis(); |
| 127 | + } |
| 128 | + |
| 129 | + try { |
| 130 | + Thread.sleep(1_000); |
| 131 | + } catch (InterruptedException e) { |
| 132 | + Thread.currentThread().interrupt(); |
| 133 | + } |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + class FileWriter implements Runnable { |
| 139 | + @Override |
| 140 | + public void run() { |
| 141 | + final List<Message> batch = new ArrayList<>(); |
| 142 | + while (!Thread.currentThread().isInterrupted()) { |
| 143 | + try { |
| 144 | + final Message msg = queue.poll(FLUSH_MS, TimeUnit.MILLISECONDS); |
| 145 | + if (msg == null) { |
| 146 | + if (!batch.isEmpty()) { |
| 147 | + write(batch); |
| 148 | + } |
| 149 | + } else { |
| 150 | + batch.add(msg); |
| 151 | + if (batch.size() >= BATCH) { |
| 152 | + write(batch); |
| 153 | + } |
| 154 | + } |
| 155 | + } catch (InterruptedException e) { |
| 156 | + Thread.currentThread().interrupt(); |
| 157 | + } |
| 158 | + } |
| 159 | + if (!batch.isEmpty()) { |
| 160 | + write(batch); |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + List<Message> read() throws IOException { |
| 166 | + if (file.exists()) { |
| 167 | + try (FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.READ)) { |
| 168 | + fileChannel.lock(0, Long.MAX_VALUE, true); |
| 169 | + |
| 170 | + final String[] lines = new String( |
| 171 | + Channels.newInputStream(fileChannel).readAllBytes(), StandardCharsets.UTF_8) |
| 172 | + .split(System.lineSeparator()); |
| 173 | + return Arrays.stream(lines) |
| 174 | + .map(m -> fromJson(m)) |
| 175 | + .filter(Objects::nonNull) |
| 176 | + .collect(Collectors.toList()); |
| 177 | + } |
| 178 | + } else { |
| 179 | + return Collections.emptyList(); |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + private void write(List<Message> batch) { |
| 184 | + lock.lock(); |
| 185 | + try (FileChannel fileChannel = FileChannel.open( |
| 186 | + file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE)) { |
| 187 | + fileChannel.lock(); |
| 188 | + |
| 189 | + final String lines = batch.stream() |
| 190 | + .map(this::toJson) |
| 191 | + .filter(Objects::nonNull) |
| 192 | + .collect(Collectors.joining(System.lineSeparator())); |
| 193 | + |
| 194 | + OutputStream os = Channels.newOutputStream(fileChannel); |
| 195 | + os.write(lines.getBytes(StandardCharsets.UTF_8)); |
| 196 | + os.write(System.lineSeparator().getBytes(StandardCharsets.UTF_8)); |
| 197 | + fileChannel.force(true); |
| 198 | + |
| 199 | + batch.clear(); |
| 200 | + |
| 201 | + lastMessage = System.currentTimeMillis(); |
| 202 | + } catch (IOException e) { |
| 203 | + e.printStackTrace(); // FIXME |
| 204 | + } finally { |
| 205 | + lock.unlock(); |
| 206 | + } |
| 207 | + } |
| 208 | + |
| 209 | + private String toJson(final Message msg) { |
| 210 | + try { |
| 211 | + return gson.toJson(msg); |
| 212 | + } catch (Exception e) { |
| 213 | + e.printStackTrace(); |
| 214 | + return null; |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + private Message fromJson(final String msg) { |
| 219 | + try { |
| 220 | + // FIXME only track |
| 221 | + return gson.fromJson(msg, TrackMessage.class); |
| 222 | + } catch (Exception e) { |
| 223 | + e.printStackTrace(); |
| 224 | + return null; |
| 225 | + } |
| 226 | + } |
| 227 | +} |
0 commit comments