Skip to content

Commit

Permalink
Fixes an error while attempting to check for island locations.
Browse files Browse the repository at this point in the history
Added Island await task for owners who doesn't want players to ditch /is reset
Removes runTaskAsync and moves to the Database threads.
Basic implementation of CoopCategory.
Thank you Nukkit for using Log4j as console logger.
Improves code stability and consistency.
Raised git try-catch block to catch Throwable, closes #6
Revised config.yml file #7
  • Loading branch information
larryTheCoder committed Jun 29, 2020
1 parent 2b0b34e commit 28a5f15
Show file tree
Hide file tree
Showing 19 changed files with 471 additions and 813 deletions.
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
<name>ASkyBlock</name>
<groupId>larryTheCoder</groupId>
<artifactId>SkyBlock</artifactId>
<version>v0.5.1-BLEEDING</version>
<version>v0.5.2-BETA</version>
<description>Minecraft BE SkyBlock minigame plugin for Nukkit</description>
<inceptionYear>2016</inceptionYear>

Expand Down Expand Up @@ -76,7 +76,7 @@
<dependency>
<groupId>cn.nukkit</groupId>
<artifactId>nukkit</artifactId>
<version>1.0-20200423.205734-801</version>
<version>1.0-SNAPSHOT</version>
</dependency>

