dotfiles from arch

This commit is contained in:
2025-09-28 11:39:12 +02:00
parent 75885729cd
commit d1c6923bbb
1358 changed files with 575835 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
{
"files" : [
"resty/redis%.lua",
"lib/resty/.*%.lua",
"src/resty/.*%.lua",
"lib/ngx.*/.*%.lua",
"src/ngx.*/.*%.lua"
],
"words" : [
"resty%.%w+",
"ngx%.%w+"
],
"settings" : {
"Lua.runtime.version" : "LuaJIT",
"Lua.diagnostics.globals" : [
"ngx"
]
}
}

View File

@@ -0,0 +1,470 @@
---@meta
--- lua cjson
---
--- https://kyne.com.au/~mark/software/lua-cjson.php
--- https://kyne.com.au/~mark/software/lua-cjson-manual.html
--- https://openresty.org/en/lua-cjson-library.html
---
--- **NOTE:** This includes the additions in the OpenResty-maintained cjson fork: https://github.com/openresty/lua-cjson
---
--- ---
---
--- The cjson module will throw an error during JSON conversion if any invalid
--- data is encountered. Refer to `cjson.encode` and cjson.decode for details.
---
--- The cjson.safe module behaves identically to the cjson module, except when
--- errors are encountered during JSON conversion. On error, the cjson_safe.encode
--- and cjson_safe.decode functions will return nil followed by the error message.
---
--- cjson.new can be used to instantiate an independent copy of the Lua CJSON
--- module. The new module has a separate persistent encoding buffer, and default settings.
---
--- Lua CJSON can support Lua implementations using multiple preemptive threads
--- within a single Lua state provided the persistent encoding buffer is not
--- shared. This can be achieved by one of the following methods:
---
--- * Disabling the persistent encoding buffer with cjson.encode_keep_buffer
--- * Ensuring each thread calls cjson.encode separately (ie, treat cjson.encode as non-reentrant).
--- * Using a separate cjson module table per preemptive thread (cjson.new)
---
--- ## Note
---
--- Lua CJSON uses `strtod` and `snprintf` to perform numeric conversion as they
--- are usually well supported, fast and bug free. However, these functions
--- require a workaround for JSON encoding/parsing under locales using a comma
--- decimal separator. Lua CJSON detects the current locale during instantiation
--- to determine and automatically implement the workaround if required. Lua
--- CJSON should be reinitialised via cjson.new if the locale of the current
--- process changes. Using a different locale per thread is not supported.
---
---@class cjson
---@field _NAME string
---@field _VERSION string
---@field null cjson.null
---@field empty_array cjson.empty_array
---@field array_mt cjson.array_mt
---@field empty_array_mt cjson.empty_array_mt
---
local cjson = {}
--- A metatable which can "tag" a table as a JSON Array in case it is empty (that
--- is, if the table has no elements, `cjson.encode()` will encode it as an empty
--- JSON Array).
---
--- Instead of:
---
---```lua
--- local function serialize(arr)
--- if #arr < 1 then
--- arr = cjson.empty_array
--- end
---
--- return cjson.encode({some_array = arr})
--- end
---```
---
--- This is more concise:
---
---```lua
--- local function serialize(arr)
--- setmetatable(arr, cjson.empty_array_mt)
---
--- return cjson.encode({some_array = arr})
--- end
---```
---
--- Both will generate:
---
---```json
--- {
--- "some_array": []
--- }
---```
---
--- **NOTE:** This field is specific to the OpenResty cjson fork.
---
---@alias cjson.empty_array_mt table
--- When lua-cjson encodes a table with this metatable, it will systematically
--- encode it as a JSON Array. The resulting, encoded Array will contain the
--- array part of the table, and will be of the same length as the `#` operator
--- on that table. Holes in the table will be encoded with the null JSON value.
---
--- ## Example
---
---```lua
--- local t = { "hello", "world" }
--- setmetatable(t, cjson.array_mt)
--- cjson.encode(t) -- ["hello","world"]
---```
---
--- Or:
---
---```lua
--- local t = {}
--- t[1] = "one"
--- t[2] = "two"
--- t[4] = "three"
--- t.foo = "bar"
--- setmetatable(t, cjson.array_mt)
--- cjson.encode(t) -- ["one","two",null,"three"]
---```
---
--- **NOTE:** This field is specific to the OpenResty cjson fork.
---
--- This value was introduced in the 2.1.0.5 release of this module.
---
---@alias cjson.array_mt table
--- Sentinel type that denotes a JSON `null` value
---@alias cjson.null lightuserdata
--- A lightuserdata, similar to `cjson.null`, which will be encoded as an empty
--- JSON Array by `cjson.encode()`.
---
--- For example, since encode_empty_table_as_object is true by default:
---
---```lua
--- local cjson = require "cjson"
---
--- local json = cjson.encode({
--- foo = "bar",
--- some_object = {},
--- some_array = cjson.empty_array
--- })
---```
---
--- This will generate:
---
---```json
--- {
--- "foo": "bar",
--- "some_object": {},
--- "some_array": []
--- }
---```
---
--- **NOTE:** This field is specific to the OpenResty cjson fork.
---
---@alias cjson.empty_array lightuserdata
--- unserialize a json string to a lua value
---
--- `cjson.decode` will deserialise any UTF-9 JSON string into a Lua value or table.
---
--- UTF-16 and UTF-32 JSON strings are not supported.
---
--- cjson.decode requires that any NULL (ASCII 0) and double quote (ASCII 34) characters are escaped within strings. All escape codes will be decoded and other bytes will be passed transparently. UTF-8 characters are not validated during decoding and should be checked elsewhere if required.
---
--- JSON null will be converted to a NULL lightuserdata value. This can be compared with `cjson.null` for convenience.
---
--- By default, numbers incompatible with the JSON specification (infinity, NaN, hexadecimal) can be decoded. This default can be changed with `cjson.decode_invalid_numbers()`.
---
--- ```lua
--- local json_text '[ true, { "foo": "bar" } ]'
--- cjson.decode(json_text) --> { true, { foo = "bar" } }
--- ```
---
---@param json string
---@return any
function cjson.decode(json) end
--- decode_invalid_numbers
---
--- Lua CJSON may generate an error when trying to decode numbers not supported
--- by the JSON specification. Invalid numbers are defined as:
---
--- * infinity
--- * not-a-number (NaN)
--- * hexadecimal
---
--- Available settings:
---
--- * `true`: Accept and decode invalid numbers. This is the default setting.
--- * `false`: Throw an error when invalid numbers are encountered.
---
--- The current setting is always returned, and is only updated when an argument is provided.
---
---@param setting? boolean # (default: `true`)
---@return boolean setting # the value of the current setting
function cjson.decode_invalid_numbers(setting) end
--- decode_max_depth
---
--- Lua CJSON will generate an error when parsing deeply nested JSON once the
--- maximum array/object depth has been exceeded. This check prevents
--- unnecessarily complicated JSON from slowing down the application, or crashing
--- the application due to lack of process stack space.
---
--- An error may be generated before the depth limit is hit if Lua is unable to
--- allocate more objects on the Lua stack.
---
--- By default, Lua CJSON will reject JSON with arrays and/or objects nested
--- more than 1000 levels deep.
---
--- The current setting is always returned, and is only updated when an argument is provided.
---
---@param depth? integer # must be positive (default `1000`)
---@return integer depth
function cjson.decode_max_depth(depth) end
--- decode_array_with_array_mt
---
--- If enabled, JSON Arrays decoded by cjson.decode will result in Lua tables
--- with the array_mt metatable. This can ensure a 1-to-1 relationship between
--- arrays upon multiple encoding/decoding of your JSON data with this module.
---
--- If disabled, JSON Arrays will be decoded to plain Lua tables, without the
--- `cjson.array_mt` metatable.
---
--- ## Example
---
---```lua
--- local cjson = require "cjson"
---
--- -- default behavior
--- local my_json = [[{"my_array":[]}]]
--- local t = cjson.decode(my_json)
--- cjson.encode(t) -- {"my_array":{}} back to an object
---
--- -- now, if this behavior is enabled
--- cjson.decode_array_with_array_mt(true)
---
--- local my_json = [[{"my_array":[]}]]
--- local t = cjson.decode(my_json)
--- cjson.encode(t) -- {"my_array":[]} properly re-encoded as an array
---```
---
--- **NOTE:** This function is specific to the OpenResty cjson fork.
---
---@param enabled boolean # (default: false)
function cjson.decode_array_with_array_mt(enabled) end
--- serialize a lua value to a json string
---
--- cjson.encode will serialise a Lua value into a string containing the JSON representation.
---
--- cjson.encode supports the following types:
---
--- * boolean
--- * lightuserdata (NULL value only)
--- * nil
--- * number
--- * string
--- * table
---
--- The remaining Lua types will generate an error:
---
--- * function
--- * lightuserdata (non-NULL values)
--- * thread
--- * userdata
---
--- By default, numbers are encoded with 14 significant digits. Refer to cjson.encode_number_precision for details.
---
--- Lua CJSON will escape the following characters within each UTF-8 string:
---
--- * Control characters (ASCII 0 - 31)
--- * Double quote (ASCII 34)
--- * Forward slash (ASCII 47)
--- * Blackslash (ASCII 92)
--- * Delete (ASCII 127)
---
--- All other bytes are passed transparently.
---
---
--- ## Caution
---
--- Lua CJSON will successfully encode/decode binary strings, but this is technically not supported by JSON and may not be compatible with other JSON libraries. To ensure the output is valid JSON, applications should ensure all Lua strings passed to cjson.encode are UTF-8.
---
--- ---
--- Base64 is commonly used to encode binary data as the most efficient encoding under UTF-8 can only reduce the encoded size by a further ~8%. Lua Base64 routines can be found in the LuaSocket and lbase64 packages.
---
--- Lua CJSON uses a heuristic to determine whether to encode a Lua table as a JSON array or an object. A Lua table with only positive integer keys of type number will be encoded as a JSON array. All other tables will be encoded as a JSON object.
---
--- Lua CJSON does not use metamethods when serialising tables.
---
--- * `rawget()` is used to iterate over Lua arrays
--- * `next()` is used to iterate over Lua objects
---
--- Lua arrays with missing entries (sparse arrays) may optionally be encoded in
--- several different ways. Refer to cjson.encode_sparse_array for details.
---
--- JSON object keys are always strings. Hence cjson.encode only supports table
--- keys which are type number or string. All other types will generate an error.
---
--- ## Note
--- Standards compliant JSON must be encapsulated in either an object ({}) or an array ([]). If strictly standards compliant JSON is desired, a table must be passed to cjson.encode.
---
--- ---
---
--- By default, encoding the following Lua values will generate errors:
---
--- * Numbers incompatible with the JSON specification (infinity, NaN)
--- * Tables nested more than 1000 levels deep
--- * Excessively sparse Lua arrays
---
--- These defaults can be changed with:
---
--- * cjson.encode_invalid_numbers
--- * cjson.encode_max_depth
--- * cjson.encode_sparse_array
---
---```lua
--- local value = { true, { foo = "bar" } }
--- cjson.encode(value) --> '[true,{"foo":"bar"}]'
---```
---
---@param value any
---@return string json
function cjson.encode(value) end
--- encode_invalid_numbers
---
--- Lua CJSON may generate an error when encoding floating point numbers not
--- supported by the JSON specification (invalid numbers):
---
--- * infinity
--- * not-a-number (NaN)
---
--- Available settings:
---
--- * `true`: Allow invalid numbers to be encoded. This will generate non-standard JSON, but this output is supported by some libraries.
--- * `false`: Throw an error when attempting to encode invalid numbers. This is the default setting.
--- * `"null"`: Encode invalid numbers as a JSON null value. This allows infinity and NaN to be encoded into valid JSON.
---
--- The current setting is always returned, and is only updated when an argument is provided.
---
---@param setting? boolean|'"null"'
---@return boolean|'"null"' setting
function cjson.encode_invalid_numbers(setting) end
--- encode_keep_buffer
---
--- Lua CJSON can reuse the JSON encoding buffer to improve performance.
---
--- Available settings:
---
--- * `true` - The buffer will grow to the largest size required and is not freed until the Lua CJSON module is garbage collected. This is the default setting.
--- * `false` - Free the encode buffer after each call to cjson.encode.
---
--- The current setting is always returned, and is only updated when an argument is provided.
---
---@param setting? boolean
---@return boolean setting
function cjson.encode_keep_buffer(setting) end
--- encode_max_depth
---
--- Once the maximum table depth has been exceeded Lua CJSON will generate an
--- error. This prevents a deeply nested or recursive data structure from
--- crashing the application.
---
--- By default, Lua CJSON will generate an error when trying to encode data
--- structures with more than 1000 nested tables.
---
--- The current setting is always returned, and is only updated when an argument is provided.
---
---@param depth? integer # must be positive (default `1000`)
---@return integer depth
function cjson.encode_max_depth(depth) end
--- encode_number_precision
---
--- The amount of significant digits returned by Lua CJSON when encoding numbers
--- can be changed to balance accuracy versus performance. For data structures
--- containing many numbers, setting cjson.encode_number_precision to a smaller
--- integer, for example 3, can improve encoding performance by up to 50%.
---
--- By default, Lua CJSON will output 14 significant digits when converting a number to text.
---
--- The current setting is always returned, and is only updated when an argument is provided.
---
--- **NOTE:** The maximum value of 16 is only supported by the OpenResty cjson
--- fork. The maximum in the upstream mpx/lua-cjson module is 14.
---
---@param precision? integer # must be between 1 and 16
---@return integer precision
function cjson.encode_number_precision(precision) end
--- encode_sparse_array
---
--- Lua CJSON classifies a Lua table into one of three kinds when encoding a JSON array. This is determined by the number of values missing from the Lua array as follows:
---
--- * Normal - All values are available.
--- * Sparse - At least 1 value is missing.
--- * Excessively sparse - The number of values missing exceeds the configured ratio.
---
--- Lua CJSON encodes sparse Lua arrays as JSON arrays using JSON null for the missing entries.
---
--- An array is excessively sparse when all the following conditions are met:
---
--- * ratio > 0
--- * maximum_index > safe
--- * maximum_index > item_count * ratio
---
--- Lua CJSON will never consider an array to be excessively sparse when ratio = 0.
--- The safe limit ensures that small Lua arrays are always encoded as sparse arrays.
---
--- By default, attempting to encode an excessively sparse array will generate
--- an error. If convert is set to true, excessively sparse arrays will be
--- converted to a JSON object.
---
--- The current settings are always returned. A particular setting is only
--- changed when the argument is provided (non-nil).
---
--- ## Example: Encoding a sparse array
---
---```lua
--- cjson.encode({ [3] = "data" })
--- -- Returns: '[null,null,"data"]'
---```
---
--- ## Example: Enabling conversion to a JSON object
---
---```lua
--- cjson.encode_sparse_array(true)
--- cjson.encode({ [1000] = "excessively sparse" })
--- -- Returns: '{"1000":"excessively sparse"}'
---```
---
---@param convert? boolean # (default: false)
---@param ratio? integer # must be positive (default: 2)
---@param safe? integer # must be positive (default: 10)
---@return boolean convert
---@return integer ratio
---@return integer safe
function cjson.encode_sparse_array(convert, ratio, safe) end
--- encode_empty_table_as_object
---
--- Change the default behavior when encoding an empty Lua table.
---
--- By default, empty Lua tables are encoded as empty JSON Objects (`{}`). If
--- this is set to false, empty Lua tables will be encoded as empty JSON Arrays
--- instead (`[]`).
---
--- **NOTE:** This function is specific to the OpenResty cjson fork.
---
---@param setting boolean|'"on"'|'"off"'
function cjson.encode_empty_table_as_object(setting) end
--- encode_escape_forward_slash
---
--- If enabled, forward slash '/' will be encoded as '\/'.
---
--- If disabled, forward slash '/' will be encoded as '/' (no escape is applied).
---
--- **NOTE:** This function is specific to the OpenResty cjson fork.
---
---@param enabled boolean # (default: true)
function cjson.encode_escape_forward_slash(enabled) end
--- instantiate an independent copy of the Lua CJSON module
---
--- The new module has a separate persistent encoding buffer, and default settings
---@return cjson
function cjson.new() end
return cjson

View File

