Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1.21.4] Refactor registry sync #4233

Draft
wants to merge 2 commits into
base: 1.21.4
Choose a base branch
from
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@
import java.util.List;
import java.util.Objects;

import org.jetbrains.annotations.Nullable;

import net.minecraft.network.NetworkPhase;
import net.minecraft.network.PacketCallbacks;
import net.minecraft.network.packet.BrandCustomPayload;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.s2c.common.CommonPingS2CPacket;
Expand All @@ -44,6 +47,8 @@ public final class ServerConfigurationNetworkAddon extends AbstractChanneledNetw
private final MinecraftServer server;
private final ServerConfigurationNetworking.Context context;
private RegisterState registerState = RegisterState.NOT_SENT;
@Nullable
private String clientBrand = null;

public ServerConfigurationNetworkAddon(ServerConfigurationNetworkHandler handler, MinecraftServer server) {
super(ServerNetworkingImpl.CONFIGURATION, ((ServerCommonNetworkHandlerAccessor) handler).getConnection(), "ServerConfigurationNetworkAddon for " + handler.getDebugProfile().getName());
Expand All @@ -55,6 +60,16 @@ public ServerConfigurationNetworkAddon(ServerConfigurationNetworkHandler handler
this.registerPendingChannels((ChannelInfoHolder) this.connection, NetworkPhase.CONFIGURATION);
}

@Override
public boolean handle(CustomPayload payload) {
if (payload instanceof BrandCustomPayload brandCustomPayload) {
clientBrand = brandCustomPayload.brand();
return false;
}

return super.handle(payload);
}

@Override
protected void invokeInitEvent() {
}
Expand Down Expand Up @@ -169,6 +184,10 @@ public void sendPacket(Packet<?> packet, PacketCallbacks callback) {
handler.send(packet, callback);
}

public @Nullable String getClientBrand() {
return clientBrand;
}

private enum RegisterState {
NOT_SENT,
SENT,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.fabric.impl.client.registry.sync;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

import it.unimi.dsi.fastutil.objects.Object2IntMap;
import org.jetbrains.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.screen.ScreenTexts;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.thread.ThreadExecutor;

import net.fabricmc.fabric.api.event.registry.RegistryAttribute;
import net.fabricmc.fabric.impl.registry.sync.RegistrySyncManager;
import net.fabricmc.fabric.impl.registry.sync.RemapException;
import net.fabricmc.fabric.impl.registry.sync.RemappableRegistry;
import net.fabricmc.fabric.impl.registry.sync.packet.RegistryPacketHandler;

public final class ClientRegistrySyncHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientRegistrySyncHandler.class);

private ClientRegistrySyncHandler() {
}

public static <T extends RegistryPacketHandler.RegistrySyncPayload> CompletableFuture<Boolean> receivePacket(ThreadExecutor<?> executor, RegistryPacketHandler<T> handler, T payload, boolean accept) {
handler.receivePayload(payload);

if (!handler.isPacketFinished()) {
return CompletableFuture.completedFuture(false);
}

if (RegistrySyncManager.DEBUG) {
String handlerName = handler.getClass().getSimpleName();
LOGGER.info("{} total packet: {}", handlerName, handler.getTotalPacketReceived());
LOGGER.info("{} raw size: {}", handlerName, handler.getRawBufSize());
LOGGER.info("{} deflated size: {}", handlerName, handler.getDeflatedBufSize());
}

RegistryPacketHandler.SyncedPacketData data = handler.getSyncedPacketData();

if (!accept) {
return CompletableFuture.completedFuture(true);
}

return executor.submit(() -> {
if (data == null) {
throw new CompletionException(new RemapException("Received null map in sync packet!"));
}

try {
apply(data);
return true;
} catch (RemapException e) {
throw new CompletionException(e);
}
});
}

public static void apply(RegistryPacketHandler.SyncedPacketData data) throws RemapException {
// First check that all of the data provided is valid before making any changes
checkRemoteRemap(data);

for (Map.Entry<Identifier, Object2IntMap<Identifier>> entry : data.idMap().entrySet()) {
final Identifier registryId = entry.getKey();

Registry<?> registry = Registries.REGISTRIES.get(registryId);

// Registry was not found on the client, is it optional?
// If so we can just ignore it.
// Otherwise we throw an exception and disconnect.
if (registry == null) {
if (isRegistryOptional(registryId, data)) {
LOGGER.info("Received registry data for unknown optional registry: {}", registryId);
continue;
} else {
throw new RemapException("Received registry data for unknown registry: " + registryId);
}
}
Comment on lines +96 to +106
Copy link
Contributor

Choose a reason for hiding this comment

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

I believe this is duplicative, as checkRemoteRemap should've already thrown in this case?


if (registry instanceof RemappableRegistry remappableRegistry) {
remappableRegistry.remap(entry.getValue(), RemappableRegistry.RemapMode.REMOTE);
return;
}

throw new RemapException("Registry " + registryId + " is not remappable");
}
}

@VisibleForTesting
public static void checkRemoteRemap(RegistryPacketHandler.SyncedPacketData data) throws RemapException {
Map<Identifier, Object2IntMap<Identifier>> map = data.idMap();
Map<Identifier, List<Identifier>> missingEntries = new HashMap<>();

for (Identifier registryId : map.keySet()) {
final Object2IntMap<Identifier> remoteRegistry = map.get(registryId);
Registry<?> registry = Registries.REGISTRIES.get(registryId);

if (registry == null) {
if (!isRegistryOptional(registryId, data)) {
LOGGER.error("Received unknown remote registry ({}) from server", registryId);

// Registry was not found on the client, and is not optional.
missingEntries.put(registryId, new ArrayList<>(remoteRegistry.keySet()));
}

continue;
}

for (Identifier remoteId : remoteRegistry.keySet()) {
if (!registry.containsId(remoteId)) {
// Found a registry entry from the server that is
Copy link
Contributor

Choose a reason for hiding this comment

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

that is... (missing?)

missingEntries.computeIfAbsent(registryId, i -> new ArrayList<>()).add(remoteId);
}
}
}

if (missingEntries.isEmpty()) {
// All good :)
return;
}

// Print out details to the log
LOGGER.error("Received unknown remote registry entries from server");

for (Map.Entry<Identifier, List<Identifier>> entry : missingEntries.entrySet()) {
for (Identifier identifier : entry.getValue()) {
LOGGER.error("Registry entry ({}) is missing from local registry ({})", identifier, entry.getKey());
}
}

// Create a nice user friendly error message.
MutableText text = Text.empty();

final int count = missingEntries.values().stream().mapToInt(List::size).sum();

if (count == 1) {
text = text.append(Text.translatable("fabric-registry-sync-v0.unknown-remote.title.singular"));
} else {
text = text.append(Text.translatable("fabric-registry-sync-v0.unknown-remote.title.plural", count));
}

text = text.append(Text.translatable("fabric-registry-sync-v0.unknown-remote.subtitle.1").formatted(Formatting.GREEN));
text = text.append(Text.translatable("fabric-registry-sync-v0.unknown-remote.subtitle.2"));

final int toDisplay = 4;
// Get the distinct missing namespaces
final List<String> namespaces = missingEntries.values().stream()
.flatMap(List::stream)
.map(Identifier::getNamespace)
.distinct()
.sorted()
.toList();

for (int i = 0; i < Math.min(namespaces.size(), toDisplay); i++) {
text = text.append(Text.literal(namespaces.get(i)).formatted(Formatting.YELLOW));
text = text.append(ScreenTexts.LINE_BREAK);
}

if (namespaces.size() > toDisplay) {
text = text.append(Text.translatable("fabric-registry-sync-v0.unknown-remote.footer", namespaces.size() - toDisplay));
}

throw new RemapException(text);
}

private static boolean isRegistryOptional(Identifier registryId, RegistryPacketHandler.SyncedPacketData data) {
EnumSet<RegistryAttribute> registryAttributes = data.attributes().get(registryId);
return registryAttributes.contains(RegistryAttribute.OPTIONAL);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public void onInitializeClient() {

private <T extends RegistryPacketHandler.RegistrySyncPayload> void registerSyncPacketReceiver(RegistryPacketHandler<T> packetHandler) {
ClientConfigurationNetworking.registerGlobalReceiver(packetHandler.getPacketId(), (payload, context) -> {
RegistrySyncManager.receivePacket(context.client(), packetHandler, payload, RegistrySyncManager.DEBUG || !context.client().isInSingleplayer())
ClientRegistrySyncHandler.receivePacket(context.client(), packetHandler, payload, RegistrySyncManager.DEBUG || !context.client().isInSingleplayer())
.whenComplete((complete, throwable) -> {
if (throwable != null) {
LOGGER.error("Registry remapping failed!", throwable);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
Expand All @@ -28,9 +29,11 @@
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.item.ItemGroups;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.util.Identifier;

import net.fabricmc.fabric.impl.registry.sync.RegistrySyncManager;
import net.fabricmc.fabric.impl.registry.sync.RemapException;
import net.fabricmc.fabric.impl.registry.sync.RemappableRegistry;
import net.fabricmc.fabric.impl.registry.sync.trackers.vanilla.BlockInitTracker;

@Mixin(MinecraftClient.class)
Expand All @@ -43,7 +46,7 @@ public class MinecraftClientMixin {
@Inject(at = @At("RETURN"), method = "disconnect(Lnet/minecraft/client/gui/screen/Screen;Z)V")
public void disconnectAfter(Screen disconnectionScreen, boolean bl, CallbackInfo ci) {
try {
RegistrySyncManager.unmap();
unmap();
} catch (RemapException e) {
LOGGER.warn("Failed to unmap Fabric registries!", e);
}
Expand All @@ -57,4 +60,15 @@ private void afterModInit(CallbackInfo ci) {
BlockInitTracker.postFreeze();
ItemGroups.collect();
}

@Unique
private static void unmap() throws RemapException {
for (Identifier registryId : Registries.REGISTRIES.getIds()) {
Registry<?> registry = Registries.REGISTRIES.get(registryId);

if (registry instanceof RemappableRegistry) {
((RemappableRegistry) registry).unmap();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,10 @@ public enum RegistryAttribute {
/**
* Registry has been modded.
*/
MODDED
MODDED,

/**
* Registry is optional, any connecting client will not be disconnected if the registry is not present.
*/
OPTIONAL
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,13 @@
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.jetbrains.annotations.VisibleForTesting;

import net.minecraft.registry.RegistryKey;

import net.fabricmc.fabric.api.event.registry.RegistryAttribute;
import net.fabricmc.fabric.api.event.registry.RegistryAttributeHolder;
import net.fabricmc.loader.api.FabricLoader;

public final class RegistryAttributeImpl implements RegistryAttributeHolder {
private static final Map<RegistryKey<?>, RegistryAttributeHolder> HOLDER_MAP = new ConcurrentHashMap<>();
Expand All @@ -43,6 +46,15 @@ public RegistryAttributeHolder addAttribute(RegistryAttribute attribute) {
return this;
}

@VisibleForTesting
public void removeAttribute(RegistryAttribute attribute) {
if (!FabricLoader.getInstance().isDevelopmentEnvironment()) {
throw new AssertionError();
}

attributes.remove(attribute);
}

@Override
public boolean hasAttribute(RegistryAttribute attribute) {
return attributes.contains(attribute);
Expand Down
Loading
Loading