PostGraphile subscriptions - what does "topic" refer to? - graphql

I'm using PgPubsub and I'm trying to get my head around listen and topic*:"" vis-a-vis what to put there.
For example, let's say I have a <PostList> component that renders a list of <Post> and I want to update the list when a Post is created or deleted.
I'm not sure how to structure my subscription so I'm listening for changes to PostList. Here's a screenshot of my GraphiQL:

In pubsub (publish-subscribe), messages are published to a "topic" and you can subscribe to that topic to receive the messages that are published there.
You appear to be using the "simple subscriptions" functionality in PostGraphile, so I'll answer assuming that's the case.
With the subscription listen(topic: "whatGoesHere?") you have, you need to broadcast to the postgraphile:whatGoesHere? topic to trigger a subscription event. You can do this by issuing the SQL statement NOTIFY "postgraphile:whatGoesHere?", '{"ok": true}';. You can do this with psql:
$ psql your_database_here
[your_database_here] # NOTIFY "postgraphile:whatGoesHere?", '{"ok": true}';
NOTIFY
[your_database_here] #
Assuming your GraphQL subscription is running, this should cause the selection set to be evaluated and the results to be sent to GraphiQL.
You'll probably want to fire this NOTIFY statement from a function or trigger; you can read more about that in the PostGraphile Subscriptions documentation.

Related

Perform action on seen/unseen messages with socket.io

What is the best practice to handle seen/unseen messages in a chat room application based on Nodejs/SocketIO/React.
Consider User1 sends a message to a room. If another user has seen that message, notify all users that the state of message has been seen.
In my opinion using message brokers can be the better solution instead socket. I actually think that socket should only handle chat messages that are synchronously. but for seen/unseen status I prefer message brokers that are asynchronous. Are there any solutions or best practice in large scale applications?
It's unclear what you have currently tried, meaning that I can only advise solutions in order to achieve your aim.
To firstly identify that a message was seen, IntersectionObserver is an inbuilt API that detects when an element has entered the viewport, meaning that it is visible, therefore; obviously seen. I have added comments in the code below where you should add a function to call to the server that the message was seen, however, that's up to you to implement.
const observer = new window.IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
// Send a message to the server that the user has viewed the message.
// Eg. socket.emit('read-message', message.id)
return
}
}, {
root: null,
threshold: 0.1,
})
observer.observe(document.getElementById(message.id));
Additionally, there's no need to use message broker, as socket.io can handle simple interactions such as this.
You then need to send a message to the server that denotes the specified message ID was seen, then broadcast to every other client that the state was changed, and update it to read - if that's needed.

Put a user on hold with Amazon Lex

We are using Amazon Connect, Lex and Lambda to create a phone bot. One use case we have is that we need to put the user on hold while we find information in other systems. So the conversation will be something like this:
- bot: hi, what can I do for you?
- user: i want to make a reservation
- bot: wait a minute while I fetch information about available rooms
... after 5 seconds ...
- bot: I found a free room blah blah
I don't see a way to send the wait a minute... message and keep control of the conversation. How can we achieve that?
You can accomplish this inside a single Lex bot by setting the intent to be fulfilled by a lambda function, the response of the function would play a message saying “please wait” and then chain another internet to perform the search using the data from the original intent.
See this link for information about sharing data between intents.
You can chain or switch to the next intent by passing the confirmIntent dialog action back in the lambda response. See this link for more information on the lambda input and response format.
You can use wait block in aws connect https://docs.aws.amazon.com/connect/latest/adminguide/flow-control-actions-wait.html
By using this block you can set time to 5 secs . after time expired you can play prompt.
This is a very common problem typically when we want to do backend lookups in an IVR. The problem is lex does not provide any means to just play prompts.
One way to do it is:
Create a dummy slot in your intent (the reservation intent from your example above) with any type (e.g. AMAZON.NUMBER), we don't really care what the value is in this slot
From the lex code-hook for the intent, return ElicitSlot for this dummy slot with prompt as "Wait a minute while I fetch available rooms... "
If you do only this much, the problem you will face is that Lex will expect input from caller and will wait for around 4 seconds before passing control back to the Init and Validation Lambda, so there will be unnecessary delay. To overcome this, you need to set timeout properties as session attribute in "Get Customer Input" block from connect.
Property1:
Lex V2 Property name: x-amz-lex:audio:start-timeout-ms:[intentName]:[slotToElicit]
Lex Classic Property name x-amz-lex:start-silence-threshold-ms:[intentName]:[slotToElicit]
value: 10 (or any small number, this is in millseconds)
Property2:
Only available in Lex Classic, to disable barge-in on Lex V2, you can do it for required slot from lex console
Property name: x-amz-lex:barge-in-enabled:[intentName]:[slotToElicit]
Value: false
If barge-in is not disabled, there is a chance user may speak in middle of your "Please wait..." prompt and it will not be played completely.
Official documentation for these properties:
https://docs.aws.amazon.com/connect/latest/adminguide/get-customer-input.html
https://docs.aws.amazon.com/lexv2/latest/dg/session-attribs-speech.html
Another way:
Whenever such a prompt needs to be played, store the lex context temporarily either as a contact attribute after serialization, or if too big in size to be stored as contact attribute in a store like dynamodb.
Return control back to connect, play the prompt using 'Play prompt' module in connect. To give control back to bot, you will need invoke a lambda to re-initialize Lex with the full lex context again- using PostText API and then again passing control to same bot using 'Get Customer Input'
I have implemented option1 and it works well. You can even create cover-prompt which gets played if the backend lookup takes longer than expected. The actual lookup could be delegated to another lambda so that the code-hook lambda can continue doing customer interaction ever x (say 5) seconds to keep them informed that you are still looking up information.

