-
Notifications
You must be signed in to change notification settings - Fork 497
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
[RFC] Remove UnifiedMessages reflection usage #1433
Conversation
I like the idea. If you enable the trimming warnings, what warnings are reported? In particular handling of incoming messages. Do note that protobuf.net is heavily reflection based, so that doesn't help us with AOT/trimming atm. |
Resources/ProtobufGen/ProtobufGen/SteamKitCSharpCodeGenerator.cs
Outdated
Show resolved
Hide resolved
There seem to be no more trimming warnings aside from protobuf.net usage. I'll try to see how to avoid these too soon ™️ |
@yaakov-h was also looking at that, and arrived at the conclusion that switching to google.protobuf is probably the way to go. |
I don't however like calling CanHandleMsg for every single interface, maybe registration and a dictionary lookup would work better. See 807fa51 for previous attempt at that. |
It's not really every interface, only for currently created services (until they are disposed that is). |
Right I see it only goes through the registered services. But it calls CanHandleMsg for every service so it does the parsing for every one of these. The handlers list could be a dictionary of <service name, handler>, so that you can parse the method name, and directly check if a handler is registered for a particular service. |
This is a very different approach to the one I was looking at, and I do like it. Keep in mind that consumers should be able to generate and run additional services (e.g. from updated protobufs) so some of those Regarding the discussion above, perhaps each service should expose its name as a public property, then we can parse the service name once and invoke any matching handlers? However, yes, for full trimming support and AOT we will almost certainly need to switch to Google.Protobuf. I haven't spiked AOT w/ Google just yet, but even manually hand-writing serializers and deserializers with protobuf-net.Core triggered trim and AOT warnings because it is annoyingly dependent on dynamic coding APIs. |
Could add service name to |
FYI this PR needs to rebase the protobufs submodule because its using an older commit. |
From what I could gather, there currently is no satisfying solution:
This is, however, out of scope of what I currently have time for. |
Resources/ProtobufGen/ProtobufGen/SteamKitCSharpCodeGenerator.cs
Outdated
Show resolved
Hide resolved
SteamKit2/SteamKit2/Steam/Handlers/SteamUnifiedMessages/SteamUnifiedMessages.cs
Outdated
Show resolved
Hide resolved
Fix the build error on ci please. Also rebase the commit on master, so that the protobufs submodule does not change (to remove the unrelated changes). |
Breaking change for consumers: old: SteamUnifiedMessages.UnifiedService<ISomething> service = unifiedMessages.CreateService<ISomething>();
SteamUnifiedMessages.ServiceMethodResponse job = await service.SendMessage(x => x.DoThing(msg));
SomeResponse response = job.GetDeserializedResponse<SomeResponse>(); new: Something service = unifiedMessages.CreateService<Something>();
SteamUnifiedMessages.ServiceMsg<SomeResponse> job = await service.DoThing(msg);
SomeResponse response = job.PacketResult;
Overall this is good because we no longer need to provide the correct type into One slight worry I have is that services directly return the service, which is an extension of |
SteamKit2/SteamKit2/Steam/Handlers/SteamUnifiedMessages/SteamUnifiedMessages.cs
Outdated
Show resolved
Hide resolved
I just noticed that |
I think this would be rather complicated to achieve since we'd need some form of mapping between the interface and implementation. |
# Conflicts: # Resources/Protobufs # SteamKit2/SteamKit2/Base/Generated/SteamMsgAuth.cs # SteamKit2/SteamKit2/Base/Generated/SteamMsgStoreBrowse.cs # SteamKit2/SteamKit2/Base/Generated/WebUI/SteamMsgAccountCart.cs # SteamKit2/SteamKit2/Base/Generated/WebUI/SteamMsgCommon.cs
Just a thought I had, calling Wouldn't it break if you called CreateService multiple times? Maybe to simplify services should be non disposable and it should return an existing one (handlers.GetOrAdd basically). |
This piece of code is not working (callback function handler not being called despite event arriving): CallbackManager.Subscribe<SteamUnifiedMessages.ServiceMethodNotification<CChatRoom_IncomingChatMessage_Notification>>(OnIncomingChatMessage);
CallbackManager.Subscribe<SteamUnifiedMessages.ServiceMethodNotification<CFriendMessages_IncomingMessage_Notification>>(OnIncomingMessage); Previously I had this and it worked properly: CallbackManager.Subscribe<SteamUnifiedMessages.ServiceMethodNotification>(OnServiceMethod);
private async void OnServiceMethod(SteamUnifiedMessages.ServiceMethodNotification notification) {
ArgumentNullException.ThrowIfNull(notification);
switch (notification.MethodName) {
case "ChatRoomClient.NotifyIncomingChatMessage#1":
await OnIncomingChatMessage((CChatRoom_IncomingChatMessage_Notification) notification.Body).ConfigureAwait(false);
break;
case "FriendMessagesClient.IncomingMessage#1":
await OnIncomingMessage((CFriendMessages_IncomingMessage_Notification) notification.Body).ConfigureAwait(false);
break;
}
} My experimental code lies in https://github.com/JustArchiNET/ArchiSteamFarm/tree/unified-experiments, the diff with main is JustArchiNET/ArchiSteamFarm@main...unified-experiments. You can also get artifacts for testing in https://github.com/JustArchiNET/ArchiSteamFarm/actions/workflows/publish.yml?query=branch%3Aunified-experiments. If I did something wrong, let me know and I can give it another try. |
I agree that using a single instance is probably the way to go, but it should still be disposable in order to be removed from |
This could be achieved by adding a separate call to remove it. I think that's more explicit than leaving it disposable (because if you call CreateService for some temporary call, disposing it would be dispose it for everything). |
You need to create the service the notification is coming from first with |
He does in ArchiHandler. |
|
My bad, missed the "Client" part. This is outside of the scope of this PR, maybe a future improvement: Subscribing to incoming notifications could be done through EDIT: Can we add the sample of receiving a notification like this to the unified messages sample? So that it is documented that you need create a service to receive stuff. FriendMessagesClient.IncomingMessage should be easily testable. Sorry for a lot of back-and-forth on this PR, just want to minimize any pain for consumers. |
One solution I've come up to solve the handler not being registered is this:
The first option makes sense because the callbacks still go through the manager, and probably preferrable to keep the logic in same place. It probably needs a separate method name, like SubscribeServiceMethodResponse and ServiceMethodNotification. However this still doesn't prevent users from shooting themselves in the foot because you still can register <WrongService, DifferentMethod>, as that would have to be validated somehow (generate another method to check? but that seems overkill, maybe at that point its not our problem anymore). And Thoughts? Any different ideas? P.S. See my comment above about adding a sample for receiving notifications. |
Resources/ProtobufGen/ProtobufGen/SteamKitCSharpCodeGenerator.cs
Outdated
Show resolved
Hide resolved
Resources/ProtobufGen/ProtobufGen/SteamKitCSharpCodeGenerator.cs
Outdated
Show resolved
Hide resolved
Thanks, I can confirm that it works after adding required clients. The only outstanding issue I see with this PR is that right now, it's possible to register for callback but skip registration of the service.
As @xPaw suggested above, any of those two would fix it. If you asked me, I like first one slightly more. |
The approach to subscribe to the manager directly seems more in line with what users currently do and therefore what is probably expected. I'll try to implement this soon and add/update the samples |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks really good!
I agree with having that one-line approach of subscribing to notifications via the callback manager - infinitely less foot-guns than needing to remember to create a service.
I'll defer to @xPaw for the final approval, feel free to consider my comments nit-picky. :)
/// </summary> | ||
public partial class SteamUnifiedMessages : ClientMsgHandler | ||
{ | ||
private readonly ConcurrentDictionary<string, object> _handlers = [ ]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can this be ConcurrentDictionary<string, IUnifiedService>
to avoid the various casts/as
to TService
?
Seems like all the type constraints are always IUnifiedService
.
break; | ||
} | ||
return ( _handlers.GetOrAdd( TService.ServiceName, static ( _, unifiedMessages ) => | ||
new TService { UnifiedMessages = unifiedMessages }, this ) as TService )!; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could cast directly to TService
rather than as
- that should avoid the extra null assertion operator (or whatever !
is called).
public static string ServiceName { get; } = "Workshop"; | ||
|
||
/// <inheritdoc /> | ||
public SteamUnifiedMessages UnifiedMessages { get; init; } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Leaving this comment for this service, but this applies to how the generator created all these.
Feels like this should be internal rather than public. A consumer could either interact with the service methods directly, or grab the handler from the SteamClient
.
There's lots of pre-existing undefined behavior that I unfortunately designed into the callback manager, but it makes me think about (edge) cases like RemoveService
ing a service but then still holding on to it for this UnifiedMessages
property.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What if a consumer wants to generate and use their own service?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good point. I think an explicit interface implementation can solve for that: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation
It would hide access to the property on the implementation types and only allow access if you cast to a IUnifiedService
, which the SteamUnifiedMessages
handler can easily do.
A consumer could end up doing the same, but it would at least make it more unlikely.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah it would be good to get rid of this property from the generated classes, and only leave it on the parent.
/// </summary> | ||
/// <param name="callbackFunc">The function to invoke with the callback.</param> | ||
/// <returns>An <see cref="IDisposable"/>. Disposing of the return value will unsubscribe the <paramref name="callbackFunc"/>.</returns> | ||
public IDisposable SubscribeNotifications<TService, TNotification>( Action<SteamUnifiedMessages.ServiceMethodNotification<TNotification>> callbackFunc ) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
SubscribeServiceNotification
perhaps?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Works for me, summary of all changes I did: JustArchiNET/ArchiSteamFarm@main...unified-experiments
This PR tries to remove the last directly existing reflection usage in SteamUnifiedMessages.
The protobuf code generator was updated instead to directly handle the messaging.
Obviously this is a breaking change, but, at least in my opinion, necessary in order to fully remove reflection.