This commit is contained in:
Luck 2017-05-14 22:15:25 +01:00
parent d4ac261e85
commit 5121fc6b1f
No known key found for this signature in database
GPG Key ID: EFA9B3EC5FD90F8B
26 changed files with 215 additions and 174 deletions

View File

@ -34,11 +34,11 @@ import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File; import java.io.File;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Set;
import java.util.stream.Collectors;
@RequiredArgsConstructor @RequiredArgsConstructor
public class BukkitConfig extends AbstractConfiguration { public class BukkitConfig extends AbstractConfiguration {
@ -82,7 +82,8 @@ public class BukkitConfig extends AbstractConfiguration {
@Override @Override
public List<String> getList(String path, List<String> def) { public List<String> getList(String path, List<String> def) {
return Optional.ofNullable(configuration.getStringList(path)).orElse(def); List<String> ret = configuration.getStringList(path);
return ret == null ? def : ret;
} }
@Override @Override
@ -92,7 +93,8 @@ public class BukkitConfig extends AbstractConfiguration {
return def; return def;
} }
return Optional.ofNullable(section.getKeys(false).stream().collect(Collectors.toList())).orElse(def); Set<String> keys = section.getKeys(false);
return keys == null ? def : new ArrayList<>(keys);
} }
@Override @Override

View File

