001package io.jstach.rainbowgum;
002
003import java.io.PrintStream;
004import java.lang.System.Logger.Level;
005import java.time.Instant;
006import java.util.ArrayList;
007import java.util.Arrays;
008import java.util.List;
009import java.util.Locale;
010import java.util.Map;
011import java.util.Objects;
012import java.util.concurrent.CopyOnWriteArrayList;
013import java.util.concurrent.atomic.AtomicLong;
014import java.util.concurrent.locks.ReentrantLock;
015import java.util.function.Supplier;
016
017import org.jspecify.annotations.Nullable;
018
019import io.jstach.rainbowgum.annotation.EnumAlias;
020
021/**
022 * Alerts (sometimes called errors or status events elsewhere) are for reporting problems
023 * with the logging system itself rather than application logging - for example an
024 * appender failing to write, or an async publisher's queue overflowing. Because logging
025 * itself may be broken these are not routed through the normal {@link LogRouter} but are
026 * instead kept in a small in memory ring buffer (see {@link #dump()} and
027 * {@link #stats()}). Warning and error alerts are also reported immediately (currently to
028 * stderr); informational alerts remain available for diagnostics without producing output
029 * by default.
030 * <p>
031 * An instance is available from every {@link LogConfig#alerts()}. Components that are
032 * {@linkplain LogProvider provided} config, or that are
033 * {@linkplain LogLifecycle#start( LogConfig) started} with config, should prefer
034 * capturing {@code config.alerts()} over reaching for global state.
035 * <p>
036 * {@link LogAlerts} is itself a {@link LogLifecycle}: {@link #start(LogConfig)} is called
037 * exactly once, after every
038 * {@link io.jstach.rainbowgum.spi.RainbowGumServiceProvider.Configurator} has run, and is
039 * where {@link UnobservedErrorsAction} (already resolved at construction, same as
040 * capacity) gets applied against whatever has been recorded by then - see that enum for
041 * what "nobody is listening yet" means and why it matters specifically at that moment
042 * rather than for the life of the process.
043 *
044 * @see LogConfig#alerts()
045 */
046public sealed interface LogAlerts extends LogLifecycle permits DefaultLogAlerts, SwappableLogAlerts {
047
048  /**
049   * Default capacity of the alert ring buffer.
050   */
051  static final int DEFAULT_CAPACITY = 512;
052
053  /**
054   * Key of the key value, set to {@code true}, that marks an alert as being about
055   * configuration, such as a property key that was set but not read. Only those alerts
056   * fail startup with {@link FailLevel#CONFIG}. See
057   * {@link #config(Class, Level, String, Throwable)}.
058   */
059  static final String CONFIG_KEY = "alert.config";
060
061  /**
062   * Records an alert.
063   * @param event event describing the alert.
064   */
065  public void alert(LogEvent event);
066
067  /**
068   * Records an alert.
069   * @param loggerName usually the class where the alert originated.
070   * @param throwable cause of the alert.
071   */
072  default void error(Class<?> loggerName, Throwable throwable) {
073    String m = Objects.requireNonNullElse(throwable.getMessage(), "exception");
074    error(loggerName, m, throwable);
075  }
076
077  /**
078   * Records an alert.
079   * @param loggerName usually the class where the alert originated.
080   * @param message alert message.
081   * @param throwable cause of the alert.
082   */
083  default void error(Class<?> loggerName, String message, Throwable throwable) {
084    alert(event(loggerName, Level.ERROR, message, throwable));
085  }
086
087  /**
088   * Records an alert about configuration, such as a property that is set wrong, as
089   * opposed to a problem while logging, such as an appender failing to write.
090   * Configuration sources outside core use it so {@link FailLevel#CONFIG} can fail
091   * startup on their alerts.
092   * @param loggerName usually the class where the alert originated.
093   * @param level alert level.
094   * @param message alert message.
095   * @param throwable cause of the alert, if any.
096   * @see #CONFIG_KEY
097   */
098  default void config(Class<?> loggerName, Level level, String message, @Nullable Throwable throwable) {
099    var currentThread = Thread.currentThread();
100    alert(LogEvent.of(Instant.now(), currentThread.getName(), currentThread.threadId(), level, loggerName.getName(),
101        message, DefaultLogAlerts.configKeyValues(), throwable));
102  }
103
104  /**
105   * Records a warning alert.
106   * @param loggerName usually the class where the alert originated.
107   * @param message alert message.
108   */
109  default void warn(Class<?> loggerName, String message) {
110    alert(event(loggerName, Level.WARNING, message, null));
111  }
112
113  /**
114   * Records an informational alert.
115   * @param loggerName usually the class where the alert originated.
116   * @param message alert message.
117   */
118  default void info(Class<?> loggerName, String message) {
119    alert(event(loggerName, Level.INFO, message, null));
120  }
121
122  private static LogEvent event(Class<?> loggerName, Level level, String message, @Nullable Throwable throwable) {
123    var currentThread = Thread.currentThread();
124    return LogEvent.of(Instant.now(), currentThread.getName(), currentThread.threadId(), level,
125        loggerName.getName(), message, KeyValues.of(), throwable);
126  }
127
128  /**
129   * A snapshot of the alerts currently held in the ring buffer, oldest first. Alerts
130   * are evicted oldest first once the buffer is at {@link Stats#capacity()}.
131   * @return immutable snapshot.
132   */
133  public List<LogEvent> dump();
134
135  /**
136   * Clears the ring buffer. Does not reset {@link Stats#total()} - like a
137   * Prometheus/Micrometer counter, that is meant to be monotonically increasing for the
138   * life of the process; a downstream metrics system computes rate of change rather
139   * than relying on the counter itself being reset. Clearing diagnostics does not undo
140   * an alert that fails startup under {@link FailLevel}.
141   */
142  public void clear();
143
144  /**
145   * Stats about the alerts recorded so far.
146   * @return stats.
147   */
148  public Stats stats();
149
150  /**
151   * Registers a listener that is notified synchronously, in addition to the alert being
152   * recorded in the ring buffer, every time {@link #alert(LogEvent)} is called.
153   * <p>
154   * <strong>Listeners are held with a normal (strong) reference and are not
155   * automatically removed.</strong> This is deliberate: alert listeners are expected to
156   * be few and long lived - typically registered once (e.g. a metrics bridge or an
157   * ops/paging integration) for as long as the owning {@link LogConfig} is - rather
158   * than one per short lived object. A weak reference would risk silently dropping a
159   * listener (a lambda with no other strong reference could be collected almost
160   * immediately) which is the wrong failure mode for something whose entire job is not
161   * losing alerts. Call {@link AutoCloseable#close()} on the returned registration to
162   * unregister deterministically once the caller's own lifecycle ends.
163   * @param listener listener to register.
164   * @return registration; {@link AutoCloseable#close()} unregisters the listener.
165   */
166  public AutoCloseable addListener(Listener listener);
167
168  /**
169   * Notified of alerts as they happen. See {@link #addListener(Listener)}.
170   */
171  @FunctionalInterface
172  interface Listener {
173
174    /**
175     * Called synchronously every time an alert is recorded. Should not throw -
176     * exceptions are caught and reported separately so a broken listener cannot
177     * disrupt alert recording or other listeners.
178     * @param event the alert.
179     */
180    void onAlert(LogEvent event);
181
182  }
183
184  /**
185   * Stats about alerts recorded.
186   *
187   * @param total total number of alerts ever recorded, including ones since evicted
188   * from the ring buffer.
189   * @param size number of alerts currently held in the ring buffer.
190   * @param capacity maximum number of alerts the ring buffer holds.
191   */
192  record Stats(long total, int size, int capacity) {
193  }
194
195  /**
196   * What building LogConfig and starting Rainbow Gum do with alerts recorded while
197   * starting, set by {@value LogProperties#ALERTS_FAIL_PROPERTY}. Checked once when
198   * {@link LogConfig} is built and once right after Rainbow Gum starts; alerts after
199   * that never fail anything. Evicting or clearing an alert from the diagnostic queue
200   * does not prevent it from failing startup.
201   */
202  enum FailLevel {
203
204    /**
205     * Alerts never fail startup.
206     */
207    @EnumAlias("false")
208    OFF,
209    /**
210     * Default. Fail if a warning or error alert about configuration is recorded while
211     * starting, such as a property key that was probably misspelled. Problems while
212     * logging, such as an appender failing to write, do not fail startup.
213     * @see LogAlerts#CONFIG_KEY
214     */
215    CONFIG,
216    /**
217     * Fail if any error alert is recorded while starting.
218     */
219    ERROR,
220    /**
221     * Fail if any warning or error alert is recorded while starting.
222     */
223    @EnumAlias({ "true", "warn" })
224    WARNING;
225
226    static FailLevel parse(String value) {
227      return switch (value.toLowerCase(java.util.Locale.ROOT)) {
228        case "true", "warn" -> WARNING;
229        case "false" -> OFF;
230        default -> LogProperty.enumValue(FailLevel.class, value, "true", "false", "warn");
231      };
232    }
233
234    boolean fails(LogEvent event) {
235      return fails(event.level(), DefaultLogAlerts.isConfig(event));
236    }
237
238    boolean fails(Level level, boolean config) {
239      boolean warningOrAbove = level == Level.ERROR || level == Level.WARNING;
240      return switch (this) {
241        case OFF -> false;
242        case CONFIG -> config && warningOrAbove;
243        case ERROR -> level == Level.ERROR;
244        case WARNING -> warningOrAbove;
245      };
246    }
247
248    /*
249     * How a failure names what it failed on.
250     */
251    String failing() {
252      return switch (this) {
253        case CONFIG -> "configuration alert(s) at warning";
254        case OFF, ERROR, WARNING -> "alert(s) at " + name().toLowerCase(Locale.ROOT);
255      };
256    }
257
258  }
259
260  /**
261   * The alert level for a property key that was set but not read while starting, set by
262   * {@value LogProperties#ALERTS_UNUSED_KEY_PROPERTY}. Keys are only checked in the
263   * debug modes that report them and when {@value LogProperties#ALERTS_FAIL_PROPERTY}
264   * would fail on them.
265   */
266  enum UnusedKeyLevel {
267
268    /**
269     * Default. A key close to a key that was read is a warning with a suggestion, as
270     * is a URI query parameter the component its URI chose does not read. Any other
271     * unread key is information, since it may be for a component that was not chosen,
272     * as is a key that differs from the suggestion only in a component's name or
273     * type.
274     */
275    INFO,
276    /**
277     * Every unread key is a warning, so the default
278     * {@code logging.alerts.fail=config} fails on any of them.
279     */
280    @EnumAlias("warn")
281    WARNING,
282    /**
283     * Every unread key is an error, so {@code logging.alerts.fail=error} fails on any
284     * of them.
285     */
286    ERROR;
287
288    static UnusedKeyLevel parse(String value) {
289      return switch (value.toLowerCase(java.util.Locale.ROOT)) {
290        case "warn" -> WARNING;
291        default -> LogProperty.enumValue(UnusedKeyLevel.class, value, "warn");
292      };
293    }
294
295    Level level(boolean likelyMistake) {
296      return switch (this) {
297        case INFO -> likelyMistake ? Level.WARNING : Level.INFO;
298        case WARNING -> Level.WARNING;
299        case ERROR -> Level.ERROR;
300      };
301    }
302
303  }
304
305  /**
306   * What {@link #start(LogConfig)} does if, at that moment, at least one error alert
307   * has been recorded and still zero {@link Listener}s are registered - the situation
308   * Logback's {@code StatusManager} calls an unobserved status: nothing is watching, so
309   * whatever went wrong during property loading or a
310   * {@link io.jstach.rainbowgum.spi.RainbowGumServiceProvider.Configurator} would
311   * otherwise only ever have reached the individual, easy to miss stderr lines each
312   * {@link #alert(LogEvent)} call already produces.
313   * <p>
314   * Deliberately keyed as
315   * {@value LogProperties#ALERTS_UNOBSERVED_ERRORS_ACTION_PROPERTY} (an enum, not a
316   * boolean) since "fail" without "dump" first would throw away the only diagnostic
317   * evidence of why it failed.
318   */
319  enum UnobservedErrorsAction {
320
321    /**
322     * Do nothing beyond the immediate reporting of warning and error events.
323     */
324    NONE,
325    /**
326     * Default. Report the whole backlog to {@code MetaLog} as one clearly labeled
327     * block, the same way Logback auto-installs a console listener and prints its
328     * accumulated status if nothing else is watching by the end of configuration -
329     * RainbowGum still starts.
330     */
331    DUMP,
332    /**
333     * Same reporting as {@link #DUMP}, but then throws, so
334     * {@link LogConfig.Builder#build()} (and therefore whatever is building a
335     * {@link RainbowGum} from it) never completes. Goes further than Logback ever
336     * does - an explicit, opt-in choice of integrity over resilience for deployments
337     * where a silently-broken bootstrap is worse than refusing to start.
338     */
339    FAIL;
340
341    static UnobservedErrorsAction parse(String value) {
342      return LogProperty.enumValue(UnobservedErrorsAction.class, value);
343    }
344
345  }
346
347}
348
349/*
350 * Handed to PropertiesProviders. Buffers alerts until the configured LogAlerts exists,
351 * then drainTo replays the buffer into it and forwards every later call, so a provider
352 * may keep this instance and alert after provideProperties returns. Replay and swap
353 * happen under one lock so a concurrent alert is neither lost nor reordered. Listener
354 * registration is never supported: providers record alerts but cannot observe them.
355 */
356final class SwappableLogAlerts implements LogAlerts {
357
358  private final List<LogEvent> events = new ArrayList<>();
359
360  private long total;
361
362  private volatile @Nullable LogAlerts delegate;
363
364  @Override
365  public void alert(LogEvent event) {
366    var d = delegate;
367    if (d == null) {
368      synchronized (this) {
369        d = delegate;
370        if (d == null) {
371          events.add(event.freeze());
372          total++;
373          return;
374        }
375      }
376    }
377    d.alert(event);
378  }
379
380  synchronized void drainTo(LogAlerts target) {
381    if (delegate != null) {
382      throw new IllegalStateException("Alerts have already been drained");
383    }
384    for (var event : events) {
385      target.alert(event);
386    }
387    events.clear();
388    delegate = target;
389  }
390
391  @Override
392  public synchronized List<LogEvent> dump() {
393    var d = delegate;
394    return d != null ? d.dump() : List.copyOf(events);
395  }
396
397  @Override
398  public synchronized void clear() {
399    var d = delegate;
400    if (d != null) {
401      d.clear();
402    }
403    else {
404      events.clear();
405    }
406  }
407
408  @Override
409  public synchronized Stats stats() {
410    var d = delegate;
411    return d != null ? d.stats() : new Stats(total, events.size(), Integer.MAX_VALUE);
412  }
413
414  @Override
415  public AutoCloseable addListener(Listener listener) {
416    throw new UnsupportedOperationException("Properties providers cannot register alert listeners");
417  }
418
419  @Override
420  public void start(LogConfig config) {
421    throw new UnsupportedOperationException("Properties provider alerts cannot be started");
422  }
423
424  @Override
425  public synchronized void close() {
426    // The drained delegate belongs to LogConfig, so only an undrained buffer is
427    // dropped.
428    if (delegate == null) {
429      events.clear();
430    }
431  }
432
433}
434
435final class DefaultLogAlerts implements LogAlerts {
436
437  /*
438   * Used when neither the property nor the builder sets the fail level. LogConfig uses
439   * it too, to decide whether to record property reads.
440   */
441  static final FailLevel DEFAULT_FAIL_LEVEL = FailLevel.CONFIG;
442
443  static KeyValues configKeyValues() {
444    return KeyValues.of(Map.of(CONFIG_KEY, "true"));
445  }
446
447  static boolean isConfig(LogEvent event) {
448    return "true".equals(event.keyValues().getValueOrNull(CONFIG_KEY));
449  }
450
451  private final LogEvent[] ring;
452
453  private int start = 0;
454
455  private int size = 0;
456
457  private final AtomicLong total = new AtomicLong();
458
459  private final AtomicLong errors = new AtomicLong();
460
461  private final ReentrantLock lock = new ReentrantLock();
462
463  private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
464
465  /*
466   * Kept apart from listeners.isEmpty() deliberately: DefaultLogConfig's own
467   * metrics-bridge listener (see its constructor) is always registered before
468   * start(...) ever runs, and a passive in-process counter nobody has wired an exporter
469   * to is not "someone is watching" in the sense UnobservedErrorsAction cares about -
470   * only a real addListener(Listener) call (this class's public API) flips this.
471   */
472  private volatile boolean hasExternalListener = false;
473
474  private final LogEventFactory eventFactory = LogEventFactory.of(DefaultLogAlerts.class.getName());
475
476  /*
477   * Resolved once, at construction (same as capacity) rather than inside start(...):
478   * unlike capacity this does not shape any constructor-time state, but LogProperties
479   * is available just as early, and start(LogConfig) is really about announcing "I have
480   * started" (config is there because a few edge cases needed it, not because this
481   * needed to be a start-time lookup).
482   */
483  private final UnobservedErrorsAction unobservedErrorsAction;
484
485  /*
486   * Private and deliberately not defensive - of(LogProperties) below is the only
487   * caller, and it has already validated both fields (capacity > 0, a resolvable
488   * UnobservedErrorsAction) before ever reaching this constructor. Re-checking here
489   * would be defensive programming duplicating what was already a real, reported
490   * validation failure one call up - see of(...)'s own comment.
491   */
492  private final FailLevel failLevel;
493
494  /*
495   * Names what set the fail level, for the failure message: the property, or
496   * logging.debug=help raising it.
497   */
498  private final String failLevelSource;
499
500  private final UnusedKeyLevel unusedKeyLevel;
501
502  /*
503   * Startup failure is independent of the bounded diagnostic queue. Keep the first
504   * failure and the count until startup ends, even if clear() or eviction removes it
505   * from the queue. All three fields are protected by lock.
506   */
507  private long startupFailures;
508
509  private @Nullable LogEvent firstStartupFailure;
510
511  private boolean startupComplete;
512
513  private DefaultLogAlerts(int capacity, UnobservedErrorsAction unobservedErrorsAction, FailLevel failLevel,
514      String failLevelSource, UnusedKeyLevel unusedKeyLevel) {
515    this.ring = new LogEvent[capacity];
516    this.unobservedErrorsAction = unobservedErrorsAction;
517    this.failLevel = failLevel;
518    this.failLevelSource = failLevelSource;
519    this.unusedKeyLevel = unusedKeyLevel;
520  }
521
522  FailLevel failLevel() {
523    return failLevel;
524  }
525
526  UnusedKeyLevel unusedKeyLevel() {
527    return unusedKeyLevel;
528  }
529
530  /*
531   * Checks the startup failure count and lists retained failing alerts, including the
532   * first failure even if it left the queue. Called when LogConfig is built and right
533   * after Rainbow Gum starts.
534   */
535  void failIfAlerted(String phase) {
536    checkStartup(phase, false);
537  }
538
539  void finishStartup() {
540    checkStartup("starting", true);
541  }
542
543  private void checkStartup(String phase, boolean complete) {
544    lock.lock();
545    try {
546      if (startupComplete) {
547        return;
548      }
549      startupComplete = complete;
550      var first = firstStartupFailure;
551      if (first == null) {
552        return;
553      }
554      var failing = new ArrayList<>(dump().stream().filter(failLevel::fails).toList());
555      if (!failing.contains(first)) {
556        failing.addFirst(first);
557      }
558      var sb = new StringBuilder();
559      sb.append(startupFailures)
560        .append(" ")
561        .append(failLevel.failing())
562        .append(" or above were recorded while ")
563        .append(phase)
564        .append(" and ")
565        .append(failLevelSource)
566        .append(":");
567      for (var e : failing) {
568        sb.append("\n[").append(e.level()).append("] ");
569        e.formattedMessage(sb);
570      }
571      if (startupFailures > failing.size()) {
572        sb.append("\n")
573          .append(startupFailures - failing.size())
574          .append(" additional failing alert(s) are no longer retained.");
575      }
576      throw new IllegalStateException(sb.toString());
577    }
578    finally {
579      if (complete) {
580        firstStartupFailure = null;
581      }
582      lock.unlock();
583    }
584  }
585
586  /*
587   * The fail level as resolved from properties, before LogAlerts exists, so LogConfig
588   * can decide whether to record property reads. Resolved again, and validated, by
589   * of(...).
590   */
591  static FailLevel failLevelOr(LogProperties properties, FailLevel fallback) {
592    var value = properties.valueOrNull(LogProperties.ALERTS_FAIL_PROPERTY);
593    try {
594      return value == null ? fallback : FailLevel.parse(value);
595    }
596    catch (RuntimeException e) {
597      return fallback;
598    }
599  }
600
601  /*
602   * The unused key level as resolved from properties, before LogAlerts exists, like
603   * failLevelOr. An invalid value is reported by of(...).
604   */
605  static UnusedKeyLevel unusedKeyLevelOr(LogProperties properties, UnusedKeyLevel fallback) {
606    var value = properties.valueOrNull(LogProperties.ALERTS_UNUSED_KEY_PROPERTY);
607    try {
608      return value == null ? fallback : UnusedKeyLevel.parse(value);
609    }
610    catch (RuntimeException e) {
611      return fallback;
612    }
613  }
614
615  /*
616   * Package-friend static factory: resolves and validates both
617   * LogProperties#ALERTS_CAPACITY_PROPERTY and
618   * LogProperties#ALERTS_UNOBSERVED_ERRORS_ACTION_PROPERTY against one shared Validator
619   * - a mistake in both at once is reported together instead of only the first one
620   * found - then constructs. requirePositiveCapacity is a plain int -> int validating
621   * transform (not an object construction) specifically so it can sit inside map(...)
622   * without tripping CheckerFramework's Initialization Checker, which does not refine a
623   * `new Foo(...)` expression back to @Initialized when it appears directly inside a
624   * lambda body passed through a generic method like map(...) - the one and only `new
625   * DefaultLogAlerts(...)` call stays a plain, unconditional statement here instead.
626   */
627  static DefaultLogAlerts of(LogProperties properties, @Nullable FailLevel failLevelFallback,
628      UnusedKeyLevel unusedKeyLevelFallback, boolean help) {
629    var validator = LogProperty.Validator.of(LogAlerts.class);
630    var failLevelResult = properties.forKey(LogProperties.ALERTS_FAIL_PROPERTY)
631      .ofString()
632      .map(FailLevel::parse)
633      .or(Objects.requireNonNullElse(failLevelFallback, DEFAULT_FAIL_LEVEL))
634      .validateIfError(validator);
635    var unobservedErrorsActionResult = properties.forKey(LogProperties.ALERTS_UNOBSERVED_ERRORS_ACTION_PROPERTY)
636      .ofString()
637      .map(UnobservedErrorsAction::parse)
638      .or(UnobservedErrorsAction.DUMP)
639      .validateIfError(validator);
640    var unusedKeyLevelResult = properties.forKey(LogProperties.ALERTS_UNUSED_KEY_PROPERTY)
641      .ofString()
642      .map(UnusedKeyLevel::parse)
643      .or(unusedKeyLevelFallback)
644      .validateIfError(validator);
645    var capacityResult = properties.forKey(LogProperties.ALERTS_CAPACITY_PROPERTY)
646      .ofInt()
647      .or(LogAlerts.DEFAULT_CAPACITY)
648      .map(DefaultLogAlerts::requirePositiveCapacity)
649      .validateIfError(validator);
650    validator.validate();
651    var failLevel = failLevelResult.value();
652    String failLevelSource = LogProperties.ALERTS_FAIL_PROPERTY + "=" + failLevel.name().toLowerCase(Locale.ROOT);
653    boolean defaulted = failLevelFallback == null
654        && properties.valueOrNull(LogProperties.ALERTS_FAIL_PROPERTY) == null;
655    if (help && (defaulted || failLevel != FailLevel.WARNING)) {
656      failLevel = FailLevel.WARNING;
657      failLevelSource = "logging.debug=help";
658    }
659    else if (defaulted) {
660      failLevelSource += " (the default)";
661    }
662    return new DefaultLogAlerts(capacityResult.value(), unobservedErrorsActionResult.value(), failLevel,
663        failLevelSource, unusedKeyLevelResult.value());
664  }
665
666  private static int requirePositiveCapacity(int capacity) {
667    if (capacity <= 0) {
668      throw new IllegalArgumentException("capacity should be greater than 0");
669    }
670    return capacity;
671  }
672
673  @Override
674  public void alert(LogEvent event) {
675    var frozen = event.freeze();
676    total.incrementAndGet();
677    if (frozen.level() == Level.ERROR) {
678      errors.incrementAndGet();
679    }
680    lock.lock();
681    try {
682      if (!startupComplete && failLevel.fails(frozen)) {
683        startupFailures++;
684        if (firstStartupFailure == null) {
685          firstStartupFailure = frozen;
686        }
687      }
688      if (size < ring.length) {
689        ring[(start + size) % ring.length] = frozen;
690        size++;
691      }
692      else {
693        ring[start] = frozen;
694        start = (start + 1) % ring.length;
695      }
696    }
697    finally {
698      lock.unlock();
699    }
700    for (var listener : listeners) {
701      try {
702        listener.onAlert(frozen);
703      }
704      catch (Exception e) {
705        MetaLog.INSTANCE.log(eventFactory.eventNoArg(Level.ERROR, "LogAlerts.Listener threw", e));
706      }
707    }
708    if (frozen.level() == Level.WARNING || frozen.level() == Level.ERROR) {
709      MetaLog.INSTANCE.log(frozen);
710    }
711  }
712
713  @Override
714  public AutoCloseable addListener(Listener listener) {
715    listeners.add(listener);
716    hasExternalListener = true;
717    return () -> listeners.remove(listener);
718  }
719
720  /*
721   * DefaultLogConfig's own metrics-bridge listener goes through this instead of
722   * addListener(Listener) - see hasExternalListener's own comment for why.
723   */
724  void addInternalListener(Listener listener) {
725    listeners.add(listener);
726  }
727
728  @Override
729  public void start(LogConfig config) {
730    if (unobservedErrorsAction == UnobservedErrorsAction.NONE || hasExternalListener || errors.get() == 0) {
731      return;
732    }
733    var backlog = dump();
734    MetaLog.error(eventFactory.eventNoArg(Level.ERROR,
735        backlog.size() + " alert(s) were recorded before any LogAlerts.Listener was registered - "
736            + "dumping the backlog now since nothing else will see it:",
737        null));
738    for (var event : backlog) {
739      MetaLog.error(event);
740    }
741    if (unobservedErrorsAction == UnobservedErrorsAction.FAIL) {
742      throw new IllegalStateException(
743          backlog.size() + " alert(s) were recorded before any LogAlerts.Listener was registered and "
744              + LogProperties.ALERTS_UNOBSERVED_ERRORS_ACTION_PROPERTY + "=FAIL - refusing to start.");
745    }
746  }
747
748  @Override
749  public void close() {
750    listeners.clear();
751    lock.lock();
752    try {
753      startupComplete = true;
754      firstStartupFailure = null;
755    }
756    finally {
757      lock.unlock();
758    }
759  }
760
761  @Override
762  public List<LogEvent> dump() {
763    lock.lock();
764    try {
765      List<LogEvent> list = new ArrayList<>(size);
766      for (int i = 0; i < size; i++) {
767        var e = ring[(start + i) % ring.length];
768        if (e != null) {
769          list.add(e);
770        }
771      }
772      return List.copyOf(list);
773    }
774    finally {
775      lock.unlock();
776    }
777  }
778
779  @Override
780  public void clear() {
781    lock.lock();
782    try {
783      Arrays.fill(ring, null);
784      start = 0;
785      size = 0;
786    }
787    finally {
788      lock.unlock();
789    }
790  }
791
792  @Override
793  public Stats stats() {
794    lock.lock();
795    try {
796      return new Stats(total.get(), size, ring.length);
797    }
798    finally {
799      lock.unlock();
800    }
801  }
802
803}
804
805/**
806 * Logging about logging. This is the static, always-available entry point used by code
807 * that cannot easily reach a {@link LogConfig} (e.g. before a {@link RainbowGum} is
808 * bound), and always reports directly (currently to stderr) rather than forwarding to a
809 * bound {@link RainbowGum}'s {@link LogConfig#alerts()} - alerts is a small bounded ring
810 * buffer meant to hold a curated, recent view of noteworthy logging-system problems, and
811 * {@link MetaLog} is used from enough different low level failure paths that routing it
812 * there risked flooding/evicting genuine alerts with whatever volume of things end up
813 * calling this class.
814 * <p>
815 * Components that already have (or can easily capture) a {@link LogConfig} - for example
816 * via {@link LogProvider} or {@link LogLifecycle#start(LogConfig)} - should prefer
817 * {@link LogConfig#alerts()} directly instead of this class.
818 *
819 * @author agentgt
820 */
821@SuppressWarnings("ImmutableEnumChecker")
822enum MetaLog implements LogEventLogger {
823
824  INSTANCE;
825
826  static Supplier<? extends @Nullable PrintStream> output = () -> System.err;
827
828  private final LogFormatter formatter = LogFormatter.builder() //
829    .text("[")
830    .level()
831    .text("] - RAINBOW_GUM")
832    .text(" - ")
833    .add(LogFormatter.of((b, e) -> {
834      b.append(gumLoggerName(e.loggerName()));
835    }))
836    .text(" - ")
837    .message()
838    .textIfThrowable(" ")
839    .throwable((b, t) -> {
840      int start = b.length();
841      try {
842        LogFormatter.ThrowableFormatter.appendThrowable(b, t);
843      }
844      catch (Throwable failure) {
845        if (failure instanceof VirtualMachineError fatal && !(failure instanceof StackOverflowError)) {
846          throw fatal;
847        }
848        // A formatting failure can retain the broken event throwable as its
849        // cause. Do not invoke either throwable again to report that failure.
850        b.setLength(start);
851        b.append(t.getClass().getName())
852          .append(" [stack trace unavailable: ")
853          .append(failure.getClass().getName())
854          .append("]");
855      }
856    })
857    .newline()
858    .build();
859
860  /**
861   * Reports a logging system event at its original level.
862   * @param event event to log.
863   */
864  static void error(LogEvent event) {
865    INSTANCE.log(event);
866  }
867
868  /**
869   * Logs an error in the logging system.
870   * @param loggerName derived from class.
871   * @param throwable error to log.
872   */
873  static void error(Class<?> loggerName, Throwable throwable) {
874    String m = Objects.requireNonNullElse(throwable.getMessage(), "exception");
875    error(loggerName, m, throwable);
876  }
877
878  /**
879   * Logs an error in the logging system.
880   * @param loggerName derived from class.
881   * @param message error message.
882   * @param throwable error to log.
883   */
884  static void error(Class<?> loggerName, String message, Throwable throwable) {
885    var currentThread = Thread.currentThread();
886    var event = LogEvent.of(Instant.now(), currentThread.getName(), currentThread.threadId(), Level.ERROR,
887        loggerName.getName(), message, KeyValues.of(), throwable);
888    error(event);
889  }
890
891  private static String gumLoggerName(String value) {
892    String prefix = "io.jstach.rainbowgum.";
893    if (value.startsWith(prefix)) {
894      value = value.substring(prefix.length());
895    }
896    return value;
897  }
898
899  @Override
900  public void log(LogEvent event) {
901    var err = output.get();
902    if (err != null) {
903      var sb = new StringBuilder();
904      formatter.format(sb, event);
905      err.append(sb);
906    }
907  }
908
909}