Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand All@@ -41,7 +41,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/maven-publish.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
126 changes: 113 additions & 13 deletions config/src/main/java/dev/faststats/config/SimpleConfig.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
import org.jspecify.annotations.Nullable;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
Expand All@@ -21,15 +20,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;

@ApiStatus.Internal
public record SimpleConfig(
UUID serverId,
boolean enabled,
boolean additionalMetrics,
boolean debug,
boolean submitMetrics,
boolean errorTracking,
boolean firstRun
) implements Config {
public final class SimpleConfig implements Config {
private static final int CONFIG_VERSION = 2;

private static final String COMMENT = """
Expand DownExpand Up@@ -58,7 +49,86 @@ public record SimpleConfig(
Learn more at: https://faststats.dev/info

Since this is your first start with FastStats, submission will not start
until you restart the server to allow you to opt out if you prefer.""";
until after a restart, to allow you to opt out if you prefer.""";

private final Path file;
private final UUID serverId;
private final boolean debug;
private final boolean firstRun;
private volatile boolean additionalMetrics;
private volatile boolean enabled;
private volatile boolean errorTracking;
private volatile boolean submitMetrics;

public SimpleConfig(
final Path file,
final UUID serverId,
final boolean enabled,
final boolean additionalMetrics,
final boolean debug,
final boolean submitMetrics,
final boolean errorTracking,
final boolean firstRun
) {
this.file = file;
this.serverId = serverId;
this.enabled = enabled;
this.additionalMetrics = additionalMetrics;
this.debug = debug;
this.submitMetrics = submitMetrics;
this.errorTracking = errorTracking;
this.firstRun = firstRun;
}

@Override
public UUID serverId() {
return serverId;
}

@Override
public boolean enabled() {
return enabled;
}

public void enabled(final boolean enabled) {
this.enabled = enabled;
}

@Override
public boolean additionalMetrics() {
return additionalMetrics;
}

public void additionalMetrics(final boolean additionalMetrics) {
this.additionalMetrics = additionalMetrics;
}

@Override
public boolean debug() {
return debug;
}

@Override
public boolean submitMetrics() {
return submitMetrics;
}

public void submitMetrics(final boolean submitMetrics) {
this.submitMetrics = submitMetrics;
}

@Override
public boolean errorTracking() {
return errorTracking;
}

public void errorTracking(final boolean errorTracking) {
this.errorTracking = errorTracking;
}

public boolean firstRun() {
return firstRun;
}

@Contract(mutates = "io")
public static SimpleConfig read(final Path file, final LoggerFactory factory) throws RuntimeException {
Expand DownExpand Up@@ -91,8 +161,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
if (configVersion != null && configVersion < CONFIG_VERSION)
logger.info("Updating config version from %s to %s", configVersion, CONFIG_VERSION);
Files.createDirectories(file.getParent());
try (final var out = Files.newOutputStream(file);
final var writer = new OutputStreamWriter(out, UTF_8)) {
try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
final var store = new Properties();

store.setProperty("enabled", Boolean.toString(enabled));
Expand All@@ -112,6 +181,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
}

return new SimpleConfig(
file,
serverId,
enabled && enabledFlag,
enabled && enabledFlag && additionalMetrics,
Expand All@@ -122,6 +192,23 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
);
}

@Contract(mutates = "io")
public void persist() throws RuntimeException {
final var properties = readOrEmpty(file);
if (properties == null) throw new IllegalStateException("Metrics config has not been initialized");

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create file


properties.setProperty("enabled", Boolean.toString(enabled()));
properties.setProperty("submitAdditionalMetrics", Boolean.toString(additionalMetrics()));
properties.setProperty("submitErrors", Boolean.toString(errorTracking()));
properties.setProperty("submitMetrics", Boolean.toString(submitMetrics()));

try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
properties.store(writer, COMMENT);
} catch (final IOException e) {
throw new RuntimeException("Failed to save metrics config", e);
}
}

// fixme: this code sucks ass
@Contract(value = "_, _, _, !null, _, _-> !null")
private static <T> @Nullable T parse(
Expand DownExpand Up@@ -180,4 +267,17 @@ public boolean preSubmissionStart(final SimpleContext context) {
}
return true;
}

@Override
public String toString() {
return "SimpleConfig{" +
"serverId=" + serverId +
", debug=" + debug +
", firstRun=" + firstRun +
", additionalMetrics=" + additionalMetrics +
", enabled=" + enabled +
", errorTracking=" + errorTracking +
", submitMetrics=" + submitMetrics +
'}';
}
}
6 changes: 6 additions & 0 deletions core/src/main/java/dev/faststats/Metrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,12 +3,18 @@
import dev.faststats.data.Metric;
import org.jetbrains.annotations.Contract;

import java.util.stream.Stream;

/**
* Metrics interface.
*
* @since 0.24.0
*/
public interface Metrics {
// todo: document
@Contract(pure = true)
Stream<Metric<?>> stream();

/**
* A metrics factory.
*
Expand Down
29 changes: 26 additions & 3 deletions core/src/main/java/dev/faststats/SimpleContext.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,11 @@
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo still valid: still dont like the impl

public non-sealed abstract class SimpleContext implements FastStatsContext {
private final @Token String token;
private final Config config;
Expand All@@ -24,6 +26,7 @@ public non-sealed abstract class SimpleContext implements FastStatsContext {
private final Logger logger;

protected volatile boolean ready = false;
public volatile boolean submissionActive;

private @Nullable Metrics metrics;
private @Nullable FeatureFlagService featureFlagService;
Expand DownExpand Up@@ -56,14 +59,33 @@ protected SimpleContext(final Factory<?, ?> factory, final LoggerFactory loggerF

@MustBeInvokedByOverriders
protected final void initializeServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, false);
}

/**
* Initializes service descriptions before consent so this context can participate in a live lifecycle registry.
*/
@MustBeInvokedByOverriders
protected final void initializeManagedServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, true);
}

private void initializeServices(final Factory<?, ?> factory, final boolean lifecycleManaged) {
if (factory.metrics == null && factory.errorTracker == null && factory.featureFlagService == null)
throw new IllegalStateException("Context created without any service attached, was this intentional?");

if (!preSubmissionStart()) return;
final var start = preSubmissionStart();
if (!lifecycleManaged && !start) return;
Comment on lines +77 to +78

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guard preSubmissionStart with lifecycleManaged; otherwise the onboarding message is printed multiple times


this.metrics = config.submitMetrics() && factory.metrics != null ? factory.metrics.apply(metricsFactory()) : null;
this.errorTrackerService = config.errorTracking() && factory.errorTracker != null ? new SimpleErrorTrackerService(this, factory.errorTracker) : null;
if (factory.metrics != null && (lifecycleManaged || config.submitMetrics())) {
final var metricsFactory = metricsFactory();
this.metrics = factory.metrics.apply(metricsFactory);
}
this.errorTrackerService = factory.errorTracker != null && (lifecycleManaged || config.errorTracking())
? new SimpleErrorTrackerService(this, factory.errorTracker)
: null;
this.featureFlagService = factory.featureFlagService != null ? factory.featureFlagService.apply(new SimpleFeatureFlagService.Factory(this)) : null;
this.submissionActive = start;

final var features = new HashSet<String>(3);
features.add("metrics=" + (metrics != null ? "yes" : "no"));
Expand DownExpand Up@@ -161,6 +183,7 @@ public void shutdown() {
if (errorTrackerService != null) errorTrackerService.shutdown();
if (featureFlagService instanceof final SimpleFeatureFlagService service) service.shutdown();
if (metrics instanceof final SimpleMetrics simpleMetrics) simpleMetrics.shutdown();
this.submissionActive = false;
ready = false;
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ private static void handleUncaughtException(final Thread thread, final Throwable
}

private void submit() {
if (!context.submissionActive || !context.getConfig().errorTracking()) return;
try {
final var data = createData();
if (data == null) return;
Expand DownExpand Up@@ -111,7 +112,7 @@ private void submit() {
return data;
}

private void clear() {
public void clear() {
globalErrorTracker.clear();
errorTrackers.forEach(SimpleErrorTracker::clear);
}
Expand Down
11 changes: 10 additions & 1 deletion core/src/main/java/dev/faststats/SimpleMetrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,10 @@
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@ApiStatus.Internal
// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: still sucks

public abstract class SimpleMetrics extends SubmissionService implements Metrics {
private static final String COLLECT_PATH = "/v1/collect";

Expand All@@ -26,7 +28,7 @@ public abstract class SimpleMetrics extends SubmissionService implements Metrics
@Contract(mutates = "io")
protected SimpleMetrics(final Factory factory) {
super(factory.context);
this.metrics = context.getConfig().additionalMetrics() ? Set.copyOf(factory.metrics) : Set.of();
this.metrics = Set.copyOf(factory.metrics);
this.flush = factory.flush;
}

Expand All@@ -43,6 +45,7 @@ public boolean isClientApplication() {
}

private boolean submit() {
if (!context.submissionActive || !context.getConfig().submitMetrics()) return false;
try {
if (submit(url, createData(), "metrics")) {
if (flush != null) flush.run();
Expand DownExpand Up@@ -78,6 +81,7 @@ private void appendInternalData(final JsonObject metrics) {
}

private void appendCustomData(final JsonObject metrics) {
if (!context.getConfig().additionalMetrics()) return;
this.metrics.forEach(metric -> {
try {
if (metrics.has(metric.getId())) {
Expand DownExpand Up@@ -124,6 +128,11 @@ protected void shutdown() {
}
}

@Override
public Stream<Metric<?>> stream() {
return metrics.stream();
}

public abstract static class Factory implements Metrics.Factory {
private @Nullable Runnable flush;
private final Set<Metric<?>> metrics = new HashSet<>(0);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/dev/faststats/internal/Logger.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ default void debug(final LogLevel level, @PrintFormat final String message, @Nul
}

String caller();

LoggerFactory factory();

void print(LogLevel level, @Nullable Throwable t, String message);
Expand Down
20 changes: 20 additions & 0 deletions fabric/build.gradle.kts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,21 +33,41 @@ allprojects {
subprojects {
if (project.name == "example-mod") return@subprojects

// todo: move to respective sub-module
val onboardingBand = when (project.name) {
"1.16.1-1.17.1" -> ":onboarding:versions:1.16.1-1.17.1"
"1.18-1.18.2" -> ":onboarding:versions:1.18-1.18.2"
"1.19-1.19.3" -> ":onboarding:versions:1.19-1.19.3"
"1.18-1.21.8" -> ":onboarding:versions:1.19.4-1.21.8"
"1.21.9-1.21.11" -> ":onboarding:versions:1.21.9-1.21.11"
"26.1-26.3" -> ":onboarding:versions:26.1-26.3"
else -> null
}
evaluationDependsOn(":onboarding")
onboardingBand?.let { evaluationDependsOn(it) }

dependencies {
compileOnlyApi(project(":fabric"))
compileOnlyApi(project(":onboarding"))
onboardingBand?.let {
compileOnlyApi(project(it))
}
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(project(":fabric").sourceSets["main"].output)
from(project(":config").sourceSets["main"].output)
from(project(":core").sourceSets["main"].output)
from(project(":onboarding").sourceSets["main"].output)
onboardingBand?.let { from(project(it).sourceSets["main"].output) }
}
}

dependencies {
compileOnlyApi(project(":core"))
compileOnly(project(":config"))
compileOnly(project(":onboarding"))
minecraft("com.mojang:minecraft:26.1.2")
compileOnly("net.fabricmc.fabric-api:fabric-api:0.150.0+26.1.2")
compileOnly("net.fabricmc:fabric-loader:0.19.3")
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand All@@ -41,7 +41,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/maven-publish.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
126 changes: 113 additions & 13 deletions config/src/main/java/dev/faststats/config/SimpleConfig.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
import org.jspecify.annotations.Nullable;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
Expand All@@ -21,15 +20,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;

@ApiStatus.Internal
public record SimpleConfig(
UUID serverId,
boolean enabled,
boolean additionalMetrics,
boolean debug,
boolean submitMetrics,
boolean errorTracking,
boolean firstRun
) implements Config {
public final class SimpleConfig implements Config {
private static final int CONFIG_VERSION = 2;

private static final String COMMENT = """
Expand DownExpand Up@@ -58,7 +49,86 @@ public record SimpleConfig(
Learn more at: https://faststats.dev/info

Since this is your first start with FastStats, submission will not start
until you restart the server to allow you to opt out if you prefer.""";
until after a restart, to allow you to opt out if you prefer.""";

private final Path file;
private final UUID serverId;
private final boolean debug;
private final boolean firstRun;
private volatile boolean additionalMetrics;
private volatile boolean enabled;
private volatile boolean errorTracking;
private volatile boolean submitMetrics;

public SimpleConfig(
final Path file,
final UUID serverId,
final boolean enabled,
final boolean additionalMetrics,
final boolean debug,
final boolean submitMetrics,
final boolean errorTracking,
final boolean firstRun
) {
this.file = file;
this.serverId = serverId;
this.enabled = enabled;
this.additionalMetrics = additionalMetrics;
this.debug = debug;
this.submitMetrics = submitMetrics;
this.errorTracking = errorTracking;
this.firstRun = firstRun;
}

@Override
public UUID serverId() {
return serverId;
}

@Override
public boolean enabled() {
return enabled;
}

public void enabled(final boolean enabled) {
this.enabled = enabled;
}

@Override
public boolean additionalMetrics() {
return additionalMetrics;
}

public void additionalMetrics(final boolean additionalMetrics) {
this.additionalMetrics = additionalMetrics;
}

@Override
public boolean debug() {
return debug;
}

@Override
public boolean submitMetrics() {
return submitMetrics;
}

public void submitMetrics(final boolean submitMetrics) {
this.submitMetrics = submitMetrics;
}

@Override
public boolean errorTracking() {
return errorTracking;
}

public void errorTracking(final boolean errorTracking) {
this.errorTracking = errorTracking;
}

public boolean firstRun() {
return firstRun;
}

@Contract(mutates = "io")
public static SimpleConfig read(final Path file, final LoggerFactory factory) throws RuntimeException {
Expand DownExpand Up@@ -91,8 +161,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
if (configVersion != null && configVersion < CONFIG_VERSION)
logger.info("Updating config version from %s to %s", configVersion, CONFIG_VERSION);
Files.createDirectories(file.getParent());
try (final var out = Files.newOutputStream(file);
final var writer = new OutputStreamWriter(out, UTF_8)) {
try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
final var store = new Properties();

store.setProperty("enabled", Boolean.toString(enabled));
Expand All@@ -112,6 +181,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
}

return new SimpleConfig(
file,
serverId,
enabled && enabledFlag,
enabled && enabledFlag && additionalMetrics,
Expand All@@ -122,6 +192,23 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
);
}

@Contract(mutates = "io")
public void persist() throws RuntimeException {
final var properties = readOrEmpty(file);
if (properties == null) throw new IllegalStateException("Metrics config has not been initialized");

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create file


properties.setProperty("enabled", Boolean.toString(enabled()));
properties.setProperty("submitAdditionalMetrics", Boolean.toString(additionalMetrics()));
properties.setProperty("submitErrors", Boolean.toString(errorTracking()));
properties.setProperty("submitMetrics", Boolean.toString(submitMetrics()));

try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
properties.store(writer, COMMENT);
} catch (final IOException e) {
throw new RuntimeException("Failed to save metrics config", e);
}
}

// fixme: this code sucks ass
@Contract(value = "_, _, _, !null, _, _-> !null")
private static <T> @Nullable T parse(
Expand DownExpand Up@@ -180,4 +267,17 @@ public boolean preSubmissionStart(final SimpleContext context) {
}
return true;
}

@Override
public String toString() {
return "SimpleConfig{" +
"serverId=" + serverId +
", debug=" + debug +
", firstRun=" + firstRun +
", additionalMetrics=" + additionalMetrics +
", enabled=" + enabled +
", errorTracking=" + errorTracking +
", submitMetrics=" + submitMetrics +
'}';
}
}
6 changes: 6 additions & 0 deletions core/src/main/java/dev/faststats/Metrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,12 +3,18 @@
import dev.faststats.data.Metric;
import org.jetbrains.annotations.Contract;

import java.util.stream.Stream;

/**
* Metrics interface.
*
* @since 0.24.0
*/
public interface Metrics {
// todo: document
@Contract(pure = true)
Stream<Metric<?>> stream();

/**
* A metrics factory.
*
Expand Down
29 changes: 26 additions & 3 deletions core/src/main/java/dev/faststats/SimpleContext.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,11 @@
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo still valid: still dont like the impl

public non-sealed abstract class SimpleContext implements FastStatsContext {
private final @Token String token;
private final Config config;
Expand All@@ -24,6 +26,7 @@ public non-sealed abstract class SimpleContext implements FastStatsContext {
private final Logger logger;

protected volatile boolean ready = false;
public volatile boolean submissionActive;

private @Nullable Metrics metrics;
private @Nullable FeatureFlagService featureFlagService;
Expand DownExpand Up@@ -56,14 +59,33 @@ protected SimpleContext(final Factory<?, ?> factory, final LoggerFactory loggerF

@MustBeInvokedByOverriders
protected final void initializeServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, false);
}

/**
* Initializes service descriptions before consent so this context can participate in a live lifecycle registry.
*/
@MustBeInvokedByOverriders
protected final void initializeManagedServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, true);
}

