Freeswitch Event Socket Library - is there abstraction like Session as for internal scripting languages like mod_lua? - freeswitch

I am trying to work with FreeSwitch using Event Socket library, and a bit surprised it has no abstraction like Session in internal scripting languages (which can be established, bridged etc using simple API). Is this the case and I have correct understanding?
If I understand well ESL allows to send API commands like originate and receive events and it's up to application to understand the state by processing events, so there are no helpers for this, correct?
So even if
Scripts using the Event Socket Library (ESL) can be run from anywhere
achieving the same results as built-in languages
it's up to application developer to implement Session abstraction on his side when using ESL, so ESL is low level interface and much more efforts are necessary to, i.g. establish call with originate, get it's state (by processing events) and then bridge it i.g. with uuid_transfer?

We are using value from "Unique-ID" header field.
The implementation is using the following library with custom addons - https://github.com/esl-client/esl-client.
PS. for LUA: How to get value of SIP header in Freeswitch?

Related

Are there any Thrift-style RPC systems that allow callbacks?

After using several different messaging and RPC systems I have come to the conclusion that you eventually always need traditional RPC, and push events of some kind. Otherwise you inevitably end up with some polling hack.
For example, HTTP originally only supported RPC-style methods (GET and POST return a response immediately). People realised that push events were needed so hacked it using long polling. Eventually this was fixed with Server-Sent Events.
CoAP (a lightweight UDP-based version of HTTP) also supports push events by adding a 'monitor' option to GET requests. It's a pretty elegant solution.
But neither of those are Thrift-style RPC, by which I mean you write an interface definition file, and there is some tool that compiles that interface into native code for your language of choice. Thereafter you can just call remote procedures almost as if they are local ones.
So my question is, are there any Thrift-style RPC systems that let you subscribe to push events and call a callback (or similar) when an event arrives?
Yes:
gRPC supports "streaming", which means a single logical RPC call can actually involve multiple messages in each direction.
Cap'n Proto supports object capabilities, which allows either side of the connection to send an object reference to the other side, to which calls can be made. For example, the client could call a method on the server and, as one of the method parameters, provide a callback object. The callback object implements some pre-defined RPC interface. When the server calls the callback object, it is making a call back to the client. In fact, Cap'n Proto connections are fully symmetric: there is no distinction at the protocol level between client and server.
(Disclosure: I am the author of Cap'n Proto, and was also the author of Protocol Buffers v2, though I am not affiliated with gRPC.)

How to provide both initial data and subsequent events via WAMP/Websockets

I have a an application from which I need to send live updates to web clients.
I'm currently happily using websockets for that, via the WAMP protocol, as it provides both publish-subscribe and RPC methods.
Now, I find that in lots of situations, when a user starts the application or a view, I need to send an initial state to the client, and then keep sending updates. I do the first with an RPC call, and the latter via publish-subscribe.
Now, this forces me to write server-side and client-side code for both of the methods, even while I'm basically conveying the same information in both cases.
On server side, I'm moving appropriate code to a common method, but I still need to take care of both sending the event and provide an entry point for the RPC call:
# RPC endpoint for getting mission info
def get_mission_info(self):
return self.get_mission_info()
# Scheduled or manually called method to send mission info to all users
def publish_mission_info(self):
self.wamp.publish("UPDATE_INFO", [self.get_mission_info()])
def get_mission_info(self):
# Here we generate a JSON serializable dict with the info
return info
And you canimagine, client side (JS or Python) shows a similar duplicity (two handler methods).
Question is: is there a more clever way of handling this, and avoiding that boilerplate code? Some approach I could follow, perhaps automatically sending last event of each type just to clients that ask for it, or that just subscribed? Perhaps something at crossbar level?
In general terms, I feel I could be doing a better state synchronization strategy leveraging these two channels (pub-sub and RPC). How does people do it?
My WAMP server is Crossbar, and my client library is autobahn.js in Python and JS.

Asynchronous methods calls with Ruby like with Ajax

I am working with XMPP and I have a message callback which is activated on the event of every message being sent. My aim is to send the data arriving by the message to an API within the callback and based on the response send something back using the XMPP client.
User type message (Browser Chat Client)
Message arrives to the server via XMPP
Message is sent to the API
Response is received
Response is sent back to the chat client.
My code for this is as follows
admin_muc_client.activate_message_callbacks do |m|
sender = m.from.resource
room_slug = m.from.node
message = m.body
r = HTTParty.get('http://example.com/api/v1/query?msg=message')
Rails.logger.debug(r.inspect)
admin_muc_client.send_message("Message #{r.body}") if m.from.resource != 'admin'
end
My concern here is that since the callback is evented and the request to the API would be a blocking call this could become a bottleneck for the entire application.
I would prefer to use something like AJAX for Javascript which would fire the request and when the response is available send data. How could I implement that in Ruby?
I have looked at delayed_job and backgroundrb which look like tools for fire and forget operations. I would need something that activates a callback in an asynchronous manner with the response.
I would really really appreciate some help on how to achieve the asynchronous behavior that i want. I am also familiar with message queues like RabbitMQ which I feel would be addition of significant complexity.
Did you look at girl_friday? From it's wiki -
girl_friday is a Ruby library for performing asynchronous tasks. Often times you don't want to block a web response by performing some task, like sending an email, so you can just use this gem to perform it in the background. It works with any Ruby application, including Rails 3 applications.
Why not use any of the zillions of other async solutions (Resque, dj, etc)? Because girl_friday is easier and more efficient than those solutions: girl_friday runs in your Rails process and uses the actor pattern for safe concurrency. Because it runs in the same process, you don't have to monitor a separate set of processes, deploy a separate codebase, waste hundreds of extra MB in RAM for those processes, etc. See my intro to Actors in Ruby for more detail.
You do need to write thread-safe code. This is not hard to do: the actor pattern means that you get a message and process that message. There is no shared data which requires locks and could lead to deadlock in your application code. Because girl_friday does use Threads under the covers, you need to ensure that your Ruby environment can execute Threads efficiently. JRuby, Rubinius 1.2 and Ruby 1.9.2 should be sufficient for most applications. I do not support Ruby 1.8 because of its poor threading support.
I think this is what you are looking for.

Web sockets make ajax/CORS obsolete?

Will web sockets when used in all web browsers make ajax obsolete?
Cause if I could use web sockets to fetch data and update data in realtime, why would I need ajax? Even if I use ajax to just fetch data once when the application started I still might want to see if this data has changed after a while.
And will web sockets be possible in cross-domains or only to the same origin?
WebSockets will not make AJAX entirely obsolete and WebSockets can do cross-domain.
AJAX
AJAX mechanisms can be used with plain web servers. At its most basic level, AJAX is just a way for a web page to make an HTTP request. WebSockets is a much lower level protocol and requires a WebSockets server (either built into the webserver, standalone, or proxied from the webserver to a standalone server).
With WebSockets, the framing and payload is determined by the application. You could send HTML/XML/JSON back and forth between client and server, but you aren't forced to. AJAX is HTTP. WebSockets has a HTTP friendly handshake, but WebSockets is not HTTP. WebSockets is a bi-directional protocol that is closer to raw sockets (intentionally so) than it is to HTTP. The WebSockets payload data is UTF-8 encoded in the current version of the standard but this is likely to be changed/extended in future versions.
So there will probably always be a place for AJAX type requests even in a world where all clients support WebSockets natively. WebSockets is trying to solve situations where AJAX is not capable or marginally capable (because WebSockets its bi-directional and much lower overhead). But WebSockets does not replace everything AJAX is used for.
Cross-Domain
Yes, WebSockets supports cross-domain. The initial handshake to setup the connection communicates origin policy information. The wikipedia page shows an example of a typical handshake: http://en.wikipedia.org/wiki/WebSockets
I'll try to break this down into questions:
Will web sockets when used in all web browsers make ajax obsolete?
Absolutely not. WebSockets are raw socket connections to the server. This comes with it's own security concerns. AJAX calls are simply async. HTTP requests that can follow the same validation procedures as the rest of the pages.
Cause if I could use web sockets to fetch data and update data in realtime, why would I need ajax?
You would use AJAX for simpler more manageable tasks. Not everyone wants to have the overhead of securing a socket connection to simply allow async requests. That can be handled simply enough.
Even if I use ajax to just fetch data once when the application started I still might want to see if this data has changed after a while.
Sure, if that data is changing. You may not have the data changing or constantly refreshing. Again, this is code overhead that you have to account for.
And will web sockets be possible in cross-domains or only to the same origin?
You can have cross domain WebSockets but you have to code your WS server to accept them. You have access to the domain (host) header which you can then use to accept / deny requests. This can, however, be spoofed by something as simple as nc. In order to truly secure the connection you will need to authenticate the connection by other means.
Websockets have a couple of big downsides in terms of scalability that ajax avoids. Since ajax sends a request/response and closes the connection (..or shortly after) if someone stays on the web page it doesn't use server resources when idling. Websockets are meant to stream data back to the browser, and they tie up server resources to do so. Servers have a limit in how many simultaneous connections they can keep open at one time. Not to mention depending on your server side technology, they may tie up a thread to handle the socket. So websockets have more resource intensive requirements for both sides per connection. You could easily exhaust all of your threads servicing clients and then no new clients could come in if lots of users are just sitting on the page. This is where nodejs, vertx, netty can really help out, but even those have upper limits as well.
Also there is the issue of state of the underlying socket, and writing the code on both sides that carry on the stateful conversation which isn't something you have to do with ajax style because it's stateless. Websockets require you create a low level protocol which is solved for you with ajax. Things like heart beating, closing idle connections, reconnection on errors, etc are vitally important now. These are things you didn't have to solve when using AJAX because it was stateless. State is very important to the stability of your app and more importantly the health of your server. It's not trivial. Pre-HTTP we built a lot of stateful TCP protocols (FTP, telnet, SSH), and then HTTP happened. And no one did that stuff much anymore because even with its limitations HTTP was surprisingly easier and more robust. Websockets bring back the good and the bad of stateful protocols. You'll learn soon enough if you didn't get a dose of that last go around.
If you need streaming of realtime data this extra overhead is warranted because polling the server to get streamed data is worse, but if all you are doing is user interaction->request->response->update UI, then ajax is easier and will use less resources because once the response is sent the conversation is over and no additional server resources are used. So I think it's a tradeoff and the architect has to decide which tool fits their problem. AJAX has its place, and websockets have their place.
Update
So the architecture of your server is what matters when we are talking about threads. If you are using a traditionally multi-threaded server (or processes) where a each socket connection gets its own thread to respond to requests then websockets matter a lot to you. So for each connection we have a socket, and eventually the OS will fall over if you have too many of these, and the same goes for threads (more so for processes). Threads are heavier than sockets (in terms of resources) so we try and conserve how many threads we have running simultaneously. That means creating a thread pool which is just a fixed number of threads that is shared among all sockets. But once a socket is opened the thread is used for the entire conversation. The length of those conversations govern how quickly you can repurpose those threads for new sockets coming in. The length of your conversation governs how much you can scale. However if you are streaming this model doesn't work well for scaling. You have to break the thread/socket design.
HTTP's request/response model makes it very efficient in turning over threads for new sockets. If you are just going to use request/response use HTTP its already built and much easier than reimplementing something like that in websockets.
Since websockets don't have to be request/response as HTTP and can stream data if your server has a fixed number of threads in its thread pool and you have the same number of websockets tying up all of your threads with active conversations, you can't service new clients coming in! You've reached your maximum capacity. That's where protocol design is important too with websockets and threads. Your protocol might allow you to loosen the thread per socket per conversation model that way people just sitting there don't use a thread on your server.
That's where asynchronous single thread servers come in. In Java we often call this NIO for non-blocking IO. That means it's a different API for sockets where sending and receiving data doesn't block the thread performing the call.
So traditional in blocking sockets when you call socket.read() or socket.write() they wait until the data is received or sent before returning control to your program. That means your program is stuck waiting for the socket data to come in or go out until you can do anything else. That's why we have threads so we can do work concurrently (at the same time). Send this data to client X while I wait on data from client Y. Concurrencies is the name of the game when we talk about servers.
In a NIO server we use a single thread to handle all clients and register callbacks to be notified when data arrives. For example
socket.read( function( data ) {
// data is here! Now you can process it very quickly without waiting!
});
The socket.read() call will return immediately without reading any data, but our function we provided will be called when it comes in. This design radically changes how you build and architect your code because if you get hung up waiting on something you can't receive any new clients. You have a single thread you can't really do two things at once! You have to keep that one thread moving.
NIO, Asynchronous IO, Event based program as this is all known as, is a much more complicated system design, and I wouldn't suggest you try and write this if you are starting out. Even very Senior programmers find it very hard to build a robust systems. Since you are asynchronous you can't call APIs that block. Like reading data from the DB or sending messages to other servers have to be performed asynchronously. Even reading/writing from the file system can slow your single thread down lowering your scalability. Once you go asynchronous it's all asynchronous all the time if you want to keep the single thread moving. That's where it gets challenging because eventually you'll run into an API, like DBs, that is not asynchronous and you have to adopt more threads at some level. So a hybrid approaches are common even in the asynchronous world.
The good news is there are other solutions that use this lower level API already built that you can use. NodeJS, Vertx, Netty, Apache Mina, Play Framework, Twisted Python, Stackless Python, etc. There might be some obscure library for C++, but honestly I wouldn't bother. Server technology doesn't require the very fastest languages because it's IO bound more than CPU bound. If you are a die hard performance nut use Java. It has a huge community of code to pull from and it's speed is very close (and sometimes better) than C++. If you just hate it go with Node or Python.
Yes, yes it does. :D
The earlier answers lack imagination. I see no more reason to use AJAX if websockets are available to you.

NetTcpBinding with Streaming and Session

I’m trying to set up a WcfService with the use of NetTcpBinding. I use Transfer mode Streamed since I will transfer large files. I need to use Session, and I have read that NetTcpBinding supports this, but when I turn it on like:
SessionMode=SessionMode.Required
I get the error:
System.InvalidOperationException: Contract requires Session, but Binding 'NetTcpBinding' doesn't support it or isn't configured properly to support it.
Does anyone know what I have to do to make NetTcpBinding work with sessions?
Thanks for any help :)
You've no doubt solved this - but for others that come across it (as I did)...
According to "Programming WCF Services" by Juval Lowy - you can't use streaming with a contract that is configured SessionMode.Required. See page 243
Neither can you use NetTcpBinding with reliable messaging with streaming.
It doesn't elaborate as to why.
One workaround might be to split the operations that require session mode into a separate contract and the streaming operations into another.
Then implement a unique ID for each client (unique GUID for the lifetime of the client app) which is passed in the non-streaming interface as a RegisterSession(Guid mySessionId) operation.
When sessions are created on the server - they can register with a session manager object which stores the GUID, SessionContractImplemenation pair in a Dictionary.
Then add a param to the streaming contract operation (same GUID) so that the streaming contract implementation can access the live non-streaming object (via the session manager you created - using the GUID provided).
You'll have to manage session lifetimes appropriately of course.
From Microsoft...
Sessions and Streaming
When you have a large amount of data to transfer, the streaming transfer mode in WCF is a feasible alternative to the default behavior of buffering and processing messages in memory in their entirety. You may get unexpected behavior when streaming calls with a session-based binding. All streaming calls are made through a single channel (the datagram channel) that does not support sessions even if the binding being used is configured to use sessions. If multiple clients make streaming calls to the same service object over a session-based binding, and the service object's concurrency mode is set to single and its instance context mode is set to PerSession, all calls must go through the datagram channel and so only one call is processed at a time. One or more clients may then time out. You can work around this issue by either setting the service object's InstanceContextMode to PerCall or Concurrency to multiple.
Note:
MaxConcurrentSessions have no effect in this case because there is only one "session" available.
See http://msdn.microsoft.com/en-us/library/ms733040.aspx

Resources