Pubnub chat application with storage

I'm looking to develop a chat application with Pubnub where I want to make sure all the chat messages that are send is been stored in the database and also want to send messages in chat.
I found out that I can use the Parse with pubnub to provide storage options, But I'm not sure how to setup those two in a way where the messages and images send in the chat are been stored in the database.
Anyone have done this before with pubnub and parse? Are there any other easy options available to use with pubnub instead of using parse?
Sutha,
What you are seeking is not a trivial solution unless you are talking about a limited number of end users. So I wouldn't say there are no "easy" solutions, but there are solutions.
The reason is your server would need to listen (subscribe) to every chat channel that is active and store the messages being sent into your database. Imagine your app scaling to 1 million users (doesn't even need to get that big, but that number should help you realize how this can get tricky to scale where several server instances are listening to channels in a non-overlapping manner or with overlap but using a server queue implementation and de-duping messages).
That said, yes, there are PubNub customers that have implemented such a solution - Parse not being the key to making this happen, by the way.
You have three basic options for implementing this:
Implement a solution that will allow many instances of your server to subscribe to all of the channels as they become active and store the messages as they come in. There are a lot of details to making this happen so if you are not up to this then this is not likely where you want to go.
There is a way to monitor all channels that become active or inactive with PubNub Presence webhooks (enable Presence on your keys). You would use this to keep a list of all channels that your server would use to pull history (enable Storage & Playback on your keys) from in an on-demand (not completely realtime) fashion.
For every channel that goes active or inactive, your server will receive these events via the REST call (and endpoint that you implement on your server - your Parse server in this case):
channel active: record "start chat" timetoken in your Parse db
channel inactive: record "end chat" timetoken in your Parse db
the inactive event is the kickoff for a process that uses start/end timetokens that you recorded for that channel to get history from for channel from PubNub: pubnub.history({channel: channelName, start:startTT, end:endTT})
you will need to iterate on this history call until you receive < 100 messages (100 is the max number of messages you can retrieve at a time)
as you retrieve these messages you will save them to your Parse db
New Presence Webhooks have been added:
We now have webhooks for all presence events: join, leave, timeout, state-change.
Finally, you could just save each message to Parse db on success of every pubnub.publish call. I am not a Parse expert and barely know all of its capabilities but I believe they have some sort or store local then sync to cloud db option (like StackMob when that was a product), but even if not, you will save msg to Parse cloud db directly.
The code would look something like this (not complete, likely errors, figure it out or ask PubNub support for details) in your JavaScript client (on the browser).
var pubnub = PUBNUB({
publish_key : your_pub_key,
subscribe_key : your_sub_key
});
var msg = ... // get the message form your UI text box or whatever
pubnub.publish({
// this is some variable you set up when you enter a chat room
channel: chat_channel,
message: msg
callback: function(event){
// DISCLAIMER: code pulled from [Parse example][4]
// but there are some object creation details
// left out here and msg object is not
// fully fleshed out in this sample code
var ChatMessage = Parse.Object.extend("ChatMessage");
var chatMsg = new ChatMessage();
chatMsg.set("message", msg);
chatMsg.set("user", uuid);
chatMsg.set("channel", chat_channel);
chatMsg.set("timetoken", event[2]);
// this ChatMessage object can be
// whatever you want it to be
chatMsg.save();
}
error: function (error) {
// Handle error here, like retry until success, for example
console.log(JSON.stringify(error));
}
});
You might even just store the entire set of publishes (on both ends of the conversation) based on time interval, number of publishes or size of total data but be careful because either user could exit the chat and the browser without notice and you will fail to save. So the per publish save is probably best practice if a bit noisy.
I hope you find one of these techniques as a means to get started in the right direction. There are details left out so I expect you will have follow up questions.
Just some other links that might be helpful:
http://blog.parse.com/learn/building-a-killer-webrtc-video-chat-app-using-pubnub-parse/
http://www.pubnub.com/blog/realtime-collaboration-sync-parse-api-pubnub/
https://www.pubnub.com/knowledge-base/discussion/293/how-do-i-publish-a-message-from-parse
And we have a PubNub Parse SDK, too. :)

