mrpmorris / Fluxor

Fluxor is a zero boilerplate Flux/Redux library for Microsoft .NET and Blazor.
MIT License
1.22k stars 139 forks source link

Possible fix for .NET 8 Blazor Web App breakage #481

Closed WhitWaldo closed 3 weeks ago

WhitWaldo commented 3 months ago

Adds .NET 8 as a valid target in addition to .NET 7 and the other versions.

Also moves state initialization out from OnAfterRenderAsync (which doesn't run on server anymore per the docs) to OnInitializedAsync which runs after existing logic in OnInitialized and after OnParametersSet (which in .NET 8 now runs before OnInitialized{Async}), so it's the last lifecycle method before OnAfterRender, assuming it were still being called.

I'm having problems getting Fluxor.Blazor.Web to build on my machine (likely missing one of your targets) so I haven't yet tested this, but as covered in the related issue,, when I set a breakpoint in the ActionDispatched method, I can see that the actions are accumulating in the Store and they don't dequeue because the store never sets HasActivatedStore to true, which only happens via this call to Store.InitializeAsync() which only happens in OnAfterRenderAsync which isn't called on the server anymore, so it intuitively feels like this might fix the problem.

I'll follow up if I'm able to validate it locally furhter.

WhitWaldo commented 3 months ago

There's unfortunately more that needs tackling here. I built a local version of Fluxor that only target .NET 8 to simplify this and it builds fine now, but while the Counter page loads without error when @rendermode InteractiveServer and I see the DequeueActions method trigger as expected, when I swap this out with @rendermode InteractiveAuto, now I'm getting a DI-related exception:

Error: One or more errors occurred. (Cannot provide a value for property 'State' on type 'Blazor8Test.Client.Pages.Counter'. There is no registered service of type 'Fluxor.IState`1[Shared.State.CounterUseCase.CounterState]'.)

This is odd since I'm registering all dependencies on the primary project so it should flow through to the client (per the guidance here) but this remains a work in progress.

mrpmorris commented 3 months ago

Fancy pairing on this one if the days?

I'm available from 5PM week days (UK time)

WhitWaldo commented 3 months ago

Sure - we can sync on that next week. I'm in the US, but if I did the math right, that puts me at 11 AM or later, so that's more than fine.

I've identified at least part of the problem.

In .NET 7, you have either a server or a WASM project. You register Fluxor via the dependency injection scheme and initialize the store by placing the <StoreInitializer> component at the top of what was then the App.razor file and the rest works like magic.

In .NET 8, you cannot quite do this because as the library author, you're not going to know what render mode the user is opting for as it can be done on a per-page/component basis instead of globally, so you've got to be a bit more flexible about how the service is initialized.

On the Server project, the <StoreInitializer> should be placed at the top of the Routes.razor file as App.razor is now what was the _Host.cshtml file. Both the server and the client need to perform the Fluxor DI registration, so this should be either put in a shared project or placed in the client app and called by both. Coupled these two with the change I made to initialize the store in OnInitializedAsync instead of in OnAfterRender to avoid conflicts with any pre-rendering.

However, on the client, we've got several limitations to consider:

As such, on the Client project, in addition to the local Fluxor DI registration mentioned above, I propose that because SetParametersAsync now runs before OnInitializedAsync in the component lifecycle, the FluxorComponent be updated to override OnParametersSetAsync with the following:

        /// <summary>
        /// Method invoked when the component has received parameters from its parent in
        /// the render tree, and the incoming values have been assigned to properties.
        /// </summary>
        /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> representing any asynchronous operation.</returns>
        protected override async Task OnParametersSetAsync()
      {
        await base.OnParametersSetAsync();

            //Attempt to initialize the store knowing that if it's already been initialized, this won't do anything.
            await Store.InitializeAsync();
        }

As the Store has a flag checking if it's already been initialized, if this runs and that flag is true, nothing will happen, but because all Fluxor components are expected to inherit a FluxorComponent this will ensure that the store is initialized and starts to dequeue pending actions as expected.

There's no need to change the FluxorOptions to prefer a Singleton over a Scoped registration (as the Client is going to treat is as a Singleton anyway). There's also no need to disable prerender to make this work. I've tested that it works on interactive auto whether prerender is enabled or not.

I've tested this several times and it now works precisely as expected on both the Server and, after waiting for it to load the WASM bundle, switching pages and switching back to validate it's disconnected from the server, successfully verified it works on the Client as well. I'll update the PR shortly with my proposed changes.

Remaining open work:

WhitWaldo commented 3 months ago

I've added a single persistence layer to Fluxor that appears to resolve the cross-rendermode issue. As observed by others on another thread about this, it's one thing to get Fluxor up and running again, but a whole other thing to completely lose your state as soon as you jump render modes (e.g. server -> web assembly).

While I've taken a stab at implementing this in a lightweight manner, it wasn't until I was integrating the changes from my test project to this branch that I realized my solution is only compatible with .NET 6 and higher because of my use of JsonNode in System.Text.Json, so I surrounded the relevant registration and implementation bits with conditional compiler flags in the shorter term. Also, I cannot get Fluxor to build on my machine as it's targeting frameworks I simply don't have installed. If you've got .NET 8 installed, clone my repo below for a .NET 8-only version of this.

A .NET 8 version of this can be seen on the latest commit here, but I'll take a moment to walk through the idea.

I built off the idea of using an action to identify when the state has initialized and an effect that triggers from that. I've added some extensions to the registration method that allows the developer to opt into the persistence feature and provide an implementation of IPersistenceManager (I wrote such an implementation in my other project using session storage here) and to allow them to register any additional dependencies here that it might require. If IPersistenceManager is never registered, Fluxor runs as it did before this implementation and that's it (with a few minor tweaks).

If it is registered, when Fluxor is activating the store instance, it first marks the store as activated, dequeues any actions and then dispatches a new StoreRehydratingAction that kicks off a registered effect that reads any persisted state from the IPersistenceManager and uses a new method on the store to rehyrdrate the state on a per-feature basis (using that RestoreState method that explicitly says it shouldn't be used for this - whoops). This concludes with a StoreRehydratedAction in case anyone wants to subscribe to it for some reason.

On a location change event in the Fluxor component, it dispatches a PersistingStoreAction and this does the opposite. It builds a JSON object (each feature to a separate named key) and persists this via the IPersistenceManager and fires off a PersistedStoreAction.

This implementation avoids having the project take on any other package dependencies and leaves it to the developer to decide where and how they want to persist any data, whether that be in session state as my demo does or bind it to a session ID and save it somewhere on the server - their choice. Just implement the IPersistenceManager and register with the provided method on FluxorOptions.

Remaining work:

GordonBeeming commented 3 months ago

@WhitWaldo thanks for the effort in getting this working ❤️

@mrpmorris

  1. Would this fix make it into 5.9.x or only 6.0?
  2. If not, do you know roughly when you are wanting 6.0 to reach stable?
mrpmorris commented 3 months ago

It'll be in 6.0

I will be releasing Beta versions, but not until they are stable so should be okay to use.

GordonBeeming commented 3 months ago

Great stuff, thanks @mrpmorris 🙂

WhitWaldo commented 3 months ago

I've made a few changes to the PR and also updated my .NET 8 demonstration to reflect them. As before, I can't actually build this locally as I'm missing some of these older .NET SDKs, but I copy/pasted the changed pieces from my demo, so I'm fairly confident it should work.

At this point, this is working well enough for my purposes that I don't know any other active work is really necessary unless you really want to replace the System.Text.Json dependency for something compatible with the broader set of targets you're looking to support.

I don't see a branch that specifically identifies as the 6.0 release, but if you can point me in the right direction, I'd be happy to apply my changes to that branch as well in a separate PR.

mikeppcom commented 2 months ago

Will this PR be in beta#3/V6? We make heavy use of Fluxor and are moving to a .NET8 hybrid Blazor server/client render model and are facing the issue that actions are no longer being dispatched.

wave9d commented 1 month ago

Will this PR be in beta#3/V6? We make heavy use of Fluxor and are moving to a .NET8 hybrid Blazor server/client render model and are facing the issue that actions are no longer being dispatched.

Any news on this PR being available for a beta release ? We're in the same situation as @mikeppcom

mrpmorris commented 1 month ago

try specifying the @rendermode in Routes.razor or on the <StoreInitializer compoonent

orosbogdan commented 1 month ago

try specifying the @rendermode in Routes.razor or on the <StoreInitializer compoonent

The problem would be if you wanted to have both server interactive and wasm interactive pages in your app right? Same for auto render mode I think.

WhitWaldo commented 1 month ago

try specifying the @rendermode in Routes.razor or on the <StoreInitializer compoonent

The problem would be if you wanted to have both server interactive and wasm interactive pages in your app right? Same for auto render mode I think.

If you don't specify an interactive mode (e.g. InteractiveServer, InteractiveWebAssembly or InteractiveAuto), you simply won't see any changes made to the page/component. If the changes are in response to interaction with an HTML element, the method isn't called and thus the value isn't updated and propagated and no changes are made to the page. For any interactivity, you have to specify one of the above interactive modes.

If your whole app already uses strictly interactive WASM or interactive server, I don't know that you'd have a problem with Fluxor's latest public build. This PR was made specifically to support InteractiveAuto as it's the transition from Server to WebAssembly (and back) that was causing issues as the state wouldn't be available across contexts.

orosbogdan commented 1 month ago

try specifying the @rendermode in Routes.razor or on the <StoreInitializer compoonent

The problem would be if you wanted to have both server interactive and wasm interactive pages in your app right? Same for auto render mode I think.

If you don't specify an interactive mode (e.g. InteractiveServer, InteractiveWebAssembly or InteractiveAuto), you simply won't see any changes made to the page/component. If the changes are in response to interaction with an HTML element, the method isn't called and thus the value isn't updated and propagated and no changes are made to the page. For any interactivity, you have to specify one of the above interactive modes.

If your whole app already uses strictly interactive WASM or interactive server, I don't know that you'd have a problem with Fluxor's latest public build. This PR was made specifically to support InteractiveAuto as it's the transition from Server to WebAssembly (and back) that was causing issues as the state wouldn't be available across contexts.

Would an blazor project having 2 separate pages, 1 server interactive and 1 wasm interactive work with latest fluxor build ?

WhitWaldo commented 1 month ago

try specifying the @rendermode in Routes.razor or on the <StoreInitializer compoonent

The problem would be if you wanted to have both server interactive and wasm interactive pages in your app right? Same for auto render mode I think.

If you don't specify an interactive mode (e.g. InteractiveServer, InteractiveWebAssembly or InteractiveAuto), you simply won't see any changes made to the page/component. If the changes are in response to interaction with an HTML element, the method isn't called and thus the value isn't updated and propagated and no changes are made to the page. For any interactivity, you have to specify one of the above interactive modes. If your whole app already uses strictly interactive WASM or interactive server, I don't know that you'd have a problem with Fluxor's latest public build. This PR was made specifically to support InteractiveAuto as it's the transition from Server to WebAssembly (and back) that was causing issues as the state wouldn't be available across contexts.

Would an blazor project having 2 separate pages, 1 server interactive and 1 wasm interactive work with latest fluxor build ?

If they use separate state from each other, the latest public build should work fine. Your issue is going to if you attempt to mix state between the two because they have no mechanism to communicate it back and forth.

That's the point of this PR, is to add a mechanism to persist the state regardless of where it's being updated so that either environment can access the latest version of that state, even if any given component is shifting between the two (e.g. per InteractiveAuto it'll start running on the server and eventually run from WASM).

The idea is that the data is persisted on the server via an IPersistenceManager (my demo simulates a Redis instance by using an in-memory key/value store as a singleton service) and then implement an IStateService on both the server and wasm clients to persist and retrieve the state. On the server, this pulls from the IPersistenceManager, on the client, this implements an HttpClient to get the same from the server. This way, we ensure that the state is in sync regardless of whether the next component accessing it is doing so from the client or server.

Do note that this does make the implementation quite chatty, but I was unable to find a better way of doing it in the current release of Web Apps. This might help in .NET 9, but we'll see.

jafin commented 3 weeks ago

This didn't make it into v6?

mikeppcom commented 3 weeks ago

Jason,

There isn’t an issue with Fluxor as such. If you’re using it with a web app you need to initialize it in the routes component with a render mode.

<Fluxor.Blazor.Web.StoreInitializer @rendermode="InteractiveServer" />

Thanks to Pete for pointing this out.

By the way not sure that webapps are really production ready as the only way I’ve been able to get them to work with layouts is to set the render mode at a global level and switch between server and client using a hard navigation.

Michael

From: Jason Finch @.> Sent: Monday, June 10, 2024 6:01 AM To: mrpmorris/Fluxor @.> Cc: Michael Aston @.>; Mention @.> Subject: Re: [mrpmorris/Fluxor] Possible fix for .NET 8 Blazor Web App breakage (PR #481)

EXTERNAL E-MAIL – This email has come from an external source. Verify the sender before responding, clicking on any links or opening attachments. Report suspicious emails.


This didn't make it into v6?

— Reply to this email directly, view it on GitHubhttps://github.com/mrpmorris/Fluxor/pull/481#issuecomment-2157272642, or unsubscribehttps://github.com/notifications/unsubscribe-auth/A6CYAQJDGHV4ODVTL6RWPG3ZGUXKJAVCNFSM6AAAAABEMHGLVSVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCNJXGI3TENRUGI. You are receiving this because you were mentioned.Message ID: @.**@.>>


This e-mail message (including any attachments) from PayPoint plc or any member of the PayPoint group of trading companies (collectively referred to as 'PayPoint') is confidential and for the personal use of the recipient(s) identified above. The message may also be legally privileged. If it is not intended for you, do not disclose, copy or distribute the message but delete it immediately and notify the sender.

Any views or opinions expressed in this message are those of the author and not necessarily those of PayPoint. The message shall not form part of any legally binding contract or obligation.

PayPoint electronic communication systems are monitored without user consent to: investigate or to detect unauthorised use; prevent or detect crime; establish the existence of facts relevant to PayPoint; or ascertain compliance with regulatory practices relevant to the business of PayPoint.

This e-mail has been scanned for viruses by a third party e-mail management provider. PayPoint cannot accept liability for any damage which you may suffer as a result of virus infection. We recommend that you carry out your own virus checks before opening any attachment.

PayPoint plc – Registered in England number 3581541 Registered office: 1 The Boulevard, Shire Park, Welwyn Garden City, Hertfordshire, AL7 1EL


WhitWaldo commented 3 weeks ago

Jason, There isn’t an issue with Fluxor as such. If you’re using it with a web app you need to initialize it in the routes component with a render mode. <Fluxor.Blazor.Web.StoreInitializer @rendermode="InteractiveServer" /> Thanks to Pete for pointing this out. By the way not sure that webapps are really production ready as the only way I’ve been able to get them to work with layouts is to set the render mode at a global level and switch between server and client using a hard navigation.

You're right in that Fluxor will work fine so long as your application and components run entirely in either a server (personally tested) or web assembly (untested) context. Sure, if you have components that run on WebAssembly but don't inject Fluxor state, they'll work fine too. But merely running initializing the store on the server isn't going to suddenly open up some backchannel for your WebAssembly components that take a Fluxor state dependency to communicate and keep in sync with it.

Rather, this PR adds a persistence layer using the same approach provided in the sparse guidance for using the new Web Apps and leaves it as an exercise for the developer to decide just how the state itself is persisted (on the server) and how the WebAssembly components will communicate with the server to read and write its own updates. When the component is initialized then, it queries this central store (which is accessible now regardless of where the component is running) and when it applies the batch of changes, it persists that result back (so other components running in either context can access the same).

Regarding layouts, assuming you're putting all your server code in one project and your client code in another (as the Web App template in VS does), I recommend you shift all your layouts to the client project as they'll be available in either render mode. The layouts themselves shouldn't necessarily need any interactivity, so they can remain statically rendered while remaining accessible for any pages in either render mode to utilize them. I personally maintain the global default (static SSR). For those components that need any interactivity support, I use interactive server for those components I haven't yet migrated to use an API endpoint for and interactive auto for those I have and it's worked fine.

mrpmorris commented 3 weeks ago

You'll need to use the workaround for now.

I intend to use a slightly different approach in V7 that should suit all the different scenarios.