last day (31 days later) » 

10:38 AM
@Jimbo OK so imagine I ask you to send someone a letter and tell me how they respond. You don't send the letter and sit there doing nothing until you get the response, you send the letter and forget about it until you get the response
You go off and do something else
 
Yeah of course, fire and forget. I only know how to fire and forget by using a separate process
 
a side effect of that is that when the response arrives, you might be busy doing something else and not tell me about it right away
Because you are only one person, you only have a single thread of execution
but you are capable of organising your available time to efficiently process the things you need to do
you use a calendar or something to manage your schedule
that's what an event loop does, it's a scheduler. It's just time management
 
Which you use together with async to tell it to continue executing and what, poll (tick()) for something back?
 
@Jimbo async is an effect of that scheduling
 
Okay, so I get the loop bit then, it's now this magical scheduling that I don't
 
10:42 AM
The loop is what does the scheduling
specifically this bit:
timeout = getTimeUntilNextTimer();

if (haveIoToWatch()) {
    watchForIo(timeout);
} else {
    sleep(timeout);
}
timeout is "how long before the next thing I have scheduled"
i.e. things done with setTimeout() etc
 
Okay, so haveIoToWatch is looking at an internal array of operations that we're 'watching' for
How does the watching work, the watchForIo bit
 
@Jimbo epoll()/kqueue()/select() - type operations
Which are dealt with by the OS
Don't worry about how those bits work underneath for now, just trust that they do
You basically say to the OS "tell me when something interesting happens on one of these streams/fds/signal sources/whatever"
@Jimbo PHP under the hood is making operating-system calls that do this for you
PHP doesn't implement this, it's just a proxy for OS level calls
Put it this way @Jimbo: I don't even really know how it works, because I don't write operating systems. It is simply not relevant to an application developer.
 
@DaveRandom So PHP can watch on three different streams, I'm guessing that kqueue is the best right. How do we say from PHP land - this operation is going to be executed over this stream?
 
It's on the same kind of level as how hardware drivers work: it just doesn't matter, you have to trust that they do
@Jimbo tbh you don't even need to worry about it at that level. PHP only exposes select() to userland (via stream_select()), other extensions like ev/uv use epoll()/kqueue() under the hood when they are available, but they are using cross-OS abstraction libs, so even the PHP extension code doesn't know what mechanism is being used underneath
it doesn't really matter
you are going too far down the rabbit hole for the purposes of this talk
Windows has a completely different mechanism for dealing with that stuff, again you just don't need to worry about it
 
Okay I'll just trying to think from PHP land then. I still need to get, briefly, how PHP achieves this though. Let's say we have a http request. Is there a list of 'things' we can do that are async, therefore we know we can do this over stream select and not block, or something?
 
10:52 AM
@Jimbo OK so it's worth getting a clear separation in your mind between "asynchronous" and "non-blocking"
asynchronous is the process of doing other stuff while you are waiting, non-blocking is just a tool that enables the process
When you mix and match the terminology (which a lot of people do, all the time) it can get really confusing really fast
...or just don't attempt to dismantle the black box, because you don't need to in order to write an application on top of it :-P
nevertheless a desire to understand is commendable
 
@DaveRandom Sure, but.. I need to first identify if something would be blocking. Is there a finite list available of what is? Secondly - let's say it is blocking. This means I can't use yield and everything will be dandy right
 
OK so going back to the letter analogy @Jimbo: sending a letter would be a blocking operation if after you had done it, they made you wait in the post office until the got the response
 
