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