@@ -0,0 +1,42 @@
---@meta
--- The `cjson.safe` module behaves identically to the `cjson` module, except when
--- errors are encountered during JSON conversion. On error, the `cjson.safe.encode`
--- and `cjson.safe.decode` functions will return `nil` followed by the error message.
---
--- @see cjson
---
---@class cjson.safe : cjson
local cjson_safe = {}
--- unserialize a json string to a lua value
---
--- Returns `nil` and an error string when the input cannot be decoded.
---
--- ```lua
--- local value, err = cjson_safe.decode(some_json_string)
--- ```
---@param json string
---@return any? decoded
---@return string? error
function cjson_safe.decode(json) end
--- serialize a lua value to a json string
---
--- Returns `nil` and an error string when the input cannot be encoded.
---
--- ```lua
--- local json, err = cjson_safe.encode(some_lua_value)
--- ```
---@param value any
---@return string? encoded
---@return string? error
function cjson_safe.encode(value) end
--- instantiate an independent copy of the Lua CJSON module
---
--- The new module has a separate persistent encoding buffer, and default settings
---@return cjson.safe
function cjson_safe.new() end
return cjson_safe

View File

@@ -0,0 +1,31 @@
---@meta
--- Returns (and optionally sets) the current PRNG state (an array of 8 Lua
--- numbers with 32-bit integer values) currently used by the JIT compiler.
---
--- When the `state` argument is non-nil, it is expected to be an array of up to 8
--- unsigned Lua numbers, each with value less than 2\*\*32-1. This will set the
--- current PRNG state and return the state that was overridden.
---
--- **Note:** For backward compatibility, `state` argument can also be an unsigned
--- Lua number less than 2\*\*32-1.
---
--- **Note:** When the `state` argument is an array and less than 8 numbers, or the
--- `state` is a number, the remaining positions are filled with zeros.
---
--- Usage:
---
--- ```lua
--- local state = jit.prngstate()
--- local oldstate = jit.prngstate{ a, b, c, ... }
---
--- jit.prngstate(32) -- {32, 0, 0, 0, 0, 0, 0, 0}
--- jit.prngstate{432, 23, 50} -- {432, 23, 50, 0, 0, 0, 0, 0}
--- ```
---
--- **Note:** This API has no effect if LuaJIT is compiled with
--- `-DLUAJIT_DISABLE_JIT`, and will return a table with all `0`.
---
---@param state? integer[]
---@return integer[] state
function jit.prngstate(state) end

View File

@@ -0,0 +1,4 @@
---@meta
ndk = {}
ndk.set_var = {}
return ndk

View File

