2 * Sone - SoneInserter.java - Copyright Β© 2010β2020 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.core;
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.newestPostFirst;
26 import static net.pterodactylus.sone.data.ReplyKt.newestReplyFirst;
29 import java.nio.charset.Charset;
30 import java.util.HashMap;
31 import java.util.HashSet;
34 import java.util.concurrent.atomic.AtomicInteger;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
38 import com.codahale.metrics.*;
39 import com.google.common.base.*;
40 import net.pterodactylus.sone.core.SoneModificationDetector.LockableFingerprintProvider;
41 import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
42 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
43 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
44 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
45 import net.pterodactylus.sone.data.AlbumKt;
46 import net.pterodactylus.sone.data.Post;
47 import net.pterodactylus.sone.data.Reply;
48 import net.pterodactylus.sone.data.Sone;
49 import net.pterodactylus.sone.data.Sone.SoneStatus;
50 import net.pterodactylus.sone.data.SoneKt;
51 import net.pterodactylus.sone.main.SonePlugin;
52 import net.pterodactylus.util.service.AbstractService;
53 import net.pterodactylus.util.template.HtmlFilter;
54 import net.pterodactylus.util.template.ReflectionAccessor;
55 import net.pterodactylus.util.template.Template;
56 import net.pterodactylus.util.template.TemplateContext;
57 import net.pterodactylus.util.template.TemplateContextFactory;
58 import net.pterodactylus.util.template.TemplateException;
59 import net.pterodactylus.util.template.TemplateParser;
60 import net.pterodactylus.util.template.XmlFilter;
62 import com.google.common.annotations.VisibleForTesting;
63 import com.google.common.collect.Ordering;
64 import com.google.common.eventbus.EventBus;
65 import com.google.common.eventbus.Subscribe;
67 import freenet.keys.FreenetURI;
68 import freenet.support.api.Bucket;
69 import freenet.support.api.ManifestElement;
70 import freenet.support.api.RandomAccessBucket;
71 import freenet.support.io.ArrayBucket;
74 * A Sone inserter is responsible for inserting a Sone if it has changed.
76 public class SoneInserter extends AbstractService {
79 private static final Logger logger = getLogger(SoneInserter.class.getName());
81 /** The insertion delay (in seconds). */
82 private static final AtomicInteger insertionDelay = new AtomicInteger(60);
84 /** The template factory used to create the templates. */
85 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
88 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
89 templateContextFactory.addFilter("xml", new XmlFilter());
90 templateContextFactory.addFilter("html", new HtmlFilter());
93 /** The UTF-8 charset. */
94 private static final Charset utf8Charset = Charset.forName("UTF-8");
97 private final Core core;
100 private final EventBus eventBus;
102 /** The Freenet interface. */
103 private final FreenetInterface freenetInterface;
105 private final SoneModificationDetector soneModificationDetector;
106 private final SoneUriCreator soneUriCreator;
107 private final long delay;
108 private final String soneId;
109 private final Histogram soneInsertDurationHistogram;
110 private final Meter soneInsertErrorMeter;
113 * Creates a new Sone inserter.
119 * @param freenetInterface
120 * The freenet interface
122 * The ID of the Sone to insert
124 public SoneInserter(final Core core, EventBus eventBus, FreenetInterface freenetInterface, MetricRegistry metricRegistry, SoneUriCreator soneUriCreator, final String soneId) {
125 this(core, eventBus, freenetInterface, metricRegistry, soneUriCreator, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
127 public boolean isLocked() {
128 Sone sone = core.getSone(soneId);
132 return core.isLocked(sone);
136 public String getFingerprint() {
137 Sone sone = core.getSone(soneId);
141 return sone.getFingerprint();
143 }, insertionDelay), 1000);
147 SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, MetricRegistry metricRegistry, SoneUriCreator soneUriCreator, String soneId, SoneModificationDetector soneModificationDetector, long delay) {
148 super("Sone Inserter for β" + soneId + "β", false);
150 this.eventBus = eventBus;
151 this.freenetInterface = freenetInterface;
152 this.soneInsertDurationHistogram = metricRegistry.histogram("sone.insert.duration", () -> new Histogram(new ExponentiallyDecayingReservoir(3000, 0)));
153 this.soneInsertErrorMeter = metricRegistry.meter("sone.insert.errors");
154 this.soneUriCreator = soneUriCreator;
155 this.soneId = soneId;
156 this.soneModificationDetector = soneModificationDetector;
165 static AtomicInteger getInsertionDelay() {
166 return insertionDelay;
170 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
171 * has noticed a Sone modification before it starts the insert.
173 * @param insertionDelay
174 * The insertion delay (in seconds)
176 private static void setInsertionDelay(int insertionDelay) {
177 SoneInserter.insertionDelay.set(insertionDelay);
181 * Returns the fingerprint of the last insert.
183 * @return The fingerprint of the last insert
185 public String getLastInsertFingerprint() {
186 return soneModificationDetector.getLastInsertFingerprint();
190 * Sets the fingerprint of the last insert.
192 * @param lastInsertFingerprint
193 * The fingerprint of the last insert
195 public void setLastInsertFingerprint(String lastInsertFingerprint) {
196 soneModificationDetector.setFingerprint(lastInsertFingerprint);
200 * Returns whether the Sone inserter has detected a modification of the
203 * @return {@code true} if the Sone has been modified, {@code false}
206 public boolean isModified() {
207 return soneModificationDetector.isModified();
218 protected void serviceRun() {
219 while (!shouldStop()) {
221 /* check every second. */
224 if (soneModificationDetector.isEligibleForInsert()) {
225 Sone sone = core.getSone(soneId);
227 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
230 InsertInformation insertInformation = new InsertInformation(sone);
231 logger.log(Level.INFO, String.format("Inserting Sone β%sββ¦", sone.getName()));
233 boolean success = false;
235 sone.setStatus(SoneStatus.inserting);
236 long insertTime = currentTimeMillis();
237 eventBus.post(new SoneInsertingEvent(sone));
238 Stopwatch stopwatch = Stopwatch.createStarted();
239 FreenetURI finalUri = freenetInterface.insertDirectory(soneUriCreator.getInsertUri(sone), insertInformation.generateManifestEntries(), "index.html");
241 soneInsertDurationHistogram.update(stopwatch.elapsed(MICROSECONDS));
242 eventBus.post(new SoneInsertedEvent(sone, stopwatch.elapsed(MILLISECONDS), insertInformation.getFingerprint()));
243 /* at this point we might already be stopped. */
245 /* if so, bail out, donβt change anything. */
248 sone.setTime(insertTime);
249 sone.setLatestEdition(finalUri.getEdition());
250 core.touchConfiguration();
252 logger.log(Level.INFO, String.format("Inserted Sone β%sβ at %s.", sone.getName(), finalUri));
253 } catch (SoneException se1) {
254 soneInsertErrorMeter.mark();
255 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
256 logger.log(Level.WARNING, String.format("Could not insert Sone β%sβ!", sone.getName()), se1);
258 insertInformation.close();
259 sone.setStatus(SoneStatus.idle);
263 * reset modification counter if Sone has not been modified
264 * while it was inserted.
267 synchronized (sone) {
268 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
269 logger.log(Level.FINE, String.format("Sone β%sβ was not modified further, resetting counterβ¦", sone));
270 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
271 core.touchConfiguration();
276 } catch (Throwable t1) {
277 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
283 public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
284 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
288 * Container for information that are required to insert a Sone. This
289 * container merely exists to copy all relevant data without holding a lock
290 * on the {@link Sone} object for too long.
293 class InsertInformation implements Closeable {
295 /** All properties of the Sone, copied for thread safety. */
296 private final Map<String, Object> soneProperties = new HashMap<>();
297 private final String fingerprint;
298 private final ManifestCreator manifestCreator;
301 * Creates a new insert information container.
306 public InsertInformation(Sone sone) {
307 this.fingerprint = sone.getFingerprint();
308 Map<String, Object> soneProperties = new HashMap<>();
309 soneProperties.put("id", sone.getId());
310 soneProperties.put("name", sone.getName());
311 soneProperties.put("time", currentTimeMillis());
312 soneProperties.put("profile", sone.getProfile());
313 soneProperties.put("posts", Ordering.from(newestPostFirst()).sortedCopy(sone.getPosts()));
314 soneProperties.put("replies", Ordering.from(newestReplyFirst()).sortedCopy(sone.getReplies()));
315 soneProperties.put("likedPostIds", new HashSet<>(sone.getLikedPostIds()));
316 soneProperties.put("likedReplyIds", new HashSet<>(sone.getLikedReplyIds()));
317 soneProperties.put("albums", SoneKt.getAllAlbums(sone).stream().filter(AlbumKt.notEmpty()::invoke).collect(toList()));
318 manifestCreator = new ManifestCreator(core, soneProperties);
326 String getFingerprint() {
335 * Generates all manifest entries required to insert this Sone.
337 * @return The manifest entries for the Sone insert
339 public HashMap<String, Object> generateManifestEntries() {
340 HashMap<String, Object> manifestEntries = new HashMap<>();
342 /* first, create an index.html. */
343 manifestEntries.put("index.html", manifestCreator.createManifestElement(
344 "index.html", "text/html; charset=utf-8",
345 "/templates/insert/index.html"));
347 /* now, store the sone. */
348 manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
349 "sone.xml", "text/xml; charset=utf-8",
350 "/templates/insert/sone.xml"));
352 return manifestEntries;
356 public void close() {
357 manifestCreator.close();
363 * Creates manifest elements for an insert by rendering a template.
366 static class ManifestCreator implements Closeable {
368 private final Core core;
369 private final Map<String, Object> soneProperties;
370 private final Set<Bucket> buckets = new HashSet<>();
372 ManifestCreator(Core core, Map<String, Object> soneProperties) {
374 this.soneProperties = soneProperties;
377 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
379 try (InputStream templateInputStream = getClass().getResourceAsStream(templateName);
380 InputStreamReader templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset)) {
381 template = TemplateParser.parse(templateInputStreamReader);
382 } catch (IOException | TemplateException e1) {
383 logger.log(Level.SEVERE, String.format("Could not parse template β%sβ!", templateName), e1);
387 TemplateContext templateContext = templateContextFactory.createTemplateContext();
388 templateContext.set("core", core);
389 templateContext.set("currentSone", soneProperties);
390 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
391 templateContext.set("version", SonePlugin.getPluginVersion());
392 try (StringWriter writer = new StringWriter()) {
393 template.render(templateContext, writer);
394 RandomAccessBucket bucket = new ArrayBucket(writer.toString().getBytes(Charsets.UTF_8));
396 return new ManifestElement(name, bucket, contentType, bucket.size());
397 } catch (IOException | TemplateException e1) {
398 logger.log(Level.SEVERE, String.format("Could not render template β%sβ!", templateName), e1);
403 public void close() {
404 for (Bucket bucket : buckets) {