moonbridge

view reference.txt @ 151:1939ffe973e0

Improved Lua reference code for moonbridge_io.run(...)
author jbe
date Fri May 08 03:35:32 2015 +0200 (2015-05-08)
parents b0e2fbf9d5a8
children 2a5bd37034c6
line source
2 Moonbridge reference
3 ====================
7 Global function listen{...}
8 ---------------------------
10 This function initializes the Moonbridge Network Server. It may be called
11 multiple times. However, it is not allowed to register additional listeners by
12 calling listen(...) from a "prepare", "connect", or "finish" handler.
14 See file "example.lua" for parametrization of the listen(...) function.
16 Warning: Moonbridge will fork the Lua environment to handle parallel requests.
17 Functions provided as "prepare", "connect", and "finish" handlers may access
18 global variables, but for every child process these global variables will not
19 be shared! If you require a global state, a DBMS, cache server, or similar is
20 necessary.
24 Global function timeout(...)
25 ----------------------------
27 Calling this function with a positive number (time in seconds) sets a timer
28 that kills the current process after the selected time runs out. The remaining
29 time can be queried by calling this function without arguments.
31 Calling this function with a single argument that is the number zero will
32 disable the timeout.
34 Another mode of operation is selected by passing two arguments: a time (in
35 seconds) as first argument and a function as second argument. In this case, a
36 sub-timer will be used to limit the execution time of the function. In case of
37 timeout, the process will be killed (and the timeout function does not return).
38 If the time for the sub-timer is longer than a previously set timeout (using
39 the timeout(...) function with one argument), the shorter timeout (of the
40 previous call of timeout(...)) will have precedence.
42 Timers are also automatically reset (disabled) when a handler (prepare handler
43 or connect handler) returns. To shutdown processes after a certain time waiting
44 for a new request, use the idle_time parameter of the listen function.
48 Socket object passed to "connect" handler
49 -----------------------------------------
51 For every incoming connection, the registered "connect" handler is called with
52 a single socket object as argument, which is described below:
55 ### socket:close()
57 Closes the socket connection (input and output stream) by flushing all data and
58 sending a TCP FIN packet.
60 Returns true on success, or nil plus error message in case of an I/O error.
61 Using this method on sockets that have already been closed (or reset) will
62 throw an error.
64 Warning: Pending data on the input stream may cause connection aborts (TCP RST)
65 when network connections are used. All pending input data should have been read
66 (or drained) before calling socket:close(). Use socket:finish() to send a
67 TCP FIN packet to the peer before waiting for EOF from the peer.
70 ### socket:drain(maxlen, terminator)
72 Same as socket:read(maxlen, terminator), but discards the input and returns the
73 number of discarded bytes (as first return value) and the status code ("term",
74 "maxlen", "eof" as second return value).
76 In case of an I/O error, nil (as first return value) plus an error message (as
77 second return value) are returned.
80 ### socket:drain_call(waitfunc, maxlen, terminator)
82 Same as socket:drain(maxlen, terminator), but calls waitfunc(socket, "r") (in
83 an infinite loop) as long as the reading is blocked.
86 ### socket:drain_nb(maxlen, terminator)
88 Same as socket:drain(maxlen, terminator), but non-blocking. The status code
89 (which is returned as second return value) may therefore be "term", "maxlen",
90 "eof", or "block".
92 In case of an I/O error, nil (as first return value) plus an error message (as
93 second return value) are returned.
96 ### socket:drain_yield(maxlen, terminator)
98 Alias for socket:drain_call(coroutine.yield, maxlen, terminator)
101 ### socket:finish()
103 Sends a TCP FIN packet to indicate EOF on write stream. Subsequent reads are
104 still possible. When there is no more input data to be read, the connection
105 should finally be closed with socket:close().
107 In case of local sockets (Unix Domain Sockets), socket:finish() simply closes
108 the underlying socket and emulates EOF on subsequent reads. Also in this case,
109 the connection should be finally closed with socket:close().
112 ### socket:flush(...)
114 Same as socket:write(...) but additionally flushes the socket (i.e. all pending
115 data is passed to the operating system).
117 In case of an I/O error, nil (as first return value) plus an error message (as
118 second return value) are returned. On success, the socket userdata object is
119 returned.
122 ### socket:flush_call(waitfunc, ...)
124 Same as socket:flush(...), but calls waitfunc(socket, "w") (in an infinite
125 loop) as long as the writing is blocked.
128 ### socket:flush_nb(...)
130 Same as socket:write_nb(...) but additionally flushes the socket (i.e. all
131 pending data is passed to the operating system). The total number of bytes that
132 could not be passed yet to the operating system is returned. Zero is returned
133 if all data could be flushed out.
135 In case of an I/O error, nil (as first return value) plus an error message (as
136 second return value) are returned.
139 ### socket:flush_yield(...)
141 Alias for socket:flush_call(coroutine.yield, ...)
144 ### socket.interval
146 Set to the name of an interval timer if the "connect" handler was called due to
147 an elapsed interval timer. Otherwise nil.
150 ### socket.local_ip4
152 Local IPv4 address used for the connection. Encoded as 4 raw bytes in form of a
153 string.
156 ### socket.local_ip6
158 Local IPv6 address used for the connection. Encoded as 16 raw bytes in form of
159 a string.
162 ### socket.local_tcpport
164 Local TCP port used for the connection.
167 ### socket:read(maxlen, terminator)
169 Reads up to maxlen bytes or until an optional termination character is
170 encountered (which is included in the result). The maxlen value may be nil, in
171 which case there is no limit on the number of bytes read.
173 In case of an I/O error, nil (as first return value) plus an error message (as
174 second return value) are returned.
176 In all other cases (including EOF), the following two values are returned:
178 - a string containing the bytes read (first return value, may be empty string)
179 - a status code equal to "term", "maxlen", or "eof" (second return value)
181 If an EOF is encountered before all data could be read, then "eof" is returned
182 as second return value. If maxlen bytes have been read and no termination
183 character has been read, then "maxlen" is returned as second return value. If
184 the termination character is the last character of the read string, the second
185 return value will be "term".
188 ### socket:read_call(waitfunc, maxlen, terminator)
190 Same as socket:read(maxlen, terminator), but calls waitfunc(
191 moonbridge_io.block, socket, "r") (in an infinite loop) as long as the reading
192 is blocked.
195 ### socket:read_nb(maxlen, terminator)
197 Same as socket:read(maxlen, terminator), but does not block.
199 In case of an I/O error, nil (as first return value) plus an error message (as
200 second return value) are returned.
202 In all other cases (including EOF), the following two values are returned:
204 - a string containing the bytes read (first return value, may be empty string)
205 - a status code equal to "term", "maxlen", "eof", "block" (second return value)
207 The status code "block" as second return value is used if the function returned
208 prematurely because it would block otherwise. In this case, the first return
209 value is a string that contains the bytes that could be read without blocking.
212 ### socket:read_yield(maxlen, terminator)
214 Alias for socket:read_call(coroutine.yield, maxlen, terminator)
217 ### socket.remote_ip4
219 Remote IPv4 address used for the connection. Encoded as 4 raw bytes in form of
220 a string.
223 ### socket.remote_ip6
225 Remote IPv6 address used for the connection. Encoded as 16 raw bytes in form of
226 a string.
229 ### socket.remote_tcpport
231 Remote TCP port used for the connection.
234 ### socket:reset()
236 Alias for socket:close(0). Closes the socket connection by sending a TCP RST
237 packet if possible to indicate error condition.
239 Returns true on success, or nil (as first return value) plus error message (as
240 second return value) in case of an I/O error. Using this method on sockets that
241 have already been closed (or reset) will throw an error.
243 Warning: Previously sent (and flushed) data may be lost during transmission.
246 ### socket:write(...)
248 Takes a variable number of strings and sends them to the peer. The operation is
249 buffered, so to actually send out the data, it is necessary to eventually call
250 socket:flush(), socket:finish(), or socket:close().
252 In case of an I/O error, nil (as first return value) plus an error message (as
253 second return value) are returned. On success, the socket userdata object is
254 returned.
257 ### socket:write_call(waitfunc, ...)
259 Same as socket:write(...), but calls waitfunc(moonbridge_io.block, socket,
260 "w") (in an infinite loop) as long as the writing is blocked.
263 ### socket:write_nb(...)
265 Takes a variable number of strings and sends them to the peer. The operation is
266 buffered, so to actually send out the data, it is necessary to eventually call
267 socket:flush_nb(), socket:flush(), socket:finish(), or socket:close().
269 This function always returns immediately (i.e. it does not block). If all data
270 (but a small buffered portion) could be sent out, then zero is returned.
271 Otherwise, all arguments that could not be sent are stored in a buffer of
272 unlimited size (up to memory capabilities) and an integer is returned that
273 indicates the number of bytes currently in the buffer.
275 In case of an I/O error, nil (as first return value) plus an error message (as
276 second return value) are returned.
279 ### socket:write_yield(...)
281 Alias for socket:write_call(coroutine.yield, ...)
285 I/O library
286 -----------
288 The Moonbridge Network Server for Lua Applications comes with its own I/O
289 library to support blocking as well as nonblocking I/O operations.
291 All methods on an I/O handle (e.g. socket) are described in the previous
292 section regarding the "socket" object. All other functions of the library are
293 listed below.
296 ### moonbridge_io.block
298 An opaque value (lightuserdata) used by yielding non-blocking I/O functions.
300 When socket:read_yield(...) could not read from a socket, it yields the three
301 values moonbridge_io.block, the socket, and the string "r".
302 When socket:write_yield(...) could not write to a socket, it yields the three
303 values moonbridge_io.block, the socket, and the string "w".
305 See reference for moonbridge_io.run(...) for further information.
308 ### moonbridge_io.localconnect(path)
310 Tries to connect to a local socket (also known as Unix Domain Socket). Returns
311 a socket object on success, or nil (as first return value) plus an error
312 message (as second return value) in case of error.
315 ### moonbridge_io.localconnect_nb(path)
317 Tries to connect to a local socket (also known as Unix Domain Socket). Returns
318 a socket object on success, or nil (as first return value) plus an error
319 message (as second return value) in case of error.
321 Same as moonbridge_io.localconnect(path), except that this function does not
322 block and immediately returns a socket object.
324 In case of an I/O error, nil (as first return value) plus an error message (as
325 second return value) may be returned. However, connection errors may also be
326 reported on first read or write on the socket.
329 ### moonbridge_io.locallisten(path)
331 Attempts to create a local socket (also known as Unix Domain Socket) to accept
332 incoming connections. If the file does already exist and is a socket, then it
333 is deleted automatically before being re-created.
335 In case of an I/O error, nil (as first return value) plus an error message (as
336 second return value) may be returned.On success, a listener object is returned
337 which supports the methods :accept(), :accept_nb(), and :close().
339 The method :accept() blocks until a new incoming connection is available in
340 which case a socket object is returned.
342 The method :accept_nb() works like :accept(), except that the call is
343 nonblocking and returns false (plus a notice as second return value) in case no
344 incoming connection is available. It is possible to wait for an incoming
345 connection by including the listener object in the input_set of the
346 moonbridge_io.poll(...) call.
348 The method :close() will close the listening socket. In case of local sockets
349 (Unix Domain Sockets), the socket will not be unlinked in the file system.
351 I/O errors by the methods of the listener object are also reported by returning
352 nil (as first return value) plus an error message (as second return value).
355 ### moonbridge_io.multiblock
357 An opaque value (lightuserdata) used by yielding non-blocking I/O functions.
358 See reference for moonbridge_io.run(...) for further information.
361 ### moonbridge_io.poll(input_set, output_set, timeout)
363 This function waits for at least one of the given file descriptors and/or
364 I/O handles to be ready for input or output. The two sets of file descriptors
365 and/or handles must contain the file descriptor or handle as a key, and a value
366 which does evaluate to true. If a set is nil, it is treated as being empty.
368 Returns true when at least one file descriptor or handle is ready for reading
369 or writing respectively. Returns false (as first return value) plus a status
370 message (as second return value) in case of timeout or when a signal was
371 received.
374 ### moonbridge_io.run(function_set, timeout_or_poll_func)
376 Executes multiple coroutines (created via coroutine.wrap(...)) in the following
377 way:
379 function moonbridge_io.run(function_set, timeout_or_poll_func)
380 local pairs = function(t) return next, t end -- raw pairs
381 local starttime = moonbridge_io.timeref()
382 local read_fds, write_fds = {}, {}
383 while true do
384 local work_to_do = false
385 for func, result_handler in pairs(function_set) do
386 ::again::
387 local res = table.pack(func())
388 if res[1] == moonbridge_io.block then
389 if string.match(res[3], "r") then
390 read_fds[res[2]] = true
391 end
392 if string.match(res[3], "w") then
393 write_fds[res[2]] = true
394 end
395 work_to_do = true
396 elseif res[1] == moonbridge_io.multiblock then
397 for fd, active in pairs(res[2]) do
398 if active then read_fds[fd] = true end
399 end
400 for fd, active in pairs(res[3]) do
401 if active then write_fds[fd] = true end
402 end
403 work_to_do = true
404 else
405 if
406 result_handler == true or
407 result_handler(table.unpack(res, 1, res.n))
408 then
409 function_set[func] = nil -- task finished
410 else
411 goto again
412 end
413 end
414 end
415 if not work_to_do then
416 return true -- all tasks finished
417 end
418 if type(timeout_or_poll_func) == "function" then
419 local poll_func = timeout_or_poll_func
420 if
421 poll_func(moonbridge_io.multiblock, read_fds, write_fds) == false
422 then
423 return false
424 end
425 elseif type(timeout_or_poll_func) == "number" then
426 local timeout = timeout_or_poll_func
427 if
428 moonbridge_io.poll(
429 read_fds,
430 write_fds,
431 timeout - moonbridge_io.timeref(starttime)
432 ) == false
433 then
434 return false -- timeout
435 end
436 else
437 moonbridge_io.poll(read_fds, write_fds)
438 end
439 for fd in pairs(read_fds) do read_fds[fd] = nil end
440 for fd in pairs(write_fds) do write_fds[fd] = nil end
441 end
442 end
445 ### moonbridge_io.tcpconnect(hostname, port)
447 Tries to open a TCP connection with the given host and TCP port number. Returns
448 a socket object on success, or nil (as first return value) plus an error
449 message (as second return value) in case of error.
452 ### moonbridge_io.tcpconnect_nb(hostname, port)
454 Same as moonbridge_io.tcpconnect(hostname, port), except that this function
455 does not block and immediately returns a socket object.
457 Note: The current implementation still blocks during the DNS lookup. Use a
458 numeric IP address as hostname to be truly nonblocking.
460 In case of an I/O error, nil (as first return value) plus an error message (as
461 second return value) may be returned. However, connection errors may also be
462 reported on first read or write on the socket.
465 ### moonbridge_io.tcplisten(hostname, port)
467 Attempts to open a TCP port for listening. To listen on the loopback interface,
468 use "::1" as hostname if IPv6 shall be used, or use "127.0.0.1" as hostname if
469 IPv4 shall be used. To listen on all available interfaces, use "::" (IPv6) or
470 "0.0.0.0" (IPv4) respectively.
472 In case of an I/O error, nil (as first return value) plus an error message (as
473 second return value) may be returned. On success, a listener object is returned
474 which supports the methods :accept(), :accept_nb(), and :close(). See reference
475 for moonbridge.io_locallisten(...).
479 HTTP module
480 -----------
482 The http module exports the function http.generate_handler(callback) that
483 converts an HTTP handler to a "connect" handler. See file "example.lua" for an
484 example of invocation. A table with options may be passed either as a second
485 argument, or as a first argument preceeding the callback function (whichever is
486 more convenient).
488 The following options are supported:
490 - request_body_size_limit: maximum size of payload of HTTP request body
491 (transfer encoding is allowed to add a limited amount of extra data)
492 - chunk_size: optional default value for maximum_input_chunk_size and
493 minimum_output_chunk_size
494 - request_header_size_limit: maximum size of HTTP request headers
495 - maximum_input_chunk_size: maximum chunk size when streaming a request body or
496 certain POST fields (bigger chunks will be fragmented automatically)
497 - minimum_output_chunk_size: minimum size for a chunk when sending a response
498 body (smaller chunks will be buffered and concatenated with future data;
499 ignored when request:flush() is called)
500 - static_headers: a set of headers to be included in every HTTP response
501 (may be a string, a table or strings, or a table of key-value pairs)
503 The callback function receives a single request object as argument, which is
504 described below.
507 ### request.body
509 The request body (without headers) as a string. Accessing this value makes
510 further access to request.post_params and request.post_params_list, or
511 invocation of request:stream_request_body(...) impossible.
514 ### request:close_after_finish()
516 Closes the connection after answering the request.
518 This method can only be called before the HTTP response header section has been
519 finished (i.e. before request:finish_headers(), request:send_data(...), or
520 request:finish() were called), but it may be called before a status code has
521 been sent using request:send_status(...).
523 A corresponding "Connection: close" header is automatically sent.
526 ### request.cookies
528 A table with all cookies sent by the client.
531 ### request.defer_reading()
533 Disables automatic request body processing on write. Can be called before
534 sending a HTTP status code to send a response before the request has been fully
535 received.
537 CAUTION: Responding to a request before the request body has been processed may
538 lead to a deadlock if the browser does not process the response while trying to
539 send the request. Therefore, this function should only be used if:
541 - the TCP stack has enough buffer space for the response (i.e. if the response
542 is small enough), and if
543 - a timer is used to cancel the response in case of a deadlock.
545 It is recommended to not use this function unless certain performance tweaks
546 are desired.
549 ### request.faulty
551 Normally set to false. In case of a read or write error on the client
552 connection, this value is set to true before a Lua error is raised.
554 A faulty request handle must not be used, or another Lua error will be raised.
557 ### request:finish()
559 Finishes and flushes a HTTP response. May be called multiple times. An
560 HTTP status, all headers, and the response body (if applicable) must have been
561 previously sent. After calling this method, no further data may be written.
564 ### request:finish_headers()
566 Finishes and flushes the HTTP response header section. May be called multiple
567 times, as long as the request is not finished completely. This method is
568 automatically invoked if the application is beginning to send a response body.
569 After calling this method, no further headers may be sent.
572 ### request:flush()
574 Flushes any pending output data. Note: In order to mark the end of a response
575 body, it is required to call request:finish().
578 ### request.get_params
580 A table that maps field names to their corresponding GET value. If there are
581 several GET values with the given field name, then the first value is used.
583 Note: May be implemented through metamethods, but does support iteration
584 through pairs(...).
587 ### request.get_params_list
589 A table that maps field names to a sequence of their corresponding GET values.
591 Note: May be implemented through metamethods, but does support iteration
592 through pairs(...).
595 ### request.headers
597 A table that maps (case-insensitively) a HTTP header field name to a sequence
598 of values. One entry is created for every occurrence of a header line with the
599 given field name).
602 ### request.headers_csv_string
604 A table that maps (case-insensitively) a HTTP header field name to a comma
605 separated string. Multiple occurrences of the header with the given field name
606 are automatically merged into the comma separated string.
609 ### request.headers_csv_table
611 A table that maps (case-insensitively) a HTTP header field name to a sequence
612 of values. One entry is created for every comma separated value of each header
613 with the given field name.
616 ### request.headers_flags
618 A table that maps (case-insensitively) a HTTP header field name to another
619 table which (again case-insensitively) maps a string to a boolean, depending on
620 whether this string occurred in the list of comma separated values of one
621 header line with the given field name that was the key in the first table.
624 ### request.headers_value
626 A table that maps (case-insensitively) a HTTP header field name to a value. If
627 multiple header lines with the given field name have been received, false is
628 used as value.
631 ### request.method
633 The HTTP request method, e.g. "HEAD", "GET", or "POST".
636 ### request.path
638 The requested path without a leading slash and without the query part (e.g.
639 "index.html" if "/index.html?a=b&c=d" has been requested). For the query part,
640 see request.query.
642 This value will be nil if (and only if) the request method is "OPTIONS" with a
643 request target equal to "*" (see also asterisk-form of request-target in
644 section 5.3.4 in RFC 7230).
647 ### request.post_metadata
649 Only set for multipart/form-data POST requests. A table that maps field names
650 to their corresponding POST metadata table which contains two entries:
651 "file_name" and "content_type". If there are several POST values with the given
652 field name, then the first value/file is used.
655 ### request.post_metadata_list
657 Only set for multipart/form-data POST requests. A table that maps field names
658 to a sequence with their corresponding POST metadata tables. Needed if multiple
659 files are uploaded with the same field name.
662 ### request.post_params
664 A table that maps field names to their corresponding POST value. If there are
665 several POST values with the given field name, then the first value is used.
667 Note: May be implemented through metamethods, but does support iteration
668 through pairs(...).
671 ### request.post_params_list
673 A table that maps field names to a sequence of their corresponding POST values.
675 Note: May be implemented through metamethods, but does support iteration
676 through pairs(...).
679 ### request.query
681 Query part of the request target including the leading question mark, e.g.
682 "?a=b&c=d" if the requested target is "/index.html?a=b&c=d". The data is
683 automatically parsed and made available through request.get_params and
684 request.get_params_list.
686 If there is no query part given in the request target, then this string is
687 the empty string. This value will be nil if (and only if) the request method
688 is "OPTIONS" with a request target equal to "*" (see also asterisk-form of
689 request-target in section 5.3.4 in RFC 7230).
692 ### request:process_request_body()
694 Starts processing the request body (if existent) to set the values
695 request.post_params, request.post_params_list, request.post_metadata, and
696 and request.post_metadata_list and/or to call POST field stream handlers that
697 have been previously registered with request:stream_post_param(...) or
698 request:stream_post_params(...).
700 This method gets invoked automatically when the POST param tables
701 (request.post_params, etc.) are accessed, or if a response is sent (to avoid
702 deadlocks with the webbrowser). (Note: Automatic request body processing on
703 write may be disabled by calling request:defer_reading().)
705 After this method returned, all registered POST field stream handlers have
706 received all data. Registration of other POST field stream handlers is not
707 possible after this method has been called (or after request.post_params_list
708 or request.post_params have been accessed).
711 ### request:send_data(...)
713 Sends data as response body. All arguments are converted via tostring(...) and
714 concatenated. May be called multiple times until the request has been finished
715 by calling request:finish().
717 If the request method (see request.method) is "HEAD", then calls to
718 request:send_data(...) are automatically ignored.
721 ### request:send_header(key, value)
723 Sends a HTTP response header that consists of the given key and the given
724 value. Note: Key and value must be provided as separate arguments. Before any
725 headers can be sent, a HTTP status must have been set with
726 request:send_status(status_string).
729 ### request:send_status(status_string)
731 Sends a HTTP response status that is given as a string consisting of a 3-digit
732 number and an explanatory string, e.g. "200 OK" or "404 Not Found". This
733 function must be called once before any headers or response body data may be
734 sent.
737 ### request.socket
739 The underlaying socket. Can be used to force a TCP RST, etc.
742 ### request:stream_post_param(field_name, callback)
744 Registers a stream handler for the given POST parameter. The callback function
745 will be called in the following manner:
747 - For the initial chunk, the first chunk gets passed as first argument while a
748 table with metadata ("field_name" and "content_type") gets passed as second
749 argument. In case of an immediate EOF (i.e. an empty file), the passed
750 chunk is the empty string. In all other cases the chunk has a length greater
751 than zero.
752 - For any remaining chunks, the respective chunk gets passed as first and only
753 argument (no metadata). Here, the chunk has always a length greater than
754 zero.
755 - To indicate the end of the stream, the callback function is called without
756 arguments. This also happens in case of an immediate EOF (see above).
758 In case of an immediate EOF (i.e. an empty file), the callback function is thus
759 called as follows:
761 - The first time with an empty string as first argument, and with the metadata
762 as second argument.
763 - The second time without any arguments.
766 ### request:stream_post_params(pattern, callback)
768 Same as request:stream_post_param(...) but providing a string pattern to match
769 multiple field names (e.g. "^file_[0-9]+$").
772 ### request:stream_request_body(callback)
774 Start streaming of request body. For each chunk of the request body, the
775 callback function is called with the corresponding chunk. End of data is
776 indicated through return of request:stream_request_body(...) (not by calling
777 the callback without arguments).
779 The function may be called with nil instead of a callback function. In this
780 case, the request body is read and discarded. Only if nil is passed instead of
781 a callback, then the function may also be invoked when the request body has
782 already been read and/or processed. In the latter case, the function performs
783 no operation.

Impressum / About Us