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 number Diff line number Diff 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 number Diff line number Diff 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 number Diff line number Diff 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 Down Expand 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 Down Expand 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
Member Author

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 Down Expand 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 number Diff line number Diff 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 number Diff line number Diff 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
Member Author

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 Down Expand 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
Member Author

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 Down Expand 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 number Diff line number Diff 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 Down Expand 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 number Diff line number Diff 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
Member Author

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 Down Expand 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 Down Expand 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 number Diff line number Diff 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 number Diff line number Diff 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