@ -76,8 +76,8 @@ import me.lucko.luckperms.common.tasks.UpdateTask;
import me.lucko.luckperms.common.treeview.PermissionVault; import me.lucko.luckperms.common.treeview.PermissionVault;
import me.lucko.luckperms.common.utils.BufferedRequest; import me.lucko.luckperms.common.utils.BufferedRequest;
import me.lucko.luckperms.common.utils.FileWatcher; import me.lucko.luckperms.common.utils.FileWatcher;
import me.lucko.luckperms.common.utils.LoggerImpl;
import me.lucko.luckperms.common.utils.LoginHelper; import me.lucko.luckperms.common.utils.LoginHelper;
import me.lucko.luckperms.common.utils.SenderLogger;
import me.lucko.luckperms.common.verbose.VerboseHandler; import me.lucko.luckperms.common.verbose.VerboseHandler;
import org.bukkit.World; import org.bukkit.World;
@ -141,7 +141,7 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
scheduler = new LPBukkitScheduler(this); scheduler = new LPBukkitScheduler(this);
localeManager = new NoopLocaleManager(); localeManager = new NoopLocaleManager();
senderFactory = new BukkitSenderFactory(this); senderFactory = new BukkitSenderFactory(this);
log = new LoggerImpl(getConsoleSender()); log = new SenderLogger(getConsoleSender());
DependencyManager.loadDependencies(this, Collections.singletonList(Dependency.CAFFEINE)); DependencyManager.loadDependencies(this, Collections.singletonList(Dependency.CAFFEINE));
} }
@ -178,7 +178,7 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
childPermissionProvider = new ChildPermissionProvider(); childPermissionProvider = new ChildPermissionProvider();
// give all plugins a chance to load their permissions, then refresh. // give all plugins a chance to load their permissions, then refresh.
scheduler.doSyncLater(() -> { scheduler.syncLater(() -> {
defaultsProvider.refresh(); defaultsProvider.refresh();
childPermissionProvider.setup(); childPermissionProvider.setup();
@ -198,7 +198,7 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
if (getConfiguration().get(ConfigKeys.WATCH_FILES)) { if (getConfiguration().get(ConfigKeys.WATCH_FILES)) {
fileWatcher = new FileWatcher(this); fileWatcher = new FileWatcher(this);
getScheduler().doAsyncRepeating(fileWatcher, 30L); getScheduler().asyncRepeating(fileWatcher, 30L);
} }
// initialise datastore // initialise datastore
@ -308,16 +308,16 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
int mins = getConfiguration().get(ConfigKeys.SYNC_TIME); int mins = getConfiguration().get(ConfigKeys.SYNC_TIME);
if (mins > 0) { if (mins > 0) {
long ticks = mins * 60 * 20; long ticks = mins * 60 * 20;
scheduler.doAsyncRepeating(() -> updateTaskBuffer.request(), ticks); scheduler.asyncRepeating(() -> updateTaskBuffer.request(), ticks);
} }
scheduler.doAsyncLater(() -> updateTaskBuffer.request(), 40L); scheduler.asyncLater(() -> updateTaskBuffer.request(), 40L);
// run an update instantly. // run an update instantly.
updateTaskBuffer.requestDirectly(); updateTaskBuffer.requestDirectly();
// register tasks // register tasks
scheduler.doAsyncRepeating(new ExpireTemporaryTask(this), 60L); scheduler.asyncRepeating(new ExpireTemporaryTask(this), 60L);
scheduler.doAsyncRepeating(new CacheHousekeepingTask(this), 2400L); scheduler.asyncRepeating(new CacheHousekeepingTask(this), 2400L);
// register permissions // register permissions
try { try {

View File

@ -63,45 +63,45 @@ public class LPBukkitScheduler implements LuckPermsScheduler {
} }
@Override @Override
public Executor getAsyncExecutor() { public Executor async() {
return useBukkitAsync ? asyncBukkitExecutor : asyncLpExecutor; return useBukkitAsync ? asyncBukkitExecutor : asyncLpExecutor;
} }
@Override @Override
public Executor getSyncExecutor() { public Executor sync() {
return syncExecutor; return syncExecutor;
} }
@Override @Override
public void doAsync(Runnable r) { public void doAsync(Runnable runnable) {
getAsyncExecutor().execute(r); async().execute(runnable);
} }
@Override @Override
public void doSync(Runnable r) { public void doSync(Runnable runnable) {
getSyncExecutor().execute(r); sync().execute(runnable);
} }
@Override @Override
public void doAsyncRepeating(Runnable r, long interval) { public void asyncRepeating(Runnable runnable, long intervalTicks) {
BukkitTask task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, r, interval, interval); BukkitTask task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, runnable, intervalTicks, intervalTicks);
tasks.add(task); tasks.add(task);
} }
@Override @Override
public void doSyncRepeating(Runnable r, long interval) { public void syncRepeating(Runnable runnable, long intervalTicks) {
BukkitTask task = plugin.getServer().getScheduler().runTaskTimer(plugin, r, interval, interval); BukkitTask task = plugin.getServer().getScheduler().runTaskTimer(plugin, runnable, intervalTicks, intervalTicks);
tasks.add(task); tasks.add(task);
} }
@Override @Override
public void doAsyncLater(Runnable r, long delay) { public void asyncLater(Runnable runnable, long delayTicks) {
plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, r, delay); plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, runnable, delayTicks);
} }
@Override @Override
public void doSyncLater(Runnable r, long delay) { public void syncLater(Runnable runnable, long delayTicks) {
plugin.getServer().getScheduler().runTaskLater(plugin, r, delay); plugin.getServer().getScheduler().runTaskLater(plugin, runnable, delayTicks);
} }
@Override @Override

View File

@ -140,11 +140,11 @@ public class VaultPermissionHook extends Permission {
public void save(PermissionHolder holder) { public void save(PermissionHolder holder) {
if (holder instanceof User) { if (holder instanceof User) {
User u = (User) holder; User u = (User) holder;
plugin.getStorage().saveUser(u).thenRunAsync(() -> u.getRefreshBuffer().request(), plugin.getScheduler().getAsyncExecutor()); plugin.getStorage().saveUser(u).thenRunAsync(() -> u.getRefreshBuffer().request(), plugin.getScheduler().async());
} }
if (holder instanceof Group) { if (holder instanceof Group) {
Group g = (Group) holder; Group g = (Group) holder;
plugin.getStorage().saveGroup(g).thenRunAsync(() -> plugin.getUpdateTaskBuffer().request(), plugin.getScheduler().getAsyncExecutor()); plugin.getStorage().saveGroup(g).thenRunAsync(() -> plugin.getUpdateTaskBuffer().request(), plugin.getScheduler().async());
} }
} }

View File

@ -69,7 +69,7 @@ import me.lucko.luckperms.common.tasks.UpdateTask;
import me.lucko.luckperms.common.treeview.PermissionVault; import me.lucko.luckperms.common.treeview.PermissionVault;
import me.lucko.luckperms.common.utils.BufferedRequest; import me.lucko.luckperms.common.utils.BufferedRequest;
import me.lucko.luckperms.common.utils.FileWatcher; import me.lucko.luckperms.common.utils.FileWatcher;
import me.lucko.luckperms.common.utils.LoggerImpl; import me.lucko.luckperms.common.utils.SenderLogger;
import me.lucko.luckperms.common.verbose.VerboseHandler; import me.lucko.luckperms.common.verbose.VerboseHandler;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -115,7 +115,7 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
scheduler = new LPBungeeScheduler(this); scheduler = new LPBungeeScheduler(this);
localeManager = new NoopLocaleManager(); localeManager = new NoopLocaleManager();
senderFactory = new BungeeSenderFactory(this); senderFactory = new BungeeSenderFactory(this);
log = new LoggerImpl(getConsoleSender()); log = new SenderLogger(getConsoleSender());
DependencyManager.loadDependencies(this, Collections.singletonList(Dependency.CAFFEINE)); DependencyManager.loadDependencies(this, Collections.singletonList(Dependency.CAFFEINE));
} }
@ -123,8 +123,8 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
@Override @Override
public void onEnable() { public void onEnable() {
LuckPermsPlugin.sendStartupBanner(getConsoleSender(), this); LuckPermsPlugin.sendStartupBanner(getConsoleSender(), this);
verboseHandler = new VerboseHandler(scheduler.getAsyncExecutor(), getVersion()); verboseHandler = new VerboseHandler(scheduler.async(), getVersion());
permissionVault = new PermissionVault(scheduler.getAsyncExecutor()); permissionVault = new PermissionVault(scheduler.async());
getLog().info("Loading configuration..."); getLog().info("Loading configuration...");
configuration = new BungeeConfig(this); configuration = new BungeeConfig(this);
@ -139,7 +139,7 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
if (getConfiguration().get(ConfigKeys.WATCH_FILES)) { if (getConfiguration().get(ConfigKeys.WATCH_FILES)) {
fileWatcher = new FileWatcher(this); fileWatcher = new FileWatcher(this);
getScheduler().doAsyncRepeating(fileWatcher, 30L); getScheduler().asyncRepeating(fileWatcher, 30L);
} }
// initialise datastore // initialise datastore
@ -234,16 +234,16 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
int mins = getConfiguration().get(ConfigKeys.SYNC_TIME); int mins = getConfiguration().get(ConfigKeys.SYNC_TIME);
if (mins > 0) { if (mins > 0) {
long ticks = mins * 60 * 20; long ticks = mins * 60 * 20;
scheduler.doAsyncRepeating(() -> updateTaskBuffer.request(), ticks); scheduler.asyncRepeating(() -> updateTaskBuffer.request(), ticks);
} }
scheduler.doAsyncLater(() -> updateTaskBuffer.request(), 40L); scheduler.asyncLater(() -> updateTaskBuffer.request(), 40L);
// run an update instantly. // run an update instantly.
updateTaskBuffer.requestDirectly(); updateTaskBuffer.requestDirectly();
// register tasks // register tasks
scheduler.doAsyncRepeating(new ExpireTemporaryTask(this), 60L); scheduler.asyncRepeating(new ExpireTemporaryTask(this), 60L);
scheduler.doAsyncRepeating(new CacheHousekeepingTask(this), 2400L); scheduler.asyncRepeating(new CacheHousekeepingTask(this), 2400L);
getLog().info("Successfully loaded."); getLog().info("Successfully loaded.");
} }