private void initializeServices(final Factory<?, ?> factory, final boolean lifecycleManaged) {
if (factory.metrics == null && factory.errorTracker == null && factory.featureFlagService == null)
throw new IllegalStateException("Context created without any service attached, was this intentional?");

if (!preSubmissionStart()) return;
final var start = preSubmissionStart();
if (!lifecycleManaged && !start) return;
Comment on lines +77 to +78

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guard preSubmissionStart with lifecycleManaged; otherwise the onboarding message is printed multiple times


this.metrics = config.submitMetrics() && factory.metrics != null ? factory.metrics.apply(metricsFactory()) : null;
this.errorTrackerService = config.errorTracking() && factory.errorTracker != null ? new SimpleErrorTrackerService(this, factory.errorTracker) : null;
if (factory.metrics != null && (lifecycleManaged || config.submitMetrics())) {
final var metricsFactory = metricsFactory();
this.metrics = factory.metrics.apply(metricsFactory);
}
this.errorTrackerService = factory.errorTracker != null && (lifecycleManaged || config.errorTracking())
? new SimpleErrorTrackerService(this, factory.errorTracker)
: null;
this.featureFlagService = factory.featureFlagService != null ? factory.featureFlagService.apply(new SimpleFeatureFlagService.Factory(this)) : null;
this.submissionActive = start;

final var features = new HashSet<String>(3);
features.add("metrics=" + (metrics != null ? "yes" : "no"));
Expand DownExpand Up@@ -161,6 +183,7 @@ public void shutdown() {
if (errorTrackerService != null) errorTrackerService.shutdown();
if (featureFlagService instanceof final SimpleFeatureFlagService service) service.shutdown();
if (metrics instanceof final SimpleMetrics simpleMetrics) simpleMetrics.shutdown();
this.submissionActive = false;
ready = false;
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ private static void handleUncaughtException(final Thread thread, final Throwable
}

private void submit() {
if (!context.submissionActive || !context.getConfig().errorTracking()) return;
try {
final var data = createData();
if (data == null) return;
Expand DownExpand Up@@ -111,7 +112,7 @@ private void submit() {
return data;
}

private void clear() {
public void clear() {
globalErrorTracker.clear();
errorTrackers.forEach(SimpleErrorTracker::clear);
}
Expand Down
11 changes: 10 additions & 1 deletion core/src/main/java/dev/faststats/SimpleMetrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,10 @@
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@ApiStatus.Internal
// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: still sucks

public abstract class SimpleMetrics extends SubmissionService implements Metrics {
private static final String COLLECT_PATH = "/v1/collect";

Expand All@@ -26,7 +28,7 @@ public abstract class SimpleMetrics extends SubmissionService implements Metrics
@Contract(mutates = "io")
protected SimpleMetrics(final Factory factory) {
super(factory.context);
this.metrics = context.getConfig().additionalMetrics() ? Set.copyOf(factory.metrics) : Set.of();
this.metrics = Set.copyOf(factory.metrics);
this.flush = factory.flush;
}

Expand All@@ -43,6 +45,7 @@ public boolean isClientApplication() {
}

private boolean submit() {
if (!context.submissionActive || !context.getConfig().submitMetrics()) return false;
try {
if (submit(url, createData(), "metrics")) {
if (flush != null) flush.run();
Expand DownExpand Up@@ -78,6 +81,7 @@ private void appendInternalData(final JsonObject metrics) {
}

private void appendCustomData(final JsonObject metrics) {
if (!context.getConfig().additionalMetrics()) return;
this.metrics.forEach(metric -> {
try {
if (metrics.has(metric.getId())) {
Expand DownExpand Up@@ -124,6 +128,11 @@ protected void shutdown() {
}
}

@Override
public Stream<Metric<?>> stream() {
return metrics.stream();
}

public abstract static class Factory implements Metrics.Factory {
private @Nullable Runnable flush;
private final Set<Metric<?>> metrics = new HashSet<>(0);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/dev/faststats/internal/Logger.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ default void debug(final LogLevel level, @PrintFormat final String message, @Nul
}

String caller();

LoggerFactory factory();

void print(LogLevel level, @Nullable Throwable t, String message);
Expand Down
20 changes: 20 additions & 0 deletions fabric/build.gradle.kts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,21 +33,41 @@ allprojects {
subprojects {
if (project.name == "example-mod") return@subprojects

// todo: move to respective sub-module
val onboardingBand = when (project.name) {
"1.16.1-1.17.1" -> ":onboarding:versions:1.16.1-1.17.1"
"1.18-1.18.2" -> ":onboarding:versions:1.18-1.18.2"
"1.19-1.19.3" -> ":onboarding:versions:1.19-1.19.3"
"1.18-1.21.8" -> ":onboarding:versions:1.19.4-1.21.8"
"1.21.9-1.21.11" -> ":onboarding:versions:1.21.9-1.21.11"
"26.1-26.3" -> ":onboarding:versions:26.1-26.3"
else -> null
}
evaluationDependsOn(":onboarding")
onboardingBand?.let { evaluationDependsOn(it) }

dependencies {
compileOnlyApi(project(":fabric"))
compileOnlyApi(project(":onboarding"))
onboardingBand?.let {
compileOnlyApi(project(it))
}
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(project(":fabric").sourceSets["main"].output)
from(project(":config").sourceSets["main"].output)
from(project(":core").sourceSets["main"].output)
from(project(":onboarding").sourceSets["main"].output)
onboardingBand?.let { from(project(it).sourceSets["main"].output) }
}
}

dependencies {
compileOnlyApi(project(":core"))
compileOnly(project(":config"))
compileOnly(project(":onboarding"))
minecraft("com.mojang:minecraft:26.1.2")
compileOnly("net.fabricmc.fabric-api:fabric-api:0.150.0+26.1.2")
compileOnly("net.fabricmc:fabric-loader:0.19.3")
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand All@@ -41,7 +41,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/maven-publish.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
126 changes: 113 additions & 13 deletions config/src/main/java/dev/faststats/config/SimpleConfig.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
import org.jspecify.annotations.Nullable;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
Expand All@@ -21,15 +20,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;

@ApiStatus.Internal
public record SimpleConfig(
UUID serverId,
boolean enabled,
boolean additionalMetrics,
boolean debug,
boolean submitMetrics,
boolean errorTracking,
boolean firstRun
) implements Config {
public final class SimpleConfig implements Config {
private static final int CONFIG_VERSION = 2;

private static final String COMMENT = """
Expand DownExpand Up@@ -58,7 +49,86 @@ public record SimpleConfig(
Learn more at: https://faststats.dev/info

Since this is your first start with FastStats, submission will not start
until you restart the server to allow you to opt out if you prefer.""";
until after a restart, to allow you to opt out if you prefer.""";

private final Path file;
private final UUID serverId;
private final boolean debug;
private final boolean firstRun;
private volatile boolean additionalMetrics;
private volatile boolean enabled;
private volatile boolean errorTracking;
private volatile boolean submitMetrics;

public SimpleConfig(
final Path file,
final UUID serverId,
final boolean enabled,
final boolean additionalMetrics,
final boolean debug,
final boolean submitMetrics,
final boolean errorTracking,
final boolean firstRun
) {
this.file = file;
this.serverId = serverId;
this.enabled = enabled;
this.additionalMetrics = additionalMetrics;
this.debug = debug;
this.submitMetrics = submitMetrics;
this.errorTracking = errorTracking;
this.firstRun = firstRun;
}

@Override
public UUID serverId() {
return serverId;
}

@Override
public boolean enabled() {
return enabled;
}

public void enabled(final boolean enabled) {
this.enabled = enabled;
}

@Override
public boolean additionalMetrics() {
return additionalMetrics;
}

public void additionalMetrics(final boolean additionalMetrics) {
this.additionalMetrics = additionalMetrics;
}

@Override
public boolean debug() {
return debug;
}

@Override
public boolean submitMetrics() {
return submitMetrics;
}

public void submitMetrics(final boolean submitMetrics) {
this.submitMetrics = submitMetrics;
}

@Override
public boolean errorTracking() {
return errorTracking;
}

public void errorTracking(final boolean errorTracking) {
this.errorTracking = errorTracking;
}

public boolean firstRun() {
return firstRun;
}

@Contract(mutates = "io")
public static SimpleConfig read(final Path file, final LoggerFactory factory) throws RuntimeException {
Expand DownExpand Up@@ -91,8 +161,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
if (configVersion != null && configVersion < CONFIG_VERSION)
logger.info("Updating config version from %s to %s", configVersion, CONFIG_VERSION);
Files.createDirectories(file.getParent());
try (final var out = Files.newOutputStream(file);
final var writer = new OutputStreamWriter(out, UTF_8)) {
try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
final var store = new Properties();

store.setProperty("enabled", Boolean.toString(enabled));
Expand All@@ -112,6 +181,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
}

return new SimpleConfig(
file,
serverId,
enabled && enabledFlag,
enabled && enabledFlag && additionalMetrics,
Expand All@@ -122,6 +192,23 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
);
}

@Contract(mutates = "io")
public void persist() throws RuntimeException {
final var properties = readOrEmpty(file);
if (properties == null) throw new IllegalStateException("Metrics config has not been initialized");

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create file


properties.setProperty("enabled", Boolean.toString(enabled()));
properties.setProperty("submitAdditionalMetrics", Boolean.toString(additionalMetrics()));
properties.setProperty("submitErrors", Boolean.toString(errorTracking()));
properties.setProperty("submitMetrics", Boolean.toString(submitMetrics()));

try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
properties.store(writer, COMMENT);
} catch (final IOException e) {
throw new RuntimeException("Failed to save metrics config", e);
}
}

// fixme: this code sucks ass
@Contract(value = "_, _, _, !null, _, _-> !null")
private static <T> @Nullable T parse(
Expand DownExpand Up@@ -180,4 +267,17 @@ public boolean preSubmissionStart(final SimpleContext context) {
}
return true;
}

@Override
public String toString() {
return "SimpleConfig{" +
"serverId=" + serverId +
", debug=" + debug +
", firstRun=" + firstRun +
", additionalMetrics=" + additionalMetrics +
", enabled=" + enabled +
", errorTracking=" + errorTracking +
", submitMetrics=" + submitMetrics +
'}';
}
}
6 changes: 6 additions & 0 deletions core/src/main/java/dev/faststats/Metrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,12 +3,18 @@
import dev.faststats.data.Metric;
import org.jetbrains.annotations.Contract;

import java.util.stream.Stream;

/**
* Metrics interface.
*
* @since 0.24.0
*/
public interface Metrics {
// todo: document
@Contract(pure = true)
Stream<Metric<?>> stream();

/**
* A metrics factory.
*
Expand Down
29 changes: 26 additions & 3 deletions core/src/main/java/dev/faststats/SimpleContext.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,11 @@
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo still valid: still dont like the impl

public non-sealed abstract class SimpleContext implements FastStatsContext {
private final @Token String token;
private final Config config;
Expand All@@ -24,6 +26,7 @@ public non-sealed abstract class SimpleContext implements FastStatsContext {
private final Logger logger;

protected volatile boolean ready = false;
public volatile boolean submissionActive;

private @Nullable Metrics metrics;
private @Nullable FeatureFlagService featureFlagService;
Expand DownExpand Up@@ -56,14 +59,33 @@ protected SimpleContext(final Factory<?, ?> factory, final LoggerFactory loggerF

@MustBeInvokedByOverriders
protected final void initializeServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, false);
}

/**
* Initializes service descriptions before consent so this context can participate in a live lifecycle registry.
*/
@MustBeInvokedByOverriders
protected final void initializeManagedServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, true);
}

private void initializeServices(final Factory<?, ?> factory, final boolean lifecycleManaged) {
if (factory.metrics == null && factory.errorTracker == null && factory.featureFlagService == null)
throw new IllegalStateException("Context created without any service attached, was this intentional?");

if (!preSubmissionStart()) return;
final var start = preSubmissionStart();
if (!lifecycleManaged && !start) return;
Comment on lines +77 to +78

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guard preSubmissionStart with lifecycleManaged; otherwise the onboarding message is printed multiple times


this.metrics = config.submitMetrics() && factory.metrics != null ? factory.metrics.apply(metricsFactory()) : null;
this.errorTrackerService = config.errorTracking() && factory.errorTracker != null ? new SimpleErrorTrackerService(this, factory.errorTracker) : null;
if (factory.metrics != null && (lifecycleManaged || config.submitMetrics())) {
final var metricsFactory = metricsFactory();
this.metrics = factory.metrics.apply(metricsFactory);
}
this.errorTrackerService = factory.errorTracker != null && (lifecycleManaged || config.errorTracking())
? new SimpleErrorTrackerService(this, factory.errorTracker)
: null;
this.featureFlagService = factory.featureFlagService != null ? factory.featureFlagService.apply(new SimpleFeatureFlagService.Factory(this)) : null;
this.submissionActive = start;

final var features = new HashSet<String>(3);
features.add("metrics=" + (metrics != null ? "yes" : "no"));
Expand DownExpand Up@@ -161,6 +183,7 @@ public void shutdown() {
if (errorTrackerService != null) errorTrackerService.shutdown();
if (featureFlagService instanceof final SimpleFeatureFlagService service) service.shutdown();
if (metrics instanceof final SimpleMetrics simpleMetrics) simpleMetrics.shutdown();
this.submissionActive = false;
ready = false;
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ private static void handleUncaughtException(final Thread thread, final Throwable
}

private void submit() {
if (!context.submissionActive || !context.getConfig().errorTracking()) return;
try {
final var data = createData();
if (data == null) return;
Expand DownExpand Up@@ -111,7 +112,7 @@ private void submit() {
return data;
}

private void clear() {
public void clear() {
globalErrorTracker.clear();
errorTrackers.forEach(SimpleErrorTracker::clear);
}
Expand Down
11 changes: 10 additions & 1 deletion core/src/main/java/dev/faststats/SimpleMetrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,10 @@
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@ApiStatus.Internal
// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: still sucks

public abstract class SimpleMetrics extends SubmissionService implements Metrics {
private static final String COLLECT_PATH = "/v1/collect";

Expand All@@ -26,7 +28,7 @@ public abstract class SimpleMetrics extends SubmissionService implements Metrics
@Contract(mutates = "io")
protected SimpleMetrics(final Factory factory) {
super(factory.context);
this.metrics = context.getConfig().additionalMetrics() ? Set.copyOf(factory.metrics) : Set.of();
this.metrics = Set.copyOf(factory.metrics);
this.flush = factory.flush;
}

Expand All@@ -43,6 +45,7 @@ public boolean isClientApplication() {
}

private boolean submit() {
if (!context.submissionActive || !context.getConfig().submitMetrics()) return false;
try {
if (submit(url, createData(), "metrics")) {
if (flush != null) flush.run();
Expand DownExpand Up@@ -78,6 +81,7 @@ private void appendInternalData(final JsonObject metrics) {
}

private void appendCustomData(final JsonObject metrics) {
if (!context.getConfig().additionalMetrics()) return;
this.metrics.forEach(metric -> {
try {
if (metrics.has(metric.getId())) {
Expand DownExpand Up@@ -124,6 +128,11 @@ protected void shutdown() {
}
}

@Override
public Stream<Metric<?>> stream() {
return metrics.stream();
}

public abstract static class Factory implements Metrics.Factory {
private @Nullable Runnable flush;
private final Set<Metric<?>> metrics = new HashSet<>(0);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/dev/faststats/internal/Logger.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ default void debug(final LogLevel level, @PrintFormat final String message, @Nul
}

String caller();

LoggerFactory factory();

void print(LogLevel level, @Nullable Throwable t, String message);
Expand Down
20 changes: 20 additions & 0 deletions fabric/build.gradle.kts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,21 +33,41 @@ allprojects {
subprojects {
if (project.name == "example-mod") return@subprojects

// todo: move to respective sub-module
val onboardingBand = when (project.name) {
"1.16.1-1.17.1" -> ":onboarding:versions:1.16.1-1.17.1"
"1.18-1.18.2" -> ":onboarding:versions:1.18-1.18.2"
"1.19-1.19.3" -> ":onboarding:versions:1.19-1.19.3"
"1.18-1.21.8" -> ":onboarding:versions:1.19.4-1.21.8"
"1.21.9-1.21.11" -> ":onboarding:versions:1.21.9-1.21.11"
"26.1-26.3" -> ":onboarding:versions:26.1-26.3"
else -> null
}
evaluationDependsOn(":onboarding")
onboardingBand?.let { evaluationDependsOn(it) }

dependencies {
compileOnlyApi(project(":fabric"))
compileOnlyApi(project(":onboarding"))
onboardingBand?.let {
compileOnlyApi(project(it))
}
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(project(":fabric").sourceSets["main"].output)
from(project(":config").sourceSets["main"].output)
from(project(":core").sourceSets["main"].output)
from(project(":onboarding").sourceSets["main"].output)
onboardingBand?.let { from(project(it).sourceSets["main"].output) }
}
}

dependencies {
compileOnlyApi(project(":core"))
compileOnly(project(":config"))
compileOnly(project(":onboarding"))
minecraft("com.mojang:minecraft:26.1.2")
compileOnly("net.fabricmc.fabric-api:fabric-api:0.150.0+26.1.2")
compileOnly("net.fabricmc:fabric-loader:0.19.3")
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand All@@ -41,7 +41,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/maven-publish.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
126 changes: 113 additions & 13 deletions config/src/main/java/dev/faststats/config/SimpleConfig.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
import org.jspecify.annotations.Nullable;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
Expand All@@ -21,15 +20,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;

@ApiStatus.Internal
public record SimpleConfig(
UUID serverId,
boolean enabled,
boolean additionalMetrics,
boolean debug,
boolean submitMetrics,
boolean errorTracking,
boolean firstRun
) implements Config {
public final class SimpleConfig implements Config {
private static final int CONFIG_VERSION = 2;

private static final String COMMENT = """
Expand DownExpand Up@@ -58,7 +49,86 @@ public record SimpleConfig(
Learn more at: https://faststats.dev/info

Since this is your first start with FastStats, submission will not start
until you restart the server to allow you to opt out if you prefer.""";
until after a restart, to allow you to opt out if you prefer.""";

private final Path file;
private final UUID serverId;
private final boolean debug;
private final boolean firstRun;
private volatile boolean additionalMetrics;
private volatile boolean enabled;
private volatile boolean errorTracking;
private volatile boolean submitMetrics;

public SimpleConfig(
final Path file,
final UUID serverId,
final boolean enabled,
final boolean additionalMetrics,
final boolean debug,
final boolean submitMetrics,
final boolean errorTracking,
final boolean firstRun
) {
this.file = file;
this.serverId = serverId;
this.enabled = enabled;
this.additionalMetrics = additionalMetrics;
this.debug = debug;
this.submitMetrics = submitMetrics;
this.errorTracking = errorTracking;
this.firstRun = firstRun;
}

@Override
public UUID serverId() {
return serverId;
}

@Override
public boolean enabled() {
return enabled;
}

public void enabled(final boolean enabled) {
this.enabled = enabled;
}

@Override
public boolean additionalMetrics() {
return additionalMetrics;
}

public void additionalMetrics(final boolean additionalMetrics) {
this.additionalMetrics = additionalMetrics;
}

@Override
public boolean debug() {
return debug;
}

@Override
public boolean submitMetrics() {
return submitMetrics;
}

public void submitMetrics(final boolean submitMetrics) {
this.submitMetrics = submitMetrics;
}

@Override
public boolean errorTracking() {
return errorTracking;
}

public void errorTracking(final boolean errorTracking) {
this.errorTracking = errorTracking;
}

public boolean firstRun() {
return firstRun;
}

@Contract(mutates = "io")
public static SimpleConfig read(final Path file, final LoggerFactory factory) throws RuntimeException {
Expand DownExpand Up@@ -91,8 +161,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
if (configVersion != null && configVersion < CONFIG_VERSION)
logger.info("Updating config version from %s to %s", configVersion, CONFIG_VERSION);
Files.createDirectories(file.getParent());
try (final var out = Files.newOutputStream(file);
final var writer = new OutputStreamWriter(out, UTF_8)) {
try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
final var store = new Properties();

store.setProperty("enabled", Boolean.toString(enabled));
Expand All@@ -112,6 +181,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
}

return new SimpleConfig(
file,
serverId,
enabled && enabledFlag,
enabled && enabledFlag && additionalMetrics,
Expand All@@ -122,6 +192,23 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
);
}

@Contract(mutates = "io")
public void persist() throws RuntimeException {
final var properties = readOrEmpty(file);
if (properties == null) throw new IllegalStateException("Metrics config has not been initialized");

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create file


properties.setProperty("enabled", Boolean.toString(enabled()));
properties.setProperty("submitAdditionalMetrics", Boolean.toString(additionalMetrics()));
properties.setProperty("submitErrors", Boolean.toString(errorTracking()));
properties.setProperty("submitMetrics", Boolean.toString(submitMetrics()));

try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
properties.store(writer, COMMENT);
} catch (final IOException e) {
throw new RuntimeException("Failed to save metrics config", e);
}
}

// fixme: this code sucks ass
@Contract(value = "_, _, _, !null, _, _-> !null")
private static <T> @Nullable T parse(
Expand DownExpand Up@@ -180,4 +267,17 @@ public boolean preSubmissionStart(final SimpleContext context) {
}
return true;
}

@Override
public String toString() {
return "SimpleConfig{" +
"serverId=" + serverId +
", debug=" + debug +
", firstRun=" + firstRun +
", additionalMetrics=" + additionalMetrics +
", enabled=" + enabled +
", errorTracking=" + errorTracking +
", submitMetrics=" + submitMetrics +
'}';
}
}
6 changes: 6 additions & 0 deletions core/src/main/java/dev/faststats/Metrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,12 +3,18 @@
import dev.faststats.data.Metric;
import org.jetbrains.annotations.Contract;

import java.util.stream.Stream;

/**
* Metrics interface.
*
* @since 0.24.0
*/
public interface Metrics {
// todo: document
@Contract(pure = true)
Stream<Metric<?>> stream();

/**
* A metrics factory.
*
Expand Down
29 changes: 26 additions & 3 deletions core/src/main/java/dev/faststats/SimpleContext.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,11 @@
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo still valid: still dont like the impl

public non-sealed abstract class SimpleContext implements FastStatsContext {
private final @Token String token;
private final Config config;
Expand All@@ -24,6 +26,7 @@ public non-sealed abstract class SimpleContext implements FastStatsContext {
private final Logger logger;

protected volatile boolean ready = false;
public volatile boolean submissionActive;

private @Nullable Metrics metrics;
private @Nullable FeatureFlagService featureFlagService;
Expand DownExpand Up@@ -56,14 +59,33 @@ protected SimpleContext(final Factory<?, ?> factory, final LoggerFactory loggerF

@MustBeInvokedByOverriders
protected final void initializeServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, false);
}

/**
* Initializes service descriptions before consent so this context can participate in a live lifecycle registry.
*/
@MustBeInvokedByOverriders
protected final void initializeManagedServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, true);
}

private void initializeServices(final Factory<?, ?> factory, final boolean lifecycleManaged) {
if (factory.metrics == null && factory.errorTracker == null && factory.featureFlagService == null)
throw new IllegalStateException("Context created without any service attached, was this intentional?");

if (!preSubmissionStart()) return;
final var start = preSubmissionStart();
if (!lifecycleManaged && !start) return;
Comment on lines +77 to +78

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guard preSubmissionStart with lifecycleManaged; otherwise the onboarding message is printed multiple times


this.metrics = config.submitMetrics() && factory.metrics != null ? factory.metrics.apply(metricsFactory()) : null;
this.errorTrackerService = config.errorTracking() && factory.errorTracker != null ? new SimpleErrorTrackerService(this, factory.errorTracker) : null;
if (factory.metrics != null && (lifecycleManaged || config.submitMetrics())) {
final var metricsFactory = metricsFactory();
this.metrics = factory.metrics.apply(metricsFactory);
}
this.errorTrackerService = factory.errorTracker != null && (lifecycleManaged || config.errorTracking())
? new SimpleErrorTrackerService(this, factory.errorTracker)
: null;
this.featureFlagService = factory.featureFlagService != null ? factory.featureFlagService.apply(new SimpleFeatureFlagService.Factory(this)) : null;
this.submissionActive = start;

final var features = new HashSet<String>(3);
features.add("metrics=" + (metrics != null ? "yes" : "no"));
Expand DownExpand Up@@ -161,6 +183,7 @@ public void shutdown() {
if (errorTrackerService != null) errorTrackerService.shutdown();
if (featureFlagService instanceof final SimpleFeatureFlagService service) service.shutdown();
if (metrics instanceof final SimpleMetrics simpleMetrics) simpleMetrics.shutdown();
this.submissionActive = false;
ready = false;
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ private static void handleUncaughtException(final Thread thread, final Throwable
}

private void submit() {
if (!context.submissionActive || !context.getConfig().errorTracking()) return;
try {
final var data = createData();
if (data == null) return;
Expand DownExpand Up@@ -111,7 +112,7 @@ private void submit() {
return data;
}

private void clear() {
public void clear() {
globalErrorTracker.clear();
errorTrackers.forEach(SimpleErrorTracker::clear);
}
Expand Down
11 changes: 10 additions & 1 deletion core/src/main/java/dev/faststats/SimpleMetrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,10 @@
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@ApiStatus.Internal
// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: still sucks

public abstract class SimpleMetrics extends SubmissionService implements Metrics {
private static final String COLLECT_PATH = "/v1/collect";

Expand All@@ -26,7 +28,7 @@ public abstract class SimpleMetrics extends SubmissionService implements Metrics
@Contract(mutates = "io")
protected SimpleMetrics(final Factory factory) {
super(factory.context);
this.metrics = context.getConfig().additionalMetrics() ? Set.copyOf(factory.metrics) : Set.of();
this.metrics = Set.copyOf(factory.metrics);
this.flush = factory.flush;
}

Expand All@@ -43,6 +45,7 @@ public boolean isClientApplication() {
}

private boolean submit() {
if (!context.submissionActive || !context.getConfig().submitMetrics()) return false;
try {
if (submit(url, createData(), "metrics")) {
if (flush != null) flush.run();
Expand DownExpand Up@@ -78,6 +81,7 @@ private void appendInternalData(final JsonObject metrics) {
}

private void appendCustomData(final JsonObject metrics) {
if (!context.getConfig().additionalMetrics()) return;
this.metrics.forEach(metric -> {
try {
if (metrics.has(metric.getId())) {
Expand DownExpand Up@@ -124,6 +128,11 @@ protected void shutdown() {
}
}

@Override
public Stream<Metric<?>> stream() {
return metrics.stream();
}

public abstract static class Factory implements Metrics.Factory {
private @Nullable Runnable flush;
private final Set<Metric<?>> metrics = new HashSet<>(0);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/dev/faststats/internal/Logger.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ default void debug(final LogLevel level, @PrintFormat final String message, @Nul
}

String caller();

LoggerFactory factory();

void print(LogLevel level, @Nullable Throwable t, String message);
Expand Down
20 changes: 20 additions & 0 deletions fabric/build.gradle.kts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,21 +33,41 @@ allprojects {
subprojects {
if (project.name == "example-mod") return@subprojects

// todo: move to respective sub-module
val onboardingBand = when (project.name) {
"1.16.1-1.17.1" -> ":onboarding:versions:1.16.1-1.17.1"
"1.18-1.18.2" -> ":onboarding:versions:1.18-1.18.2"
"1.19-1.19.3" -> ":onboarding:versions:1.19-1.19.3"
"1.18-1.21.8" -> ":onboarding:versions:1.19.4-1.21.8"
"1.21.9-1.21.11" -> ":onboarding:versions:1.21.9-1.21.11"
"26.1-26.3" -> ":onboarding:versions:26.1-26.3"
else -> null
}
evaluationDependsOn(":onboarding")
onboardingBand?.let { evaluationDependsOn(it) }

dependencies {
compileOnlyApi(project(":fabric"))
compileOnlyApi(project(":onboarding"))
onboardingBand?.let {
compileOnlyApi(project(it))
}
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(project(":fabric").sourceSets["main"].output)
from(project(":config").sourceSets["main"].output)
from(project(":core").sourceSets["main"].output)
from(project(":onboarding").sourceSets["main"].output)
onboardingBand?.let { from(project(it).sourceSets["main"].output) }
}
}

dependencies {
compileOnlyApi(project(":core"))
compileOnly(project(":config"))
compileOnly(project(":onboarding"))
minecraft("com.mojang:minecraft:26.1.2")
compileOnly("net.fabricmc.fabric-api:fabric-api:0.150.0+26.1.2")
compileOnly("net.fabricmc:fabric-loader:0.19.3")
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand All@@ -41,7 +41,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/maven-publish.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
126 changes: 113 additions & 13 deletions config/src/main/java/dev/faststats/config/SimpleConfig.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
import org.jspecify.annotations.Nullable;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
Expand All@@ -21,15 +20,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;

@ApiStatus.Internal
public record SimpleConfig(
UUID serverId,
boolean enabled,
boolean additionalMetrics,
boolean debug,
boolean submitMetrics,
boolean errorTracking,
boolean firstRun
) implements Config {
public final class SimpleConfig implements Config {
private static final int CONFIG_VERSION = 2;

private static final String COMMENT = """
Expand DownExpand Up@@ -58,7 +49,86 @@ public record SimpleConfig(
Learn more at: https://faststats.dev/info

Since this is your first start with FastStats, submission will not start
until you restart the server to allow you to opt out if you prefer.""";
until after a restart, to allow you to opt out if you prefer.""";

private final Path file;
private final UUID serverId;
private final boolean debug;
private final boolean firstRun;
private volatile boolean additionalMetrics;
private volatile boolean enabled;
private volatile boolean errorTracking;
private volatile boolean submitMetrics;

public SimpleConfig(
final Path file,
final UUID serverId,
final boolean enabled,
final boolean additionalMetrics,
final boolean debug,
final boolean submitMetrics,
final boolean errorTracking,
final boolean firstRun
) {
this.file = file;
this.serverId = serverId;
this.enabled = enabled;
this.additionalMetrics = additionalMetrics;
this.debug = debug;
this.submitMetrics = submitMetrics;
this.errorTracking = errorTracking;
this.firstRun = firstRun;
}

@Override
public UUID serverId() {
return serverId;
}

@Override
public boolean enabled() {
return enabled;
}

public void enabled(final boolean enabled) {
this.enabled = enabled;
}

@Override
public boolean additionalMetrics() {
return additionalMetrics;
}

public void additionalMetrics(final boolean additionalMetrics) {
this.additionalMetrics = additionalMetrics;
}

@Override
public boolean debug() {
return debug;
}

@Override
public boolean submitMetrics() {
return submitMetrics;
}

public void submitMetrics(final boolean submitMetrics) {
this.submitMetrics = submitMetrics;
}

@Override
public boolean errorTracking() {
return errorTracking;
}

public void errorTracking(final boolean errorTracking) {
this.errorTracking = errorTracking;
}

public boolean firstRun() {
return firstRun;
}

@Contract(mutates = "io")
public static SimpleConfig read(final Path file, final LoggerFactory factory) throws RuntimeException {
Expand DownExpand Up@@ -91,8 +161,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
if (configVersion != null && configVersion < CONFIG_VERSION)
logger.info("Updating config version from %s to %s", configVersion, CONFIG_VERSION);
Files.createDirectories(file.getParent());
try (final var out = Files.newOutputStream(file);
final var writer = new OutputStreamWriter(out, UTF_8)) {
try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
final var store = new Properties();

store.setProperty("enabled", Boolean.toString(enabled));
Expand All@@ -112,6 +181,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
}

return new SimpleConfig(
file,
serverId,
enabled && enabledFlag,
enabled && enabledFlag && additionalMetrics,
Expand All@@ -122,6 +192,23 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
);
}

@Contract(mutates = "io")
public void persist() throws RuntimeException {
final var properties = readOrEmpty(file);
if (properties == null) throw new IllegalStateException("Metrics config has not been initialized");

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create file


properties.setProperty("enabled", Boolean.toString(enabled()));
properties.setProperty("submitAdditionalMetrics", Boolean.toString(additionalMetrics()));
properties.setProperty("submitErrors", Boolean.toString(errorTracking()));
properties.setProperty("submitMetrics", Boolean.toString(submitMetrics()));

try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
properties.store(writer, COMMENT);
} catch (final IOException e) {
throw new RuntimeException("Failed to save metrics config", e);
}
}

// fixme: this code sucks ass
@Contract(value = "_, _, _, !null, _, _-> !null")
private static <T> @Nullable T parse(
Expand DownExpand Up@@ -180,4 +267,17 @@ public boolean preSubmissionStart(final SimpleContext context) {
}
return true;
}

@Override
public String toString() {
return "SimpleConfig{" +
"serverId=" + serverId +
", debug=" + debug +
", firstRun=" + firstRun +
", additionalMetrics=" + additionalMetrics +
", enabled=" + enabled +
", errorTracking=" + errorTracking +
", submitMetrics=" + submitMetrics +
'}';
}
}
6 changes: 6 additions & 0 deletions core/src/main/java/dev/faststats/Metrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,12 +3,18 @@
import dev.faststats.data.Metric;
import org.jetbrains.annotations.Contract;

import java.util.stream.Stream;

/**
* Metrics interface.
*
* @since 0.24.0
*/
public interface Metrics {
// todo: document
@Contract(pure = true)
Stream<Metric<?>> stream();

/**
* A metrics factory.
*
Expand Down
29 changes: 26 additions & 3 deletions core/src/main/java/dev/faststats/SimpleContext.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,11 @@
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo still valid: still dont like the impl

public non-sealed abstract class SimpleContext implements FastStatsContext {
private final @Token String token;
private final Config config;
Expand All@@ -24,6 +26,7 @@ public non-sealed abstract class SimpleContext implements FastStatsContext {
private final Logger logger;

protected volatile boolean ready = false;
public volatile boolean submissionActive;

private @Nullable Metrics metrics;
private @Nullable FeatureFlagService featureFlagService;
Expand DownExpand Up@@ -56,14 +59,33 @@ protected SimpleContext(final Factory<?, ?> factory, final LoggerFactory loggerF

@MustBeInvokedByOverriders
protected final void initializeServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, false);
}

/**
* Initializes service descriptions before consent so this context can participate in a live lifecycle registry.
*/
@MustBeInvokedByOverriders
protected final void initializeManagedServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, true);
}

private void initializeServices(final Factory<?, ?> factory, final boolean lifecycleManaged) {
if (factory.metrics == null && factory.errorTracker == null && factory.featureFlagService == null)
throw new IllegalStateException("Context created without any service attached, was this intentional?");

if (!preSubmissionStart()) return;
final var start = preSubmissionStart();
if (!lifecycleManaged && !start) return;
Comment on lines +77 to +78

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guard preSubmissionStart with lifecycleManaged; otherwise the onboarding message is printed multiple times


this.metrics = config.submitMetrics() && factory.metrics != null ? factory.metrics.apply(metricsFactory()) : null;
this.errorTrackerService = config.errorTracking() && factory.errorTracker != null ? new SimpleErrorTrackerService(this, factory.errorTracker) : null;
if (factory.metrics != null && (lifecycleManaged || config.submitMetrics())) {
final var metricsFactory = metricsFactory();
this.metrics = factory.metrics.apply(metricsFactory);
}
this.errorTrackerService = factory.errorTracker != null && (lifecycleManaged || config.errorTracking())
? new SimpleErrorTrackerService(this, factory.errorTracker)
: null;
this.featureFlagService = factory.featureFlagService != null ? factory.featureFlagService.apply(new SimpleFeatureFlagService.Factory(this)) : null;
this.submissionActive = start;

final var features = new HashSet<String>(3);
features.add("metrics=" + (metrics != null ? "yes" : "no"));
Expand DownExpand Up@@ -161,6 +183,7 @@ public void shutdown() {
if (errorTrackerService != null) errorTrackerService.shutdown();
if (featureFlagService instanceof final SimpleFeatureFlagService service) service.shutdown();
if (metrics instanceof final SimpleMetrics simpleMetrics) simpleMetrics.shutdown();
this.submissionActive = false;
ready = false;
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ private static void handleUncaughtException(final Thread thread, final Throwable
}

private void submit() {
if (!context.submissionActive || !context.getConfig().errorTracking()) return;
try {
final var data = createData();
if (data == null) return;
Expand DownExpand Up@@ -111,7 +112,7 @@ private void submit() {
return data;
}

private void clear() {
public void clear() {
globalErrorTracker.clear();
errorTrackers.forEach(SimpleErrorTracker::clear);
}
Expand Down
11 changes: 10 additions & 1 deletion core/src/main/java/dev/faststats/SimpleMetrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,10 @@
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@ApiStatus.Internal
// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: still sucks

public abstract class SimpleMetrics extends SubmissionService implements Metrics {
private static final String COLLECT_PATH = "/v1/collect";

Expand All@@ -26,7 +28,7 @@ public abstract class SimpleMetrics extends SubmissionService implements Metrics
@Contract(mutates = "io")
protected SimpleMetrics(final Factory factory) {
super(factory.context);
this.metrics = context.getConfig().additionalMetrics() ? Set.copyOf(factory.metrics) : Set.of();
this.metrics = Set.copyOf(factory.metrics);
this.flush = factory.flush;
}

Expand All@@ -43,6 +45,7 @@ public boolean isClientApplication() {
}

private boolean submit() {
if (!context.submissionActive || !context.getConfig().submitMetrics()) return false;
try {
if (submit(url, createData(), "metrics")) {
if (flush != null) flush.run();
Expand DownExpand Up@@ -78,6 +81,7 @@ private void appendInternalData(final JsonObject metrics) {
}

private void appendCustomData(final JsonObject metrics) {
if (!context.getConfig().additionalMetrics()) return;
this.metrics.forEach(metric -> {
try {
if (metrics.has(metric.getId())) {
Expand DownExpand Up@@ -124,6 +128,11 @@ protected void shutdown() {
}
}

@Override
public Stream<Metric<?>> stream() {
return metrics.stream();
}

public abstract static class Factory implements Metrics.Factory {
private @Nullable Runnable flush;
private final Set<Metric<?>> metrics = new HashSet<>(0);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/dev/faststats/internal/Logger.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ default void debug(final LogLevel level, @PrintFormat final String message, @Nul
}

String caller();

LoggerFactory factory();

void print(LogLevel level, @Nullable Throwable t, String message);
Expand Down
20 changes: 20 additions & 0 deletions fabric/build.gradle.kts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,21 +33,41 @@ allprojects {
subprojects {
if (project.name == "example-mod") return@subprojects

// todo: move to respective sub-module
val onboardingBand = when (project.name) {
"1.16.1-1.17.1" -> ":onboarding:versions:1.16.1-1.17.1"
"1.18-1.18.2" -> ":onboarding:versions:1.18-1.18.2"
"1.19-1.19.3" -> ":onboarding:versions:1.19-1.19.3"
"1.18-1.21.8" -> ":onboarding:versions:1.19.4-1.21.8"
"1.21.9-1.21.11" -> ":onboarding:versions:1.21.9-1.21.11"
"26.1-26.3" -> ":onboarding:versions:26.1-26.3"
else -> null
}
evaluationDependsOn(":onboarding")
onboardingBand?.let { evaluationDependsOn(it) }

dependencies {
compileOnlyApi(project(":fabric"))
compileOnlyApi(project(":onboarding"))
onboardingBand?.let {
compileOnlyApi(project(it))
}
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(project(":fabric").sourceSets["main"].output)
from(project(":config").sourceSets["main"].output)
from(project(":core").sourceSets["main"].output)
from(project(":onboarding").sourceSets["main"].output)
onboardingBand?.let { from(project(it).sourceSets["main"].output) }
}
}

dependencies {
compileOnlyApi(project(":core"))
compileOnly(project(":config"))
compileOnly(project(":onboarding"))
minecraft("com.mojang:minecraft:26.1.2")
compileOnly("net.fabricmc.fabric-api:fabric-api:0.150.0+26.1.2")
compileOnly("net.fabricmc:fabric-loader:0.19.3")
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand All@@ -41,7 +41,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/maven-publish.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
126 changes: 113 additions & 13 deletions config/src/main/java/dev/faststats/config/SimpleConfig.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
import org.jspecify.annotations.Nullable;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
Expand All@@ -21,15 +20,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;

@ApiStatus.Internal
public record SimpleConfig(
UUID serverId,
boolean enabled,
boolean additionalMetrics,
boolean debug,
boolean submitMetrics,
boolean errorTracking,
boolean firstRun
) implements Config {
public final class SimpleConfig implements Config {
private static final int CONFIG_VERSION = 2;

private static final String COMMENT = """
Expand DownExpand Up@@ -58,7 +49,86 @@ public record SimpleConfig(
Learn more at: https://faststats.dev/info

Since this is your first start with FastStats, submission will not start
until you restart the server to allow you to opt out if you prefer.""";
until after a restart, to allow you to opt out if you prefer.""";

private final Path file;
private final UUID serverId;
private final boolean debug;
private final boolean firstRun;
private volatile boolean additionalMetrics;
private volatile boolean enabled;
private volatile boolean errorTracking;
private volatile boolean submitMetrics;

public SimpleConfig(
final Path file,
final UUID serverId,
final boolean enabled,
final boolean additionalMetrics,
final boolean debug,
final boolean submitMetrics,
final boolean errorTracking,
final boolean firstRun
) {
this.file = file;
this.serverId = serverId;
this.enabled = enabled;
this.additionalMetrics = additionalMetrics;
this.debug = debug;
this.submitMetrics = submitMetrics;
this.errorTracking = errorTracking;
this.firstRun = firstRun;
}

@Override
public UUID serverId() {
return serverId;
}

@Override
public boolean enabled() {
return enabled;
}

public void enabled(final boolean enabled) {
this.enabled = enabled;
}

@Override
public boolean additionalMetrics() {
return additionalMetrics;
}

public void additionalMetrics(final boolean additionalMetrics) {
this.additionalMetrics = additionalMetrics;
}

@Override
public boolean debug() {
return debug;
}

@Override
public boolean submitMetrics() {
return submitMetrics;
}

public void submitMetrics(final boolean submitMetrics) {
this.submitMetrics = submitMetrics;
}

@Override
public boolean errorTracking() {
return errorTracking;
}

public void errorTracking(final boolean errorTracking) {
this.errorTracking = errorTracking;
}

public boolean firstRun() {
return firstRun;
}

@Contract(mutates = "io")
public static SimpleConfig read(final Path file, final LoggerFactory factory) throws RuntimeException {
Expand DownExpand Up@@ -91,8 +161,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
if (configVersion != null && configVersion < CONFIG_VERSION)
logger.info("Updating config version from %s to %s", configVersion, CONFIG_VERSION);
Files.createDirectories(file.getParent());
try (final var out = Files.newOutputStream(file);
final var writer = new OutputStreamWriter(out, UTF_8)) {
try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
final var store = new Properties();

store.setProperty("enabled", Boolean.toString(enabled));
Expand All@@ -112,6 +181,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
}

return new SimpleConfig(
file,
serverId,
enabled && enabledFlag,
enabled && enabledFlag && additionalMetrics,
Expand All@@ -122,6 +192,23 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
);
}

@Contract(mutates = "io")
public void persist() throws RuntimeException {
final var properties = readOrEmpty(file);
if (properties == null) throw new IllegalStateException("Metrics config has not been initialized");

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create file


properties.setProperty("enabled", Boolean.toString(enabled()));
properties.setProperty("submitAdditionalMetrics", Boolean.toString(additionalMetrics()));
properties.setProperty("submitErrors", Boolean.toString(errorTracking()));
properties.setProperty("submitMetrics", Boolean.toString(submitMetrics()));

try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
properties.store(writer, COMMENT);
} catch (final IOException e) {
throw new RuntimeException("Failed to save metrics config", e);
}
}

// fixme: this code sucks ass
@Contract(value = "_, _, _, !null, _, _-> !null")
private static <T> @Nullable T parse(
Expand DownExpand Up@@ -180,4 +267,17 @@ public boolean preSubmissionStart(final SimpleContext context) {
}
return true;
}

@Override
public String toString() {
return "SimpleConfig{" +
"serverId=" + serverId +
", debug=" + debug +
", firstRun=" + firstRun +
", additionalMetrics=" + additionalMetrics +
", enabled=" + enabled +
", errorTracking=" + errorTracking +
", submitMetrics=" + submitMetrics +
'}';
}
}
6 changes: 6 additions & 0 deletions core/src/main/java/dev/faststats/Metrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,12 +3,18 @@
import dev.faststats.data.Metric;
import org.jetbrains.annotations.Contract;

import java.util.stream.Stream;

/**
* Metrics interface.
*
* @since 0.24.0
*/
public interface Metrics {
// todo: document
@Contract(pure = true)
Stream<Metric<?>> stream();

/**
* A metrics factory.
*
Expand Down
29 changes: 26 additions & 3 deletions core/src/main/java/dev/faststats/SimpleContext.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,11 @@
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo still valid: still dont like the impl

public non-sealed abstract class SimpleContext implements FastStatsContext {
private final @Token String token;
private final Config config;
Expand All@@ -24,6 +26,7 @@ public non-sealed abstract class SimpleContext implements FastStatsContext {
private final Logger logger;

protected volatile boolean ready = false;
public volatile boolean submissionActive;

private @Nullable Metrics metrics;
private @Nullable FeatureFlagService featureFlagService;
Expand DownExpand Up@@ -56,14 +59,33 @@ protected SimpleContext(final Factory<?, ?> factory, final LoggerFactory loggerF

@MustBeInvokedByOverriders
protected final void initializeServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, false);
}

/**
* Initializes service descriptions before consent so this context can participate in a live lifecycle registry.
*/
@MustBeInvokedByOverriders
protected final void initializeManagedServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, true);
}

private void initializeServices(final Factory<?, ?> factory, final boolean lifecycleManaged) {
if (factory.metrics == null && factory.errorTracker == null && factory.featureFlagService == null)
throw new IllegalStateException("Context created without any service attached, was this intentional?");

if (!preSubmissionStart()) return;
final var start = preSubmissionStart();
if (!lifecycleManaged && !start) return;
Comment on lines +77 to +78

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guard preSubmissionStart with lifecycleManaged; otherwise the onboarding message is printed multiple times


this.metrics = config.submitMetrics() && factory.metrics != null ? factory.metrics.apply(metricsFactory()) : null;
this.errorTrackerService = config.errorTracking() && factory.errorTracker != null ? new SimpleErrorTrackerService(this, factory.errorTracker) : null;
if (factory.metrics != null && (lifecycleManaged || config.submitMetrics())) {
final var metricsFactory = metricsFactory();
this.metrics = factory.metrics.apply(metricsFactory);
}
this.errorTrackerService = factory.errorTracker != null && (lifecycleManaged || config.errorTracking())
? new SimpleErrorTrackerService(this, factory.errorTracker)
: null;
this.featureFlagService = factory.featureFlagService != null ? factory.featureFlagService.apply(new SimpleFeatureFlagService.Factory(this)) : null;
this.submissionActive = start;

final var features = new HashSet<String>(3);
features.add("metrics=" + (metrics != null ? "yes" : "no"));
Expand DownExpand Up@@ -161,6 +183,7 @@ public void shutdown() {
if (errorTrackerService != null) errorTrackerService.shutdown();
if (featureFlagService instanceof final SimpleFeatureFlagService service) service.shutdown();
if (metrics instanceof final SimpleMetrics simpleMetrics) simpleMetrics.shutdown();
this.submissionActive = false;
ready = false;
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ private static void handleUncaughtException(final Thread thread, final Throwable
}

private void submit() {
if (!context.submissionActive || !context.getConfig().errorTracking()) return;
try {
final var data = createData();
if (data == null) return;
Expand DownExpand Up@@ -111,7 +112,7 @@ private void submit() {
return data;
}

private void clear() {
public void clear() {
globalErrorTracker.clear();
errorTrackers.forEach(SimpleErrorTracker::clear);
}
Expand Down
11 changes: 10 additions & 1 deletion core/src/main/java/dev/faststats/SimpleMetrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,10 @@
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@ApiStatus.Internal
// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: still sucks

public abstract class SimpleMetrics extends SubmissionService implements Metrics {
private static final String COLLECT_PATH = "/v1/collect";

Expand All@@ -26,7 +28,7 @@ public abstract class SimpleMetrics extends SubmissionService implements Metrics
@Contract(mutates = "io")
protected SimpleMetrics(final Factory factory) {
super(factory.context);
this.metrics = context.getConfig().additionalMetrics() ? Set.copyOf(factory.metrics) : Set.of();
this.metrics = Set.copyOf(factory.metrics);
this.flush = factory.flush;
}

Expand All@@ -43,6 +45,7 @@ public boolean isClientApplication() {
}

private boolean submit() {
if (!context.submissionActive || !context.getConfig().submitMetrics()) return false;
try {
if (submit(url, createData(), "metrics")) {
if (flush != null) flush.run();
Expand DownExpand Up@@ -78,6 +81,7 @@ private void appendInternalData(final JsonObject metrics) {
}

private void appendCustomData(final JsonObject metrics) {
if (!context.getConfig().additionalMetrics()) return;
this.metrics.forEach(metric -> {
try {
if (metrics.has(metric.getId())) {
Expand DownExpand Up@@ -124,6 +128,11 @@ protected void shutdown() {
}
}

@Override
public Stream<Metric<?>> stream() {
return metrics.stream();
}

public abstract static class Factory implements Metrics.Factory {
private @Nullable Runnable flush;
private final Set<Metric<?>> metrics = new HashSet<>(0);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/dev/faststats/internal/Logger.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ default void debug(final LogLevel level, @PrintFormat final String message, @Nul
}

String caller();

LoggerFactory factory();

void print(LogLevel level, @Nullable Throwable t, String message);
Expand Down
20 changes: 20 additions & 0 deletions fabric/build.gradle.kts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,21 +33,41 @@ allprojects {
subprojects {
if (project.name == "example-mod") return@subprojects

// todo: move to respective sub-module
val onboardingBand = when (project.name) {
"1.16.1-1.17.1" -> ":onboarding:versions:1.16.1-1.17.1"
"1.18-1.18.2" -> ":onboarding:versions:1.18-1.18.2"
"1.19-1.19.3" -> ":onboarding:versions:1.19-1.19.3"
"1.18-1.21.8" -> ":onboarding:versions:1.19.4-1.21.8"
"1.21.9-1.21.11" -> ":onboarding:versions:1.21.9-1.21.11"
"26.1-26.3" -> ":onboarding:versions:26.1-26.3"
else -> null
}
evaluationDependsOn(":onboarding")
onboardingBand?.let { evaluationDependsOn(it) }

dependencies {
compileOnlyApi(project(":fabric"))
compileOnlyApi(project(":onboarding"))
onboardingBand?.let {
compileOnlyApi(project(it))
}
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(project(":fabric").sourceSets["main"].output)
from(project(":config").sourceSets["main"].output)
from(project(":core").sourceSets["main"].output)
from(project(":onboarding").sourceSets["main"].output)
onboardingBand?.let { from(project(it).sourceSets["main"].output) }
}
}

dependencies {
compileOnlyApi(project(":core"))
compileOnly(project(":config"))
compileOnly(project(":onboarding"))
minecraft("com.mojang:minecraft:26.1.2")
compileOnly("net.fabricmc.fabric-api:fabric-api:0.150.0+26.1.2")
compileOnly("net.fabricmc:fabric-loader:0.19.3")
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand All@@ -41,7 +41,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/maven-publish.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
126 changes: 113 additions & 13 deletions config/src/main/java/dev/faststats/config/SimpleConfig.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
import org.jspecify.annotations.Nullable;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
Expand All@@ -21,15 +20,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;

@ApiStatus.Internal
public record SimpleConfig(
UUID serverId,
boolean enabled,
boolean additionalMetrics,
boolean debug,
boolean submitMetrics,
boolean errorTracking,
boolean firstRun
) implements Config {
public final class SimpleConfig implements Config {
private static final int CONFIG_VERSION = 2;

private static final String COMMENT = """
Expand DownExpand Up@@ -58,7 +49,86 @@ public record SimpleConfig(
Learn more at: https://faststats.dev/info

Since this is your first start with FastStats, submission will not start
until you restart the server to allow you to opt out if you prefer.""";
until after a restart, to allow you to opt out if you prefer.""";

private final Path file;
private final UUID serverId;
private final boolean debug;
private final boolean firstRun;
private volatile boolean additionalMetrics;
private volatile boolean enabled;
private volatile boolean errorTracking;
private volatile boolean submitMetrics;

public SimpleConfig(
final Path file,
final UUID serverId,
final boolean enabled,
final boolean additionalMetrics,
final boolean debug,
final boolean submitMetrics,
final boolean errorTracking,
final boolean firstRun
) {
this.file = file;
this.serverId = serverId;
this.enabled = enabled;
this.additionalMetrics = additionalMetrics;
this.debug = debug;
this.submitMetrics = submitMetrics;
this.errorTracking = errorTracking;
this.firstRun = firstRun;
}

@Override
public UUID serverId() {
return serverId;
}

@Override
public boolean enabled() {
return enabled;
}

public void enabled(final boolean enabled) {
this.enabled = enabled;
}

@Override
public boolean additionalMetrics() {
return additionalMetrics;
}

public void additionalMetrics(final boolean additionalMetrics) {
this.additionalMetrics = additionalMetrics;
}

@Override
public boolean debug() {
return debug;
}

@Override
public boolean submitMetrics() {
return submitMetrics;
}

public void submitMetrics(final boolean submitMetrics) {
this.submitMetrics = submitMetrics;
}

@Override
public boolean errorTracking() {
return errorTracking;
}

public void errorTracking(final boolean errorTracking) {
this.errorTracking = errorTracking;
}

public boolean firstRun() {
return firstRun;
}

@Contract(mutates = "io")
public static SimpleConfig read(final Path file, final LoggerFactory factory) throws RuntimeException {
Expand DownExpand Up@@ -91,8 +161,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
if (configVersion != null && configVersion < CONFIG_VERSION)
logger.info("Updating config version from %s to %s", configVersion, CONFIG_VERSION);
Files.createDirectories(file.getParent());
try (final var out = Files.newOutputStream(file);
final var writer = new OutputStreamWriter(out, UTF_8)) {
try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
final var store = new Properties();

store.setProperty("enabled", Boolean.toString(enabled));
Expand All@@ -112,6 +181,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
}

return new SimpleConfig(
file,
serverId,
enabled && enabledFlag,
enabled && enabledFlag && additionalMetrics,
Expand All@@ -122,6 +192,23 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
);
}

@Contract(mutates = "io")
public void persist() throws RuntimeException {
final var properties = readOrEmpty(file);
if (properties == null) throw new IllegalStateException("Metrics config has not been initialized");

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create file


properties.setProperty("enabled", Boolean.toString(enabled()));
properties.setProperty("submitAdditionalMetrics", Boolean.toString(additionalMetrics()));
properties.setProperty("submitErrors", Boolean.toString(errorTracking()));
properties.setProperty("submitMetrics", Boolean.toString(submitMetrics()));

try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
properties.store(writer, COMMENT);
} catch (final IOException e) {
throw new RuntimeException("Failed to save metrics config", e);
}
}

// fixme: this code sucks ass
@Contract(value = "_, _, _, !null, _, _-> !null")
private static <T> @Nullable T parse(
Expand DownExpand Up@@ -180,4 +267,17 @@ public boolean preSubmissionStart(final SimpleContext context) {
}
return true;
}

@Override
public String toString() {
return "SimpleConfig{" +
"serverId=" + serverId +
", debug=" + debug +
", firstRun=" + firstRun +
", additionalMetrics=" + additionalMetrics +
", enabled=" + enabled +
", errorTracking=" + errorTracking +
", submitMetrics=" + submitMetrics +
'}';
}
}
6 changes: 6 additions & 0 deletions core/src/main/java/dev/faststats/Metrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,12 +3,18 @@
import dev.faststats.data.Metric;
import org.jetbrains.annotations.Contract;

import java.util.stream.Stream;

/**
* Metrics interface.
*
* @since 0.24.0
*/
public interface Metrics {
// todo: document
@Contract(pure = true)
Stream<Metric<?>> stream();

/**
* A metrics factory.
*
Expand Down
29 changes: 26 additions & 3 deletions core/src/main/java/dev/faststats/SimpleContext.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,11 @@
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo still valid: still dont like the impl

public non-sealed abstract class SimpleContext implements FastStatsContext {
private final @Token String token;
private final Config config;
Expand All@@ -24,6 +26,7 @@ public non-sealed abstract class SimpleContext implements FastStatsContext {
private final Logger logger;

protected volatile boolean ready = false;
public volatile boolean submissionActive;

private @Nullable Metrics metrics;
private @Nullable FeatureFlagService featureFlagService;
Expand DownExpand Up@@ -56,14 +59,33 @@ protected SimpleContext(final Factory<?, ?> factory, final LoggerFactory loggerF

@MustBeInvokedByOverriders
protected final void initializeServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, false);
}

/**
* Initializes service descriptions before consent so this context can participate in a live lifecycle registry.
*/
@MustBeInvokedByOverriders
protected final void initializeManagedServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, true);
}

private void initializeServices(final Factory<?, ?> factory, final boolean lifecycleManaged) {
if (factory.metrics == null && factory.errorTracker == null && factory.featureFlagService == null)
throw new IllegalStateException("Context created without any service attached, was this intentional?");

if (!preSubmissionStart()) return;
final var start = preSubmissionStart();
if (!lifecycleManaged && !start) return;
Comment on lines +77 to +78

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guard preSubmissionStart with lifecycleManaged; otherwise the onboarding message is printed multiple times


this.metrics = config.submitMetrics() && factory.metrics != null ? factory.metrics.apply(metricsFactory()) : null;
this.errorTrackerService = config.errorTracking() && factory.errorTracker != null ? new SimpleErrorTrackerService(this, factory.errorTracker) : null;
if (factory.metrics != null && (lifecycleManaged || config.submitMetrics())) {
final var metricsFactory = metricsFactory();
this.metrics = factory.metrics.apply(metricsFactory);
}
this.errorTrackerService = factory.errorTracker != null && (lifecycleManaged || config.errorTracking())
? new SimpleErrorTrackerService(this, factory.errorTracker)
: null;
this.featureFlagService = factory.featureFlagService != null ? factory.featureFlagService.apply(new SimpleFeatureFlagService.Factory(this)) : null;
this.submissionActive = start;

final var features = new HashSet<String>(3);
features.add("metrics=" + (metrics != null ? "yes" : "no"));
Expand DownExpand Up@@ -161,6 +183,7 @@ public void shutdown() {
if (errorTrackerService != null) errorTrackerService.shutdown();
if (featureFlagService instanceof final SimpleFeatureFlagService service) service.shutdown();
if (metrics instanceof final SimpleMetrics simpleMetrics) simpleMetrics.shutdown();
this.submissionActive = false;
ready = false;
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ private static void handleUncaughtException(final Thread thread, final Throwable
}

private void submit() {
if (!context.submissionActive || !context.getConfig().errorTracking()) return;
try {
final var data = createData();
if (data == null) return;
Expand DownExpand Up@@ -111,7 +112,7 @@ private void submit() {
return data;
}

private void clear() {
public void clear() {
globalErrorTracker.clear();
errorTrackers.forEach(SimpleErrorTracker::clear);
}
Expand Down
11 changes: 10 additions & 1 deletion core/src/main/java/dev/faststats/SimpleMetrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,10 @@
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@ApiStatus.Internal
// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: still sucks

public abstract class SimpleMetrics extends SubmissionService implements Metrics {
private static final String COLLECT_PATH = "/v1/collect";

Expand All@@ -26,7 +28,7 @@ public abstract class SimpleMetrics extends SubmissionService implements Metrics
@Contract(mutates = "io")
protected SimpleMetrics(final Factory factory) {
super(factory.context);
this.metrics = context.getConfig().additionalMetrics() ? Set.copyOf(factory.metrics) : Set.of();
this.metrics = Set.copyOf(factory.metrics);
this.flush = factory.flush;
}

Expand All@@ -43,6 +45,7 @@ public boolean isClientApplication() {
}

private boolean submit() {
if (!context.submissionActive || !context.getConfig().submitMetrics()) return false;
try {
if (submit(url, createData(), "metrics")) {
if (flush != null) flush.run();
Expand DownExpand Up@@ -78,6 +81,7 @@ private void appendInternalData(final JsonObject metrics) {
}

private void appendCustomData(final JsonObject metrics) {
if (!context.getConfig().additionalMetrics()) return;
this.metrics.forEach(metric -> {
try {
if (metrics.has(metric.getId())) {
Expand DownExpand Up@@ -124,6 +128,11 @@ protected void shutdown() {
}
}

@Override
public Stream<Metric<?>> stream() {
return metrics.stream();
}

public abstract static class Factory implements Metrics.Factory {
private @Nullable Runnable flush;
private final Set<Metric<?>> metrics = new HashSet<>(0);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/dev/faststats/internal/Logger.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ default void debug(final LogLevel level, @PrintFormat final String message, @Nul
}

String caller();

LoggerFactory factory();

void print(LogLevel level, @Nullable Throwable t, String message);
Expand Down
20 changes: 20 additions & 0 deletions fabric/build.gradle.kts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,21 +33,41 @@ allprojects {
subprojects {
if (project.name == "example-mod") return@subprojects

// todo: move to respective sub-module
val onboardingBand = when (project.name) {
"1.16.1-1.17.1" -> ":onboarding:versions:1.16.1-1.17.1"
"1.18-1.18.2" -> ":onboarding:versions:1.18-1.18.2"
"1.19-1.19.3" -> ":onboarding:versions:1.19-1.19.3"
"1.18-1.21.8" -> ":onboarding:versions:1.19.4-1.21.8"
"1.21.9-1.21.11" -> ":onboarding:versions:1.21.9-1.21.11"
"26.1-26.3" -> ":onboarding:versions:26.1-26.3"
else -> null
}
evaluationDependsOn(":onboarding")
onboardingBand?.let { evaluationDependsOn(it) }

dependencies {
compileOnlyApi(project(":fabric"))
compileOnlyApi(project(":onboarding"))
onboardingBand?.let {
compileOnlyApi(project(it))
}
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(project(":fabric").sourceSets["main"].output)
from(project(":config").sourceSets["main"].output)
from(project(":core").sourceSets["main"].output)
from(project(":onboarding").sourceSets["main"].output)
onboardingBand?.let { from(project(it).sourceSets["main"].output) }
}
}

dependencies {
compileOnlyApi(project(":core"))
compileOnly(project(":config"))
compileOnly(project(":onboarding"))
minecraft("com.mojang:minecraft:26.1.2")
compileOnly("net.fabricmc.fabric-api:fabric-api:0.150.0+26.1.2")
compileOnly("net.fabricmc:fabric-loader:0.19.3")
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand All@@ -41,7 +41,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/maven-publish.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ jobs:
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 21
java-version: 25
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
with:
Expand Down
126 changes: 113 additions & 13 deletions config/src/main/java/dev/faststats/config/SimpleConfig.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
import org.jspecify.annotations.Nullable;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
Expand All@@ -21,15 +20,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;

@ApiStatus.Internal
public record SimpleConfig(
UUID serverId,
boolean enabled,
boolean additionalMetrics,
boolean debug,
boolean submitMetrics,
boolean errorTracking,
boolean firstRun
) implements Config {
public final class SimpleConfig implements Config {
private static final int CONFIG_VERSION = 2;

private static final String COMMENT = """
Expand DownExpand Up@@ -58,7 +49,86 @@ public record SimpleConfig(
Learn more at: https://faststats.dev/info

Since this is your first start with FastStats, submission will not start
until you restart the server to allow you to opt out if you prefer.""";
until after a restart, to allow you to opt out if you prefer.""";

private final Path file;
private final UUID serverId;
private final boolean debug;
private final boolean firstRun;
private volatile boolean additionalMetrics;
private volatile boolean enabled;
private volatile boolean errorTracking;
private volatile boolean submitMetrics;

public SimpleConfig(
final Path file,
final UUID serverId,
final boolean enabled,
final boolean additionalMetrics,
final boolean debug,
final boolean submitMetrics,
final boolean errorTracking,
final boolean firstRun
) {
this.file = file;
this.serverId = serverId;
this.enabled = enabled;
this.additionalMetrics = additionalMetrics;
this.debug = debug;
this.submitMetrics = submitMetrics;
this.errorTracking = errorTracking;
this.firstRun = firstRun;
}

@Override
public UUID serverId() {
return serverId;
}

@Override
public boolean enabled() {
return enabled;
}

public void enabled(final boolean enabled) {
this.enabled = enabled;
}

@Override
public boolean additionalMetrics() {
return additionalMetrics;
}

public void additionalMetrics(final boolean additionalMetrics) {
this.additionalMetrics = additionalMetrics;
}

@Override
public boolean debug() {
return debug;
}

@Override
public boolean submitMetrics() {
return submitMetrics;
}

public void submitMetrics(final boolean submitMetrics) {
this.submitMetrics = submitMetrics;
}

@Override
public boolean errorTracking() {
return errorTracking;
}

public void errorTracking(final boolean errorTracking) {
this.errorTracking = errorTracking;
}

public boolean firstRun() {
return firstRun;
}

@Contract(mutates = "io")
public static SimpleConfig read(final Path file, final LoggerFactory factory) throws RuntimeException {
Expand DownExpand Up@@ -91,8 +161,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
if (configVersion != null && configVersion < CONFIG_VERSION)
logger.info("Updating config version from %s to %s", configVersion, CONFIG_VERSION);
Files.createDirectories(file.getParent());
try (final var out = Files.newOutputStream(file);
final var writer = new OutputStreamWriter(out, UTF_8)) {
try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
final var store = new Properties();

store.setProperty("enabled", Boolean.toString(enabled));
Expand All@@ -112,6 +181,7 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
}

return new SimpleConfig(
file,
serverId,
enabled && enabledFlag,
enabled && enabledFlag && additionalMetrics,
Expand All@@ -122,6 +192,23 @@ public static SimpleConfig read(final Path file, final LoggerFactory factory) th
);
}

@Contract(mutates = "io")
public void persist() throws RuntimeException {
final var properties = readOrEmpty(file);
if (properties == null) throw new IllegalStateException("Metrics config has not been initialized");

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create file


properties.setProperty("enabled", Boolean.toString(enabled()));
properties.setProperty("submitAdditionalMetrics", Boolean.toString(additionalMetrics()));
properties.setProperty("submitErrors", Boolean.toString(errorTracking()));
properties.setProperty("submitMetrics", Boolean.toString(submitMetrics()));

try (final var writer = Files.newBufferedWriter(file, UTF_8)) {
properties.store(writer, COMMENT);
} catch (final IOException e) {
throw new RuntimeException("Failed to save metrics config", e);
}
}

// fixme: this code sucks ass
@Contract(value = "_, _, _, !null, _, _-> !null")
private static <T> @Nullable T parse(
Expand DownExpand Up@@ -180,4 +267,17 @@ public boolean preSubmissionStart(final SimpleContext context) {
}
return true;
}

@Override
public String toString() {
return "SimpleConfig{" +
"serverId=" + serverId +
", debug=" + debug +
", firstRun=" + firstRun +
", additionalMetrics=" + additionalMetrics +
", enabled=" + enabled +
", errorTracking=" + errorTracking +
", submitMetrics=" + submitMetrics +
'}';
}
}
6 changes: 6 additions & 0 deletions core/src/main/java/dev/faststats/Metrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,12 +3,18 @@
import dev.faststats.data.Metric;
import org.jetbrains.annotations.Contract;

import java.util.stream.Stream;

/**
* Metrics interface.
*
* @since 0.24.0
*/
public interface Metrics {
// todo: document
@Contract(pure = true)
Stream<Metric<?>> stream();

/**
* A metrics factory.
*
Expand Down
29 changes: 26 additions & 3 deletions core/src/main/java/dev/faststats/SimpleContext.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,11 @@
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo still valid: still dont like the impl

public non-sealed abstract class SimpleContext implements FastStatsContext {
private final @Token String token;
private final Config config;
Expand All@@ -24,6 +26,7 @@ public non-sealed abstract class SimpleContext implements FastStatsContext {
private final Logger logger;

protected volatile boolean ready = false;
public volatile boolean submissionActive;

private @Nullable Metrics metrics;
private @Nullable FeatureFlagService featureFlagService;
Expand DownExpand Up@@ -56,14 +59,33 @@ protected SimpleContext(final Factory<?, ?> factory, final LoggerFactory loggerF

@MustBeInvokedByOverriders
protected final void initializeServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, false);
}

/**
* Initializes service descriptions before consent so this context can participate in a live lifecycle registry.
*/
@MustBeInvokedByOverriders
protected final void initializeManagedServices(final Factory<?, ?> factory) throws IllegalStateException {
initializeServices(factory, true);
}

private void initializeServices(final Factory<?, ?> factory, final boolean lifecycleManaged) {
if (factory.metrics == null && factory.errorTracker == null && factory.featureFlagService == null)
throw new IllegalStateException("Context created without any service attached, was this intentional?");

if (!preSubmissionStart()) return;
final var start = preSubmissionStart();
if (!lifecycleManaged && !start) return;
Comment on lines +77 to +78

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guard preSubmissionStart with lifecycleManaged; otherwise the onboarding message is printed multiple times


this.metrics = config.submitMetrics() && factory.metrics != null ? factory.metrics.apply(metricsFactory()) : null;
this.errorTrackerService = config.errorTracking() && factory.errorTracker != null ? new SimpleErrorTrackerService(this, factory.errorTracker) : null;
if (factory.metrics != null && (lifecycleManaged || config.submitMetrics())) {
final var metricsFactory = metricsFactory();
this.metrics = factory.metrics.apply(metricsFactory);
}
this.errorTrackerService = factory.errorTracker != null && (lifecycleManaged || config.errorTracking())
? new SimpleErrorTrackerService(this, factory.errorTracker)
: null;
this.featureFlagService = factory.featureFlagService != null ? factory.featureFlagService.apply(new SimpleFeatureFlagService.Factory(this)) : null;
this.submissionActive = start;

final var features = new HashSet<String>(3);
features.add("metrics=" + (metrics != null ? "yes" : "no"));
Expand DownExpand Up@@ -161,6 +183,7 @@ public void shutdown() {
if (errorTrackerService != null) errorTrackerService.shutdown();
if (featureFlagService instanceof final SimpleFeatureFlagService service) service.shutdown();
if (metrics instanceof final SimpleMetrics simpleMetrics) simpleMetrics.shutdown();
this.submissionActive = false;
ready = false;
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ private static void handleUncaughtException(final Thread thread, final Throwable
}

private void submit() {
if (!context.submissionActive || !context.getConfig().errorTracking()) return;
try {
final var data = createData();
if (data == null) return;
Expand DownExpand Up@@ -111,7 +112,7 @@ private void submit() {
return data;
}

private void clear() {
public void clear() {
globalErrorTracker.clear();
errorTrackers.forEach(SimpleErrorTracker::clear);
}
Expand Down
11 changes: 10 additions & 1 deletion core/src/main/java/dev/faststats/SimpleMetrics.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,10 @@
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@ApiStatus.Internal
// todo: revise

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: still sucks

public abstract class SimpleMetrics extends SubmissionService implements Metrics {
private static final String COLLECT_PATH = "/v1/collect";

Expand All@@ -26,7 +28,7 @@ public abstract class SimpleMetrics extends SubmissionService implements Metrics
@Contract(mutates = "io")
protected SimpleMetrics(final Factory factory) {
super(factory.context);
this.metrics = context.getConfig().additionalMetrics() ? Set.copyOf(factory.metrics) : Set.of();
this.metrics = Set.copyOf(factory.metrics);
this.flush = factory.flush;
}

Expand All@@ -43,6 +45,7 @@ public boolean isClientApplication() {
}

private boolean submit() {
if (!context.submissionActive || !context.getConfig().submitMetrics()) return false;
try {
if (submit(url, createData(), "metrics")) {
if (flush != null) flush.run();
Expand DownExpand Up@@ -78,6 +81,7 @@ private void appendInternalData(final JsonObject metrics) {
}

private void appendCustomData(final JsonObject metrics) {
if (!context.getConfig().additionalMetrics()) return;
this.metrics.forEach(metric -> {
try {
if (metrics.has(metric.getId())) {
Expand DownExpand Up@@ -124,6 +128,11 @@ protected void shutdown() {
}
}

@Override
public Stream<Metric<?>> stream() {
return metrics.stream();
}

public abstract static class Factory implements Metrics.Factory {
private @Nullable Runnable flush;
private final Set<Metric<?>> metrics = new HashSet<>(0);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/dev/faststats/internal/Logger.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ default void debug(final LogLevel level, @PrintFormat final String message, @Nul
}

String caller();

LoggerFactory factory();

void print(LogLevel level, @Nullable Throwable t, String message);
Expand Down
20 changes: 20 additions & 0 deletions fabric/build.gradle.kts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,21 +33,41 @@ allprojects {
subprojects {
if (project.name == "example-mod") return@subprojects

// todo: move to respective sub-module
val onboardingBand = when (project.name) {
"1.16.1-1.17.1" -> ":onboarding:versions:1.16.1-1.17.1"
"1.18-1.18.2" -> ":onboarding:versions:1.18-1.18.2"
"1.19-1.19.3" -> ":onboarding:versions:1.19-1.19.3"
"1.18-1.21.8" -> ":onboarding:versions:1.19.4-1.21.8"
"1.21.9-1.21.11" -> ":onboarding:versions:1.21.9-1.21.11"
"26.1-26.3" -> ":onboarding:versions:26.1-26.3"
else -> null
}
evaluationDependsOn(":onboarding")
onboardingBand?.let { evaluationDependsOn(it) }

dependencies {
compileOnlyApi(project(":fabric"))
compileOnlyApi(project(":onboarding"))
onboardingBand?.let {
compileOnlyApi(project(it))
}
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(project(":fabric").sourceSets["main"].output)
from(project(":config").sourceSets["main"].output)
from(project(":core").sourceSets["main"].output)
from(project(":onboarding").sourceSets["main"].output)
onboardingBand?.let { from(project(it).sourceSets["main"].output) }
}
}

dependencies {
compileOnlyApi(project(":core"))
compileOnly(project(":config"))
compileOnly(project(":onboarding"))
minecraft("com.mojang:minecraft:26.1.2")
compileOnly("net.fabricmc.fabric-api:fabric-api:0.150.0+26.1.2")
compileOnly("net.fabricmc:fabric-loader:0.19.3")
Expand Down
Loading