<dependency>
Expand Down
15 changes: 7 additions & 8 deletions src/main/java/com/larryTheCoder/ASkyBlock.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@
import org.sql2o.data.Table;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -240,7 +239,7 @@ private void initGitCheckup() {
Properties properties = new Properties();
try {
properties.load(getResource("git-sb.properties"));
} catch (IOException e) {
} catch (Throwable e) {
getServer().getLogger().info("§cERROR! We cannot load the git loader for this ASkyBlock build!");
// Wtf? Maybe this user is trying to using unofficial build of ASkyBlock?
// Or they just wanna to create a PR to do a fix?
Expand Down Expand Up @@ -278,9 +277,9 @@ private void initConfig() {
Utils.EnsureDirectory(Utils.UPDATES_DIRECTORY);

// Use common sense on every damn thing
saveResource("config.yml");
saveResource("config.yml", true);
saveResource("worlds.yml");
saveResource("quests.yml");
//saveResource("quests.yml"); // TODO
saveResource("blockvalues.yml", true);
saveResource("schematics/island.schematic");
saveResource("schematics/featured.schematic");
Expand All @@ -290,21 +289,21 @@ private void initConfig() {

cfg = new Config(new File(getDataFolder(), "config.yml"), Config.YAML);
worldConfig = new Config(new File(getDataFolder(), "worlds.yml"), Config.YAML);
recheck();

ConfigManager.load();
}

@SuppressWarnings("ResultOfMethodCallIgnored")
private void recheck() {
public static void recheck() {
File file = new File(ASkyBlock.get().getDataFolder(), "config.yml");
Config config = new Config(file, Config.YAML);
if (!Utils.isNumeric(config.get("version")) || config.getInt("version", 0) < 1) {
if (!Utils.isNumeric(config.get("version")) || config.getInt("version", 0) < 2) {
file.renameTo(new File(ASkyBlock.get().getDataFolder(), "config.old"));
ASkyBlock.get().saveResource("config.yml");
Utils.send("&cYour configuration file is outdated! We are creating you new one, please wait...");
Utils.send("&aYour old config will be renamed into config.old!");
}
cfg.reload(); // Reload the config
ASkyBlock.get().cfg.reload(); // Reload the config
}

private void generateLevel() {
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/larryTheCoder/cache/CoopData.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ public class CoopData {
@Getter
private String teamName;
@Getter
private List<String> members;
private final List<String> members;
@Getter
private List<String> admins;
private final List<String> admins;

public CoopData(Row coopData) {
this.islandUniqueId = coopData.getString("defaultIsland");
Expand Down
57 changes: 30 additions & 27 deletions src/main/java/com/larryTheCoder/cache/FastCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
import com.larryTheCoder.ASkyBlock;
import com.larryTheCoder.database.DatabaseManager;
import com.larryTheCoder.database.TableSet;
import com.larryTheCoder.task.TaskManager;
import com.larryTheCoder.utils.Settings;
import com.larryTheCoder.utils.Utils;
import lombok.Getter;
Expand Down Expand Up @@ -69,8 +68,8 @@ public class FastCache {
private String cacheValidationId;

// To securely store FastCache timestamp into a .json file.
public static final ConcurrentLinkedQueue<FastCacheData> storeSchedule = new ConcurrentLinkedQueue<>();
public final AtomicBoolean isClosed = new AtomicBoolean(true);
public final ConcurrentLinkedQueue<FastCacheData> storeSchedule = new ConcurrentLinkedQueue<>();
public final AtomicBoolean isRunning = new AtomicBoolean(false);

public FastCache(ASkyBlock plugin) {
this.plugin = plugin;
Expand All @@ -79,15 +78,15 @@ public FastCache(ASkyBlock plugin) {
}

public void shutdownCache() {
isClosed.compareAndSet(true, false);
isRunning.compareAndSet(true, false);
}

private void addAllCacheData(List<FastCacheData> list) {
dataCache.addAll(list);
}

private void loadFastCache() {
config = new Config(Utils.DIRECTORY + "cache.yml", Config.YAML);
config = new Config(Utils.DIRECTORY + "cache.json", Config.JSON);

if (config.getString("cacheVerificationId").isEmpty()) {
config.set("cacheVerificationId", DatabaseManager.currentCacheId);
Expand Down Expand Up @@ -181,29 +180,33 @@ public void onCompletion(Exception err) {
ASkyBlock.get().getFastCache().addAllCacheData(dataCache);
storeSchedule.clear(); // Remove useless caches.

TaskManager.runTaskAsync(() -> {
while (isClosed.get()) {
FastCacheData consumer;
while ((consumer = storeSchedule.poll()) != null) {
ConfigSection playerSec = new ConfigSection();
playerSec.set("lastFetched", consumer.lastUpdatedQuery);
playerSec.set("islandIds", new ArrayList<>(consumer.getIslandData().keySet()));

config.set(consumer.getDataIdentifier(), playerSec);
config.save();
}

try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
isRunning.compareAndSet(true, false);
}
});
}

/**
* This function is to be used by Database class to save the config file without
* sacrificing the server TPS by running this in another thread.
* <p>
* This usage is INTERNAL ONLY, DO NOT RUN THIS IN ANY CODE.
*/
public void databaseTick() {
if (!isRunning.get()) return;

FastCacheData consumer;
while ((consumer = storeSchedule.poll()) != null) {
ConfigSection playerSec = new ConfigSection();
playerSec.set("lastFetched", consumer.lastUpdatedQuery);
playerSec.set("islandIds", new ArrayList<>(consumer.getIslandData().keySet()));

config.set(consumer.getDataIdentifier(), playerSec);
config.save();
}

Utils.send("Ticking...");
}

public boolean containsId(String value) {
return uniqueId.contains(value);
}
Expand Down Expand Up @@ -771,13 +774,13 @@ private static class FastCacheData {

private Timestamp lastUpdatedQuery;

private String ownedBy;

@Getter
private Map<Integer, IslandData> islandData = new HashMap<>();
@Getter
private PlayerData playerData = null;

private final String ownedBy;

FastCacheData(String playerName) {
this.ownedBy = playerName;
}
Expand Down Expand Up @@ -842,7 +845,7 @@ IslandData getIslandById(int homeId) {
void updateTime() {
lastUpdatedQuery = Timestamp.from(Instant.now());

storeSchedule.offer(this);
ASkyBlock.get().getFastCache().storeSchedule.offer(this);
}

public String getDataIdentifier() {
Expand Down
26 changes: 7 additions & 19 deletions src/main/java/com/larryTheCoder/command/category/CoopCategory.java
Original file line number Diff line number Diff line change
Expand Up @@ -152,31 +152,19 @@ public void execute(CommandSender sender, String commandLabel, String[] args) {
}

if (!data.isAdmin(p)) {
p.sendMessage(getPrefix() + "You are not an admin in this server.");
p.sendMessage(getPrefix() + "You are not an admin in this island.");
return;
}

getPlugin().getFastCache().getIslandData(data.getIslandUniqueId(), pd -> {
Player inviter = p.getServer().getPlayer(args[1]);
if (inviter == null) {
p.sendMessage(getPrefix() + getLocale(p).errorOfflinePlayer);
return;
}

getPlugin().getInvitationHandler().addInvitation(sender, inviter, pd);
});
// if (!data.getPlotOwner().equalsIgnoreCase(p.getName())) {
// p.sendMessage(getPrefix() + "That is not your island!");
// return;
// }
//
// Player inviter = p.getServer().getPlayer(args[1]);
// if (inviter == null) {
// p.sendMessage(getPrefix() + getLocale(p).errorOfflinePlayer);
// return;
// }
//
// getPlugin().getFastCache().getRelations(p.getName(), relation -> {
// if (relation == null) {
// //getPlugin().getInvitationHandler().addInvitation(p, inviter, );
// } else {
// sender.sendMessage(getPrefix() + getLocale(p).errorInTeam.replace("[player]", args[1]));
// }
// });
});
break;
}
Expand Down
17 changes: 14 additions & 3 deletions src/main/java/com/larryTheCoder/database/DatabaseManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,15 @@

import cn.nukkit.api.API;
import cn.nukkit.utils.TextFormat;
import com.larryTheCoder.ASkyBlock;
import com.larryTheCoder.cache.FastCache;
import com.larryTheCoder.database.config.AbstractConfig;
import com.larryTheCoder.database.config.MySQLConfig;
import com.larryTheCoder.task.TaskManager;
import com.larryTheCoder.utils.IslandAwaitStore;
import com.larryTheCoder.utils.Settings;
import com.larryTheCoder.utils.Utils;
import lombok.extern.log4j.Log4j2;
import org.sql2o.Connection;
import org.sql2o.Query;
import org.sql2o.data.Row;
Expand All @@ -55,6 +59,7 @@
* to execute the query using FIFO order. This method is more reliable as the process
* will not be interrupted on main thread.
*/
@Log4j2
public class DatabaseManager {

public static final String DB_VERSION = "0.1.7";
Expand Down Expand Up @@ -109,7 +114,8 @@ private void startConnection() {
PLAYER_CHALLENGES,
ISLAND_TABLE,
ISLAND_DATA,
ISLAND_RELATIONS
ISLAND_RELATIONS,
ISLAND_LIMIT_COUNT
};

if (isMysql) {
Expand Down Expand Up @@ -159,6 +165,7 @@ private void startConnection() {
Utils.send(TextFormat.GOLD + "Updated database information to " + TextFormat.YELLOW + "v" + DB_VERSION);
}
}
IslandAwaitStore.init(connection);

// If the database is a mysql database, we can
// apply as many connections we want since this database
Expand Down Expand Up @@ -226,6 +233,10 @@ private void startAsyncPool(int maxPool) {
}
});
}
IslandAwaitStore.databaseTick(connection);
FastCache cache = ASkyBlock.get().getFastCache();
if (cache != null) cache.databaseTick();

long nowTick = System.currentTimeMillis() - lastTick;

// The execution took 50ms to execute, do not bother sleeping this thread.
Expand All @@ -235,8 +246,7 @@ private void startAsyncPool(int maxPool) {
Thread.sleep(50 - nowTick);
} catch (Throwable e) {
// Sync up with console.

TaskManager.runTask(e::printStackTrace);
log.throwing(e);
}
}
});
Expand All @@ -249,6 +259,7 @@ private void startAsyncPool(int maxPool) {
if (currentPoolSize < maxPool) startAsyncPool(maxPool);
}

// TODO: Use Future<> class for better performance?
public abstract static class DatabaseImpl {

/**
Expand Down
7 changes: 6 additions & 1 deletion src/main/java/com/larryTheCoder/database/TableSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ public enum TableSet {
"FOREIGN KEY (islandLeader) REFERENCES player(playerName) ON UPDATE CASCADE," +
"PRIMARY KEY (defaultIsland, islandLeader)) %OPTIMIZE"),

ISLAND_LIMIT_COUNT("CREATE TABLE IF NOT EXISTS lastExecution(" +
"playerUniqueId VARCHAR(64) NOT NULL," +
"lastQueried BIGINT NOT NULL" +
") %OPTIMIZE"),

METADATA_TABLE("CREATE TABLE IF NOT EXISTS cacheMetadata(" +
"dbVersion INT NOT NULL," +
"firstInit DEFAULT CURRENT_TIMESTAMP," +
Expand All @@ -95,7 +100,7 @@ public enum TableSet {
FETCH_PLAYER_MAIN("SELECT * FROM player WHERE playerName = :plotOwner"),
FETCH_PLAYER_DATA("SELECT * FROM challenges WHERE player = :playerName"),
FETCH_ISLAND_UNIQUE("SELECT * FROM island WHERE islandUniqueId = :islandUniqueId AND levelName = :levelName"),
FETCH_LEVEL_PLOT("SELECT * FROM island WHERE AND islandUniqueId = :islandId"),
FETCH_LEVEL_PLOT("SELECT * FROM island WHERE islandUniqueId = :islandId"),
FETCH_ISLAND_PLOTS("SELECT * FROM island WHERE playerName = :pName"),
FETCH_ISLAND_PLOT("SELECT * FROM island WHERE playerName = :pName AND islandId = :islandId"),
FETCH_ISLAND_NAME("SELECT * FROM island WHERE playerName = :pName AND islandName = :islandName"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public class SQLiteConfig implements AbstractConfig {
private Sql2o connection;

public SQLiteConfig(Config data) {
this.file = new File(ASkyBlock.get().getDataFolder(), data.getString("database.SQLite.file-name") + ".db");
this.file = new File(ASkyBlock.get().getDataFolder(), data.getString("database.SQLite.file-name"));
this.dbLocation = file.getAbsolutePath();
}

Expand Down
Loading

0 comments on commit 28a5f15

Please sign in to comment.