View File

@ -46,46 +46,46 @@ public class LPBungeeScheduler implements LuckPermsScheduler {
} }
@Override @Override
public Executor getAsyncExecutor() { public Executor async() {
return asyncExecutor; return asyncExecutor;
} }
@Override @Override
public Executor getSyncExecutor() { public Executor sync() {
return asyncExecutor; return asyncExecutor;
} }
@Override @Override
public void doAsync(Runnable r) { public void doAsync(Runnable runnable) {
asyncExecutor.execute(r); asyncExecutor.execute(runnable);
} }
@Override @Override
public void doSync(Runnable r) { public void doSync(Runnable runnable) {
doAsync(r); doAsync(runnable);
} }
@Override @Override
public void doAsyncRepeating(Runnable r, long interval) { public void asyncRepeating(Runnable runnable, long intervalTicks) {
long millis = interval * 50L; // convert from ticks to milliseconds long millis = intervalTicks * 50L; // convert from ticks to milliseconds
ScheduledTask task = plugin.getProxy().getScheduler().schedule(plugin, r, millis, millis, TimeUnit.MILLISECONDS); ScheduledTask task = plugin.getProxy().getScheduler().schedule(plugin, runnable, millis, millis, TimeUnit.MILLISECONDS);
tasks.add(task); tasks.add(task);
} }
@Override @Override
public void doSyncRepeating(Runnable r, long interval) { public void syncRepeating(Runnable runnable, long intervalTicks) {
doAsyncRepeating(r, interval); asyncRepeating(runnable, intervalTicks);
} }
@Override @Override
public void doAsyncLater(Runnable r, long delay) { public void asyncLater(Runnable runnable, long delayTicks) {
long millis = delay * 50L; // convert from ticks to milliseconds long millis = delayTicks * 50L; // convert from ticks to milliseconds
plugin.getProxy().getScheduler().schedule(plugin, r, millis, TimeUnit.MILLISECONDS); plugin.getProxy().getScheduler().schedule(plugin, runnable, millis, TimeUnit.MILLISECONDS);
} }
@Override @Override
public void doSyncLater(Runnable r, long delay) { public void syncLater(Runnable runnable, long delayTicks) {
doAsyncLater(r, delay); asyncLater(runnable, delayTicks);
} }
@Override @Override

View File

@ -69,12 +69,12 @@ public class StorageDelegate implements Storage {
@Override @Override
public Executor getSyncExecutor() { public Executor getSyncExecutor() {
return plugin.getScheduler().getSyncExecutor(); return plugin.getScheduler().sync();
} }
@Override @Override
public Executor getAsyncExecutor() { public Executor getAsyncExecutor() {
return plugin.getScheduler().getAsyncExecutor(); return plugin.getScheduler().async();
} }
@Override @Override

View File

@ -246,7 +246,7 @@ public class Exporter implements Runnable {
e.printStackTrace(); e.printStackTrace();
} }
} }
}, plugin.getScheduler().getAsyncExecutor())); }, plugin.getScheduler().async()));
} }
// all of the threads have been scheduled now and are running. we just need to wait for them all to complete // all of the threads have been scheduled now and are running. we just need to wait for them all to complete

View File

