🔀 Merge “work/next” into “next”
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneInserter.java
1 /*
2  * Sone - SoneInserter.java - Copyright Â© 2010–2020 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
20 import static java.lang.String.format;
21 import static java.lang.System.currentTimeMillis;
22 import static java.util.concurrent.TimeUnit.*;
23 import static java.util.logging.Logger.getLogger;
24 import static java.util.stream.Collectors.toList;
25 import static net.pterodactylus.sone.data.PostKt.newestFirst;
26
27 import java.io.*;
28 import java.nio.charset.Charset;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.concurrent.atomic.AtomicInteger;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
36
37 import com.codahale.metrics.*;
38 import com.google.common.base.*;
39 import net.pterodactylus.sone.core.SoneModificationDetector.LockableFingerprintProvider;
40 import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
41 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
42 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
43 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
44 import net.pterodactylus.sone.data.AlbumKt;
45 import net.pterodactylus.sone.data.Post;
46 import net.pterodactylus.sone.data.Reply;
47 import net.pterodactylus.sone.data.Sone;
48 import net.pterodactylus.sone.data.Sone.SoneStatus;
49 import net.pterodactylus.sone.data.SoneKt;
50 import net.pterodactylus.sone.main.SonePlugin;
51 import net.pterodactylus.util.service.AbstractService;
52 import net.pterodactylus.util.template.HtmlFilter;
53 import net.pterodactylus.util.template.ReflectionAccessor;
54 import net.pterodactylus.util.template.Template;
55 import net.pterodactylus.util.template.TemplateContext;
56 import net.pterodactylus.util.template.TemplateContextFactory;
57 import net.pterodactylus.util.template.TemplateException;
58 import net.pterodactylus.util.template.TemplateParser;
59 import net.pterodactylus.util.template.XmlFilter;
60
61 import com.google.common.annotations.VisibleForTesting;
62 import com.google.common.collect.Ordering;
63 import com.google.common.eventbus.EventBus;
64 import com.google.common.eventbus.Subscribe;
65
66 import freenet.keys.FreenetURI;
67 import freenet.support.api.Bucket;
68 import freenet.support.api.ManifestElement;
69 import freenet.support.api.RandomAccessBucket;
70 import freenet.support.io.ArrayBucket;
71
72 /**
73  * A Sone inserter is responsible for inserting a Sone if it has changed.
74  */
75 public class SoneInserter extends AbstractService {
76
77         /** The logger. */
78         private static final Logger logger = getLogger(SoneInserter.class.getName());
79
80         /** The insertion delay (in seconds). */
81         private static final AtomicInteger insertionDelay = new AtomicInteger(60);
82
83         /** The template factory used to create the templates. */
84         private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
85
86         static {
87                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
88                 templateContextFactory.addFilter("xml", new XmlFilter());
89                 templateContextFactory.addFilter("html", new HtmlFilter());
90         }
91
92         /** The UTF-8 charset. */
93         private static final Charset utf8Charset = Charset.forName("UTF-8");
94
95         /** The core. */
96         private final Core core;
97
98         /** The event bus. */
99         private final EventBus eventBus;
100
101         /** The Freenet interface. */
102         private final FreenetInterface freenetInterface;
103
104         private final SoneModificationDetector soneModificationDetector;
105         private final SoneUriCreator soneUriCreator;
106         private final long delay;
107         private final String soneId;
108         private final Histogram soneInsertDurationHistogram;
109         private final Meter soneInsertErrorMeter;
110
111         /**
112          * Creates a new Sone inserter.
113          *
114          * @param core
115          *            The core
116          * @param eventBus
117          *            The event bus
118          * @param freenetInterface
119          *            The freenet interface
120          * @param soneId
121          *            The ID of the Sone to insert
122          */
123         public SoneInserter(final Core core, EventBus eventBus, FreenetInterface freenetInterface, MetricRegistry metricRegistry, SoneUriCreator soneUriCreator, final String soneId) {
124                 this(core, eventBus, freenetInterface, metricRegistry, soneUriCreator, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
125                         @Override
126                         public boolean isLocked() {
127                                 Sone sone = core.getSone(soneId);
128                                 if (sone == null) {
129                                         return false;
130                                 }
131                                 return core.isLocked(sone);
132                         }
133
134                         @Override
135                         public String getFingerprint() {
136                                 Sone sone = core.getSone(soneId);
137                                 if (sone == null) {
138                                         return null;
139                                 }
140                                 return sone.getFingerprint();
141                         }
142                 }, insertionDelay), 1000);
143         }
144
145         @VisibleForTesting
146         SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, MetricRegistry metricRegistry, SoneUriCreator soneUriCreator, String soneId, SoneModificationDetector soneModificationDetector, long delay) {
147                 super("Sone Inserter for â€ś" + soneId + "”", false);
148                 this.core = core;
149                 this.eventBus = eventBus;
150                 this.freenetInterface = freenetInterface;
151                 this.soneInsertDurationHistogram = metricRegistry.histogram("sone.insert.duration", () -> new Histogram(new ExponentiallyDecayingReservoir(3000, 0)));
152                 this.soneInsertErrorMeter = metricRegistry.meter("sone.insert.errors");
153                 this.soneUriCreator = soneUriCreator;
154                 this.soneId = soneId;
155                 this.soneModificationDetector = soneModificationDetector;
156                 this.delay = delay;
157         }
158
159         //
160         // ACCESSORS
161         //
162
163         @VisibleForTesting
164         static AtomicInteger getInsertionDelay() {
165                 return insertionDelay;
166         }
167
168         /**
169          * Changes the insertion delay, i.e. the time the Sone inserter waits after it
170          * has noticed a Sone modification before it starts the insert.
171          *
172          * @param insertionDelay
173          *            The insertion delay (in seconds)
174          */
175         private static void setInsertionDelay(int insertionDelay) {
176                 SoneInserter.insertionDelay.set(insertionDelay);
177         }
178
179         /**
180          * Returns the fingerprint of the last insert.
181          *
182          * @return The fingerprint of the last insert
183          */
184         public String getLastInsertFingerprint() {
185                 return soneModificationDetector.getLastInsertFingerprint();
186         }
187
188         /**
189          * Sets the fingerprint of the last insert.
190          *
191          * @param lastInsertFingerprint
192          *            The fingerprint of the last insert
193          */
194         public void setLastInsertFingerprint(String lastInsertFingerprint) {
195                 soneModificationDetector.setFingerprint(lastInsertFingerprint);
196         }
197
198         /**
199          * Returns whether the Sone inserter has detected a modification of the
200          * Sone.
201          *
202          * @return {@code true} if the Sone has been modified, {@code false}
203          *         otherwise
204          */
205         public boolean isModified() {
206                 return soneModificationDetector.isModified();
207         }
208
209         //
210         // SERVICE METHODS
211         //
212
213         /**
214          * {@inheritDoc}
215          */
216         @Override
217         protected void serviceRun() {
218                 while (!shouldStop()) {
219                         try {
220                                 /* check every second. */
221                                 sleep(delay);
222
223                                 if (soneModificationDetector.isEligibleForInsert()) {
224                                         Sone sone = core.getSone(soneId);
225                                         if (sone == null) {
226                                                 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
227                                                 return;
228                                         }
229                                         InsertInformation insertInformation = new InsertInformation(sone);
230                                         logger.log(Level.INFO, String.format("Inserting Sone â€ś%s”…", sone.getName()));
231
232                                         boolean success = false;
233                                         try {
234                                                 sone.setStatus(SoneStatus.inserting);
235                                                 long insertTime = currentTimeMillis();
236                                                 eventBus.post(new SoneInsertingEvent(sone));
237                                                 Stopwatch stopwatch = Stopwatch.createStarted();
238                                                 FreenetURI finalUri = freenetInterface.insertDirectory(soneUriCreator.getInsertUri(sone), insertInformation.generateManifestEntries(), "index.html");
239                                                 stopwatch.stop();
240                                                 soneInsertDurationHistogram.update(stopwatch.elapsed(MICROSECONDS));
241                                                 eventBus.post(new SoneInsertedEvent(sone, stopwatch.elapsed(MILLISECONDS), insertInformation.getFingerprint()));
242                                                 /* at this point we might already be stopped. */
243                                                 if (shouldStop()) {
244                                                         /* if so, bail out, don’t change anything. */
245                                                         break;
246                                                 }
247                                                 sone.setTime(insertTime);
248                                                 sone.setLatestEdition(finalUri.getEdition());
249                                                 core.touchConfiguration();
250                                                 success = true;
251                                                 logger.log(Level.INFO, String.format("Inserted Sone â€ś%s” at %s.", sone.getName(), finalUri));
252                                         } catch (SoneException se1) {
253                                                 soneInsertErrorMeter.mark();
254                                                 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
255                                                 logger.log(Level.WARNING, String.format("Could not insert Sone â€ś%s”!", sone.getName()), se1);
256                                         } finally {
257                                                 insertInformation.close();
258                                                 sone.setStatus(SoneStatus.idle);
259                                         }
260
261                                         /*
262                                          * reset modification counter if Sone has not been modified
263                                          * while it was inserted.
264                                          */
265                                         if (success) {
266                                                 synchronized (sone) {
267                                                         if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
268                                                                 logger.log(Level.FINE, String.format("Sone â€ś%s” was not modified further, resetting counter…", sone));
269                                                                 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
270                                                                 core.touchConfiguration();
271                                                         }
272                                                 }
273                                         }
274                                 }
275                         } catch (Throwable t1) {
276                                 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
277                         }
278                 }
279         }
280
281         @Subscribe
282         public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
283                 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
284         }
285
286         /**
287          * Container for information that are required to insert a Sone. This
288          * container merely exists to copy all relevant data without holding a lock
289          * on the {@link Sone} object for too long.
290          */
291         @VisibleForTesting
292         class InsertInformation implements Closeable {
293
294                 /** All properties of the Sone, copied for thread safety. */
295                 private final Map<String, Object> soneProperties = new HashMap<>();
296                 private final String fingerprint;
297                 private final ManifestCreator manifestCreator;
298
299                 /**
300                  * Creates a new insert information container.
301                  *
302                  * @param sone
303                  *            The sone to insert
304                  */
305                 public InsertInformation(Sone sone) {
306                         this.fingerprint = sone.getFingerprint();
307                         Map<String, Object> soneProperties = new HashMap<>();
308                         soneProperties.put("id", sone.getId());
309                         soneProperties.put("name", sone.getName());
310                         soneProperties.put("time", currentTimeMillis());
311                         soneProperties.put("profile", sone.getProfile());
312                         soneProperties.put("posts", Ordering.from(newestFirst()).sortedCopy(sone.getPosts()));
313                         soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
314                         soneProperties.put("likedPostIds", new HashSet<>(sone.getLikedPostIds()));
315                         soneProperties.put("likedReplyIds", new HashSet<>(sone.getLikedReplyIds()));
316                         soneProperties.put("albums", SoneKt.getAllAlbums(sone).stream().filter(AlbumKt.notEmpty()::invoke).collect(toList()));
317                         manifestCreator = new ManifestCreator(core, soneProperties);
318                 }
319
320                 //
321                 // ACCESSORS
322                 //
323
324                 @VisibleForTesting
325                 String getFingerprint() {
326                         return fingerprint;
327                 }
328
329                 //
330                 // ACTIONS
331                 //
332
333                 /**
334                  * Generates all manifest entries required to insert this Sone.
335                  *
336                  * @return The manifest entries for the Sone insert
337                  */
338                 public HashMap<String, Object> generateManifestEntries() {
339                         HashMap<String, Object> manifestEntries = new HashMap<>();
340
341                         /* first, create an index.html. */
342                         manifestEntries.put("index.html", manifestCreator.createManifestElement(
343                                         "index.html", "text/html; charset=utf-8",
344                                         "/templates/insert/index.html"));
345
346                         /* now, store the sone. */
347                         manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
348                                         "sone.xml", "text/xml; charset=utf-8",
349                                         "/templates/insert/sone.xml"));
350
351                         return manifestEntries;
352                 }
353
354                 @Override
355                 public void close() {
356                         manifestCreator.close();
357                 }
358
359         }
360
361         /**
362          * Creates manifest elements for an insert by rendering a template.
363          */
364         @VisibleForTesting
365         static class ManifestCreator implements Closeable {
366
367                 private final Core core;
368                 private final Map<String, Object> soneProperties;
369                 private final Set<Bucket> buckets = new HashSet<>();
370
371                 ManifestCreator(Core core, Map<String, Object> soneProperties) {
372                         this.core = core;
373                         this.soneProperties = soneProperties;
374                 }
375
376                 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
377                         Template template;
378                         try (InputStream templateInputStream = getClass().getResourceAsStream(templateName);
379                                         InputStreamReader templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset)) {
380                                 template = TemplateParser.parse(templateInputStreamReader);
381                         } catch (IOException | TemplateException e1) {
382                                 logger.log(Level.SEVERE, String.format("Could not parse template â€ś%s”!", templateName), e1);
383                                 return null;
384                         }
385
386                         TemplateContext templateContext = templateContextFactory.createTemplateContext();
387                         templateContext.set("core", core);
388                         templateContext.set("currentSone", soneProperties);
389                         templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
390                         templateContext.set("version", SonePlugin.getPluginVersion());
391                         try (StringWriter writer = new StringWriter()) {
392                                 template.render(templateContext, writer);
393                                 RandomAccessBucket bucket = new ArrayBucket(writer.toString().getBytes(Charsets.UTF_8));
394                                 buckets.add(bucket);
395                                 return new ManifestElement(name, bucket, contentType, bucket.size());
396                         } catch (IOException | TemplateException e1) {
397                                 logger.log(Level.SEVERE, String.format("Could not render template â€ś%s”!", templateName), e1);
398                                 return null;
399                         }
400                 }
401
402                 public void close() {
403                         for (Bucket bucket : buckets) {
404                                 bucket.free();
405                         }
406                 }
407
408         }
409
410 }