Does Firebase functions retain state for google assistant - actions-on-google

The scenario is this. I want to show the user one or two items, but I don't want to keep showing the same items over and over again. I don't think Firebase functions will retain state because each function call will activate the function again. So how do I maintain state without having to store it in the database.

No, Firebase Functions don't retain state. In fact, you're not even guaranteed to be running on the same server in between calls to the same webhook.
If you want to maintain the state during the conversation, but between different parts of the conversation, you have two good ways to do it:
If you're using the actions-on-google JavaScript library, you can put data into the app.data field and it will be available in the same place in the next call. (I can't find documentation on this, but its reported in https://plus.google.com/105458329026934344336/posts/Xr1KPiMPzpH)
Since you're using Dialogflow, you can add the state as parameters to a Context. These parameters will remain in the Context, and available to future Intents that expect it as an incoming Context, as long as the Context is active.
If you need to maintain state between conversations, you will need to save that state, probably associated with the anonymous UserID that is passed to you with each request.
These methods are similar to what you have when you're working with web requests for a user.

Related

Flutter SIP call from background service

I'm making a Flutter SIP call application using dart-sip-ua https://github.com/flutter-webrtc/dart-sip-ua.
I need to use PUSH messages to wake up the application and set the call.
I was able to wake up the application, but how to connect with the current call?
According to the documentation, when making a call, a Call object is created and it has an answer() method.
But when the Call object wakes up, we do not have, respectively, the answer() method either.
I tried to find a solution using SIPUAHelper.findCall(callUUID), but without success: callUUID is generated when the call is initialized, and we do not know it in advance to pass it via PUSH.
That is, I show my CallScreen, but I don’t have a Call object...
Is there really only one option? Wait until the SIP connects itself? It could be 5, 10, 30 seconds...
Help me please. What is the approach to accomplish this task? I feel that my approach is not correct.
Thank you!
One possible solution to your problem could be to store the Call object in a persistent storage, such as a database or a file, whenever it is created. Then, when the application wakes up and receives the PUSH message, you can retrieve the Call object from the storage and pass it to the CallScreen. To do this, you can use a database library like "sqflite" or a file library like "path_provider" to store and retrieve the Call object as a serialized object.
Another option could be to use the "callUUID" of the Call object as a key to store and retrieve it from the storage. You can pass the "callUUID" via PUSH message, and use it to retrieve the Call object from the storage. However, you need to make sure that the "callUUID" is unique and persistent across sessions, so you may need to use a combination of the SIP call ID and the local session ID.
A third option could be to use a global state manager like "Provider" or "Redux" to store the Call object and share it across the application. This way, you can access the Call object from any widget, even if it is not passed directly as an argument. However, you need to be careful with the performance and complexity of using a global state manager, especially if you have a large and complex application.
I hope these suggestions can help you solve your problem

What are the best practices when working with data from multiple sources in Flutter/Bloc?

The Bloc manual describes the example of a simple Todos app. It works as an example, but I get stuck when trying to make it into a more realistic app. Clearly, a more realistic Todos app needs to keep working when the user temporarily loses network connection, and also needs to occasionally check the server for updates that the user might have added from another device.
So as a basic data model I have:
dataFromServer, which is refreshed every five minutes, and
localData, that describes what changes have been made locally but haven't been synchronized to the server yet.
My current idea is to have three kinds of events:
on<GetTodosFromServer>() which runs every few minutes to check the server for updates and only changes the dataFromServer,
on<TodoAdded>() (and its friends TodoDeleted, TodoChecked, and so on) which get triggered when the user changes the data, and only change the localData, and
on<SyncTodoToServer>() which runs whenever the user changes the todo list, or when network connectivity is restored, and tries to send the changes to the server, retrieves the new value from the server, and then sets the new dataFromServer and localData.
So obviously there's a lot of interaction between these three methods. When a new todo is added after the synchronization to the server starts, but before synchronization is finished, it needs to stay in the local changes object. When GetTodosFromServer and SyncTodoToServer both return server data, they need to find out who has the latest data and keep that. And so on.
Coming from a Redux background, I'm used to having two reducers (one for local data, one for server data) that would only respond to simple actions. E.g. an action { "type": "TodoSuccessfullySyncedToServer", uploadedData: [...], serverResponse: [...] } would be straightforward to parse for both the localData and the dataFromServer reducer. The reducer doesn't contain any of the business logic, it receives actions one by one and all you need to think about inside the reducer is the state before the action, the action itself, and the state after the action. Anything you rely on to handle the action will be in the action itself, not in the context. So different pieces of code that generate those actions can just fire these actions without thinking, knowing that the reducer will handle them correctly.
Bloc on the other hand seems to mix business logic and updating the state. API calls are made within the event handlers, which will emit a value possibly many seconds later. So every time you return from an asynchronous call in an event handler, you need to think about how the state might have changed while that call was happening and the consequences this has on what you're currently doing. Also, an object in the state can be updated by different events that need to coordinate among themselves how to avoid conflicts while doing so.
Is there a best practice on how to avoid the complexity that brings? Is it best practice to split large events into "StartSyncToServer" and "SuccessfullySyncedToServer" events where the second behaves a lot like a Redux reducer? I don't see any of that in the examples, so is there another way this complexity is typically avoided in Bloc? Or is Bloc entirely unopinionated on these things?
I'm not looking for personal opinions here, only if there's something I missed in the Bloc manual (or other authoritative source) about how this was intended to work.

