Skip to content

Commit

Permalink
basic indexing kinda working
Browse files Browse the repository at this point in the history
  • Loading branch information
DaNussi committed Mar 26, 2024
1 parent f35fa6a commit 0b48307
Show file tree
Hide file tree
Showing 11 changed files with 738 additions and 261 deletions.
Binary file added redis/data/dump.rdb
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import net.minecraftforge.fml.common.Mod;
import org.slf4j.Logger;

import java.util.UUID;

@Mod.EventBusSubscriber(modid = DedicatedAppliedEnegistics.MODID)
public class DedicatedAppliedEnergisticsController {
private static final Logger LOGGER = LogUtils.getLogger();
Expand All @@ -16,6 +18,7 @@ public class DedicatedAppliedEnergisticsController {

public static ForgeConfigSpec.ConfigValue<String> CONFIG_VALUE_RABBITMQ_URI;
public static ForgeConfigSpec.ConfigValue<String> CONFIG_VALUE_REDIS_URI;
public static ForgeConfigSpec.ConfigValue<String> CONFIG_VALUE_HOST_ID;

public static ForgeConfigSpec.ConfigValue<Boolean> CONFIG_VALUE_BEHAVIOUR_AUTOSTART;

Expand All @@ -24,6 +27,7 @@ public class DedicatedAppliedEnergisticsController {

CONFIG_VALUE_RABBITMQ_URI = CONFIG_BUILDER.define("RABBITMQ_URI", "amqp://guest:guest@localhost:5672/");
CONFIG_VALUE_REDIS_URI = CONFIG_BUILDER.define("REDIS_URI", "redis://localhost:6379/");
CONFIG_VALUE_HOST_ID = CONFIG_BUILDER.define("HOST_ID", UUID.randomUUID().toString());

CONFIG_VALUE_BEHAVIOUR_AUTOSTART = CONFIG_BUILDER.define("BEHAVIOUR_AUTOSTART", false);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,124 +1,112 @@
package net.nussi.dedicated_applied_energistics.blockentities;

import appeng.api.crafting.IPatternDetails;
import appeng.api.networking.GridFlags;
import appeng.api.networking.IGridNodeListener;
import appeng.api.networking.crafting.ICraftingProvider;
import appeng.api.networking.ticking.IGridTickable;
import appeng.api.orientation.BlockOrientation;
import appeng.api.stacks.AEItemKey;
import appeng.api.stacks.AEKey;
import appeng.api.stacks.KeyCounter;
import appeng.api.storage.IStorageMounts;
import appeng.api.storage.IStorageProvider;
import appeng.api.util.AECableType;
import appeng.blockentity.grid.AENetworkBlockEntity;
import com.mojang.logging.LogUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.event.level.BlockEvent;
import net.minecraftforge.event.level.ChunkEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.nussi.dedicated_applied_energistics.DedicatedAppliedEnegistics;
import net.nussi.dedicated_applied_energistics.init.BlockEntityTypeInit;
import net.nussi.dedicated_applied_energistics.init.ItemInit;
import net.nussi.dedicated_applied_energistics.providers.InterDimensionalInterfaceCrafting;
import net.nussi.dedicated_applied_energistics.providers.InterDimensionalInterfaceStorage;
import org.slf4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import static net.nussi.dedicated_applied_energistics.DedicatedAppliedEnegistics.MODID;
import static net.nussi.dedicated_applied_energistics.DedicatedAppliedEnergisticsController.*;

@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class InterDimensionalInterfaceBlockEntity extends AENetworkBlockEntity implements IStorageProvider, ICraftingProvider {
public class InterDimensionalInterfaceBlockEntity extends AENetworkBlockEntity {
private static final Logger LOGGER = LogUtils.getLogger();
public static final HashMap<BlockPos ,InterDimensionalInterfaceBlockEntity> blockEntities = new HashMap<>();

private InterDimensionalInterfaceStorage storage;
private InterDimensionalInterfaceCrafting crafting;

private String uuid;

public InterDimensionalInterfaceBlockEntity(BlockPos pos, BlockState state) {
super(BlockEntityTypeInit.INTER_DIMENSIONAL_INTERFACE_ENTITY_TYPE.get(), pos, state);


this.uuid = CONFIG_VALUE_HOST_ID.get() + "_" + this.getBlockPos().getX() + "_" + this.getBlockPos().getY() + "_" + this.getBlockPos().getZ();

getMainNode()
.setFlags(GridFlags.REQUIRE_CHANNEL)
.setFlags(GridFlags.DENSE_CAPACITY)
.setVisualRepresentation(AEItemKey.of(new ItemStack(ItemInit.INTER_DIMENSIONAL_INTERFACE_BLOCK_ITEM.get())))
.setIdlePowerUsage(1000);


this.storage = new InterDimensionalInterfaceStorage(this);
this.getMainNode().addService(IStorageProvider.class, this);
this.getMainNode().addService(IStorageProvider.class, this.storage);
this.getMainNode().addService(IGridTickable.class, this.storage);

this.crafting = new InterDimensionalInterfaceCrafting(this);
this.getMainNode().addService(ICraftingProvider.class, this);
this.getMainNode().addService(ICraftingProvider.class, this.crafting);


// Index Block Entity
var oldBlockEntity = blockEntities.get(pos);
if(oldBlockEntity != null) {
oldBlockEntity.onStop();
}
blockEntities.put(pos, this);
registerBlockEntity(this, pos);
}

public String getUuid() {
return uuid;
}

public Channel getRabbitmq() {
return rabbitmq_channel;
}

public Jedis getRedis() {
return redis_connection;
}

public boolean running = false;

public void onStart() {
if(this.running) return;
this.running = true;
LOGGER.info(uuid + " | Starting storage provider");

boolean success = connectDatabase();
if(!success) return;

this.storage.onStart();
this.crafting.onStart();

this.running = true;
LOGGER.info(uuid + " | Started storage provider");
}

public void onStop() {
if(!this.running) return;
LOGGER.info(uuid + " | Stopping storage provider");
this.running = false;

this.storage.onStop();
this.crafting.onStop();
}


this.disconnectDatabase();

@Override
public void mountInventories(IStorageMounts storageMounts) {
storage.mountInventories(storageMounts);
}

@Override
public List<IPatternDetails> getAvailablePatterns() {
return crafting.getAvailablePatterns();
}

@Override
public int getPatternPriority() {
return crafting.getPatternPriority();
}

@Override
public boolean pushPattern(IPatternDetails patternDetails, KeyCounter[] inputHolder) {
return crafting.pushPattern(patternDetails, inputHolder);
}

@Override
public boolean isBusy() {
return crafting.isBusy();
}

@Override
public Set<AEKey> getEmitableItems() {
return crafting.getEmitableItems();
LOGGER.info(uuid + " | Stopped storage provider");
}

@Override
Expand All @@ -134,39 +122,98 @@ public AECableType getCableConnectionType(Direction dir) {
@Override
public void onMainNodeStateChanged(IGridNodeListener.State reason) {
super.onMainNodeStateChanged(reason);
this.storage.onMainNodeStateChanged(reason);
}

// Connect Database
private Connection rabbit_connection;
private Channel rabbitmq_channel;
private JedisPool redis_pool;
private Jedis redis_connection;

private boolean connectDatabase() {

for (int i = 0; i <= 5; i++) {
try {
LOGGER.debug(uuid + " | Connecting to " + CONFIG_VALUE_RABBITMQ_URI.get());
ConnectionFactory factory = new ConnectionFactory();
factory.setUri(CONFIG_VALUE_RABBITMQ_URI.get());


this.rabbit_connection = factory.newConnection();
this.rabbitmq_channel = rabbit_connection.createChannel();
break;
} catch (Exception e) {
LOGGER.error(uuid + " | Failed to start rabbit mq connection! Retry " + i + "/5... ");
// e.printStackTrace();
if(i == 5) return false;
}
}

for (int i = 0; i <= 5; i++) {
try {
LOGGER.debug(uuid + " | Connecting to " + CONFIG_VALUE_REDIS_URI.get());
redis_pool = new JedisPool(new URI(CONFIG_VALUE_REDIS_URI.get()));
redis_connection = redis_pool.getResource();
} catch (Exception e) {
LOGGER.error(uuid + " | Failed to start redis connection! Retry " + i + "/5... ");
// e.printStackTrace();
if(i == 5) return false;
}
}
return true;
}

private void disconnectDatabase() {

// TEST
if(this.rabbitmq_channel != null && this.rabbitmq_channel.isOpen()) {
try {
this.rabbitmq_channel.close();
} catch (Exception e) {
LOGGER.error(uuid + " | Failed to close rabbit mq channel");
e.printStackTrace();
}
}

try {
var nodes = this.getMainNode().getGrid().getNodes();
if(this.rabbit_connection != null && this.rabbit_connection.isOpen()) {
try {
this.rabbit_connection.close();
} catch (Exception e) {
LOGGER.error(uuid + " | Failed to close rabbit mq connection");
e.printStackTrace();
}
}

int i = 0;
for(var node : nodes) {
LOGGER.info(" | Found " + i++ + " " + node.getVisualRepresentation().toString());
try {
KeyCounter itemKeys = new KeyCounter();
IStorageProvider provider = node.getService(IStorageProvider.class);
IStorageMounts mounts = (inventory, priority) -> {
inventory.getAvailableStacks(itemKeys);
};
provider.mountInventories(mounts);
if(this.redis_connection != null && this.redis_connection.isConnected()) {
try {
this.redis_connection.close();
} catch (Exception e) {
LOGGER.error(uuid + " | Failed to close redis connection");
e.printStackTrace();
}
}

LOGGER.info(" | Found items " + itemKeys);

} catch (Exception e) {
LOGGER.info(" | Failed to index node");
e.printStackTrace();
}
if(this.redis_pool != null && !this.redis_pool.isClosed()) {
try {
this.redis_pool.close();
} catch (Exception e) {
LOGGER.error(uuid + " | Failed to close redis pool");
e.printStackTrace();
}
} catch (Exception e) {
LOGGER.info(" | Failed to get nodes");
e.printStackTrace();
}
}

// Loading / Unloading Handling
public static final HashMap<BlockPos ,InterDimensionalInterfaceBlockEntity> blockEntities = new HashMap<>();

// Loading / Unloading Hanndling
public static void registerBlockEntity(InterDimensionalInterfaceBlockEntity blockEntity, BlockPos pos) {
var oldBlockEntity = blockEntities.get(pos);
if(oldBlockEntity != null) {
oldBlockEntity.onStop();
}
blockEntities.put(pos, blockEntity);
}

public static void onStartBlockPos(BlockPos pos) {
InterDimensionalInterfaceBlockEntity blockEntity = blockEntities.get(pos);
Expand Down Expand Up @@ -196,7 +243,6 @@ public static void onBlockBreak(BlockEvent.BreakEvent event) {
onStopBlockPos(event.getPos());
}


@SubscribeEvent
public static void onBlockLoad(ChunkEvent.Load event) {
for (BlockPos blockEntityPositions : event.getChunk().getBlockEntitiesPos()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,12 @@
import appeng.blockentity.AEBaseBlockEntity;
import appeng.blockentity.ClientTickingBlockEntity;
import appeng.blockentity.ServerTickingBlockEntity;
import appeng.core.AppEng;
import appeng.core.definitions.AEBlockEntities;
import appeng.core.definitions.BlockDefinition;
import com.google.common.base.Preconditions;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import net.nussi.dedicated_applied_energistics.blockentities.InterDimensionalInterfaceBlockEntity;
import net.nussi.dedicated_applied_energistics.blocks.InterDimensionalInterfaceBlock;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import static net.nussi.dedicated_applied_energistics.DedicatedAppliedEnegistics.MODID;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package net.nussi.dedicated_applied_energistics.misc;

import appeng.api.storage.MEStorage;
import net.nussi.dedicated_applied_energistics.DedicatedAppliedEnergisticsController;
import net.nussi.dedicated_applied_energistics.blockentities.InterDimensionalInterfaceBlockEntity;

public class RedisHelper {

public static String getPath(MEStorage storage, InterDimensionalInterfaceBlockEntity blockEntity) {
return DedicatedAppliedEnergisticsController.CONFIG_VALUE_HOST_ID.get() + "/" +
blockEntity.getBlockPos().getX() + "_" + blockEntity.getBlockPos().getY() + "_" + blockEntity.getBlockPos().getZ() + "/" +
storage.hashCode();
}

}
Loading

0 comments on commit 0b48307

Please sign in to comment.