So saying yield allows me to continue doing what I want, until the operation has finished and the CB is executed (as in, I say, thanks, I'm going to do something with your letter back now)
 
Kinda noisying up #11 with this
 
Yeah
> So saying yield allows me to continue doing what I want, until the operation has finished and the CB is executed (as in, I say, thanks, I'm going to do something with your letter back now)
 
10:58 AM
39 messages moved from PHP
1 message moved from PHP
 
need to go now, But I'll read this up later to give feedback about Daves suggestions…
 
@Jimbo yield is basically like writing something down in your calendar
It's saying "I'll come back to this when I can do something else with it"
When you send that letter:
$response = yield $postOffice->send($letter);
The yield there is basically saying "when the response arrives, put it into $response and the progress, until then you can go do something else"
 
Okay, so we write that line of code, what confuses me is how that's picked up and stored (?) in "things to process" or "watchForIoFrom"
Why isn't it $eventLoop->addThingToBeProcessed(yield $postOffice->send($letter)); or something
 
@Jimbo because yield is more like return
Think about how a regular generator works
moment
So in that code, $i is being echoed, but the generator doesn't know that
 
Yep, same as return there right, except.. something about not storing everything in memory or something?
 
11:06 AM
The function is returning a value without ending execution, it's just pausing execution
But it is the caller of the function that needs to worry about what to do with the value that is emitted
So you don't need to do this:
3 mins ago, by Jimbo
Why isn't it $eventLoop->addThingToBeProcessed(yield $postOffice->send($letter)); or something
because it is the event loop that is calling the generator
 
Okay, so the event loop is calling gen(). gen() yields. I get that bit so far..
 
@Jimbo Write a coroutine and use debug_print_backtrace() to see who's calling the coroutine.
 
@Jimbo OK, now consider this code (moment)
So by using Generator::send(), the caller is able to send a value back in to the generator
 
@Jimbo Right, Coroutine then calls onResolve on the returned promise. To resolve the promise, there will be event handler form the loop that will be called and finally resolve the Deferred this promise is linked to. That then calls all onResolve callbacks and continues the coroutine.
 
brb 5 min
OK right
So do you follow what Generator::send() is doing @Jimbo?
 
11:20 AM
@DaveRandom Mhmm, no. I'm still messing with it
 
@Jimbo have you ever written a custom Iterator implementation?
 
Nah
 
damn
 
I'm guessing this is a prerequisite? :P
 
No but if you have a good understanding of how Iterator works it might be easier to understand what Generator::send() does
at the end of the day, generators are just syntactic sugar for iterators
(although send() is unique to generators, you could easily implement it manually with an iterator)
OK leaving that aside for a moment, do you understand what that pseudo-code loop is doing and why it does it like that, in that order?
Because that is a pre-requisite to understanding how generators work in the context of async
 
11:27 AM
Okay one sec, maybe
So..
 
remember that generators are not required in order to use an event loop, they are just sugar
 
It makes the output iteratable ?
the output of the for loop
?
I don't get the send bit though
Maybe that's completely bollocks
Is $i += yield $i; really the simplest example?
 
No the loop has no "output" as such, it's at a much lower level than the generators
forget about the generators for now, just pretend it doesn't exist
 
lol
Okay
 
The loop itself is just invoking callbacks
I have an idea
do you have paid github?
in fact fuck it
give me a minute
 
Wes
11:32 AM
i thought id find sexy pictures of both of you here
4
how disappointing
 
You have a github collab invite @Jimbo
 
I'm in
 
k, give me 10 mins
 
@DaveRandom Need a private repo?
 
No I just made it public
Also it seems github have sorted their shit out and I now have a working paid account again anyway
plus I use bitbucket for private stuff a lot anyway
 
11:37 AM
I think GitHub is unlimited private repos now anyway, right?
 
yeh, but when they made that change I had a disagreement with them over my account (they screwed up the billing when they made the change)
no big deal, but I just didn't have private repos for a while
hadn't checked for ages
 
I have them for free anyway :D
 
oh maybe I do then
not check whether they have actually billed me :-P
 
(Because student) :P
 
incoherent muttering about bloody students
 
11:49 AM
Oh, and once I'm no student anymore, I'll ask them to apply my 6 months from the security bug bounty which I haven't received yet, as I always had the student membership. :D
 
Do I need to check anything out or something?
 
OK @Jimbo clone that and dissect it
That is a very very simple (and deliberately inefficient for simplicity) event loop
it just does timers, it doesn't do I/O, we'll move on to that when you have looked at the it
You will notice, in particular, that Loop::run() has the exact same structure as that pseudo-code loop
Repo link for anyone else who is interested
brb 10 mins @Jimbo
 
12:23 PM
Okay I'm just checking it out now
 
the main thing to note is that the code doesn't actually do anything until you call Loop::run() @Jimbo, and Loop::run() blocks until everything has executed. So that effectively becomes the entry point of the program itself.
before that point, all you are doing is registering things that will happen at some point in the future.
The I/O stuff can be bolted on without modifying any of that code apart from run()
which I am doing now
 
Okay, so.. the loop is calculating as time goes on whether or not something needs to be executed
So, scheduling
 
Yes, exactly. It's just managing when things need to happen.
The only difference between that and one that manages I/O as well is that at the point where usleep() is, it will instead wait for something to happen on one (or more) of the registered streams
 
But if it waits, it blocks?
Or does it just poll it
 
12:39 PM
Well "polling" is waiting/blocking
It's waiting until there is something to do
 
I understood polling in this case would be if (stream has something) then use it else continue
 
Well yes that does describe a poll
but in this case, we know there is nothing else useful to do until either there is some activity on a stream or the timeout expires
so we block until one of those things happens
 
So checking for activity on a stream is okay?
Even if we wait and block everyone else?
Why don't we just check, if nothing, continue then come back to it afterwards and try again?
 
It's not a case of blocking everyone else, we know that there is nothing else to do
 
Ah, that's only because we've specified in this case 1000, 2000 etc
right?
 
12:42 PM
yes, we calculated the next time we would need to do something
 
When you make a http request, you don't state how long it'll take...
 
wait a minute, let me finish writing this
 
If you push it could you do it in another branch so I can see the progression?
 
@Jimbo you can just diff the commits...?
 
Tsch, fine
 
12:48 PM
:-P
 
@DaveRandom Have fun turning that into a blog series :P
 
It should be, but from the mind of a retard <me>
 
let's see how successful it is first :-P
 
@Jimbo The difference is that it's the scheduler that blocks once for all streams, not every stream operation blocking.
 
I don't understand that sentence :P Try to be less, technically concise? :D
 
1:01 PM
And the stream_select will stop blocking once something on any stream happens, not on one stream.
 
Ah, there are multiple streams...
I didn't get this
 
There can be
 
Oh wait, yeah I did. So there's one stream per operation?
 
There can be, yes.
 
@Jimbo A "stream" is a file descriptor or a network socket
 
1:02 PM
There's no other types?
 
So for each open file or open network socket in the application, you register a "watcher"
@Jimbo There might be, but none that you need to worry about right now (read: none that I have ever done anything with ever)
 
So the example we have right now is just executing something that immediately runs. Except the running of it is blocking. So when we actually run something, we need to... "put it into a stream" (for lack of a better understanding) then watch it for it's response?
Or something something
 
Well it depends what the application is doing. If the application only needs to do something every second (e.g. updating a clock in a GUI) then you don't need to do anything else at all.
The point of the event loop is the entire application is running within it
 
I'm gonna go grab a sandwich and some pills, but I get what we're doing right now, not how we'll register things that need to be done but take an indeterminate amount of time using these stream things
 
I should be done with this in a few minutes, I'm just debugging it
 
1:23 PM
pushed @Jimbo (and @kelunik if you are interested)
Something notable about it now is that even with that super-simple example we are starting to see callback hell with the stream processing code, even though it isn't really even doing anything
so next we'll look at a few ways to rewrite the example code. We don't need to touch the event loop for a while now, possibly never again
obviously the event loop leaves a lot to be desired - it's not very efficient because it iterates potentially very large arrays a lot of times, and it currently has no way to cancel a setTimeout(). Those are ways in which it can be improved, but that will make the code a lot more complex and it won't fundamentally change the way it works, so we're ignoring that stuff for now because we aren't trying to build a real-world application.
@Jimbo @kelunik I'm about to rewrite history, sorry :-/
OK done, force pull if you had already pulled
 
1:45 PM
@DaveRandom Any pull will force pull.
 
will it? I didn't think that was true, you'll get a merge conflict?
 
@DaveRandom Only if you have changes I think.
 
meh, would have to test
I just modified the example so that it used several remote servers to increase the chances that things will happen in a different order to the way they were written, to demonstrate that it actually is async
when you send google.com 5 requests in a row, they tend to respond in the same order
 
2:03 PM
Ok am back
Do we monitor all streams at once?
 
Yes
 
Ah nice, and activity on any triggers a callback?
 
You only ever have one loop instance (it is effectively the runtime) and you register all streams with that loop
@Jimbo yes
OK so there are now 2 more commits, but don't look at them until you are ready
or well, let me know when you are ready to move on and I will explain them first
 
2:21 PM
Okay so
Only once the stream is writeable and the callback is being executed for it do we add a read one in
That's where the callback hell is starting?
The TCP client I just accept is 'magic' in that it can do async
Okay I think I get it
 
@Jimbo "callback hell" is a result of the fact that you can't register the next callback until the previous one completes
we couldn't register that onReadable() callback until we'd done the write
then if you have some other action to perform after the read, you'd end up with another nested layer, and the code swiftly become impossible to follow
 
Yep exactly
I saw that, okay
 
@Jimbo The TCP client is just a socket, nothing particularly special about it
 
Except it has this magic flag that makes it async
 
that tcp_client() function is only there to remove boilerplate
@Jimbo OK so how well do you understand TCP?
 
2:33 PM
Hello would you like to hear a TCP joke? Also - no, nothing.
 
:-P
 
But I guess that's not necessary for this example
 
@Jimbo it's necessary to understand what the ASYNC_CONNECT flag is doing
and it's not particularly difficult
So when a TCP connection is being initiated, the client sends a SYN (synchronisation) packet to the server
the server then responds with a SYN/ACK (synchronisation/acknowledgment) packet
when you call stream_socket_client() without the ASYNC_CONNECT flag, it blocks until it receives the response packet from the server
when you pass that flag, the client just sends the SYN packet and then returns immediately
after that, when the client's OS has received the SYN/ACK from the server, the socket will become writable
hence the reason that code creates the client socket, then watches for writability
 
2:52 PM
Ah, I see
Pretty simple
 
OK so if you look at the next 2 commits, the first one is just creating some function primitives. We do this because the loop is effectively the runtime, it doesn't make sense to have more than one instance, and it needs to be globally accessible.
 
Okay so you expose them globally yep
 
The second commit is just rewriting the 2nd example to use those primitives
 
Do we have to do this?
 
@Jimbo no, you can still DI everything if you want, but it makes the code messier and is actually unnecessary
 
2:56 PM
Ok
 
I know it goes against everything that one holds dear in terms of good OOP practice, but when you are writing an application you shouldn't be thinking about how the loop works
 
So that custom DB implementation that (was it PeeHaa who wrote it) works async, that's just calling MySQL over TCP?
 
You mean amp/mysql?
 
Yep
Or even in this implementation
That's how we could code it?
 
That's a mysql protocol implementation written in PHP
it's a layer higher up than the loop
OK so I added another example @Jimbo which is just another way of writing that code without the nested callbacks
 
3:06 PM
Nice, I get it
 
It still hasn't fundamentally changed, it's just restructured to be a little bit more readable, but it's still not great
So next we're going to introduce promises, which will initially look like a step backwards
 
3:34 PM
Totally unrelated, but I maybe just found a way to pass data back into the running event loop via SI_QUEUE, perhaps
Supported in PHP as of 5.3
Ah, but enabling PCNTL is slow because of the polling, nvm
 
OK @Jimbo so I added a promise/promisor example. That is going to look like a shit mess at first, and it is not going to look like progress, but it's a means to an end
@Jimbo signalling is also doable, I've ignored that for now because it would make the loop quite a lot more complex
It's also not that useful most of the time, you generally only use that for administrative operations (telling your program to exit/restart/reload config etc)
 
yep yep, it'd be a bit of a hack really
 
If you want to pass data around, you use sockets
This can be a unix domain socket though, it doesn't need to hit the network
You can also use stdio for a child process (this is effectively a file descriptor, and the loop handles it in the same way)
I'm going home but I will be back in a bit
I'm certain you will have a lot of questions about the promises thing because it look confusing and horrid
bbiab
 
Well, yeah. Brain deadded
You just wrote a deferred promise implementation and broke my brain
I think we should take a break for now maybe? :D
 
4:16 PM
@Jimbo re signals: signals will just interrupt the select(2) syscall and we can then do a simple signal dispatch after the stream_select() returns, i.e. we just pcntl_signal_dispatch(), which will call our registered callbacks and we are done.
 
 
2 hours later…
5:58 PM
Okay so back to streams
Let's say we've done 2 requests. We don't get to the point where we check the stream and then block, do we?
Or we do... and we block because we're checking both streams at once
And what if only one stream returns, we just execute the callback for the first one, and then re-go-around and do the second one?
Please say this is the case, because if so I think my understanding upped a bit. If not, fuck
 
@Jimbo Then we continue the while loop and stream_select on both streams again
 
No because the first stream will be done
 
Unless the first one is finished and unregistered
 
Excellent :)
Okay I get it, so it's okay to block because we're blocking on everything
There's nothing else that needs to happen while we wait for anything to come back
Hmm, actually... we can't subscribe to new streams during this time
 
If we wouldn't block there, we'd run at 100% CPU.
 
6:07 PM
Ah, and this is blocking IO
amiright
 
@Jimbo Hm?
@Jimbo To subscribe to a new stream, something has to subscribe to it. As nothing is ready to execute, there can't be anything that wants to subscribe to a new stream
 
Okay so stream_select, while it's waiting for something to come back on a stream, we want to do something else... like, add a new stream to be polled
Okay I'm jumping too far ahead with dynamically added events
 
@Jimbo Where does the new stream come from?
 
Client wants to subscribe to result of stream
 
@Jimbo When some code is currently running, we're not currently blocking in stream_select
If it's a timer, then stream_select might have timed out and the timer is executed and can subscribe. If it's a new connection, stream_select will return and execute the readable event handler of the server socket.
 
6:14 PM
5 hours ago, by kelunik
And the stream_select will stop blocking once something on any stream happens, not on one stream.
So at one point it was blocking, and that's the time that I'm talking about for when we can't do anything else
But, I think I get it
It's okay because there's nothing else to do, or something..
 
@Jimbo That or something indicates we're not quite there yet :D
 
@kelunik Say we have two streams. One's TCP, one's a file descriptor
The file descriptor - we have to wait until we get something back. But from what I remember from our discussions today, the TCP one returns instantly
w/ the async flag
I have a question revolving somewhere around that
Because I get the file descriptor bit - we block on that stream
 
@Jimbo Usually you shouldn't do that, because it blocks everything.
 
@Jimbo local files are, for the purposes of this exercise, instant
 
But if we're blocking by using stream select, what's the point of using that and not just a file get contents or something? Just so we're to polling?
Is it just so we have a file watcher for change?
 
6:22 PM
real non-blocking filesystem I/O is a huge pita, but that is because of OS-level limitations, nothing we can do about that
@Jimbo the default implementation of amp/file uses blocking I/O
 
@DaveRandom Which is what we've got here right?
 
libuv has some non-blocking implementations which are used if available (I think?)
 
@DaveRandom Yes. And we have a parallel driver to avoid blocking even without uv.
 
@Jimbo yes, like I said for the purposes of this exercise, file-system I/O is instant
 
Okay
As for network... we have the async thing. If it returns instantly...
We don't block with stream select?
 
6:25 PM
filesystem stuff is a rabbit hole you really don't want to start down...
@Jimbo A file descriptor, from the point of view of select(), is always readable and always writable
i.e. select() will always return instantly if you give it a local file descriptor in any of the fd sets
It's still a valid thing to do, it's just that OS lies to you a bit
not much though, tbh especially if you have SSDs it may as well actually be instant
@Jimbo you know how I was saying people mix up "async" and "non-blocking" a lot, as if they are interchangeable?
STREAM_CLIENT_ASYNC_CONNECT is a good example of that
it would be more accurately named STREAM_CLIENT_NONBLOCKING_CONNECT
 
If it returns instantly though, how do we know the difference between an instant return and 'we actually have the data now'?
To invoke the callback with
 
@Jimbo that's why you watch for writability
when the connection is fully established, the socket becomes writable
 
Ah, I forgot we watch for both read and write
Oh okay
 
yes, in general you watch a socket for readability constantly, but you only watch it for writability when you actually need to
that's because, fairly obviously, you need to be prepared to recieve data at any time because you have no control over that, but you know when you are sending
 
And because this is a stream we're dealing with, and we get streaming data, we apply the callback every time the data is written on it?
 
6:35 PM
Well the callback is only a notification handler, effectively. So in the case of onReadable() the callback is invoked every time there is some data available to read from the socket
you'll notice that the loop itself never performs any actual read/write operations
it only watches them for the requested status
It's the responsibility of the consuming code to deal with actually performing open/close/read/write operations
brb 5 min
OK are you ready to move on to generators yet @Jimbo? :-P
 
Lol
Right now I'm looking over my slides for my talk for tomorrow, and removing all the stuff about IPC a buffer filling for event loops because it's nothing like that in PHP
Well, it is, sort of, but very abstract
 
The thing to remember is the word "event", i.e. only doing something when there is something to do.
Like, if you go back to example #1, if you told those callbacks to run after 1,2,3,4,5 milliseconds, they wouldn't actually all run at the exact times you specified, because they will most likely take longer than 1ms to execute
 
Of course
 
6:51 PM
Whenever you see a timeout in a single-threaded async application, it's more an expression of desire than a rule, you are saying "I'd like to run this as close as possible to, but not before, this timeout expires"
In reality though that doesn't matter for real world applications, things will generally run within a few milliseconds of precision
 

  last day (31 days later) »