@ -141,12 +141,12 @@ public class GenericUserManager extends AbstractManager<UserIdentifier, User> im
@Override @Override
public void scheduleUnload(UUID uuid) { public void scheduleUnload(UUID uuid) {
plugin.getScheduler().doAsyncLater(() -> { plugin.getScheduler().asyncLater(() -> {
// check once to see if the user can be unloaded. // check once to see if the user can be unloaded.
if (getIfLoaded(plugin.getUuidCache().getUUID(uuid)) != null && !plugin.isPlayerOnline(uuid)) { if (getIfLoaded(plugin.getUuidCache().getUUID(uuid)) != null && !plugin.isPlayerOnline(uuid)) {
// check again in 40 ticks, we want to be sure the player won't have re-logged before we unload them. // check again in 40 ticks, we want to be sure the player won't have re-logged before we unload them.
plugin.getScheduler().doAsyncLater(() -> { plugin.getScheduler().asyncLater(() -> {
User user = getIfLoaded(plugin.getUuidCache().getUUID(uuid)); User user = getIfLoaded(plugin.getUuidCache().getUUID(uuid));
if (user != null && !plugin.isPlayerOnline(uuid)) { if (user != null && !plugin.isPlayerOnline(uuid)) {
user.unregisterData(); user.unregisterData();

View File

@ -187,12 +187,12 @@ public interface LuckPermsPlugin {
*/ */
LuckPermsScheduler getScheduler(); LuckPermsScheduler getScheduler();
default void doAsync(Runnable r) { default void doAsync(Runnable runnable) {
getScheduler().doAsync(r); getScheduler().doAsync(runnable);
} }
default void doSync(Runnable r) { default void doSync(Runnable runnable) {
getScheduler().doSync(r); getScheduler().doSync(runnable);
} }
/** /**

View File

@ -27,20 +27,70 @@ package me.lucko.luckperms.common.plugin;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
/**
* A scheduler for running tasks using the systems provided by the platform
*/
public interface LuckPermsScheduler { public interface LuckPermsScheduler {
Executor getAsyncExecutor(); /**
Executor getSyncExecutor(); * Gets an async executor instance
*
* @return an async executor instance
*/
Executor async();
void doAsync(Runnable r); /**
void doSync(Runnable r); * Gets a sync executor instance
*
* @return a sync executor instance
*/
Executor sync();
void doAsyncRepeating(Runnable r, long interval); /**
void doSyncRepeating(Runnable r, long interval); * Executes a runnable async
*
* @param runnable the runnable
*/
void doAsync(Runnable runnable);
void doAsyncLater(Runnable r, long delay); /**
void doSyncLater(Runnable r, long delay); * Executes a runnable sync
*
* @param runnable the runnable
*/
void doSync(Runnable runnable);
/**
* Runs a runnable repeatedly until the plugin disables. Will wait for the interval before the first iteration of the task is ran.
* @param runnable the runnable
* @param intervalTicks the interval in ticks.
*/
void asyncRepeating(Runnable runnable, long intervalTicks);
/**
* Runs a runnable repeatedly until the plugin disables. Will wait for the interval before the first iteration of the task is ran.
* @param runnable the runnable
* @param intervalTicks the interval in ticks.
*/
void syncRepeating(Runnable runnable, long intervalTicks);
/**
* Runs a runnable with a delay
* @param runnable the runnable
* @param delayTicks the delay in ticks
*/
void asyncLater(Runnable runnable, long delayTicks);
/**
* Runs a runnable with a delay
* @param runnable the runnable
* @param delayTicks the delay in ticks
*/
void syncLater(Runnable runnable, long delayTicks);
/**
* Shuts down this executor instance
*/
void shutdown(); void shutdown();
} }

View File

@ -43,7 +43,7 @@ import me.lucko.luckperms.common.data.Log;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.storage.backing.AbstractBacking; import me.lucko.luckperms.common.storage.backing.AbstractBacking;
import me.lucko.luckperms.common.storage.wrappings.BufferedOutputStorage; import me.lucko.luckperms.common.storage.wrappings.BufferedOutputStorage;
import me.lucko.luckperms.common.storage.wrappings.TolerantStorage; import me.lucko.luckperms.common.storage.wrappings.PhasedStorage;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -57,8 +57,8 @@ import java.util.function.Supplier;
@RequiredArgsConstructor(access = AccessLevel.PRIVATE) @RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class AbstractStorage implements Storage { public class AbstractStorage implements Storage {
public static Storage wrap(LuckPermsPlugin plugin, AbstractBacking backing) { public static Storage wrap(LuckPermsPlugin plugin, AbstractBacking backing) {
BufferedOutputStorage bufferedDs = BufferedOutputStorage.wrap(TolerantStorage.wrap(new AbstractStorage(plugin, backing)), 1000L); BufferedOutputStorage bufferedDs = BufferedOutputStorage.wrap(PhasedStorage.wrap(new AbstractStorage(plugin, backing)), 1000L);
plugin.getScheduler().doAsyncRepeating(bufferedDs, 10L); plugin.getScheduler().asyncRepeating(bufferedDs, 10L);
return bufferedDs; return bufferedDs;
} }
@ -77,7 +77,7 @@ public class AbstractStorage implements Storage {
} }
private <T> CompletableFuture<T> makeFuture(Supplier<T> supplier) { private <T> CompletableFuture<T> makeFuture(Supplier<T> supplier) {
return CompletableFuture.supplyAsync(supplier, backing.getPlugin().getScheduler().getAsyncExecutor()); return CompletableFuture.supplyAsync(supplier, backing.getPlugin().getScheduler().async());
} }
@Override @Override

View File

@ -605,7 +605,7 @@ public class YAMLBacking extends FlatfileBacking {
int size = vals.size(); int size = vals.size();
if (size == 1) { if (size == 1) {
context.put(e.getKey(), vals.get(0));; context.put(e.getKey(), vals.get(0));
} else if (size > 1) { } else if (size > 1) {
context.put(e.getKey(), vals); context.put(e.getKey(), vals);
} }

View File

@ -52,33 +52,10 @@ public class BufferedOutputStorage implements Storage, Runnable {
private final long flushTime; private final long flushTime;
private final Buffer<User, Boolean> userOutputBuffer = new Buffer<User, Boolean>() { private final Buffer<User, Boolean> userOutputBuffer = Buffer.of(user -> backing.saveUser(user).join());
@Override private final Buffer<Group, Boolean> groupOutputBuffer = Buffer.of(group -> backing.saveGroup(group).join());
public Boolean dequeue(User user) { private final Buffer<Track, Boolean> trackOutputBuffer = Buffer.of(track -> backing.saveTrack(track).join());
return backing.saveUser(user).join(); private final Buffer<UserIdentifier, Boolean> uuidDataOutputBuffer = Buffer.of(userIdentifier -> backing.saveUUIDData(userIdentifier.getUsername().get(), userIdentifier.getUuid()).join());
}
};
private final Buffer<Group, Boolean> groupOutputBuffer = new Buffer<Group, Boolean>() {
@Override
public Boolean dequeue(Group group) {
return backing.saveGroup(group).join();
}
};
private final Buffer<Track, Boolean> trackOutputBuffer = new Buffer<Track, Boolean>() {
@Override
public Boolean dequeue(Track track) {
return backing.saveTrack(track).join();
}
};
private final Buffer<UserIdentifier, Boolean> uuidDataOutputBuffer = new Buffer<UserIdentifier, Boolean>() {
@Override
protected Boolean dequeue(UserIdentifier userIdentifier) {
return backing.saveUUIDData(userIdentifier.getUsername().get(), userIdentifier.getUuid()).join();
}
};
@Override @Override
public void run() { public void run() {

View File

@ -53,9 +53,9 @@ import java.util.concurrent.TimeoutException;
* A Datastore wrapping that ensures all tasks are completed before {@link Storage#shutdown()} is called. * A Datastore wrapping that ensures all tasks are completed before {@link Storage#shutdown()} is called.
*/ */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE) @RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class TolerantStorage implements Storage { public class PhasedStorage implements Storage {
public static TolerantStorage wrap(Storage storage) { public static PhasedStorage wrap(Storage storage) {
return new TolerantStorage(storage); return new PhasedStorage(storage);
} }
@Delegate(types = Delegated.class) @Delegate(types = Delegated.class)

View File

@ -36,6 +36,7 @@ import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
/** /**
* Thread-safe buffer utility. Holds a buffer of objects to be processed after they've been waiting in the buffer * Thread-safe buffer utility. Holds a buffer of objects to be processed after they've been waiting in the buffer
@ -44,11 +45,20 @@ import java.util.concurrent.locks.ReentrantLock;
* @param <T> the type of objects in the buffer * @param <T> the type of objects in the buffer
* @param <R> the type of result produced by the final process * @param <R> the type of result produced by the final process
*/ */
public abstract class Buffer<T, R> implements Runnable { public class Buffer<T, R> implements Runnable {
private static final long DEFAULT_FLUSH_TIME = 1000; // 1 second private static final long DEFAULT_FLUSH_TIME = 1000; // 1 second
public static <T, R> Buffer<T, R> of(Function<T, R> dequeueFunc) {
return new Buffer<>(dequeueFunc);
}
private final ReentrantLock lock = new ReentrantLock(); private final ReentrantLock lock = new ReentrantLock();
private final List<BufferedObject<T, R>> buffer = new LinkedList<>(); private final List<BufferedObject<T, R>> buffer = new LinkedList<>();
private final Function<T, R> dequeueFunc;
private Buffer(Function<T, R> dequeueFunc) {
this.dequeueFunc = dequeueFunc;
}
public CompletableFuture<R> enqueue(@NonNull T t) { public CompletableFuture<R> enqueue(@NonNull T t) {
lock.lock(); lock.lock();
@ -80,7 +90,9 @@ public abstract class Buffer<T, R> implements Runnable {
} }
} }
protected abstract R dequeue(T t); protected R dequeue(T t) {
return dequeueFunc.apply(t);
}
public void flush(long flushTime) { public void flush(long flushTime) {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();

View File

@ -68,7 +68,7 @@ public class FileWatcher implements Runnable {
} }
// Register with a delay to ignore changes made at startup // Register with a delay to ignore changes made at startup
plugin.getScheduler().doAsyncLater(() -> { plugin.getScheduler().asyncLater(() -> {
try { try {
// doesn't need to be atomic // doesn't need to be atomic
if (keyMap.containsKey(id)) { if (keyMap.containsKey(id)) {

View File

@ -37,30 +37,37 @@ import java.util.stream.Collector;
@UtilityClass @UtilityClass
public class ImmutableCollectors { public class ImmutableCollectors {
private static final Collector<Object, ImmutableList.Builder<Object>, ImmutableList<Object>> LIST = Collector.of(
ImmutableList.Builder::new,
ImmutableList.Builder::add,
(l, r) -> l.addAll(r.build()),
ImmutableList.Builder::build
);
private static final Collector<Object, ImmutableSet.Builder<Object>, ImmutableSet<Object>> SET = Collector.of(
ImmutableSet.Builder::new,
ImmutableSet.Builder::add,
(l, r) -> l.addAll(r.build()),
ImmutableSet.Builder::build
);
public static <T> Collector<T, ImmutableList.Builder<T>, ImmutableList<T>> toImmutableList() {
//noinspection unchecked
return (Collector) LIST;
}
public static <T> Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>> toImmutableSet() {
//noinspection unchecked
return (Collector) SET;
}
public static <T, K, V> Collector<T, ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> toImmutableMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) { public static <T, K, V> Collector<T, ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> toImmutableMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
return Collector.of( return Collector.of(
ImmutableMap.Builder<K, V>::new, ImmutableMap.Builder<K, V>::new,
(r, t) -> r.put(keyMapper.apply(t), valueMapper.apply(t)), (r, t) -> r.put(keyMapper.apply(t), valueMapper.apply(t)),
(l, r) -> l.putAll(r.build()), (l, r) -> l.putAll(r.build()),
ImmutableMap.Builder::build, ImmutableMap.Builder::build
Collector.Characteristics.UNORDERED); );
}
public static <T> Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>> toImmutableSet() {
return Collector.of(
ImmutableSet.Builder<T>::new,
ImmutableSet.Builder<T>::add,
(l, r) -> l.addAll(r.build()),
ImmutableSet.Builder<T>::build,
Collector.Characteristics.UNORDERED);
}
public static <T> Collector<T, ImmutableList.Builder<T>, ImmutableList<T>> toImmutableList() {
return Collector.of(
ImmutableList.Builder<T>::new,
ImmutableList.Builder<T>::add,
(l, r) -> l.addAll(r.build()),
ImmutableList.Builder<T>::build);
} }
} }

View File

@ -32,7 +32,7 @@ import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
@AllArgsConstructor @AllArgsConstructor
public class LoggerImpl implements Logger { public class SenderLogger implements Logger {
private final Sender console; private final Sender console;
@Override @Override

View File

@ -65,7 +65,7 @@ import me.lucko.luckperms.common.tasks.UpdateTask;
import me.lucko.luckperms.common.treeview.PermissionVault; import me.lucko.luckperms.common.treeview.PermissionVault;
import me.lucko.luckperms.common.utils.BufferedRequest; import me.lucko.luckperms.common.utils.BufferedRequest;
import me.lucko.luckperms.common.utils.FileWatcher; import me.lucko.luckperms.common.utils.FileWatcher;
import me.lucko.luckperms.common.utils.LoggerImpl; import me.lucko.luckperms.common.utils.SenderLogger;
import me.lucko.luckperms.common.verbose.VerboseHandler; import me.lucko.luckperms.common.verbose.VerboseHandler;
import me.lucko.luckperms.sponge.commands.SpongeMainCommand; import me.lucko.luckperms.sponge.commands.SpongeMainCommand;
import me.lucko.luckperms.sponge.contexts.WorldCalculator; import me.lucko.luckperms.sponge.contexts.WorldCalculator;
@ -170,11 +170,11 @@ public class LPSpongePlugin implements LuckPermsPlugin {
scheduler = new LPSpongeScheduler(this); scheduler = new LPSpongeScheduler(this);
localeManager = new NoopLocaleManager(); localeManager = new NoopLocaleManager();
senderFactory = new SpongeSenderFactory(this); senderFactory = new SpongeSenderFactory(this);
log = new LoggerImpl(getConsoleSender()); log = new SenderLogger(getConsoleSender());
LuckPermsPlugin.sendStartupBanner(getConsoleSender(), this); LuckPermsPlugin.sendStartupBanner(getConsoleSender(), this);
verboseHandler = new VerboseHandler(scheduler.getAsyncExecutor(), getVersion()); verboseHandler = new VerboseHandler(scheduler.async(), getVersion());
permissionVault = new PermissionVault(scheduler.getAsyncExecutor()); permissionVault = new PermissionVault(scheduler.async());
timings = new LPTimings(this); timings = new LPTimings(this);
getLog().info("Loading configuration..."); getLog().info("Loading configuration...");
@ -190,7 +190,7 @@ public class LPSpongePlugin implements LuckPermsPlugin {
if (getConfiguration().get(ConfigKeys.WATCH_FILES)) { if (getConfiguration().get(ConfigKeys.WATCH_FILES)) {
fileWatcher = new FileWatcher(this); fileWatcher = new FileWatcher(this);
getScheduler().doAsyncRepeating(fileWatcher, 30L); getScheduler().asyncRepeating(fileWatcher, 30L);
} }
// initialise datastore // initialise datastore
@ -297,18 +297,18 @@ public class LPSpongePlugin implements LuckPermsPlugin {
int mins = getConfiguration().get(ConfigKeys.SYNC_TIME); int mins = getConfiguration().get(ConfigKeys.SYNC_TIME);
if (mins > 0) { if (mins > 0) {
long ticks = mins * 60 * 20; long ticks = mins * 60 * 20;
scheduler.doAsyncRepeating(() -> updateTaskBuffer.request(), ticks); scheduler.asyncRepeating(() -> updateTaskBuffer.request(), ticks);
} }
scheduler.doAsyncLater(() -> updateTaskBuffer.request(), 40L); scheduler.asyncLater(() -> updateTaskBuffer.request(), 40L);
// run an update instantly. // run an update instantly.
updateTaskBuffer.requestDirectly(); updateTaskBuffer.requestDirectly();
// register tasks // register tasks
scheduler.doAsyncRepeating(new ExpireTemporaryTask(this), 60L); scheduler.asyncRepeating(new ExpireTemporaryTask(this), 60L);
scheduler.doAsyncRepeating(new CacheHousekeepingTask(this), 2400L); scheduler.asyncRepeating(new CacheHousekeepingTask(this), 2400L);
scheduler.doAsyncRepeating(new ServiceCacheHousekeepingTask(service), 2400L); scheduler.asyncRepeating(new ServiceCacheHousekeepingTask(service), 2400L);
// scheduler.doAsyncRepeating(() -> userManager.performCleanup(), 2400L); // scheduler.asyncRepeating(() -> userManager.performCleanup(), 2400L);
getLog().info("Successfully loaded."); getLog().info("Successfully loaded.");
} }

View File

@ -42,45 +42,45 @@ public class LPSpongeScheduler implements LuckPermsScheduler {
} }
@Override @Override
public Executor getAsyncExecutor() { public Executor async() {
return plugin.getAsyncExecutorService(); return plugin.getAsyncExecutorService();
} }
@Override @Override
public Executor getSyncExecutor() { public Executor sync() {
return plugin.getSyncExecutorService(); return plugin.getSyncExecutorService();
} }
@Override @Override
public void doAsync(Runnable r) { public void doAsync(Runnable runnable) {
plugin.getSpongeScheduler().createTaskBuilder().async().execute(r).submit(plugin); plugin.getSpongeScheduler().createTaskBuilder().async().execute(runnable).submit(plugin);
} }
@Override @Override
public void doSync(Runnable r) { public void doSync(Runnable runnable) {
plugin.getSpongeScheduler().createTaskBuilder().execute(r).submit(plugin); plugin.getSpongeScheduler().createTaskBuilder().execute(runnable).submit(plugin);
} }
@Override @Override
public void doAsyncRepeating(Runnable r, long interval) { public void asyncRepeating(Runnable runnable, long intervalTicks) {
Task task = plugin.getSpongeScheduler().createTaskBuilder().async().intervalTicks(interval).delayTicks(interval).execute(r).submit(plugin); Task task = plugin.getSpongeScheduler().createTaskBuilder().async().intervalTicks(intervalTicks).delayTicks(intervalTicks).execute(runnable).submit(plugin);
tasks.add(task); tasks.add(task);
} }
@Override @Override
public void doSyncRepeating(Runnable r, long interval) { public void syncRepeating(Runnable runnable, long intervalTicks) {
Task task = plugin.getSpongeScheduler().createTaskBuilder().intervalTicks(interval).delayTicks(interval).execute(r).submit(plugin); Task task = plugin.getSpongeScheduler().createTaskBuilder().intervalTicks(intervalTicks).delayTicks(intervalTicks).execute(runnable).submit(plugin);
tasks.add(task); tasks.add(task);
} }
@Override @Override
public void doAsyncLater(Runnable r, long delay) { public void asyncLater(Runnable runnable, long delayTicks) {
plugin.getSpongeScheduler().createTaskBuilder().async().delayTicks(delay).execute(r).submit(plugin); plugin.getSpongeScheduler().createTaskBuilder().async().delayTicks(delayTicks).execute(runnable).submit(plugin);
} }
@Override @Override
public void doSyncLater(Runnable r, long delay) { public void syncLater(Runnable runnable, long delayTicks) {
plugin.getSpongeScheduler().createTaskBuilder().delayTicks(delay).execute(r).submit(plugin); plugin.getSpongeScheduler().createTaskBuilder().delayTicks(delayTicks).execute(runnable).submit(plugin);
} }
@Override @Override

View File

@ -95,13 +95,6 @@ class SpongeCommand extends CommandManager implements CommandCallable {
} }
} }
// For API 4
public List<String> getSuggestions(CommandSource source, String s) throws CommandException {
try (Timing ignored = plugin.getTimings().time(LPTiming.COMMAND_TAB_COMPLETE)) {
return onTabComplete(plugin.getSenderFactory().wrap(source), Splitter.on(' ').splitToList(s));
}
}
@Override @Override
public boolean testPermission(CommandSource source) { public boolean testPermission(CommandSource source) {
return true; return true;
@ -114,11 +107,11 @@ class SpongeCommand extends CommandManager implements CommandCallable {
@Override @Override
public Optional<Text> getHelp(CommandSource source) { public Optional<Text> getHelp(CommandSource source) {
return Optional.of(Text.of("Type /perms for help.")); return Optional.of(Text.of("Type /luckperms for help."));
} }
@Override @Override
public Text getUsage(CommandSource source) { public Text getUsage(CommandSource source) {
return Text.of("/perms"); return Text.of("/luckperms");
} }
} }

View File

@ -55,9 +55,9 @@ public class SpongeConfig extends AbstractConfiguration {
private ConfigurationNode root; private ConfigurationNode root;
@SuppressWarnings("ResultOfMethodCallIgnored")
private Path makeFile(Path file) throws IOException { private Path makeFile(Path file) throws IOException {
File cfg = file.toFile(); File cfg = file.toFile();
//noinspection ResultOfMethodCallIgnored
cfg.getParentFile().mkdirs(); cfg.getParentFile().mkdirs();
if (!cfg.exists()) { if (!cfg.exists()) {

View File

@ -200,7 +200,7 @@ public class SpongeGroupManager implements GroupManager, LPSubjectCollection {
return CompletableFuture.completedFuture(present); return CompletableFuture.completedFuture(present);
} }
return CompletableFuture.supplyAsync(() -> subjectLoadingCache.get(identifier.toLowerCase()), plugin.getScheduler().getAsyncExecutor()); return CompletableFuture.supplyAsync(() -> subjectLoadingCache.get(identifier.toLowerCase()), plugin.getScheduler().async());
} }
@Override @Override
@ -226,7 +226,7 @@ public class SpongeGroupManager implements GroupManager, LPSubjectCollection {
} }
return ret.build(); return ret.build();
}, plugin.getScheduler().getAsyncExecutor()); }, plugin.getScheduler().async());
} }
@Override @Override
@ -252,7 +252,7 @@ public class SpongeGroupManager implements GroupManager, LPSubjectCollection {
} }
return ret.build(); return ret.build();
}, plugin.getScheduler().getAsyncExecutor()); }, plugin.getScheduler().async());
} }
@Override @Override
@ -268,7 +268,7 @@ public class SpongeGroupManager implements GroupManager, LPSubjectCollection {
} }
return ret.build(); return ret.build();
}, plugin.getScheduler().getAsyncExecutor()); }, plugin.getScheduler().async());
} }
@Override @Override

View File

@ -265,7 +265,7 @@ public class SpongeUserManager implements UserManager, LPSubjectCollection {
return CompletableFuture.completedFuture(present); return CompletableFuture.completedFuture(present);
} }
return CompletableFuture.supplyAsync(() -> subjectLoadingCache.get(uuid), plugin.getScheduler().getAsyncExecutor()); return CompletableFuture.supplyAsync(() -> subjectLoadingCache.get(uuid), plugin.getScheduler().async());
} }
@Override @Override
@ -314,7 +314,7 @@ public class SpongeUserManager implements UserManager, LPSubjectCollection {
} }
return ret.build(); return ret.build();
}, plugin.getScheduler().getAsyncExecutor()); }, plugin.getScheduler().async());
} }
@Override @Override
@ -331,7 +331,7 @@ public class SpongeUserManager implements UserManager, LPSubjectCollection {
plugin.getStorage().getUniqueUsers().join().forEach(uuid -> ids.add(uuid.toString())); plugin.getStorage().getUniqueUsers().join().forEach(uuid -> ids.add(uuid.toString()));
return ids.build(); return ids.build();
}, plugin.getScheduler().getAsyncExecutor()); }, plugin.getScheduler().async());
} }
@Override @Override
@ -347,7 +347,7 @@ public class SpongeUserManager implements UserManager, LPSubjectCollection {
} }
return ret.build(); return ret.build();
}, plugin.getScheduler().getAsyncExecutor()); }, plugin.getScheduler().async());
} }
@Override @Override
@ -363,7 +363,7 @@ public class SpongeUserManager implements UserManager, LPSubjectCollection {
} }
return ret.build(); return ret.build();
}, plugin.getScheduler().getAsyncExecutor()); }, plugin.getScheduler().async());
} }
@Override @Override

View File

@ -486,10 +486,10 @@ public class LuckPermsSubjectData implements LPSubjectData {
} else { } else {
if (t instanceof User) { if (t instanceof User) {
User user = ((User) t); User user = ((User) t);
return service.getPlugin().getStorage().saveUser(user).thenCombineAsync(user.getRefreshBuffer().request(), (b, v) -> v, service.getPlugin().getScheduler().getAsyncExecutor()); return service.getPlugin().getStorage().saveUser(user).thenCombineAsync(user.getRefreshBuffer().request(), (b, v) -> v, service.getPlugin().getScheduler().async());
} else { } else {
Group group = ((Group) t); Group group = ((Group) t);
return service.getPlugin().getStorage().saveGroup(group).thenCombineAsync(service.getPlugin().getUpdateTaskBuffer().request(), (b, v) -> v, service.getPlugin().getScheduler().getAsyncExecutor()); return service.getPlugin().getStorage().saveGroup(group).thenCombineAsync(service.getPlugin().getUpdateTaskBuffer().request(), (b, v) -> v, service.getPlugin().getScheduler().async());
} }
} }
} }