Why would a WCF OracleDB receive location be triggered by its FK instead of an actual update on its table?

Strange behavior in our receive locations:
RL_REPRESENTATIVE is waiting for a notification from the REPRESENTATIVE table (fields: (PK)id, fname, lname, etc).
RL_CLIENT_REPRESENTATIVE is waiting for a notification from the CLIENT_REPRESENTATIVE table (fields: (FK)id_rep, (FK)id_client).
When both of the locations are active and I commit a change in the CLIENT_REPRESENTATIVE.id_rep table I get a couple of warnings (apparently from RL_REPRESENTATIVE).
The adapter "WCF OracleDB" raised an error message. Details "System.InvalidOperationException: The notification query returned an error. Info="Error". Source="Data". Type="Change".
at Microsoft.Adapters.OracleDB.OracleDBInboundContract.Notification_TryReceive(OracleCommonExecutionHelper executionHelper, Message& wcfMessage)
at Microsoft.Adapters.OracleDB.OracleDBInboundContract.TryReceive(TimeSpan timeout, Message& message, IInboundReply& reply)
at Microsoft.ServiceModel.Channels.Common.Channels.AdapterInputChannel.TryReceive(TimeSpan timeout, Message& message)
at System.ServiceModel.Dispatcher.InputChannelBinder.TryReceive(TimeSpan timeout, RequestContext& requestContext)
at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.TryReceive(TimeSpan timeout, RequestContext& requestContext)".
and
The adapter "WCF OracleDB" raised an error message. Details "The WCF service host at address oracledb://d01-isis:1521/D01ISIS/Dedicated?CallingTable=REPRESENTATIVE has faulted and as a result no more messages can be received on the corresponding receive location. To fix the issue, BizTalk Server will automatically attempt to restart the service host.".
Otherwise the process that is activated by a modification in CLIENT_REPRESENTATIVE takes place with no problems.
(If I update, instead, id_client in CLIENT_REPRESENTATIVE - the error comes from another receive location that subscribes to notifications from the CLIENT table.)
Two further clues:
If I disable RL_REPRESENTATIVE, the warnings won't appear.
If I update both CLIENT_REPRESENTATIVE.id_rep and REPRESENTATIVE.fname and commit both in the same transaction, the warnings won't appear.
Note that there are no triggers in either tables and all my timeouts are set to almost 24 hours.
I suspect that the FK constraint does its job in a way that ends up sending a notification to the port but I never get the actual message that I'm supposed to receive.
Question: Is there a parameter in Oracle that controls this behavior? Have any Biztalk devs ever run into this problem?
It could be:
the order in which things are saved.
a transactional problem, receive locations on seperate transactions, therefore it looks like related items are missing
a locking problem related to the transactional problem
The way to track it down would be to setup profiling on the database, and see exactly which commands are sent in which order.
In the end, the solution was to change a flag in all the receive locations (NotifyOnListenerStart) to "false".
After further development, this solution was not complete - the errant triggering is occurring again - so I'm toggling the check to off until I (or someone else) finds the correct solution.
Edit: This is a side-effect of the FK, changing its value seems to trigger a notification of a change in the table containing the PK (despite there not being any).

Pusher App Client Events

I'm writing a multiplayer chess game, and using Pusher for the websocket server part.
Anyways, if I have a list of users, and I select any one of them and challenge them, how do I send challenge to just that one user? I know I would use the client event like:
channel.trigger("client-challenge_member1", {some : "data"});
But this event would have to have already been created I think. So do I create this event dynamically after each member subscribes? as possibly in:
channel.bind("pusher:subscribed_completed", function(member) // not sure of correct syntax but...
{
channel.bind("client-challenge_" + member.memberID, function(data)
{
alert(data.Name + " is challenging you.");
});
});
I would think there'd be a overloaded method for trigger, like:
channel.trigger(eventName, data, memberID)
But I cannot see anything like this. Any ideas? Thanks.
I ran into this problem on my application. At this time Pusher does not provide methods for sending events to a specific user. I think the approach that you mentioned would work for your situation. For my application I had each user subscribe to a channel with their user id as the channel id, then I could send messages to a single user through that channel.
client = new Pusher(PUSHER_API_KEY);
channel = client.subscribe(user_id);
channel.bind('my_event',function(data){
//Do stuff
});
I talked this approach over with the pusher team and they assured me there was no real overhead in having the extra channels. The new Pusher() command is the code that creates a new socket connection so you don't have to worry about extra sockets per channel or anything like that. Hope this helps.
I'm from Pusher. As Braden says, you can easily make a channel per user. This is more efficient than having the user id in the event name which means you spam everyone with useless messages.
This is an area we want to improve on further, so thanks for the feedback.
If you're able to consider another service, Beaconpush has the ability to send messages to a specific user.
From their site:
POST /1.0.0/[API key]/users/[user]

Resources