@@ -0,0 +1,117 @@
---@meta
local balancer = {
version = require("resty.core.base").version,
}
--- Sets the peer address (host and port) for the current backend query (which
--- may be a retry).
---
--- Domain names in host do not make sense. You need to use OpenResty libraries
--- like lua-resty-dns to obtain IP address(es) from all the domain names before
--- entering the `balancer_by_lua*` handler (for example, you can perform DNS
--- lookups in an earlier phase like `access_by_lua*` and pass the results to the
--- `balancer_by_lua*` handler via `ngx.ctx`.
---
---@param addr string
---@param port integer
---@return boolean ok
---@return string? error
function balancer.set_current_peer(addr, port) end
--- Sets the upstream timeout (connect, send and read) in seconds for the
--- current and any subsequent backend requests (which might be a retry).
---
--- If you want to inherit the timeout value of the global nginx.conf
--- configuration (like `proxy_connect_timeout`), then just specify the nil value
--- for the corresponding argument (like the `connect_timeout` argument).
---
--- Zero and negative timeout values are not allowed.
---
--- You can specify millisecond precision in the timeout values by using floating
--- point numbers like 0.001 (which means 1ms).
---
--- Note: `send_timeout` and `read_timeout` are controlled by the same config
--- `proxy_timeout` for `ngx_stream_proxy_module`. To keep API compatibility, this
--- function will use `max(send_timeout, read_timeout)` as the value for setting
--- proxy_timeout.
---
--- Returns `true` when the operation is successful; returns `nil` and a string
--- describing the error otherwise.
---
--- This only affects the current downstream request. It is not a global change.
---
--- For the best performance, you should use the OpenResty bundle.
---
---@param connect_timeout? number
---@param send_timeout? number
---@param read_timeout? number
---@return boolean ok
---@return string? error
function balancer.set_timeouts(connect_timeout, send_timeout, read_timeout) end
---@alias ngx.balancer.failure
---| '"next"' # Failures due to bad status codes sent from the backend server. The origin's response is same though, which means the backend connection can still be reused for future requests.
---| '"failed"' Fatal errors while communicating to the backend server (like connection timeouts, connection resets, and etc). In this case, the backend connection must be aborted and cannot get reused.
--- Retrieves the failure details about the previous failed attempt (if any) when
--- the next_upstream retrying mechanism is in action. When there was indeed a
--- failed previous attempt, it returned a string describing that attempt's state
--- name, as well as an integer describing the status code of that attempt.
---
--- Possible status codes are those HTTP error status codes like 502 and 504.
---
--- For stream module, `status_code` will always be 0 (`ngx.OK`) and is provided
--- for compatibility reasons.
---
--- When the current attempt is the first attempt for the current downstream
--- request (which means there is no previous attempts at all), this method
--- always returns a single `nil` value.
---
---@return ngx.balancer.failure? state_name
---@return integer? status_code
function balancer.get_last_failure() end
--- Sets the tries performed when the current attempt (which may be a retry)
--- fails (as determined by directives like proxy_next_upstream, depending on
--- what particular nginx uptream module you are currently using).
--
--- Note that the current attempt is excluded in the count number set here.
---
--- Please note that, the total number of tries in a single downstream request
--- cannot exceed the hard limit configured by directives like
--- `proxy_next_upstream_tries`, depending on what concrete NGINX upstream
--- module you are using. When exceeding this limit, the count value will get
--- reduced to meet the limit and the second return value will be the string
--- "reduced tries due to limit", which is a warning, while the first return
--- value is still a `true` value.
---
---@param count integer
---@return boolean ok
---@return string? error
function balancer.set_more_tries(count) end
--- Recreates the request buffer for sending to the upstream server.
---
--- This is useful, for example if you want to change a request header field
--- to the new upstream server on balancer retries.
---
--- Normally this does not work because the request buffer is created once
--- during upstream module initialization and won't be regenerated for subsequent
--- retries. However you can use `proxy_set_header My-Header $my_header` and
--- set the `ngx.var.my_header` variable inside the balancer phase. Calling
--- `recreate_request()` after updating a header field will cause the request
--- buffer to be re-generated and the `My-Header` header will thus contain the
--- new value.
---
--- Warning: because the request buffer has to be recreated and such allocation
--- occurs on the request memory pool, the old buffer has to be thrown away and
--- will only be freed after the request finishes. Do not call this function too
--- often or memory leaks may be noticeable. Even so, a call to this function
--- should be made only if you know the request buffer must be regenerated,
--- instead of unconditionally in each balancer retries.
---
---@return boolean ok
---@return string? error
function balancer.recreate_request() end
return balancer

View File

@@ -0,0 +1,21 @@
---@meta
local base64 = {
version = require("resty.core.base").version,
}
---Encode input using base64url rules. Returns the encoded string.
---@param s string
---@return string
function base64.encode_base64url(s) end
---Decode input using base64url rules. Returns the decoded string.
---
---If the input is not a valid base64url encoded string, decoded will be `nil`
---and err will be a string describing the error.
---
---@param s string
---@return string? decoded
---@return string? err
function base64.decode_base64url(s) end
return base64

View File

@@ -0,0 +1,119 @@
---@meta
local errlog = {
version = require("resty.core.base").version,
}
--- Return the nginx core's error log filter level (defined via the `error_log` configuration directive in nginx.conf) as an integer value.
---@return ngx.log.level
function errlog.get_sys_filter_level() end
--- Specifies the filter log level, only to capture and buffer the error logs with a log level no lower than the specified level.
---
--- If we don't call this API, all of the error logs will be captured by default.
---
--- In case of error, `nil` will be returned as well as a string describing the error.
---
--- This API should always work with directive `lua_capture_error_log`.
---
---@param level ngx.log.level
---@return boolean ok
---@return string? err
function errlog.set_filter_level(level) end
--- Fetches the captured nginx error log messages if any in the global data buffer specified by ngx_lua's `lua_capture_error_log` directive. Upon return, this Lua function also removes those messages from that global capturing buffer to make room for future new error log data.
---
--- In case of error, nil will be returned as well as a string describing the error.
---
--- The optional max argument is a number that when specified, will prevent `get_logs()` from adding more than max messages to the res array.
---
---```lua
--- for i = 1, 20 do
--- ngx.log(ngx.ERR, "test")
--- end
---
--- local errlog = require "ngx.errlog"
--- local res = errlog.get_logs(10)
--- -- the number of messages in the `res` table is 10 and the `res` table
--- -- has 30 elements.
---```
---
--- The resulting table has the following structure:
---
---```
--- { level1, time1, msg1, level2, time2, msg2, ... }
---```
---
--- The levelX values are constants defined below:
---
--- https://github.com/openresty/lua-nginx-module/#nginx-log-level-constants
---
--- The timeX values are UNIX timestamps in seconds with millisecond precision. The sub-second part is presented as the decimal part. The time format is exactly the same as the value returned by ngx.now. It is also subject to NGINX core's time caching.
---
--- The msgX values are the error log message texts.
---
--- So to traverse this array, the user can use a loop like this:
---
---```lua
---
--- for i = 1, #res, 3 do
--- local level = res[i]
--- if not level then
--- break
--- end
---
--- local time = res[i + 1]
--- local msg = res[i + 2]
---
--- -- handle the current message with log level in `level`,
--- -- log time in `time`, and log message body in `msg`.
--- end
---```
---
--- Specifying max <= 0 disables this behavior, meaning that the number of results won't be limited.
---
--- The optional 2th argument res can be a user-supplied Lua table to hold the result instead of creating a brand new table. This can avoid unnecessary table dynamic allocations on hot Lua code paths. It is used like this:
---
---```lua
--- local errlog = require "ngx.errlog"
--- local new_tab = require "table.new"
---
--- local buffer = new_tab(100 * 3, 0) -- for 100 messages
---
--- local errlog = require "ngx.errlog"
--- local res, err = errlog.get_logs(0, buffer)
--- if res then
--- -- res is the same table as `buffer`
--- for i = 1, #res, 3 do
--- local level = res[i]
--- if not level then
--- break
--- end
--- local time = res[i + 1]
--- local msg = res[i + 2]
--- ...
--- end
--- end
---```
---
--- When provided with a res table, `get_logs()` won't clear the table for performance reasons, but will rather insert a trailing nil value after the last table element.
---
--- When the trailing nil is not enough for your purpose, you should clear the table yourself before feeding it into the `get_logs()` function.
---
---@param max number
---@param res? table
---@return table? res
---@return string? err
function errlog.get_logs(max, res) end
--- Log msg to the error logs with the given logging level.
---
--- Just like the ngx.log API, the log_level argument can take constants like ngx.ERR and ngx.WARN. Check out Nginx log level constants for details.
---
--- However, unlike the ngx.log API which accepts variadic arguments, this function only accepts a single string as its second argument msg.
---
--- This function differs from ngx.log in the way that it will not prefix the written logs with any sort of debug information (such as the caller's file and line number).
---@param level ngx.log.level
---@param msg string
function errlog.raw_log(level, msg) end
return errlog

View File

@@ -0,0 +1,60 @@
---@meta
local ocsp = {
version = require("resty.core.base").version,
}
--- Extracts the OCSP responder URL (like "http://test.com/ocsp/") from the SSL server certificate chain in the DER format.
---
--- Usually the SSL server certificate chain is originally formatted in PEM. You can use the Lua API provided by the ngx.ssl module to do the PEM to DER conversion.
---
--- The optional max_len argument specifies the maximum length of OCSP URL allowed. This determines the buffer size; so do not specify an unnecessarily large value here. It defaults to the internal string buffer size used throughout this lua-resty-core library (usually default to 4KB).
---
--- In case of failures, returns `nil` and a string describing the error.
---
---@param der_cert_chain string
---@param max_len? number
---@return string? ocsp_url
---@return string? error
function ocsp.get_ocsp_responder_from_der_chain(der_cert_chain, max_len) end
--- Validates the raw OCSP response data specified by the `ocsp_resp` argument using the SSL server certificate chain in DER format as specified in the `der_cert_chain` argument.
---
--- Returns true when the validation is successful.
---
--- In case of failures, returns `nil` and a string describing the failure. The maximum length of the error string is controlled by the optional `max_err_msg` argument (which defaults to the default internal string buffer size used throughout this lua-resty-core library, usually being 4KB).
---
---@param ocsp_resp string
---@param der_cert_chain string
---@param max_err_msg_len? number
---@return boolean ok
---@return string? error
function ocsp.validate_ocsp_response(ocsp_resp, der_cert_chain, max_err_msg_len) end
--- Builds an OCSP request from the SSL server certificate chain in the DER format, which can be used to send to the OCSP server for validation.
---
--- The optional `max_len` argument specifies the maximum length of the OCSP request allowed. This value determines the size of the internal buffer allocated, so do not specify an unnecessarily large value here. It defaults to the internal string buffer size used throughout this lua-resty-core library (usually defaults to 4KB).
---
--- In case of failures, returns `nil` and a string describing the error.
---
--- The raw OCSP response data can be used as the request body directly if the POST method is used for the OCSP request. But for GET requests, you need to do base64 encoding and then URL encoding on the data yourself before appending it to the OCSP URL obtained by the `get_ocsp_responder_from_der_chain()` function.
---
---@param der_cert_chain string
---@param max_len? number
---@return string? ocsp_req
---@return string? error
function ocsp.create_ocsp_request(der_cert_chain, max_len) end
--- Sets the OCSP response as the OCSP stapling for the current SSL connection.
---
--- Returns `true` in case of successes. If the SSL client does not send a "status request" at all, then this method still returns true but also with a string as the warning "no status req".
---
--- In case of failures, returns `nil` and a string describing the error.
---
--- The OCSP response is returned from CA's OCSP server. See the `create_ocsp_request()` function for how to create an OCSP request and also validate_ocsp_response for how to validate the OCSP response.
---
---@param ocsp_resp string
---@return boolean ok
---@return string? error
function ocsp.set_ocsp_status_resp(ocsp_resp) end
return ocsp

View File

@@ -0,0 +1,307 @@
---@meta
local pipe = {}
pipe._gc_ref_c_opt = "-c"
pipe.version = require("resty.core.base").version
--- Creates and returns a new sub-process instance we can communicate with later.
---
--- For example:
---
---```lua
--- local ngx_pipe = require "ngx.pipe"
--- local proc, err = ngx_pipe.spawn({"sh", "-c", "sleep 0.1 && exit 2"})
--- if not proc then
--- ngx.say(err)
--- return
--- end
---```
---
--- In case of failure, this function returns nil and a string describing the error.
---
--- The sub-process will be killed via SIGKILL if it is still alive when the instance is collected by the garbage collector.
---
--- Note that args should either be a single level array-like Lua table with string values, or just a single string.
---
--- Some more examples:
---
---```lua
--- local proc, err = ngx_pipe.spawn({"ls", "-l"})
---
--- local proc, err = ngx_pipe.spawn({"perl", "-e", "print 'hello, wolrd'"})
---
---```
---
--- If args is specified as a string, it will be executed by the operating system shell, just like os.execute. The above example could thus be rewritten as:
---
---```lua
--- local ngx_pipe = require "ngx.pipe"
--- local proc, err = ngx_pipe.spawn("sleep 0.1 && exit 2")
--- if not proc then
--- ngx.say(err)
--- return
--- end
---```
---
--- In the shell mode, you should be very careful about shell injection attacks when interpolating variables into command string, especially variables from untrusted sources. Please make sure that you escape those variables while assembling the command string. For this reason, it is highly recommended to use the multi-arguments form (args as a table) to specify each command-line argument explicitly.
---
--- Since by default, Nginx does not pass along the PATH system environment variable, you will need to configure the env PATH directive if you wish for it to be respected during the searching of sub-processes:
---
---```nginx
--- env PATH;
--- ...
--- content_by_lua_block {
--- local ngx_pipe = require "ngx.pipe"
---
--- local proc = ngx_pipe.spawn({'ls'})
--- }
---```
---
--- The optional table argument opts can be used to control the behavior of spawned processes. For instance:
---
---```lua
--- local opts = {
--- merge_stderr = true,
--- buffer_size = 256,
--- environ = {"PATH=/tmp/bin", "CWD=/tmp/work"}
--- }
--- local proc, err = ngx_pipe.spawn({"sh", "-c", ">&2 echo data"}, opts)
--- if not proc then
--- ngx.say(err)
--- return
--- end
---```
---
---
---@param args string[]|string
---@param opts? ngx.pipe.spawn.opts
---@return ngx.pipe.proc? proc
---@return string? error
function pipe.spawn(args, opts) end
--- Options for ngx.pipe.spawn()
---
---@class ngx.pipe.spawn.opts : table
---
--- when set to true, the output to stderr will be redirected to stdout in the spawned process. This is similar to doing 2>&1 in a shell.
---@field merge_stderr boolean
---
--- specifies the buffer size used by reading operations, in bytes. The default buffer size is 4096.
---@field buffer_size number
---
--- specifies environment variables for the spawned process. The value must be a single-level, array-like Lua table with string values.
---@field environ string[]
---
--- specifies the write timeout threshold, in milliseconds. The default threshold is 10000. If the threshold is 0, the write operation will never time out.
---@field write_timeout number
---
--- specifies the stdout read timeout threshold, in milliseconds. The default threshold is 10000. If the threshold is 0, the stdout read operation will never time out.
---@field stdout_read_timeout number
---
--- specifies the stderr read timeout threshold, in milliseconds. The default threshold is 10000. If the threshold is 0, the stderr read operation will never time out.
---@field stderr_read_timeout number
---
--- specifies the wait timeout threshold, in milliseconds. The default threshold is 10000. If the threshold is 0, the wait operation will never time out.
---@field wait_timeout number
---@class ngx.pipe.proc : table
local proc = {}
--- Respectively sets: the write timeout threshold, stdout read timeout threshold, stderr read timeout threshold, and wait timeout threshold. All timeouts are in milliseconds.
---
--- The default threshold for each timeout is 10 seconds.
---
--- If the specified timeout argument is `nil`, the corresponding timeout threshold will not be changed. For example:
---
---```lua
--- local proc, err = ngx_pipe.spawn({"sleep", "10s"})
---
--- -- only change the wait_timeout to 0.1 second.
--- proc:set_timeouts(nil, nil, nil, 100)
---
--- -- only change the send_timeout to 0.1 second.
--- proc:set_timeouts(100)
---```
---
--- If the specified timeout argument is 0, the corresponding operation will never time out.
---
---@param write_timeout? number
---@param stdout_read_timeout? number
---@param stderr_read_timeout? number
---@param wait_timeout? number
function proc:set_timeouts(write_timeout, stdout_read_timeout, stderr_read_timeout, wait_timeout) end
--- Waits until the current sub-process exits.
---
--- It is possible to control how long to wait via set_timeouts. The default timeout is 10 seconds.
---
--- If process exited with status code zero, the ok return value will be true.
---
--- If process exited abnormally, the ok return value will be false.
---
--- The second return value, reason, will be a string. Its values may be:
---
--- exit: the process exited by calling exit(3), _exit(2), or by returning from main(). In this case, status will be the exit code.
--- signal: the process was terminated by a signal. In this case, status will be the signal number.
---
--- Note that only one light thread can wait on a process at a time. If another light thread tries to wait on a process, the return values will be `nil` and the error string "pipe busy waiting".
---
--- If a thread tries to wait an exited process, the return values will be `nil` and the error string "exited".
---
---@return boolean ok
---@return '"exit"'|'"signal"' reason
---@return number status
function proc:wait() end
--- Returns the pid number of the sub-process.
---@return number pid
function proc:pid() end
--- Sends a signal to the sub-process.
---
--- Note that the signum argument should be signal's numerical value. If the specified signum is not a number, an error will be thrown.
---
--- You should use lua-resty-signal's `signum()` function to convert signal names to signal numbers in order to ensure portability of your application.
---
--- In case of success, this method returns true. Otherwise, it returns `nil` and a string describing the error.
---
--- Killing an exited sub-process will return `nil` and the error string "exited".
---
--- Sending an invalid signal to the process will return `nil` and the error string "invalid signal".
---
---@param signum integer
---@return boolean ok
---@return string? error
function proc:kill(signum) end
---Closes the specified direction of the current sub-process.
---
---The direction argument should be one of these three values: stdin, stdout and stderr.
---
---In case of success, this method returns true. Otherwise, it returns `nil` and a string describing the error.
---
---If the `merge_stderr` option is specified in spawn, closing the stderr direction will return `nil` and the error string "merged to stdout".
---
---Shutting down a direction when a light thread is waiting on it (such as during reading or writing) will abort the light thread and return true.
---
---Shutting down directions of an exited process will return `nil` and the error string "closed".
---
---It is fine to shut down the same direction of the same stream multiple times; no side effects are to be expected.
---
---@param direction '"stdin"'|'"stdout"'|'"stderr"'
---@return boolean ok
---@return string? error
function proc:shutdown(direction) end
--- Writes data to the current sub-process's stdin stream.
---
--- The data argument can be a string or a single level array-like Lua table with string values.
---
--- This method is a synchronous and non-blocking operation that will not return until all the data has been flushed to the sub-process's stdin buffer, or an error occurs.
---
--- In case of success, it returns the total number of bytes that have been sent. Otherwise, it returns `nil` and a string describing the error.
---
--- The timeout threshold of this write operation can be controlled by the `set_timeouts` method. The default timeout threshold is 10 seconds.
---
--- When a timeout occurs, the data may be partially written into the sub-process's stdin buffer and read by the sub-process.
---
--- Only one light thread is allowed to write to the sub-process at a time. If another light thread tries to write to it, this method will return `nil` and the error string "pipe busy writing".
---
--- If the write operation is aborted by the shutdown method, it will return `nil` and the error string "aborted".
---
--- Writing to an exited sub-process will return `nil` and the error string "closed".
---
---@param data string
---@return integer? nbytes
---@return string? error
function proc:write(data) end
--- Reads all data from the current sub-process's stderr stream until it is closed.
---
--- This method is a synchronous and non-blocking operation, just like the write method.
---
--- The timeout threshold of this reading operation can be controlled by `set_timeouts`. The default timeout is 10 seconds.
---
--- In case of success, it returns the data received. Otherwise, it returns three values: `nil`, a string describing the error, and, optionally, the partial data received so far.
---
--- When `merge_stderr` is specified in spawn, calling `stderr_read_all` will return `nil` and the error string "merged to stdout".
---
--- Only one light thread is allowed to read from a sub-process's stderr or stdout stream at a time. If another thread tries to read from the same stream, this method will return `nil` and the error string "pipe busy reading".
---
--- If the reading operation is aborted by the shutdown method, it will return `nil` and the error string "aborted".
---
--- Streams for stdout and stderr are separated, so at most two light threads may be reading from a sub-process at a time (one for each stream).
---
--- The same way, a light thread may read from a stream while another light thread is writing to the sub-process stdin stream.
---
--- Reading from an exited process's stream will return `nil` and the error string "closed".
---
---@return string? data
---@return string? error
---@return string? partial
function proc:stderr_read_all() end
--- Similar to the `stderr_read_all` method, but reading from the stdout stream of the sub-process.
---@return string? data
---@return string? error
---@return string? partial
function proc:stdout_read_all() end
--- Reads from stderr like `stderr_read_all`, but only reads a single line of data.
---
--- When `merge_stderr` is specified in spawn, calling `stderr_read_line` will return `nil` plus the error string "merged to stdout".
---
--- When the data stream is truncated without a new-line character, it returns 3 values: `nil`, the error string "closed", and the partial data received so far.
---
--- The line should be terminated by a Line Feed (LF) character (ASCII 10), optionally preceded by a Carriage Return (CR) character (ASCII 13). The CR and LF characters are not included in the returned line data.
---@return string? data
---@return string? error
---@return string? partial
function proc:stderr_read_line() end
--- Similar to `stderr_read_line`, but reading from the stdout stream of the sub-process.
---@return string? data
---@return string? error
---@return string? partial
function proc:stdout_read_line() end
--- Reads from stderr like `stderr_read_all`, but only reads the specified number of bytes.
---
--- If `merge_stderr` is specified in spawn, calling `stderr_read_bytes` will return `nil` plus the error string "merged to stdout".
---
--- If the data stream is truncated (fewer bytes of data available than requested), this method returns 3 values: `nil`, the error string "closed", and the partial data string received so far.
---
---@param len number
---@return string? data
---@return string? error
---@return string? partial
function proc:stderr_read_bytes(len) end
--- Similar to `stderr_read_bytes`, but reading from the stdout stream of the sub-process.
---
---@param len number
---@return string? data
---@return string? error
---@return string? partial
function proc:stdout_read_bytes(len) end
--- Reads from stderr like `stderr_read_all`, but returns immediately when any amount of data is received.
---
--- At most max bytes are received.
---
--- If `merge_stderr` is specified in spawn, calling `stderr_read_any` will return `nil` plus the error string "merged to stdout".
---
--- If the received data is more than `max` bytes, this method will return with exactly `max` bytes of data. The remaining data in the underlying receive buffer can be fetched with a subsequent reading operation.
---@param max number
---@return string? data
---@return string? error
function proc:stderr_read_any(max) end
--- Similar to `stderr_read_any`, but reading from the stdout stream of the sub-process.
---
---@param max number
---@return string? data
---@return string? error
function proc:stdout_read_any(max) end
return pipe

View File

@@ -0,0 +1,48 @@
---@meta
local process = {
version = require("resty.core.base").version,
}
--- Returns a number value for the nginx master process's process ID (or PID).
---
---@return integer? pid
function process.get_master_pid() end
--- Enables the privileged agent process in Nginx.
---
--- The privileged agent process does not listen on any virtual server ports
--- like those worker processes. And it uses the same system account as the
--- nginx master process, which is usually a privileged account like root.
---
--- The `init_worker_by_lua*` directive handler still runs in the privileged
--- agent process. And one can use the `type()` function provided by this module
--- to check if the current process is a privileged agent.
---
--- In case of failures, returns `nil` and a string describing the error.
---
---@param connections integer sets the maximum number of simultaneous connections that can be opened by the privileged agent process.
---@return boolean ok
---@return string? error
function process.enable_privileged_agent(connections) end
---@alias ngx.process.type
---| '"master"' # the NGINX master process
---| '"worker"' # an NGINX worker process
---| '"privileged agent"' # the NGINX privileged agent process
---| '"single"' # returned when Nginx is running in the single process mode
---| '"signaller"' # returned when Nginx is running as a signaller process
--- Returns the type of the current NGINX process.
---
---@return ngx.process.type type
function process.type() end
--- Signals the current NGINX worker process to quit gracefully, after all the
--- timers have expired (in time or expired prematurely).
---
--- Note that this API function simply sets the nginx global C variable
--- `ngx_quit` to signal the nginx event loop directly. No UNIX signals or IPC
--- are involved here.
function process.signal_graceful_exit() end
return process

View File

@@ -0,0 +1,102 @@
---@meta
local re = {}
re.version = require("resty.core.base").version
--- Allows changing of regex settings. Currently, it can only change the `jit_stack_size` of the PCRE engine, like so:
---
---```nginx
--- init_by_lua_block { require "ngx.re".opt("jit_stack_size", 200 * 1024) }
---
--- server {
--- location /re {
--- content_by_lua_block {
--- -- full regex and string are taken from https://github.com/JuliaLang/julia/issues/8278
--- local very_long_string = [[71.163.72.113 - - [30/Jul/2014:16:40:55 -0700] ...]]
--- local very_complicated_regex = [[([\d\.]+) ([\w.-]+) ([\w.-]+) (\[.+\]) ...]]
--- local from, to, err = ngx.re.find(very_long_string, very_complicated_regex, "jo")
---
--- -- with the regular jit_stack_size, we would get the error 'pcre_exec() failed: -27'
--- -- instead, we get a match
--- ngx.print(from .. "-" .. to) -- prints '1-1563'
--- }
--- }
--- }
---```
---
--- The `jit_stack_size` cannot be set to a value lower than PCRE's default of 32K.
---
---@param option string '"jit_stack_size"'
---@param value any
function re.opt(option, value) end
--- Splits the subject string using the Perl compatible regular expression regex with the optional options.
---
--- This function returns a Lua (array) table (with integer keys) containing the split values.
---
--- In case of error, `nil` will be returned as well as a string describing the error.
---
--- When regex contains a sub-match capturing group, and when such a match is found, the first submatch capture will be inserted in between each split value, like so:
---
---```lua
--- local ngx_re = require "ngx.re"
---
--- local res, err = ngx_re.split("a,b,c,d", "(,)")
--- -- res is now {"a", ",", "b", ",", "c", ",", "d"}
---```
---
--- When regex is empty string "", the subject will be split into chars, like so:
---
---```lua
--- local ngx_re = require "ngx.re"
---
--- local res, err = ngx_re.split("abcd", "")
--- -- res is now {"a", "b", "c", "d"}
---```
---
--- The optional max argument is a number that when specified, will prevent `split()` from adding more than max matches to the res array:
---
---```lua
--- local ngx_re = require "ngx.re"
---
--- local res, err = ngx_re.split("a,b,c,d", ",", nil, nil, 3)
--- -- res is now {"a", "b", "c,d"}
---```
---
--- Specifying max <= 0 disables this behavior, meaning that the number of results won't be limited.
---
--- The optional 6th argument res can be a table that `split()` will re-use to hold the results instead of creating a new one, which can improve performance in hot code paths. It is used like so:
---
---```lua
--- local ngx_re = require "ngx.re"
---
--- local my_table = {"hello world"}
---
--- local res, err = ngx_re.split("a,b,c,d", ",", nil, nil, nil, my_table)
--- -- res/my_table is now {"a", "b", "c", "d"}
---```
---
--- When provided with a res table, `split()` won't clear the table for performance reasons, but will rather insert a trailing `nil` value when the split is completed:
---
---```lua
--- local ngx_re = require "ngx.re"
---
--- local my_table = {"W", "X", "Y", "Z"}
---
--- local res, err = ngx_re.split("a,b", ",", nil, nil, nil, my_table)
--- -- res/my_table is now {"a", "b", nil, "Z"}
---```
---
--- When the trailing `nil` is not enough for your purpose, you should clear the table yourself before feeding it into the split function.
---
---@param subj string
---@param regex string
---@param opts? ngx.re.options
---@param ctx? ngx.re.ctx
---@param max? number
---@param res? string[]
---@return string[]? res
---@return string? error
function re.split(subj, regex, opts, ctx, max, res) end
return re

View File

@@ -0,0 +1,16 @@
---@meta
local req = {}
req.version = require("resty.core.base").version
---This method adds the specified header and its value to the current request. It works similarly as ngx.req.set_header, with the exception that when the header already exists, the specified value(s) will be appended instead of overriden.
---
---When the specified `header_name` is a builtin header (e.g. User-Agent), this method will override its values.
---
---The `header_value` argument can either be a string or a non-empty, array-like table. A nil or empty table value will cause this function to throw an error.
---
---@param header_name string must be a non-empty string.
---@param header_value string|string[]
function req.add_header(header_name, header_value) end
return req

View File

@@ -0,0 +1,23 @@
---@meta
local resp = {}
resp.version = require("resty.core.base").version
--- This function adds specified header with corresponding value to the response of current request.
---
--- The `header_value` could be either a string or a table.
---
--- The ngx.resp.add_header works mostly like:
---
--- `ngx.header.HEADER`
--- Nginx's `add_header` directive.
---
--- However, unlike `ngx.header.HEADER`, this method appends new header to the old one instead of overriding it.
---
--- Unlike `add_header` directive, this method will override the builtin header instead of appending it.
---
---@param key string
---@param value string|string[]
function resp.add_header(key, value) end
return resp

View File

@@ -0,0 +1,62 @@
---@meta
---@class ngx.semaphore
--- sem is the internal c handler
---@field sem userdata
local semaphore = {
version = require("resty.core.base").version,
}
---Creates and returns a new semaphore instance.
---
---@param n? integer the number of resources the semaphore will begin with (default 0)
---@return ngx.semaphore? semaphore
---@return string? error
function semaphore.new(n) end
--- Returns the number of resources readily available in the sema semaphore
--- instance (if any).
---
--- When the returned number is negative, it means the number of "light threads"
--- waiting on this semaphore.
---
---@return integer count
function semaphore:count() end
--- Requests a resource from the semaphore instance.
---
--- Returns `true` immediately when there is resources available for the current
--- running "light thread". Otherwise the current "light thread" will enter the
--- waiting queue and yield execution. The current "light thread" will be
--- automatically waken up and the wait function call will return true when there
--- is resources available for it, or return nil and a string describing the error
--- in case of failure (like "timeout").
---
--- The timeout argument specifies the maximum time this function call should
--- wait for (in seconds).
---
--- When the timeout argument is 0, it means "no wait", that is, when there is
--- no readily available "resources" for the current running "light thread",
--- this wait function call returns immediately nil and the error string "timeout".
---
--- You can specify millisecond precision in the timeout value by using floating
--- point numbers like 0.001 (which means 1ms).
---
--- "Light threads" created by different contexts (like request handlers) can
--- wait on the same semaphore instance without problem.
---
---@param timeout? number
---@return boolean ok
---@return string|'"timeout"' error
function semaphore:wait(timeout) end
--- Releases n (default to 1) "resources" to the semaphore instance.
---
--- This will not yield the current running "light thread".
---
--- At most n "light threads" will be waken up when the current running "light thread" later yields (or terminates).
---
---@param n? integer
function semaphore:post(n) end
return semaphore

View File

@@ -0,0 +1,276 @@
---@meta
local ssl = {}
--- Sets the DER-formatted prviate key for the current SSL connection.
---
--- Returns true on success, or a nil value and a string describing the error otherwise.
---
--- Usually, the private keys are encoded in the PEM format. You can either use the priv_key_pem_to_der function to do the PEM to DER conversion or just use the openssl command-line utility offline, like below
---
--- openssl rsa -in key.pem -outform DER -out key.der
---
---@param der_priv_key string
---@return boolean ok
---@return string? error
function ssl.set_der_priv_key(der_priv_key) end
--- Converts the PEM-formatted SSL private key data into an opaque cdata pointer (for later uses in the set_priv_key function, for example).
---
--- In case of failures, returns nil and a string describing the error.
---
--- This function can be called in any context.
---
---@param pem_priv_key string
---@return ffi.cdata*? priv_key
---@return string? error
function ssl.parse_pem_priv_key(pem_priv_key) end
--- Returns the TLS 1.x version number used by the current SSL connection. Returns nil and a string describing the error otherwise.
---
--- Typical return values are:
---
--- 0x0300(SSLv3)
--- 0x0301(TLSv1)
--- 0x0302(TLSv1.1)
--- 0x0303(TLSv1.2)
--- 0x0304(TLSv1.3)
---
--- This function can be called in any context where downstream https is used.
---@return number? version
---@return string? error
function ssl.get_tls1_version() end
--- Sets the SSL certificate chain opaque pointer returned by the parse_pem_cert function for the current SSL connection.
---
--- Returns true on success, or a nil value and a string describing the error otherwise.
---
--- Note that this set_cert function will run slightly faster, in terms of CPU cycles wasted, than the set_der_cert variant, since the first function uses opaque cdata pointers which do not require any additional conversion needed to be performed by the SSL library during the SSL handshake.
---
---@param cert_chain ffi.cdata*
---@return boolean ok
---@return string? error
function ssl.set_cert(cert_chain) end
ssl.TLS1_VERSION = 769
--- Sets the SSL private key opaque pointer returned by the parse_pem_priv_key function for the current SSL connection.
---
--- Returns true on success, or a nil value and a string describing the error otherwise.
---
--- Note that this set_priv_key function will run slightly faster, in terms of CPU cycles wasted, than the set_der_priv_key variant, since the first function uses opaque cdata pointers which do not require any additional conversion needed to be performed by the SSL library during the SSL handshake.
---
---@param priv_key ffi.cdata*
---@return boolean ok
---@return string? error
function ssl.set_priv_key(priv_key) end
--- Returns the raw server address actually accessed by the client in the current SSL connection.
---
--- The first two return values are strings representing the address data and the address type, respectively. The address values are interpreted differently according to the address type values:
---
--- unix : The address data is a file path for the UNIX domain socket.
--- inet : The address data is a binary IPv4 address of 4 bytes long.
--- inet6 : The address data is a binary IPv6 address of 16 bytes long.
---
--- Returns two nil values and a Lua string describing the error.
---
--- The following code snippet shows how to print out the UNIX domain socket address and the IPv4 address as human-readable strings:
---
---```lua
--- local ssl = require "ngx.ssl"
--- local byte = string.byte
---
--- local addr, addrtyp, err = ssl.raw_server_addr()
--- if not addr then
--- ngx.log(ngx.ERR, "failed to fetch raw server addr: ", err)
--- return
--- end
---
--- if addrtyp == "inet" then -- IPv4
--- ip = string.format("%d.%d.%d.%d", byte(addr, 1), byte(addr, 2),
--- byte(addr, 3), byte(addr, 4))
--- print("Using IPv4 address: ", ip)
---
--- elseif addrtyp == "unix" then -- UNIX
--- print("Using unix socket file ", addr)
---
--- else -- IPv6
--- -- leave as an exercise for the readers
--- end
---```
---
--- This function can be called in any context where downstream https is used.
---
---@return string? addr_data
---@return ngx.ssl.addr_type? addr_type
---@return string? error
function ssl.raw_server_addr() end
---@alias ngx.ssl.addr_type
---| '"unix"' # a file path for the UNIX domain socket.
---| '"inet"' # a binary IPv4 address of 4 bytes long.
---| '"inet6"' # a binary IPv6 address of 16 bytes long.
--- Clears any existing SSL certificates and/or private keys set on the current SSL connection.
---
--- Returns true on success, or a nil value and a string describing the error otherwise.
---@return boolean ok
---@return string? error
function ssl.clear_certs() end
--- Returns the raw client address of the current SSL connection.
---
--- The first two return values are strings representing the address data and the address type, respectively. The address values are interpreted differently according to the address type values:
---
--- unix : The address data is a file path for the UNIX domain socket.
--- inet : The address data is a binary IPv4 address of 4 bytes long.
--- inet6 : The address data is a binary IPv6 address of 16 bytes long.
---
--- Returns two nil values and a Lua string describing the error.
---
--- The following code snippet shows how to print out the UNIX domain socket address and the IPv4 address as human-readable strings:
---
---```lua
--- local ssl = require "ngx.ssl"
--- local byte = string.byte
---
--- local addr, addrtyp, err = ssl.raw_client_addr()
--- if not addr then
--- ngx.log(ngx.ERR, "failed to fetch raw client addr: ", err)
--- return
--- end
---
--- if addrtyp == "inet" then -- IPv4
--- ip = string.format("%d.%d.%d.%d", byte(addr, 1), byte(addr, 2),
--- byte(addr, 3), byte(addr, 4))
--- print("Client IPv4 address: ", ip)
---
--- elseif addrtyp == "unix" then -- UNIX
--- print("Client unix socket file ", addr)
---
--- else -- IPv6
--- -- leave as an exercise for the readers
--- end
---```
---
--- This function can be called in any context where downstream https is used.
---
---@return string? addr_data
---@return ngx.ssl.addr_type? addr_type
---@return string? error
function ssl.raw_client_addr() end
--- Converts the PEM-formated SSL certificate chain data into an opaque cdata pointer (for later uses in the set_cert function, for example).
---
--- In case of failures, returns nil and a string describing the error.
---
--- You can always use libraries like lua-resty-lrucache to cache the cdata result.
---
--- This function can be called in any context.
---
---@param pem_cert_chain string
---@return ffi.cdata*? cert_chain
---@return string? error
function ssl.parse_pem_cert(pem_cert_chain) end
ssl.version = require("resty.core.base").version
ssl.TLS1_2_VERSION = 771
--- Returns the TLS SNI (Server Name Indication) name set by the client. Returns nil when the client does not set it.
---
--- In case of failures, it returns nil and a string describing the error.
---
--- Usually we use this SNI name as the domain name (like www.openresty.org) to identify the current web site while loading the corresponding SSL certificate chain and private key for the site.
---
--- Please note that not all https clients set the SNI name, so when the SNI name is missing from the client handshake request, we use the server IP address accessed by the client to identify the site. See the raw_server_addr method for more details.
---
--- This function can be called in any context where downstream https is used.
---
---@return string? server_name
---@return string? error
function ssl.server_name() end
--- Returns the server port. Returns nil when server dont have a port.
---
--- In case of failures, it returns nil and a string describing the error.
---
--- This function can be called in any context where downstream https is used.
---
---@return number? server_port
---@return string? error
function ssl.server_port() end
ssl.TLS1_1_VERSION = 770
ssl.SSL3_VERSION = 768
--- Sets the DER-formatted SSL certificate chain data for the current SSL connection. Note that the DER data is directly in the Lua string argument. No external file names are supported here.
---
--- Returns true on success, or a nil value and a string describing the error otherwise.
---
--- Note that, the SSL certificate chain is usually encoded in the PEM format. So you need to use the cert_pem_to_der function to do the conversion first.
---@param der_cert_chain string
---@return boolean ok
---@return string? error
function ssl.set_der_cert(der_cert_chain) end
--- Returns the TLS 1.x version string used by the current SSL connection. Returns nil and a string describing the error otherwise.
---
--- If the TLS 1.x version number used by the current SSL connection is not recognized, the return values will be nil and the string "unknown version".
---
--- Typical return values are:
---
--- SSLv3
--- TLSv1
--- TLSv1.1
--- TLSv1.2
--- TLSv1.3
---
--- This function can be called in any context where downstream https is used.
---
---@return string? version
---@return string? error
function ssl.get_tls1_version_str() end
--- Converts the PEM-formatted SSL private key data into the DER format (for later uses in the set_der_priv_key function, for example).
---
--- In case of failures, returns nil and a string describing the error.
---
--- Alternatively, you can do the PEM to DER conversion offline with the openssl command-line utility, like below
---
--- openssl rsa -in key.pem -outform DER -out key.der
---
--- This function can be called in any context.
---
---@param pem_priv_key string
---@return string? der_priv_key
---@return string? error
function ssl.priv_key_pem_to_der(pem_priv_key) end
--- Converts the PEM-formatted SSL certificate chain data into the DER format (for later uses in the set_der_cert function, for example).
---
--- In case of failures, returns nil and a string describing the error.
---
--- It is known that the openssl command-line utility may not convert the whole SSL certificate chain from PEM to DER correctly. So always use this Lua function to do the conversion. You can always use libraries like lua-resty-lrucache and/or ngx_lua APIs like lua_shared_dict to do the caching of the DER-formatted results, for example.
---
--- This function can be called in any context.
---
---@param pem_cert_chain string
---@return string? der_cert_chain
---@return string? error
function ssl.cert_pem_to_der(pem_cert_chain) end
--- Requires a client certificate during TLS handshake.
---
--- Returns true on success, or a nil value and a string describing the error otherwise.
---
--- Note that TLS is not terminated when verification fails. You need to examine Nginx variable $ssl_client_verify later to determine next steps.
---
--- This function was first added in version 0.1.20.
---
---@param ca_certs? ffi.cdata* # the CA certificate chain opaque pointer returned by the parse_pem_cert function for the current SSL connection. The list of certificates will be sent to clients. Also, they will be added to trusted store. If omitted, will not send any CA certificate to clients.
---@param depth? number verification depth in the client certificates chain. If omitted, will use the value specified by ssl_verify_depth.
---@return boolean ok
---@return string? error
function ssl.verify_client(ca_certs, depth) end
return ssl

View File

@@ -0,0 +1,99 @@
---@meta
local clienthello = {}
clienthello.version = require("resty.core.base").version
---Returns the TLS SNI (Server Name Indication) name set by the client.
---
---Return `nil` when then the extension does not exist.
---
---In case of errors, it returns `nil` and a string describing the error.
---
---Note that the SNI name is gotten from the raw extensions of the client hello message associated with the current downstream SSL connection.
---
---So this function can only be called in the context of `ssl_client_hello_by_lua*`.
---@return string? host
---@return string? error
function clienthello.get_client_hello_server_name() end
--- Returns raw data of arbitrary SSL client hello extension including custom extensions.
---
--- Returns `nil` if the specified extension type does not exist.
---
--- In case of errors, it returns `nil` and a string describing the error.
---
--- Note that the ext is gotten from the raw extensions of the client hello message associated with the current downstream SSL connection.
---
--- So this function can only be called in the context of `ssl_client_hello_by_lua*`.
---
--- Example:
---
--- Gets server name from raw extension data. The `0` in `ssl_clt.get_client_hello_ext(0)` denotes `TLSEXT_TYPE_server_name`, and the `0` in `byte(ext, 3) ~= 0` denotes `TLSEXT_NAMETYPE_host_name`.
---
--- ```nginx
--- # nginx.conf
--- server {
--- listen 443 ssl;
--- server_name test.com;
--- ssl_client_hello_by_lua_block {
--- local ssl_clt = require "ngx.ssl.clienthello"
--- local byte = string.byte
--- local ext = ssl_clt.get_client_hello_ext(0)
--- if not ext then
--- print("failed to get_client_hello_ext(0)")
--- ngx.exit(ngx.ERROR)
--- end
--- local total_len = string.len(ext)
--- if total_len <= 2 then
--- print("bad SSL Client Hello Extension")
--- ngx.exit(ngx.ERROR)
--- end
--- local len = byte(ext, 1) * 256 + byte(ext, 2)
--- if len + 2 ~= total_len then
--- print("bad SSL Client Hello Extension")
--- ngx.exit(ngx.ERROR)
--- end
--- if byte(ext, 3) ~= 0 then
--- print("bad SSL Client Hello Extension")
--- ngx.exit(ngx.ERROR)
--- end
--- if total_len <= 5 then
--- print("bad SSL Client Hello Extension")
--- ngx.exit(ngx.ERROR)
--- end
--- len = byte(ext, 4) * 256 + byte(ext, 5)
--- if len + 5 > total_len then
--- print("bad SSL Client Hello Extension")
--- ngx.exit(ngx.ERROR)
--- end
--- local name = string.sub(ext, 6, 6 + len -1)
---
--- print("read SNI name from Lua: ", name)
--- }
--- ssl_certificate test.crt;
--- ssl_certificate_key test.key;
--- }
--- ```
---
---@param ext_type number
---@return string? ext
function clienthello.get_client_hello_ext(ext_type) end
--- Sets the SSL protocols supported by the current downstream SSL connection.
---
--- Returns `true` on success, or a `nil` value and a string describing the error otherwise.
---
--- Considering it is meaningless to set ssl protocols after the protocol is determined,
--- so this function may only be called in the context of `ssl_client_hello_by_lua*`.
---
--- Example:
--- ```lua
--- ssl_clt.set_protocols({"TLSv1.1", "TLSv1.2", "TLSv1.3"})`
--- ```
---
---@param protocols string[]
---@return boolean ok
---@return string? error
function clienthello.set_protocols(protocols) end
return clienthello

View File

@@ -0,0 +1,51 @@
---@meta
local session = {}
session.version = require("resty.core.base").version
--- Sets the serialized SSL session provided as the argument to the current SSL connection.
--- If the SSL session is successfully set, the current SSL connection can resume the session
--- directly without going through the full SSL handshake process (which is very expensive in terms of CPU time).
---
--- This API is usually used in the context of `ssl_session_fetch_by_lua*`
--- when a cache hit is found with the current SSL session ID.
---
--- The serialized SSL session used as the argument should be originally returned by the
--- `get_serialized_session` function.
---
---@param session string
---@return boolean ok
---@return string? error
function session.set_serialized_session(session) end
--- Returns the serialized form of the SSL session data of the current SSL connection, in a Lua string.
---
--- This session can be cached in `lua-resty-lrucache`, `lua_shared_dict`,
--- and/or external data storage services like `memcached` and `redis`. The SSL session ID returned
--- by the `get_session_id` function is usually used as the cache key.
---
--- The returned SSL session data can later be loaded into other SSL connections using the same
--- session ID via the `set_serialized_session` function.
---
--- In case of errors, it returns `nil` and a string describing the error.
---
--- This API function is usually called in the context of `ssl_session_store_by_lua*`
--- where the SSL handshake has just completed.
---
---@return string? session
---@return string? error
function session.get_serialized_session() end
--- Fetches the SSL session ID associated with the current downstream SSL connection.
--- The ID is returned as a Lua string.
---
--- In case of errors, it returns `nil` and a string describing the error.
---
--- This API function is usually called in the contexts of
--- `ssl_session_store_by_lua*` and `ssl_session_fetch_by_lua*`.
---
---@return string? id
---@return string? error
function session.get_session_id() end
return session

View File

@@ -0,0 +1,9 @@
---@meta
local upstream = {}
function upstream.get_backup_peers() end
function upstream.get_servers() end
function upstream.current_upstream_name() end
function upstream.get_primary_peers() end
function upstream.set_peer_down() end
function upstream.get_upstreams() end
return upstream

View File

@@ -0,0 +1,247 @@
---@meta
---@class PrometheusLib
local PrometheusLib = {}
---@class PrometheusOptions
---is a table of configuration options that can be provided.
local PrometheusOptions = {}
---metric name prefix.
---This string will be prepended to metric names on output.
PrometheusOptions.prefix = ""
---Can be used to change the default name of error metric (see
---[Built-in metrics](https://github.com/knyar/nginx-lua-prometheus#built-in-metrics)
---for details).
PrometheusOptions.error_metric_name = ""
---sets per-worker counter sync interval in seconds.
---This sets the boundary on eventual consistency of counter metrics.
---Defaults to `1`.
PrometheusOptions.sync_interval = 0
---maximum size of a per-metric lookup table maintained by
---each worker to cache full metric names. Defaults to `1000`.
---If you have metrics with extremely high cardinality and lots
---of available RAM, you might want to increase this to avoid
---cache getting flushed too often.
---Decreasing this makes sense if you have a very large number of metrics
---or need to minimize memory usage of this library.
PrometheusOptions.lookup_max_size = 0
---Initializes the module.
---This should be called once from the
---[init_worker_by_lua_block](https://github.com/openresty/lua-nginx-module#init_worker_by_lua_block)
---section of nginx configuration.
---
---Example:
---```
---init_worker_by_lua_block {
--- prometheus = require("prometheus").init("prometheus_metrics", {sync_interval=3})
---}
---```
---@param dict_name string is the name of the nginx shared dictionary which will be used to store all metrics. Defaults to `prometheus_metrics` if not specified.
---@param options? PrometheusOptions is a table of configuration options that can be provided.
---@return Prometheus prometheus Returns a `prometheus` object that should be used to register metrics.
PrometheusLib.init = function(dict_name, options) end
---@class Prometheus
local Prometheus = {}
---Registers a counter.
---
---Should be called once for each gauge from the
---[init_worker_by_lua_block](https://github.com/openresty/lua-nginx-module#init_worker_by_lua_block)
---section.
---
---Example:
---```
---init_worker_by_lua_block {
--- prometheus = require("prometheus").init("prometheus_metrics")
---
--- metric_bytes = prometheus:counter(
--- "nginx_http_request_size_bytes", "Total size of incoming requests")
--- metric_requests = prometheus:counter(
--- "nginx_http_requests_total", "Number of HTTP requests", {"host", "status"})
---}
---```
---@param name string is the name of the metric.
---@param description? string is the text description. Optional.
---@param label_names? string[] is an array of label names for the metric. Optional.
---@return PrometheusCounter
function Prometheus:counter(name, description, label_names) end
---Registers a gauge.
---
---Should be called once for each gauge from the
---[init_worker_by_lua_block](https://github.com/openresty/lua-nginx-module#init_worker_by_lua_block)
---section.
---
---Example:
---```
---init_worker_by_lua_block {
--- prometheus = require("prometheus").init("prometheus_metrics")
---
--- metric_connections = prometheus:gauge(
--- "nginx_http_connections", "Number of HTTP connections", {"state"})
---}
---```
---@param name string is the name of the metric.
---@param description? string is the text description. Optional.
---@param label_names? string[] is an array of label names for the metric. Optional.
---@return PrometheusGauge
function Prometheus:gauge(name, description, label_names) end
---Registers a histogram.
---
---Should be called once for each histogram from the
---[init_worker_by_lua_block](https://github.com/openresty/lua-nginx-module#init_worker_by_lua_block)
---section.
---
---Example:
---```
---init_worker_by_lua_block {
--- prometheus = require("prometheus").init("prometheus_metrics")
---
--- metric_latency = prometheus:histogram(
--- "nginx_http_request_duration_seconds", "HTTP request latency", {"host"})
--- metric_response_sizes = prometheus:histogram(
--- "nginx_http_response_size_bytes", "Size of HTTP responses", nil,
--- {10,100,1000,10000,100000,1000000})
---}
---```
---@param name string is the name of the metric.
---@param description? string is the text description. Optional.
---@param label_names? string[] is an array of label names for the metric. Optional.
---@param buckets? number[] is an array of numbers defining bucket boundaries. Optional, defaults to 20 latency buckets covering a range from 5ms to 10s (in seconds).
---@return PrometheusHist
function Prometheus:histogram(name, description, label_names, buckets) end
---Presents all metrics in a text format compatible with Prometheus.
---This should be called in [content_by_lua_block](https://github.com/openresty/lua-nginx-module#content_by_lua_block)
---to expose the metrics on a separate HTTP page.
---
---Example:
---```
---location /metrics {
--- content_by_lua_block { prometheus:collect() }
--- allow 192.168.0.0/16;
--- deny all;
---}
---```
function Prometheus:collect() end
---Returns metric data as an array of strings.
---@return string[]
function Prometheus:metric_data() end
---@class PrometheusCounter
local PrometheusCounter = {}
---Increments a previously registered counter.
---This is usually called from log_by_lua_block globally or per server/location.
---
---The number of label values should match the number of label names
---defined when the counter was registered using `prometheus:counter()`.
---No label values should be provided for counters with no labels.
---Non-printable characters will be stripped from label values.
---
---Example:
---```
---log_by_lua_block {
--- metric_bytes:inc(tonumber(ngx.var.request_length))
--- metric_requests:inc(1, {ngx.var.server_name, ngx.var.status})
---}
---```
---@param value number is a value that should be added to the counter. Defaults to 1.
---@param label_values? string[] is an array of label values.
function PrometheusCounter:inc(value, label_values) end
---Delete a previously registered counter.
---This is usually called when you don't need to observe such counter
---(or a metric with specific label values in this counter) any more.
---If this counter has labels, you have to pass `label_values` to delete
---the specific metric of this counter.
---If you want to delete all the metrics of a counter with labels,
---you should call `Counter:reset()`.
---
---This function will wait for sync_interval before deleting the metric to
---allow all workers to sync their counters.
---@param label_values string[] The number of label values should match the number of label names defined when the counter was registered using `prometheus:counter()`. No label values should be provided for counters with no labels. Non-printable characters will be stripped from label values.
function PrometheusCounter:del(label_values) end
---Delete all metrics for a previously registered counter.
---If this counter have no labels, it is just the same as `Counter:del()` function.
---If this counter have labels, it will delete all the metrics with different label values.
---
---This function will wait for `sync_interval` before deleting the metrics to allow all workers to sync their counters.
function PrometheusCounter:reset() end
---@class PrometheusGauge
local PrometheusGauge = {}
---Sets the current value of a previously registered gauge.
---This could be called from
---[log_by_lua_block](https://github.com/openresty/lua-nginx-module#log_by_lua_block)
---globally or per server/location to modify a gauge on each request, or from
---[content_by_lua_block](https://github.com/openresty/lua-nginx-module#content_by_lua_block)
---just before `prometheus::collect()` to return a real-time value.
---
---@param value number is a value that the gauge should be set to. Required.
---@param label_values? string[] is an array of label values.
function PrometheusGauge:set(value, label_values) end
---Increments a previously registered gauge.
---This is usually called from log_by_lua_block globally or per server/location.
---
---The number of label values should match the number of label names
---defined when the gauge was registered using `prometheus:gauge()`.
---No label values should be provided for gauge with no labels.
---Non-printable characters will be stripped from label values.
---@param value number is a value that should be added to the gauge. Defaults to 1.
---@param label_values? string[] is an array of label values.
function PrometheusGauge:inc(value, label_values) end
---Delete a previously registered gauge.
---This is usually called when you don't need to observe such gauge
---(or a metric with specific label values in this gauge) any more.
---If this gauge has labels, you have to pass `label_values` to delete
---the specific metric of this gauge.
---If you want to delete all the metrics of a gauge with labels,
---you should call `Gauge:reset()`.
---
---This function will wait for sync_interval before deleting the metric to
---allow all workers to sync their counters.
---@param label_values string[] The number of label values should match the number of label names defined when the gauge was registered using `prometheus:gauge()`. No label values should be provided for counters with no labels. Non-printable characters will be stripped from label values.
function PrometheusGauge:del(label_values) end
---Delete all metrics for a previously registered gauge.
---If this gauge have no labels, it is just the same as `Gauge:del()` function.
---If this gauge have labels, it will delete all the metrics with different
---label values.
function PrometheusGauge:reset() end
---@class PrometheusHist
local PrometheusHist = {}
---Records a value in a previously registered histogram.
---Usually called from
---[log_by_lua_block](https://github.com/openresty/lua-nginx-module#log_by_lua_block)
---globally or per server/location.
---
---Example:
---```
---log_by_lua_block {
--- metric_latency:observe(tonumber(ngx.var.request_time), {ngx.var.server_name})
--- metric_response_sizes:observe(tonumber(ngx.var.bytes_sent))
---}
---```
---@param value number is a value that should be recorded. Required.
---@param label_values? string[] is an array of label values.
function PrometheusHist:observe(value, label_values) end
---Delete all metrics for a previously registered histogram.
---
---This function will wait for `sync_interval` before deleting the
---metrics to allow all workers to sync their counters.
function PrometheusHist:reset() end
return PrometheusLib

View File

@@ -0,0 +1,74 @@
---@meta
local aes = {}
---@alias resty.aes.cipher.name
---| '"ecb"'
---| '"cbc"'
---| '"cfb1"'
---| '"cfb128"'
---| '"cfb8"'
---| '"ctr"
---| '"gcm"'
---| '"ofb"'
---@alias resty.aes.cipher.size '128'|'192'|'256'
---@class resty.aes.cipher : table
---@field size resty.aes.cipher.size
---@field cipher resty.aes.cipher.name
---@field method userdata
---@param size resty.aes.cipher.size # cipher size (default `128`)
---@param cipher? resty.aes.cipher.name # cipher name (default `"cbc"`)
---@return resty.aes.cipher?
function aes.cipher(size, cipher) end
---@class resty.aes.hash_table : table
---@field iv string
---@field method? fun(key:string):string
---@class resty.aes.hash_cdata : userdata
---@type table<string, resty.aes.hash_cdata>
aes.hash = {}
aes.hash.sha1 = {}
aes.hash.md5 = {}
aes.hash.sha224 = {}
aes.hash.sha512 = {}
aes.hash.sha256 = {}
aes.hash.sha384 = {}
---@alias resty.aes.hash resty.aes.hash_cdata|resty.aes.hash_table
---@param key string encryption key
---@param salt? string if provided, must be exactly 8 characters in length
---@param cipher? resty.aes.cipher (default is 128 CBC)
---@param hash? resty.aes.hash (default is md5)
---@param hash_rounds? number (default: `1`)
---@param iv_len? number
---@param enable_padding? boolean (default: `true`)
---
---@return resty.aes?
---@return string? error
function aes:new(key, salt, cipher, hash, hash_rounds, iv_len, enable_padding) end
---@class resty.aes : table
local aes_ctx = {}
--- Decrypt a string
---
---@param s string
---@param tag? string
---@return string? decrypted
---@return string? error
function aes_ctx:decrypt(s, tag) end
--- Encrypt a string.
---
---@param s string
---@return string? encrypted
---@return string? error
function aes_ctx:encrypt(s) end
return aes

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core = {}
resty_core.version = require("resty.core.base").version
return resty_core

View File

@@ -0,0 +1,51 @@
---@meta
local resty_core_base = {}
---@param ... string
function resty_core_base.allows_subsystem(...) end
---@param t table
function resty_core_base.clear_tab(t) end
---@return userdata
function resty_core_base.get_errmsg_ptr() end
---@return userdata
function resty_core_base.get_request() end
---@return userdata
function resty_core_base.get_size_ptr() end
---@param size number
---@param must_alloc? boolean
---@return userdata
function resty_core_base.get_string_buf(size, must_alloc) end
---@return number
function resty_core_base.get_string_buf_size() end
---@param narr number
---@param nrec number
---@return table
function resty_core_base.new_tab(narr, nrec) end
---@param tb table
---@param key any
---@return any
function resty_core_base.ref_in_table(tb, key) end
---@param size number
function resty_core_base.set_string_buf_size(size) end
resty_core_base.FFI_OK = 0
resty_core_base.FFI_NO_REQ_CTX = -100
resty_core_base.FFI_BAD_CONTEXT = -101
resty_core_base.FFI_ERROR = -1
resty_core_base.FFI_AGAIN = -2
resty_core_base.FFI_BUSY = -3
resty_core_base.FFI_DONE = -4
resty_core_base.FFI_DECLINED = -5
resty_core_base.version = "0.1.23"
return resty_core_base

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_base64 = {}
resty_core_base64.version = require("resty.core.base").version
return resty_core_base64

View File

@@ -0,0 +1,9 @@
---@meta
local resty_core_ctx = {}
resty_core_ctx._VERSION = require("resty.core.base").version
---@param ctx? table
---@return table
function resty_core_ctx.get_ctx_table(ctx) end
return resty_core_ctx

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_exit = {}
resty_core_exit.version = require("resty.core.base").version
return resty_core_exit

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_hash = {}
resty_core_hash.version = require("resty.core.base").version
return resty_core_hash

View File

@@ -0,0 +1,6 @@
---@meta
local resty_core_misc = {}
function resty_core_misc.register_ngx_magic_key_getter() end
function resty_core_misc.register_ngx_magic_key_setter() end
resty_core_misc._VERSION = require("resty.core.base").version
return resty_core_misc

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_ndk = {}
resty_core_ndk.version = require("resty.core.base").version
return resty_core_ndk

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_phase = {}
resty_core_phase.version = require("resty.core.base").version
return resty_core_phase

View File

@@ -0,0 +1,55 @@
---@meta
---@class resty.core.regex
---@field no_pcre boolean
local regex = {}
---@param ratio integer
function regex.set_buf_grow_ratio(ratio) end
---@return boolean is_empty
function regex.is_regex_cache_empty() end
---@class resty.core.regex.compiled : ffi.cdata*
---@field captures ffi.cdata*
---@field ncaptures integer
---@field name_count integer
---@field name_table ffi.cdata*
---@field name_entry_size integer
---@param compiled resty.core.regex.compiled
---@param flags integer
---@param res ngx.re.captures
function regex.collect_captures(compiled, flags, res) end
---@param compiled resty.core.regex.compiled
function regex.destroy_compiled_regex(compiled) end
---@param re string
---@param opts ngx.re.options
---@return resty.core.regex.compiled? compiled
---@return boolean|string compile_once_or_error
---@return integer? flags
function regex.re_match_compile(re, opts) end
---@param buf ffi.cdata*
---@param buf_size integer
---@param pos integer
---@param len integer
---@param new_len integer
---@param must_alloc boolean
---@return ffi.cdata* buf
---@return integer buf_size
---@return integer new_len
function regex.check_buf_size(buf, buf_size, pos, len, new_len, must_alloc) end
---@param re string
---@param opts ngx.re.options
---@param replace? string
---@param func? fun(match:string):string
---@return resty.core.regex.compiled? compiled
---@return boolean|string compile_once_or_error
---@return integer? flags
function regex.re_sub_compile(re, opts, replace, func) end
return regex

View File

@@ -0,0 +1,5 @@
---@meta
local resty_core_request = {}
resty_core_request.version = require("resty.core.base").version
function resty_core_request.set_req_header(name, value, override) end
return resty_core_request

View File

@@ -0,0 +1,5 @@
---@meta
local resty_core_response = {}
function resty_core_response.set_resp_header() end
resty_core_response.version = require("resty.core.base").version
return resty_core_response

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_shdict = {}
resty_core_shdict.version = require("resty.core.base").version
return resty_core_shdict

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_time = {}
resty_core_time.version = require("resty.core.base").version
return resty_core_time

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_uri = {}
resty_core_uri.version = require("resty.core.base").version
return resty_core_uri

View File

@@ -0,0 +1,10 @@
---@meta
local resty_core_utils = {}
---@param str string
---@param find string
---@param replace string
---@return string
function resty_core_utils.str_replace_char(str, find, replace) end
resty_core_utils.version = require("resty.core.base").version
return resty_core_utils

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_var = {}
resty_core_var.version = require("resty.core.base").version
return resty_core_var

View File

@@ -0,0 +1,4 @@
---@meta
local resty_core_worker = {}
resty_core_worker._VERSION = require("resty.core.base").version
return resty_core_worker

View File

@@ -0,0 +1,395 @@
---@meta
---
--- lua-resty-dns - Lua DNS resolver for the ngx_lua based on the cosocket API
---
--- https://github.com/openresty/lua-resty-dns
---
---# Description
---
--- This Lua library provides a DNS resolver for the ngx_lua nginx module:
---
--- https://github.com/openresty/lua-nginx-module/#readme
---
--- This Lua library takes advantage of ngx_lua's cosocket API, which ensures
--- 100% nonblocking behavior.
---
--- Note that at least [ngx_lua 0.5.12](https://github.com/openresty/lua-nginx-module/tags) or [OpenResty 1.2.1.11](http://openresty.org/#Download) is required.
---
--- Also, the [bit library](http://bitop.luajit.org/) is also required. If you're using LuaJIT 2.0 with ngx_lua, then the `bit` library is already available by default.
---
--- Note that, this library is bundled and enabled by default in the [OpenResty bundle](http://openresty.org/).
---
--- IMPORTANT: to be able to generate unique ids, the random generator must be properly seeded using `math.randomseed` prior to using this module.
---
---# Automatic Error Logging
---
--- By default, the underlying [ngx_lua](https://github.com/openresty/lua-nginx-module/#readme) module does error logging when socket errors happen. If you are already doing proper error handling in your own Lua code, then you are recommended to disable this automatic error logging by turning off [ngx_lua](https://github.com/openresty/lua-nginx-module/#readme)'s [lua_socket_log_errors](https://github.com/openresty/lua-nginx-module/#lua_socket_log_errors) directive, that is:
---
---```nginx
--- lua_socket_log_errors off;
---```
---
---# Limitations
---
--- * This library cannot be used in code contexts like `set_by_lua*`, `log_by_lua*`, and `header_filter_by_lua*` where the ngx_lua cosocket API is not available.
--- * The `resty.dns.resolver` object instance cannot be stored in a Lua variable at the Lua module level, because it will then be shared by all the concurrent requests handled by the same nginx worker process (see https://github.com/openresty/lua-nginx-module/#data-sharing-within-an-nginx-worker ) and result in bad race conditions when concurrent requests are trying to use the same `resty.dns.resolver` instance. You should always initiate `resty.dns.resolver` objects in function local variables or in the `ngx.ctx` table. These places all have their own data copies for each request.
---
---@class resty.dns.resolver
---@field _VERSION string
---
--- undocumented/private fields--use at your own risk
---
---@field cur integer
---@field socks udpsock[]
---@field tcp_sock tcpsock
---@field servers resty.dns.resolver.nameserver_tuple[]
---@field retrans integer
---@field no_recurse boolean
local resolver = {}
--- The `A` resource record type, equal to the decimal number 1.
---@class resty.dns.resolver.TYPE_A
resolver.TYPE_A = 1
--- The `NS` resource record type, equal to the decimal number `2`.
---@class resty.dns.resolver.TYPE_NS
resolver.TYPE_NS = 2
--- The `CNAME` resource record type, equal to the decimal number `5`.
---@class resty.dns.resolver.TYPE_CNAME
resolver.TYPE_CNAME = 5
--- The `SOA` resource record type, equal to the decimal number `6`.
---@class resty.dns.resolver.TYPE_SOA
resolver.TYPE_SOA = 6
--- The `PTR` resource record type, equal to the decimal number `12`.
---@class resty.dns.resolver.TYPE_PTR
resolver.TYPE_PTR = 12
--- The `MX` resource record type, equal to the decimal number `15`.
---@class resty.dns.resolver.TYPE_MX
resolver.TYPE_MX = 15
--- The `TXT` resource record type, equal to the decimal number `16`.
---@class resty.dns.resolver.TYPE_TXT
resolver.TYPE_TXT = 16
--- The `AAAA` resource record type, equal to the decimal number `28`.
---@class resty.dns.resolver.TYPE_AAAA
resolver.TYPE_AAAA = 28
--- The `SRV` resource record type, equal to the decimal number `33`.
---
--- See RFC 2782 for details.
---@class resty.dns.resolver.TYPE_SRV
resolver.TYPE_SRV = 33
--- The `SPF` resource record type, equal to the decimal number `99`.
---
--- See RFC 4408 for details.
---@class resty.dns.resolver.TYPE_SPF
resolver.TYPE_SPF = 99
---@alias resty.dns.resolver.TYPE integer
---| `resolver.TYPE_A` # A
---| 1 # A
---| `resolver.TYPE_NS` # NS
---| 2 # NS
---| `resolver.TYPE_CNAME` # CNAME
---| 5 # CNAME
---| `resolver.TYPE_SOA` # SOA
---| 6 # SOA
---| `resolver.TYPE_PTR` # PTR
---| 12 # PTR
---| `resolver.TYPE_MX` # MX
---| 15 # MX
---| `resolver.TYPE_TXT` # TXT
---| 16 # TXT
---| `resolver.TYPE_AAAA` # AAAA
---| 28 # AAAA
---| `resolver.TYPE_SRV` # SRV
---| 33 # SRV
---| `resolver.TYPE_SPF` # SPF
---| 99 # SPF
---@alias resty.dns.resolver.CLASS integer
---| `resolver.CLASS_IN`
---| 1
--- The `Internet` resource record type
---@class resty.dns.resolver.CLASS_IN
resolver.CLASS_IN = 1
---@alias resty.dns.resolver.SECTION integer
---| `resolver.SECTION_AN` # Answer section
---| 1 # Answer section
---| `resolver.SECTION_NS` # Authority section
---| 2 # Authority section
---| `resolver.SECTION_AR` # Additional section
---| 3 # Additional section
--- Identifier of the `Answer` section in the DNS response.
---@class resty.dns.resolver.SECTION_AN
resolver.SECTION_AN = 1
--- Identifier of the `Authority` section in the DNS response.
---@class resty.dns.resolver.SECTION_NS
resolver.SECTION_NS = 2
--- Identifier of the `Additional` section in the DNS response.
---@class resty.dns.resolver.SECTION_AR
resolver.SECTION_AR = 3
---@alias resty.dns.resolver.ERRCODE integer
---| 1 # format error
---| 2 # server failure
---| 3 # name error
---| 4 # not implemented
---| 5 # refused
---@alias resty.dns.resolver.ERRSTR
---| "format error" # errcode 1
---| "server failure" # errcode 2
---| "name error" # errcode 3
---| "not implemented" # errcode 4
---| "refused" # errcode 5
---| "unknown" # errcode unknown
--- Creates a dns.resolver object.
---
--- On error, returns `nil` and an error string.
---
---@param opts resty.dns.resolver.new.opts
---@return resty.dns.resolver? resolver
---@return string? error
function resolver:new(opts) end
---@class resty.dns.resolver.nameserver_tuple
---@field [1] string # hostname or addr
---@field [2] integer # port number
---@alias resty.dns.resolver.nameserver
---| string
---| resty.dns.resolver.nameserver_tuple
--- Options for `resty.dns.resolver:new()`
---
---@class resty.dns.resolver.new.opts : table
---
---@field nameservers resty.dns.resolver.nameserver[] # a list of nameservers to be used. Each nameserver entry can be either a single hostname string or a table holding both the hostname string and the port number. The nameserver is picked up by a simple round-robin algorithm for each `query` method call. This option is required.
---
---@field retrans? number # (default: `5`) the total number of times of retransmitting the DNS request when receiving a DNS response times out according to the `timeout` setting. When trying to retransmit the query, the next nameserver according to the round-robin algorithm will be picked up.
---
---@field timeout? number # (default: `2000`) the time in milliseconds for waiting for the response for a single attempt of request transmission. note that this is ''not'' the maximal total waiting time before giving up, the maximal total waiting time can be calculated by the expression `timeout x retrans`. The `timeout` setting can also be changed by calling the `set_timeout` method.
---
---@field no_recurse? boolean # (default: `false`) a boolean flag controls whether to disable the "recursion desired" (RD) flag in the UDP request.
---
---@field no_random? boolean # (default: `false`) a boolean flag controls whether to randomly pick the nameserver to query first, if `true` will always start with the first nameserver listed.
--- Performs a DNS standard query.
---
--- The query is sent to the nameservers specified by the `new` method, and
---
--- Returns all the answer records in an array-like Lua table.
---
--- In case of errors, it will return nil and a string describing the error instead.
---
--- If the server returns a non-zero error code, the fields `errcode` and `errstr` will be set accordingly in the Lua table returned.
---
--- The optional parameter `tries` can be provided as an empty table, and will be returned as a third result. The table will be an array with the error message for each (if any) failed try.
---
--- When data truncation happens, the resolver will automatically retry using the TCP transport mode to query the current nameserver. All TCP connections are short lived.
---
---@param qname string
---@param opts? resty.dns.resolver.query.opts
---@param tries? string[]
---@return resty.dns.resolver.query.answer[] results
---@return string? error
---@return string[]? tries
function resolver:query(qname, opts, tries) end
---@class resty.dns.resolver.answer : table
---
---@field name string # The resource record name.
---
---@field type resty.dns.resolver.TYPE # The current resource record type, possible values are 1 (TYPE_A), 5 (TYPE_CNAME), 28 (TYPE_AAAA), and any other values allowed by RFC 1035.
---
---@field section resty.dns.resolver.SECTION # The identifier of the section that the current answer record belongs to. Possible values are 1 (SECTION_AN), 2 (SECTION_NS), and 3 (SECTION_AR).
---
---@field ttl number # The time-to-live (TTL) value in seconds for the current resource record.
---
---@field class resty.dns.resolver.CLASS # The current resource record class, possible values are 1 (CLASS_IN) or any other values allowed by RFC 1035.
---
---@field rdata string # The raw resource data (RDATA) for resource records that are not recognized.
---
---@field errcode? resty.dns.resolver.ERRCODE # Error code returned by the DNS server
---
---@field errstr? resty.dns.resolver.ERRSTR # Error string returned by the DNS server
--- A-type answer
---
---@class resty.dns.resolver.answer.A : resty.dns.resolver.answer
---
---@field address string # The IPv4 address.
--- AAAA-type answer
---
---@class resty.dns.resolver.answer.AAAA : resty.dns.resolver.answer
---
---@field address string # The IPv6 address. Successive 16-bit zero groups in IPv6 addresses will not be compressed by default, if you want that, you need to call the compress_ipv6_addr static method instead.
--- CNAME-type answer
---
---@class resty.dns.resolver.answer.CNAME : resty.dns.resolver.answer
---
---@field cname? string # The (decoded) record data value for CNAME resource records.
--- MX-type answer
---
---@class resty.dns.resolver.answer.MX : resty.dns.resolver.answer
---
---@field preference integer # The preference integer number for MX resource records.
---
---@field exchange? string # The exchange domain name for MX resource records.
--- SRV-type answer
---
---@class resty.dns.resolver.answer.SRV : resty.dns.resolver.answer
---
---@field priority number
---
---@field weight number
---
---@field port integer
---
---@field target string
--- NS-type answer
---
---@class resty.dns.resolver.answer.NS : resty.dns.resolver.answer
---
---@field nsdname string # A domain-name which specifies a host which should be authoritative for the specified class and domain. Usually present for NS type records.
---
--- TXT-type answer
---
---@class resty.dns.resolver.answer.TXT : resty.dns.resolver.answer
---
---@field txt? string|string[] # The record value for TXT records. When there is only one character string in this record, then this field takes a single Lua string. Otherwise this field takes a Lua table holding all the strings.
--- SPF-type answer
---
---@class resty.dns.resolver.answer.SPF : resty.dns.resolver.answer
---
---@field spf? string|string[] # The record value for SPF records. When there is only one character string in this record, then this field takes a single Lua string. Otherwise this field takes a Lua table holding all the strings.
--- PTR-type answer
---
---@class resty.dns.resolver.answer.PTR : resty.dns.resolver.answer
---
---@field ptrdname string # The record value for PTR records.
--- SOA-type answer
---
---@class resty.dns.resolver.answer.SOA : resty.dns.resolver.answer
---
---@field serial integer # SOA serial
---@field refresh integer # SOA refresh
---@field retry integer # SOA retry
---@field expire integer # SOA expire
---@field minimum integer # SOA minimum
---@alias resty.dns.resolver.query.answer
---| resty.dns.resolver.answer
---| resty.dns.resolver.answer.A
---| resty.dns.resolver.answer.AAAA
---| resty.dns.resolver.answer.CNAME
---| resty.dns.resolver.answer.MX
---| resty.dns.resolver.answer.NS
---| resty.dns.resolver.answer.PTR
---| resty.dns.resolver.answer.SOA
---| resty.dns.resolver.answer.SPF
---| resty.dns.resolver.answer.SRV
---| resty.dns.resolver.answer.TXT
--- Options for `resty.dns.resolver:query()`
---
---@class resty.dns.resolver.query.opts : table
---
---@field qtype? resty.dns.resolver.TYPE # (default: `1`) The type of the question. Possible values are 1 (TYPE_A), 5 (TYPE_CNAME), 28 (TYPE_AAAA), or any other QTYPE value specified by RFC 1035 and RFC 3596.
---
---@field authority_section? boolean # (default: `false`) When `true`, the answers return value includes the `Authority` section of the DNS response.
---
---@field additional_section? boolean # (default: `false`) When `true`, the answers return value includes the `Additional` section of the DNS response.
--- Just like the query method, but enforce the TCP transport mode instead of UDP.
---
--- All TCP connections are short lived.
---
---@param qname string
---@param opts? resty.dns.resolver.query.opts
---@return resty.dns.resolver.query.answer[] results
---@return string? error
function resolver:tcp_query(qname, opts) end
--- Performs a PTR lookup for both IPv4 and IPv6 addresses.
---
--- This function is basically a wrapper for the query command which uses the `arpa_str` function to convert the IP address on the fly.
---
---@param addr string
---@return resty.dns.resolver.query.answer[] results
---@return string? error
function resolver:reverse_query(addr) end
--- Overrides the current timeout setting for all nameserver peers.
---
---@param timeout number # timeout in milliseconds
function resolver:set_timeout(timeout) end
--- Compresses the successive 16-bit zero groups in the textual format of the IPv6 address.
---
--- For example, the following will yield `FF01::101` in the new_addr return value:
---
---```lua
--- local resolver = require "resty.dns.resolver"
--- local compress = resolver.compress_ipv6_addr
--- local new_addr = compress("FF01:0:0:0:0:0:0:101")
---```
---
---@param addr string
---@return string compressed
function resolver.compress_ipv6_addr(addr) end
--- Expands the successive 16-bit zero groups in the textual format of the IPv6 address.
---
--- For example, the following will yield `FF01:0:0:0:0:0:0:101` in the new_addr return value:
---
---```lua
--- local resolver = require "resty.dns.resolver"
--- local expand = resolver.expand_ipv6_addr
--- local new_addr = expand("FF01::101")
---```
---
---@param addr string
---@return string expanded
function resolver.expand_ipv6_addr(addr) end
--- Generates the reverse domain name for PTR lookups for both IPv4 and IPv6 addresses.
---
--- Compressed IPv6 addresses will be automatically expanded.
---
--- For example, the following will yield `4.3.2.1.in-addr.arpa` for `ptr4` and `1.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.F.F.ip6.arpa` for `ptr6`:
---
---```lua
--- local resolver = require "resty.dns.resolver"
--- local ptr4 = resolver.arpa_str("1.2.3.4")
--- local ptr6 = resolver.arpa_str("FF01::101")
---```
---
---@param addr string
---@return string
function resolver.arpa_str(addr) end
return resolver

View File

@@ -0,0 +1,11 @@
---@meta
resty_limit_conn = {}
function resty_limit_conn.set_conn(self, conn) end
function resty_limit_conn.uncommit(self, key) end
function resty_limit_conn.is_committed(self) end
function resty_limit_conn.new(dict_name, max, burst, default_conn_delay) end
function resty_limit_conn.set_burst(self, burst) end
function resty_limit_conn.leaving(self, key, req_latency) end
function resty_limit_conn.incoming(self, key, commit) end
resty_limit_conn._VERSION = "0.06"
return resty_limit_conn

View File

@@ -0,0 +1,7 @@
---@meta
resty_limit_count = {}
function resty_limit_count.uncommit(self, key) end
function resty_limit_count.incoming(self, key, commit) end
resty_limit_count._VERSION = "0.06"
function resty_limit_count.new(dict_name, limit, window) end
return resty_limit_count

View File

@@ -0,0 +1,9 @@
---@meta
resty_limit_req = {}
function resty_limit_req.set_rate(self, rate) end
function resty_limit_req.uncommit(self, key) end
function resty_limit_req.set_burst(self, burst) end
function resty_limit_req.new(dict_name, rate, burst) end
function resty_limit_req.incoming(self, key, commit) end
resty_limit_req._VERSION = "0.06"
return resty_limit_req

View File

@@ -0,0 +1,5 @@
---@meta
resty_limit_traffic = {}
resty_limit_traffic._VERSION = "0.06"
function resty_limit_traffic.combine(limiters, keys, states) end
return resty_limit_traffic

View File

@@ -0,0 +1,125 @@
---@meta
--- lua-resty-lock
---
--- https://github.com/openresty/lua-resty-lock
---
---@class resty.lock : table
local lock = {
_VERSION = "0.08",
}
---@class resty.lock.opts : table
---
--- Specifies expiration time (in seconds) for the lock entry in the shared memory
--- dictionary. You can specify up to 0.001 seconds. Default to 30 (seconds). Even
--- if the invoker does not call unlock or the object holding the lock is not GC'd,
--- the lock will be released after this time. So deadlock won't happen even when the
--- worker process holding the lock crashes.
---@field exptime number
---
--- Specifies the maximal waiting time (in seconds) for the lock method calls on
--- the current object instance. You can specify up to 0.001 seconds. Default to 5
--- (seconds). This option value cannot be bigger than `exptime`. This timeout is
--- to prevent a lock method call from waiting forever. You can specify 0 to make
--- the lock method return immediately without waiting if it cannot acquire the
--- lock right away.
---@field timeout number
---
--- Specifies the initial step (in seconds) of sleeping when waiting for the lock.
--- Default to 0.001 (seconds). When the lock method is waiting on a busy lock, it
--- sleeps by steps. The step size is increased by a ratio (specified by the ratio
--- option) until reaching the step size limit (specified by the max_step option).
---@field step number
---
--- Specifies the step increasing ratio. Default to 2, that is, the step size
--- doubles at each waiting iteration.
---@field ratio number
---
--- Specifies the maximal step size (i.e., sleep interval, in seconds) allowed.
--- See also the step and ratio options). Default to 0.5 (seconds).
---@field max_step number
--- Creates a new lock object instance by specifying the shared dictionary name
--- (created by `lua_shared_dict`) and an optional options table `opts`.
---
---@param dict_name string
---@param opts? resty.lock.opts
---@return resty.lock? lock
---@return string? err
function lock.new(_, dict_name, opts) end
--- Tries to lock a key across all the Nginx worker processes in the current
--- NGINX server instance. Different keys are different locks.
---
--- The length of the key string must not be larger than 65535 bytes.
---
--- Returns the waiting time (in seconds) if the lock is successfully acquired.
--- Otherwise returns `nil` and a string describing the error.
---
--- The waiting time is not from the wallclock, but rather is from simply adding
--- up all the waiting "steps". A nonzero elapsed return value indicates that
--- someone else has just hold this lock. But a zero return value cannot gurantee
--- that no one else has just acquired and released the lock.
---
--- When this method is waiting on fetching the lock, no operating system threads
--- will be blocked and the current Lua "light thread" will be automatically yielded
--- behind the scene.
---
--- It is strongly recommended to always call the unlock() method to actively
--- release the lock as soon as possible.
---
--- If the `unlock()` method is never called after this method call, the lock
--- will get released when
---
--- The current `resty.lock` object instance is collected automatically by the Lua GC.
--- OR
--- The exptime for the lock entry is reached.
---
--- Common errors for this method call is
---
--- "timeout" : The timeout threshold specified by the timeout option of the new method is exceeded.
--- "locked" : The current `resty.lock` object instance is already holding a lock (not necessarily of the same key).
---
--- Other possible errors are from ngx_lua's shared dictionary API.
---
--- It is required to create different `resty.lock` instances for multiple
--- simultaneous locks (i.e., those around different keys).
---
---@param key string
---@return number? elapsed
---@return string? error
function lock:lock(key) end
--- Releases the lock held by the current `resty.lock` object instance.
---
--- Returns 1 on success. Returns `nil` and a string describing the error otherwise.
---
--- If you call unlock when no lock is currently held, the error "unlocked" will
--- be returned.
---
---@return boolean ok
---@return string? error
function lock:unlock() end
--- Sets the TTL of the lock held by the current `resty.lock` object instance.
--- This will reset the timeout of the lock to timeout seconds if it is given,
--- otherwise the timeout provided while calling new will be used.
---
--- Note that the timeout supplied inside this function is independent from the
--- timeout provided while calling new. Calling `expire()` will not change the
--- timeout value specified inside new and subsequent `expire(nil)` call will
--- still use the timeout number from new.
---
--- Returns true on success. Returns `nil` and a string describing the error
--- otherwise.
---
--- If you call expire when no lock is currently held, the error "unlocked" will
--- be returned.
---
---@param timeout? number
---@return boolean ok
---@return string? error
function lock:expire(timeout) end
return lock

View File

@@ -0,0 +1,107 @@
---@meta
---@class resty.lrucache : table
local lrucache = {
_VERSION = "0.11",
}
--- User flags value associated with the item to be stored.
---
--- It can be retrieved later with the item. The user flags are stored as an
--- unsigned 32-bit integer internally, and thus must be specified as a Lua
--- number. If not specified, flags will have a default value of 0. This
--- argument was added in the v0.10 release.
---
---@alias resty.lrucache.flags integer
--- Creates a new cache instance.
---
--- Upon failure, returns nil and a string describing the error.
---
---@param max_items number specifies the maximal number of items this cache can hold.
---@return resty.lrucache? cache
---@return string? error
function lrucache.new(max_items) end
--- Sets a key with a value and an expiration time.
---
--- When the cache is full, the cache will automatically evict the least
--- recently used item.
---
---
---@param key string
---@param value any
---@param ttl? number Expiration time, in seconds. If omitted, the value never expires.
---@param flags? resty.lrucache.flags
function lrucache:set(key, value, ttl, flags) end
--- Fetches a value with the key.
---
--- If the key does not exist in the cache or has already expired, `nil` will
--- be returned.
---
--- Starting from v0.03, the stale data is also returned as the second return
--- value if available.
---
---@param key string
---@return any? data
---@return any? stale_data
---@return resty.lrucache.flags? integer
function lrucache:get(key) end
--- Removes an item specified by the key from the cache.
---
---@param key string
function lrucache:delete(key) end
--- Returns the number of items currently stored in the cache, including expired
--- items if any.
---
--- The returned count value will always be greater or equal to 0 and smaller
--- than or equal to the size argument given to cache:new.
---
--- This method was added in the v0.10 release.
---
---@return integer
function lrucache:count() end
--- Returns the maximum number of items the cache can hold.
---
--- The return value is the same as the size argument given to
--- `resty.lrucache.new()` when the cache was created.
---
--- This method was added in the v0.10 release.
---
---@return integer
function lrucache:capacity() end
--- Fetch the list of keys currently inside the cache, up to `max_count`.
---
--- The keys will be ordered in MRU fashion (Most-Recently-Used keys first).
---
--- This function returns a Lua (array) table (with integer keys) containing
--- the keys.
---
--- When `max_count` is `nil` or `0`, all keys (if any) will be returned.
---
--- When provided with a `res` table argument, this function will not allocate a
--- table and will instead insert the keys in `res`, along with a trailing `nil`
--- value.
---
--- This method was added in the v0.10 release.
---
---@param max_count? integer
---@param res? table
---@return table keys
function lrucache:get_keys(max_count, res) end
--- Flushes all the existing data (if any) in the current cache instance.
---
--- This is an O(1) operation and should be much faster than creating a brand
--- new cache instance.
---
--- Note however that the `flush_all()` method of `resty.lrucache.pureffi` is any
--- O(n) operation.
function lrucache:flush_all() end
return lrucache

View File

@@ -0,0 +1,18 @@
---@meta
---@class resty.lrucache.pureffi : resty.lrucache
local lrucache_pureffi = {
_VERSION = "0.11",
}
--- Creates a new cache instance.
---
--- Upon failure, returns nil and a string describing the error.
---
---@param max_items number specifies the maximal number of items this cache can hold.
---@param load_factor? number designates the "load factor" of the FFI-based hash-table used internally by `resty.lrucache.pureffi`; the default value is 0.5 (i.e. 50%); if the load factor is specified, it will be clamped to the range of [0.1, 1] (i.e. if load factor is greater than 1, it will be saturated to 1; likewise, if load-factor is smaller than 0.1, it will be clamped to 0.1).
---@return resty.lrucache.pureffi? cache
---@return string? error
function lrucache_pureffi.new(max_items, load_factor) end
return lrucache_pureffi

View File

@@ -0,0 +1,16 @@
---@meta
---@class resty.md5 : resty.string.checksum
local md5 = {}
--- Create a new md5 checksum object.
---@return resty.md5
function md5:new() end
--- Add a string to the md5 checksum data
---@param s string
---@param len? number Optional length (defaults to the length of `s`)
---@return boolean ok
function md5:update(s, len) end
return md5

View File

@@ -0,0 +1,27 @@
---@meta
resty_memcached = {}
function resty_memcached.cas(self, key, value, cas_uniq, exptime, flags) end
function resty_memcached.new(self, opts) end
function resty_memcached.append(self, ...) end
function resty_memcached.gets(self, key) end
function resty_memcached.quit(self) end
function resty_memcached.get_reused_times(self) end
function resty_memcached.close(self) end
function resty_memcached.touch(self, key, exptime) end
function resty_memcached.replace(self, ...) end
function resty_memcached.delete(self, key) end
function resty_memcached.version(self) end
function resty_memcached.set(self, ...) end
function resty_memcached.stats(self, args) end
function resty_memcached.flush_all(self, time) end
function resty_memcached.add(self, ...) end
function resty_memcached.set_timeout(self, timeout) end
function resty_memcached.incr(self, key, value) end
function resty_memcached.set_keepalive(self, ...) end
function resty_memcached.connect(self, ...) end
function resty_memcached.prepend(self, ...) end
function resty_memcached.decr(self, key, value) end
function resty_memcached.verbosity(self, level) end
resty_memcached._VERSION = "0.13"
function resty_memcached.get(self, key) end
return resty_memcached

View File

@@ -0,0 +1,15 @@
---@meta
resty_mysql = {}
function resty_mysql.read_result() end
function resty_mysql.new(self) end
function resty_mysql.connect(self, opts) end
function resty_mysql.server_ver(self) end
function resty_mysql.send_query() end
function resty_mysql.set_keepalive(self, ...) end
function resty_mysql.set_compact_arrays(self, value) end
function resty_mysql.query(self, query, est_nrows) end
function resty_mysql.set_timeout(self, timeout) end
function resty_mysql.close(self) end
resty_mysql._VERSION = "0.21"
function resty_mysql.get_reused_times(self) end
return resty_mysql

View File

@@ -0,0 +1,10 @@
---@meta
local random = {}
--- Generate random bytes.
---@param len integer
---@param strong boolean
---@return string
function random.bytes(len, strong) end
return random

View File

@@ -0,0 +1,57 @@
---@meta
resty_redis = {}
function resty_redis.lrange() end
function resty_redis.new(self) end
function resty_redis.hset() end
function resty_redis.hexists() end
function resty_redis.punsubscribe() end
function resty_redis.incr() end
function resty_redis.lindex() end
function resty_redis.read_reply(self) end
function resty_redis.sismember() end
function resty_redis.set() end
function resty_redis.unsubscribe() end
function resty_redis.linsert() end
function resty_redis.zrem() end
function resty_redis.add_commands(...) end
function resty_redis.array_to_hash(self, t) end
function resty_redis.mset() end
function resty_redis.commit_pipeline(self) end
function resty_redis.zrange() end
function resty_redis.auth() end
function resty_redis.cancel_pipeline(self) end
resty_redis._VERSION = "0.27"
function resty_redis.eval() end
function resty_redis.expire() end
function resty_redis.sdiff() end
function resty_redis.sinter() end
function resty_redis.hmset(self, hashname, ...) end
function resty_redis.zrank() end
function resty_redis.psubscribe() end
function resty_redis.sunion() end
function resty_redis.sadd() end
function resty_redis.srem() end
function resty_redis.script() end
function resty_redis.lpush() end
function resty_redis.init_pipeline(self, n) end
function resty_redis.zincrby() end
function resty_redis.get_reused_times(self) end
function resty_redis.zrangebyscore() end
function resty_redis.zadd() end
function resty_redis.subscribe() end
function resty_redis.hdel() end
function resty_redis.hget() end
function resty_redis.sort() end
function resty_redis.smembers() end
function resty_redis.connect(self, ...) end
function resty_redis.hmget() end
function resty_redis.set_timeout(self, timeout) end
function resty_redis.mget() end
function resty_redis.set_keepalive(self, ...) end
function resty_redis.llen() end
function resty_redis.del() end
function resty_redis.decr() end
function resty_redis.lpop() end
function resty_redis.close() end
function resty_redis.get() end
return resty_redis

View File

@@ -0,0 +1,4 @@
---@meta
local resty_sha = {}
resty_sha._VERSION = require("resty.string")._VERSION
return resty_sha

View File

@@ -0,0 +1,10 @@
---@meta
---@class resty.sha1 : resty.string.checksum
local sha1 = {}
--- Create a new sha1 checksum object.
---@return resty.sha1
function sha1:new() end
return sha1

View File

@@ -0,0 +1,10 @@
---@meta
---@class resty.sha244 : resty.string.checksum
local sha224 = {}
--- Create a new sha244 checksum object.
---@return resty.sha244
function sha224:new() end
return sha224

View File

@@ -0,0 +1,10 @@
---@meta
---@class resty.sha256 : resty.string.checksum
local sha256 = {}
--- Create a new sha256 checksum object.
---@return resty.sha256
function sha256:new() end
return sha256

View File

@@ -0,0 +1,10 @@
---@meta
---@class resty.sha384 : resty.string.checksum
local sha384 = {}
--- Create a new sha384 checksum object.
---@return resty.sha384
function sha384:new() end
return sha384

View File

@@ -0,0 +1,10 @@
---@meta
---@class resty.sha512 : resty.string.checksum
local sha512 = {}
--- Create a new sha512 checksum object.
---@return resty.sha512
function sha512:new() end
return sha512

View File

@@ -0,0 +1,60 @@
---@meta
local shell = {
version = 0.03,
}
--- Runs a shell command, `cmd`, with an optional stdin.
---
--- The `cmd` argument can either be a single string value (e.g. `"echo 'hello,
--- world'"`) or an array-like Lua table (e.g. `{"echo", "hello, world"}`). The
--- former is equivalent to `{"/bin/sh", "-c", "echo 'hello, world'"}`, but simpler
--- and slightly faster.
---
--- When the `stdin` argument is `nil` or `""`, the stdin device will immediately
--- be closed.
---
--- The `timeout` argument specifies the timeout threshold (in ms) for
--- stderr/stdout reading timeout, stdin writing timeout, and process waiting
--- timeout. The default is 10 seconds as per https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/pipe.md#set_timeouts
---
--- The `max_size` argument specifies the maximum size allowed for each output
--- data stream of stdout and stderr. When exceeding the limit, the `run()`
--- function will immediately stop reading any more data from the stream and return
--- an error string in the `reason` return value: `"failed to read stdout: too much
--- data"`.
---
--- Upon terminating successfully (with a zero exit status), `ok` will be `true`,
--- `reason` will be `"exit"`, and `status` will hold the sub-process exit status.
---
--- Upon terminating abnormally (non-zero exit status), `ok` will be `false`,
--- `reason` will be `"exit"`, and `status` will hold the sub-process exit status.
---
--- Upon exceeding a timeout threshold or any other unexpected error, `ok` will be
--- `nil`, and `reason` will be a string describing the error.
---
--- When a timeout threshold is exceeded, the sub-process will be terminated as
--- such:
---
--- 1. first, by receiving a `SIGTERM` signal from this library,
--- 2. then, after 1ms, by receiving a `SIGKILL` signal from this library.
---
--- Note that child processes of the sub-process (if any) will not be terminated.
--- You may need to terminate these processes yourself.
---
--- When the sub-process is terminated by a UNIX signal, the `reason` return value
--- will be `"signal"` and the `status` return value will hold the signal number.
---
---@param cmd string|string[]
---@param stdin? string
---@param timeout? number
---@param max_size? number
---
---@return boolean ok
---@return string? stdout
---@return string? stderr
---@return string|'"exit"'|'"signal"' reason
---@return number? status
function shell.run(cmd, stdin, timeout, max_size) end
return shell

View File

@@ -0,0 +1,69 @@
---@meta
local signal = {
version = 0.03,
}
---@alias resty.signal.name
---| "NONE" # SIG_NONE
---| "HUP" # SIG_HUP
---| "INT" # SIG_INT
---| "QUIT" # SIG_QUIT
---| "ILL" # SIG_ILL
---| "TRAP" # SIG_TRAP
---| "ABRT" # SIG_ABRT
---| "BUS" # SIG_BUS
---| "FPE" # SIG_FPE
---| "KILL" # SIG_KILL
---| "USR1" # SIG_USR1
---| "SEGV" # SIG_SEGV
---| "USR2" # SIG_USR2
---| "PIPE" # SIG_PIPE
---| "ALRM" # SIG_ALRM
---| "TERM" # SIG_TERM
---| "CHLD" # SIG_CHLD
---| "CONT" # SIG_CONT
---| "STOP" # SIG_STOP
---| "TSTP" # SIG_TSTP
---| "TTIN" # SIG_TTIN
---| "TTOU" # SIG_TTOU
---| "URG" # SIG_URG
---| "XCPU" # SIG_XCPU
---| "XFSZ" # SIG_XFSZ
---| "VTALRM" # SIG_VTALRM
---| "PROF" # SIG_PROF
---| "WINCH" # SIG_WINCH
---| "IO" # SIG_IO
---| "PWR" # SIG_PWR
---| "EMT" # SIG_EMT
---| "SYS" # SIG_SYS
---| "INFO" # SIG_INFO
---@alias resty.signal.signal
---| resty.signal.name
---| integer
---| string
---
-- Sends a signal with its name string or number value to the process of the specified pid.
--
-- All signal names accepted by signum are supported, like HUP, KILL, and TERM.
--
-- Signal numbers are also supported when specifying nonportable system-specific signals is desired.
--
---@param pid number
---@param signal_name_or_num resty.signal.signal
---
---@return boolean ok
---@return string? error
function signal.kill(pid, signal_name_or_num) end
---
-- Maps the signal name specified to the system-specific signal number.
-- Returns `nil` if the signal name is not known.
--
---@param name string|resty.signal.name
---@return integer|nil
function signal.signum(name) end
return signal

View File

@@ -0,0 +1,72 @@
---@meta
--- OpenResty string functions.
--- https://github.com/openresty/lua-resty-string
local str = {
_VERSION = "0.14",
}
--- Encode byte string in hexidecimal.
---
--- This is most useful for retrieving a printable string from a checksum
--- result.
---
--- Usage:
---
---```lua
--- local str = require "resty.string"
--- local md5 = require "resty.md5"
---
--- local sum = md5:new()
--- sum:update("hello")
--- sum:update("goodbye")
--- local digest = sum:final()
--- print(str.to_hex(digest)) --> 441add4718519b71e42d329a834d6d5e
---```
---@param s string
---@return string hex
function str.to_hex(s) end
--- Convert an ASCII string to an integer.
---
--- If the string is not numeric, `-1` is returned.
---
--- Usage:
---
---```lua
--- local str = require "resty.string"
--- print(str.atoi("250")) --> 250
--- print(str.atoi("abc")) --> -1
---```
---
---@param s string
---@return number
function str.atoi(s) end
--- A lua-resty-string checksum object.
---@class resty.string.checksum : table
local checksum = {
_VERSION = str._VERSION,
}
--- Create a new checksum object.
---@return resty.string.checksum?
function checksum:new() end
--- Add a string to the checksum data.
---
--- This can be called multiple times.
---
---@param s string
---@return boolean ok
function checksum:update(s) end
--- Calculate the final checksum.
---@return string? digest
function checksum:final() end
--- Reset the checksum object.
---@return boolean ok
function checksum:reset() end
return str

View File

@@ -0,0 +1,7 @@
---@meta
resty_upload = {}
function resty_upload.read(self) end
function resty_upload.set_timeout(self, timeout) end
resty_upload._VERSION = "0.10"
function resty_upload.new(self, chunk_size, max_line_size) end
return resty_upload

View File

@@ -0,0 +1,6 @@
---@meta
resty_upstream_healthcheck = {}
function resty_upstream_healthcheck.status_page() end
resty_upstream_healthcheck._VERSION = "0.05"
function resty_upstream_healthcheck.spawn_checker(opts) end
return resty_upstream_healthcheck

View File

@@ -0,0 +1,62 @@
---@meta
---@class resty.websocket.client : resty.websocket
local client = {
_VERSION = "0.09",
}
---Instantiates a WebSocket client object.
---
---In case of error, it returns nil and a string describing the error.
---
---An optional options table can be specified.
---
---@param opts? resty.websocket.new.opts
---@return resty.websocket.client? client
---@return string? error
function client:new(opts) end
---Connects to the remote WebSocket service port and performs the websocket
---handshake process on the client side.
---
---Before actually resolving the host name and connecting to the remote backend,
---this method will always look up the connection pool for matched idle
---connections created by previous calls of this method.
---
---@param url string
---@param opts? resty.websocket.client.connect.opts
---@return boolean ok
---@return string? error
function client:connect(uri, opts) end
--- Puts the current WebSocket connection immediately into the ngx_lua cosocket connection pool.
---
--- You can specify the max idle timeout (in ms) when the connection is in the pool and the maximal size of the pool every nginx worker process.
---
--- In case of success, returns 1. In case of errors, returns nil with a string describing the error.
---
--- Only call this method in the place you would have called the close method instead. Calling this method will immediately turn the current WebSocket object into the closed state. Any subsequent operations other than connect() on the current object will return the closed error.
----
---@param max_idle_timeout number
---@param pool_size integer
---@return boolean ok
---@return string? error
function client:set_keepalive(max_idle_timeout, pool_size) end
---Closes the current WebSocket connection.
---
---If no close frame is sent yet, then the close frame will be automatically sent.
---
---@return boolean ok
---@return string? error
function client:close() end
---@class resty.websocket.client.connect.opts : table
---
---@field protocols string|string[] subprotocol(s) used for the current WebSocket session
---@field origin string the value of the Origin request header
---@field pool string custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template <host>:<port>.
---@field ssl_verify boolean whether to perform SSL certificate verification during the SSL handshake if the wss:// scheme is used.
---@field headers string[] custom headers to be sent in the handshake request. The table is expected to contain strings in the format {"a-header: a header value", "another-header: another header value"}.
return client

View File

@@ -0,0 +1,172 @@
---@meta
---@class resty.websocket.protocol
local protocol = {
_VERSION = "0.09",
}
--- websocket object
--- https://github.com/openresty/lua-resty-websocket
---
---@class resty.websocket : table
---@field sock tcpsock
---@field fatal boolean
---@field max_payload_len number
---@field send_masked boolean
local websocket = {}
---@param ms integer sets the timeout delay (in milliseconds) for the network-related operations
function websocket:set_timeout(ms) end
---Sends the text argument out as an unfragmented data frame of the text type.
---
---Returns the number of bytes that have actually been sent on the TCP level.
---
---In case of errors, returns nil and a string describing the error.
---
---@param text string
---@return integer? bytes
---@return string? error
function websocket:send_text(text) end
---Sends the data argument out as an unfragmented data frame of the binary type.
---
---Returns the number of bytes that have actually been sent on the TCP level.
---
---In case of errors, returns nil and a string describing the error.
---
---@param data string
---@return integer? bytes
---@return string? error
function websocket:send_binary(data) end
---Sends out a ping frame with an optional message specified by the msg argument.
---Returns the number of bytes that have actually been sent on the TCP level.
---
---In case of errors, returns nil and a string describing the error.
---
---Note that this method does not wait for a pong frame from the remote end.
---
---@param msg? string
---@return integer? bytes
---@return string? error
function websocket:send_ping(msg) end
---Sends out a pong frame with an optional message specified by the msg argument.
---Returns the number of bytes that have actually been sent on the TCP level.
---
---In case of errors, returns nil and a string describing the error.
---@param msg? string
---@return integer? bytes
---@return string? error
function websocket:send_pong(msg) end
---Sends out a close frame with an optional status code and a message.
---
---In case of errors, returns nil and a string describing the error.
---
---For a list of valid status code, see the following document:
---
---http://tools.ietf.org/html/rfc6455#section-7.4.1
---
---Note that this method does not wait for a close frame from the remote end.
---@param code? integer
---@param msg? string
---@return integer? bytes
---@return string? error
function websocket:send_close(code, msg) end
---Sends out a raw websocket frame by specifying the fin field (boolean value), the opcode, and the payload.
---
---For a list of valid opcode, see
---
---http://tools.ietf.org/html/rfc6455#section-5.2
---
---In case of errors, returns nil and a string describing the error.
---
---To control the maximal payload length allowed, you can pass the max_payload_len option to the new constructor.
---
---To control whether to send masked frames, you can pass true to the send_masked option in the new constructor method. By default, unmasked frames are sent.
---@param fin boolean
---@param opcode resty.websocket.protocol.opcode
---@param payload string
---@return integer? bytes
---@return string? error
function websocket:send_frame(fin, opcode, payload) end
---Receives a WebSocket frame from the wire.
---
---In case of an error, returns two nil values and a string describing the error.
---
---The second return value is always the frame type, which could be one of continuation, text, binary, close, ping, pong, or nil (for unknown types).
---
---For close frames, returns 3 values: the extra status message (which could be an empty string), the string "close", and a Lua number for the status code (if any). For possible closing status codes, see
---
---http://tools.ietf.org/html/rfc6455#section-7.4.1
---
---For other types of frames, just returns the payload and the type.
---
---For fragmented frames, the err return value is the Lua string "again".
---
---@return string? data
---@return resty.websocket.protocol.type? typ
---@return string|integer? error_or_status_code
function websocket:recv_frame() end
---@class resty.websocket.new.opts : table
---@field max_payload_len integer maximal length of payload allowed when sending and receiving WebSocket frames
---@field send_masked boolean whether to send out masked WebSocket frames
---@field timeout integer network timeout threshold in milliseconds
--- Websocket op code
---
--- Defines the interpretation of the payload data.
---
--- See RFC 6455 section 5.2
---
---@alias resty.websocket.protocol.opcode
---| '0x0' # continuation
---| '0x1' # text
---| '0x2' # binary
---| '0x8' # close
---| '0x9' # ping
---| '0xa' # pong
---@alias resty.websocket.protocol.type
---| '"continuation"'
---| '"text"'
---| '"binary"'
---| '"close"'
---| '"ping"'
---| '"pong"'
--- Builds a raw WebSocket frame.
---@param fin boolean
---@param opcode resty.websocket.protocol.opcode
---@param payload_len integer
---@param payload string
---@param masking boolean
---@return string
function protocol.build_frame(fin, opcode, payload_len, payload, masking) end
--- Sends a raw WebSocket frame.
---@param sock tcpsock
---@param fin boolean
---@param opcode resty.websocket.protocol.opcode
---@param payload string
---@param max_payload_len interger
---@param masking boolean
---@return bytes? number
---@return string? error
function protocol.send_frame(sock, fin, opcode, payload, max_payload_len, masking) end
--- Receives a WebSocket frame from the wire.
---@param sock tcpsock
---@param max_payload_len interger
---@param force_masking boolean
---@return string? data
---@return resty.websocket.protocol.type? typ
---@return string? error
function protocol.recv_frame(sock, max_payload_len, force_masking) end
return protocol

View File

@@ -0,0 +1,16 @@
---@meta
---@class resty.websocket.server : resty.websocket
local server = {
_VERSION = "0.09",
}
---Performs the websocket handshake process on the server side and returns a WebSocket server object.
---
---In case of error, it returns nil and a string describing the error.
---@param opts? resty.websocket.new.opts
---@return resty.websocket.server? server
---@return string? error
function server:new(opts) end
return server

View File

@@ -0,0 +1,25 @@
---@meta
--- Returns a shallow copy of the given Lua table.
---
--- This API can be JIT compiled.
---
--- Usage:
---
--- ```lua
--- local clone = require "table.clone"
---
--- local x = {x=12, y={5, 6, 7}}
--- local y = clone(x)
--- ```
---
--- **Note:** We observe 7% over-all speedup in the edgelang-fan compiler's
--- compiling speed whose Lua is generated by the fanlang compiler.
---
--- **Note bis:** Deep cloning is planned to be supported by adding `true` as a second argument.
---
---@param t table
---@return table
local function clone(t) end
return clone

View File

@@ -0,0 +1,23 @@
---@meta
--- Returns `true` when the given Lua table is a pure array-like Lua table, or
--- `false` otherwise.
---
--- Empty Lua tables are treated as arrays.
---
--- This API can be JIT compiled.
---
--- Usage:
---
--- ```lua
--- local isarray = require "table.isarray"
---
--- print(isarray{"a", true, 3.14}) -- true
--- print(isarray{dog = 3}) -- false
--- print(isarray{}) -- true
--- ```
---@param t table
---@return boolean
local function isarray(t) end
return isarray

View File

@@ -0,0 +1,22 @@
---@meta
--- Returns `true` when the given Lua table contains neither non-nil array elements nor non-nil key-value pairs, or `false` otherwise.
---
--- This API can be JIT compiled.
--- Usage:
---
--- ```lua
--- local isempty = require "table.isempty"
---
--- print(isempty({})) -- true
--- print(isempty({nil, dog = nil})) -- true
--- print(isempty({"a", "b"})) -- false
--- print(isempty({nil, 3})) -- false
--- print(isempty({cat = 3})) -- false
--- ```
---
---@param t table
---@return boolean
local function isempty(t) end
return isempty

View File

@@ -0,0 +1,23 @@
---@meta
--- Returns the total number of elements in a given Lua table (i.e. from both the
--- array and hash parts combined).
---
--- This API can be JIT compiled.
---
--- Usage:
---
--- ```lua
--- local nkeys = require "table.nkeys"
---
--- print(nkeys({})) -- 0
--- print(nkeys({ "a", nil, "b" })) -- 2
--- print(nkeys({ dog = 3, cat = 4, bird = nil })) -- 2
--- print(nkeys({ "a", dog = 3, cat = 4 })) -- 3
--- ```
---
---@param t table
---@return integer
local function nkeys(t) end
return nkeys

View File

@@ -0,0 +1,29 @@
---@meta
local tablepool = {}
--- Releases the already used Lua table, `tb`, into the table pool named `pool_name`. If the specified table pool does not exist, create it right away.
---
--- The caller must *not* continue using the released Lua table, `tb`, after this call. Otherwise random data corruption is expected.
---
--- The optional `no_clear` parameter specifies whether to clear the contents in the Lua table `tb` before putting it into the pool. Defaults to `false`, that is, always clearing the Lua table.
---
--- If you always initialize all the elements in the Lua table and always use the exactly same number of elements in the Lua table, then you can set this argument to `true` to avoid the overhead of explicit table clearing.
---
--- According to the current implementation, for maximum 200 Lua tables can be cached in an individual pool. We may make this configurable in the future. If the specified table pool already exceeds its size limit, then the `tb` table is subject to garbage collection. This behavior is to avoid potential memory leak due to unbalanced `fetch` and `release` method calls.
---
---@param pool_name string
---@param tb table
---@param no_clear? boolean
function tablepool.release(pool_name, tb, no_clear) end
--- Fetches a (free) Lua table from the table pool of the specified name `pool_name`.
---
--- If the pool does not exist or the pool is empty, simply create a Lua table whose array part has `narr` elements and whose hash table part has `nrec` elements.
---
---@param pool_name string
---@param narr number size of the array-like part of the table
---@param nrec number size of the hash-like part of the table
---@return table
function tablepool.fetch(pool_name, narr, nrec) end
return tablepool

View File

@@ -0,0 +1,43 @@
---@meta
--- **syntax:** *exdata = th_exdata(data?)*
---
--- This API allows for embedding user data into a thread (`lua_State`).
---
--- The retrieved `exdata` value on the Lua land is represented as a cdata object
--- of the ctype `void*`.
---
--- As of this version, retrieving the `exdata` (i.e. `th_exdata()` without any
--- argument) can be JIT compiled.
---
--- Usage:
---
--- ```lua
--- local th_exdata = require "thread.exdata"
---
--- th_exdata(0xdeadbeefLL) -- set the exdata of the current Lua thread
--- local exdata = th_exdata() -- fetch the exdata of the current Lua thread
--- ```
---
--- Also available are the following public C API functions for manipulating
--- `exdata` on the C land:
---
--- ```C
--- void lua_setexdata(lua_State *L, void *exdata);
--- void *lua_getexdata(lua_State *L);
--- ```
---
--- The `exdata` pointer is initialized to `NULL` when the main thread is created.
--- Any child Lua thread will inherit its parent's `exdata`, but still can override
--- it.
---
--- **Note:** This API will not be available if LuaJIT is compiled with
--- `-DLUAJIT_DISABLE_FFI`.
---
--- **Note bis:** This API is used internally by the OpenResty core, and it is
--- strongly discouraged to use it yourself in the context of OpenResty.
---@param data? any
---@return any? data
local function exdata(data) end
return exdata

View File

@@ -0,0 +1,8 @@
---@meta
--- Similar to `thread.exdata` but for a 2nd separate user data as a pointer value.
---@param data? any
---@return any? data
local function exdata2(data) end
return exdata2