riverpod conditional provider state updates

I'm porting my app to river_pod, it's been great so far but I always stumble upon the same problem. There is some situations where I need a provider to update its state only conditionally depending on the new value acquired by the ref.watch.
An example of this is my last road-block:
I have a ChangeNotifier provider that exposes the current user location. This provider is listened to by multiple other providers. One of them is a FutureProvider that fetches the trending posts nearby every time the location changes. The problem here is that this location updates very frequently (every 10s or so) so this fetch is done a very unnecessary amount of time.
What I would like to do in that situation is, in this FutureProvider, be able to get the new position but update only conditionally (here the condition being, if the last fetch was done more than 1km away) to avoid this unnecessary network call and all underlying UI updates it causes.
This implies two things, having access to the last state to make the comparison, and be able to cancel an update (because here even if I don't do the fetch and return the last value, the UI will still read that as an update).
I understand that those mechanisms are not built-in, so I was wondering, was is the river_pod way to approach this problem?
Cheers!
I was having same problem to solve. I had to compare old data and new data and change the state in provider only if there is a change.

Does Firebase Realtime .once() still download the entire node, when .keepSynced(true)?

I am trying to reconcile two seemingly conflicting sources of information from Google.
In the official docs they say that 'value' from .once() is downloaded in full.
But here in a fascinating post from a Firebase expert at Google, Frank van Puffelen, he says that .keepSynced(true) uses 'delta-sync' to only sync the parts which have changed.
In this case, if I set keepSynced(true), and then call .once() on this same node, presumably it is not downloading the entire 'value' , only what has changed - is this correct?
If you call once() you will get the value as it is currently cached.
If on the same node you called keepSynced(true) the value in the cache should be up to date with the server.
By using the combination of both, there won't be a client-to-server call per once() call, but there will still be client-to-server call when the app starts (to attach the implicit listener of keepSynced(true)) and a server-to-client push whenever the data changes.
It sounds like you're trying to work around a problem, instead of addressing it head on though: if data can change, you should use on() listeners instead of once().

What triggers UI refresh in CQRS client app?

I am attempting to learn and apply the CQRS design approach (pattern and architecture) to a new project but seem to be missing a key piece.
My client application executes a query and retrieves a list of light-weight, read-only DTOs from the read model. The user selects an item and clicks a button to initiate some action. The action is performed by creating and sending the corresponding command object to the write model (where the command handler carries out the action, updates the data store, etc.) At some point, however, I need to update the UI to reflect changes to the state of the application resulting from the action.
How does the UI know when it is time to refresh the original list?
Additional Info
I have noticed that most articles/blogs discussing CQRS use MVC client apps in their examples. I am working on a Silverlight client right now and am beginning to wonder if the pattern simply doesn't work in that case.
Follow-Up Question
After thinking more about Bartlomiej's response and subsequent discussion, I am wondering about error handling in CQRS. Given that commands are basically fire-and-forget asynchronous operations, how do we report an error condition to the UI?
I see 'refreshing the UI' to take one of two forms:
The operation succeeds, data has changed and the UI should be updated to reflect these changes
The operation fails, data has not changed but the user should be notified of the failure and potential corrective actions.
Even with a Post-Redirect-Get pattern in an MVC, you can't really Redirect until you know the outcome of the operation. None of the examples I've seen thus far address these real-world concerns.
I've been struggling with similar issues for a WPF client. The re-query trigger for any data is dependent on the data your updating, commands tend to fall into categories:
The command is a true fire and forget method, it informs the back-end of a state change but this change does not need to be reflected in the UI, or the change simply isn't important to the UI.
The command will alter the result of a single query
The command will alter the result of multiple queries, usually (in my domain at least) in a cascading fashion, that is, changing the state of a single "high level" piece of data will likely affect many "low level" caches.
My first trigger is the page load, very few items are exempt from this as most pages must assume data has been updated since it was last visited. Though some systems may be able to escape with only updating financial and other critical data in this way.
For short commands I also update data when 'success' is returned from a command. Though this is mostly laziness as IMHO all CQRS commands should be fired asynchronously. It's still an option I couldn't live without but one you may have to if your implementation expects high latency between command and query.
One pattern I'm starting to make use of is the mediator (most MVVM frameworks come with one). When I fire a command, I also fire a message to the mediator specifying which command was launched. Each Cache (A view model property Retriever<T>) listens for commands which affect it and then updates appropriately. I try to minimise the number of messages while still minimising the number of caches that update unnecessary from a single message so I'll (hopefully) eventually end up with a shortlist of update reasons, with each 'reason' updating a list of caches.
Another approach is simple honesty, I find that by exposing graphically how the system updates itself makes users more willing to be patient with it. On firing a command show some UI indicating you're waiting for the successful response, on error you could offer to retry / show the error, on success you start the update of the relevant fields. Baring in mind that this command could have been fired from another terminal (of which you have no knowledge) so data will need to timeout eventually to avoid missing state changes invoked by other machines also.
Noting the irony that the only efficient method of updating cache's and values on a client is to un-separate the commands and queries again, be it through hardcoding or something like a hashmap.
My two cents.
I think MVVM actually fits into CQRS quite well. The ViewModel simply becomes an observable ReadModel.
1 - You initialize your ViewModel state via a query on the ReadModel.
2 - Changes on your ViewModel are automatically reflected on any Views that are bound to it.
3 - Certain changes on your ViewModel trigger a command to propegate to a message queue, an object responsible for sending those commands to the server takes those messages off the queue and sends them to the WriteModel.
4 - Clients should be well formed, meaning the ViewModel should have performed appropriate validation before it ever triggered the command. Once the command has been triggered, any event notifications can be published onto an event bus for the client to communicate changes to other ViewModels or components in the system interested in those changes. These events should carry the relevant information necessary. Typically, this means that other view models usually don't have to re-query the read model as a result of the change unless they are dependent on other data that needs to be retrieved.
5 - There is an object that connects to the message bus on the server for real-time push notifications when other clients make changes that this client is interested in knowing about, falling back to long-polling if necessary. It propagates those to the internal message bus that ties the components on the client together.
6 - The last part to handle is the fact that clients can be occasionally connected, which should be the only reason a command fails (they don't have internet access at the moment), which is when the client should be notified of problems.
In my ASP.NET MVC 3 I use 2 techniques depending on use case:
already well-known Post-Redirect-Get pattern which fits nicely with CQRS. Your MVC action that triggers the command returns a redirection to action that performs a query.
in some cases, like real-time updates of other clients, I rely on domain events/messages. I create an event handler that uses singlarR to push changes to all connected and interested clients.
There are two major ways you can take as far as I know :
1) design your UI , so that the user does not see its changes right away. Like for instance a message to tell him his action is a success, and offering him different choices to continue his work. this should buy you enough time to have updated your readmodel.
2) more complex, but you might keep the information you have send to the server and shows them in the interface.
The most important I guess, educate your user if you can so that they know why the data is not here... yet!
I am thinking about it only now, but these are for sync command handling, not async, in async things go really harder on the brain...the client interface becomes an event eater too..