t1k.lua 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. local consts = require "resty.t1k.constants"
  2. local filter = require "resty.t1k.filter"
  3. local handler = require "resty.t1k.handler"
  4. local log = require "resty.t1k.log"
  5. local request = require "resty.t1k.request"
  6. local utils = require "resty.t1k.utils"
  7. local lower = string.lower
  8. local ngx = ngx
  9. local nlog = ngx.log
  10. local log_fmt = log.fmt
  11. local debug_fmt = log.debug_fmt
  12. local _M = {
  13. _VERSION = '1.0.0'
  14. }
  15. local DEFAULT_T1K_CONNECT_TIMEOUT = 1000 -- 1s
  16. local DEFAULT_T1K_SEND_TIMEOUT = 1000 -- 1s
  17. local DEFAULT_T1K_READ_TIMEOUT = 1000 -- 1s
  18. local DEFAULT_T1K_REQ_BODY_SIZE = 1024 -- 1024 KB
  19. local DEFAULT_T1K_KEEPALIVE_SIZE = 256
  20. local DEFAULT_T1K_KEEPALIVE_TIMEOUT = 60 * 1000 -- 60s
  21. function _M.do_access(t, handle)
  22. local ok, err, result
  23. local opts = {}
  24. t = t or {}
  25. if not t.mode then
  26. return true, nil, nil
  27. end
  28. opts.mode = lower(t.mode)
  29. if opts.mode == consts.MODE_OFF then
  30. nlog(debug_fmt("t1k is not enabled"))
  31. return true, nil, nil
  32. end
  33. if opts.mode ~= consts.MODE_OFF and opts.mode ~= consts.MODE_BLOCK and opts.mode ~= consts.MODE_MONITOR then
  34. err = log_fmt("invalid t1k mode: %s", t.mode)
  35. return nil, err, nil
  36. end
  37. if not t.host then
  38. err = log_fmt("invalid t1k host: %s", t.host)
  39. return nil, err, nil
  40. end
  41. opts.host = t.host
  42. if utils.starts_with(opts.host, consts.UNIX_SOCK_PREFIX) then
  43. opts.uds = true
  44. else
  45. if not tonumber(t.port) then
  46. err = log_fmt("invalid t1k port: %s", t.port)
  47. return nil, err, nil
  48. end
  49. opts.port = tonumber(t.port)
  50. end
  51. opts.connect_timeout = t.connect_timeout or DEFAULT_T1K_CONNECT_TIMEOUT
  52. opts.send_timeout = t.send_timeout or DEFAULT_T1K_SEND_TIMEOUT
  53. opts.read_timeout = t.read_timeout or DEFAULT_T1K_READ_TIMEOUT
  54. opts.req_body_size = t.req_body_size or DEFAULT_T1K_REQ_BODY_SIZE
  55. opts.keepalive_size = t.keepalive_size or DEFAULT_T1K_KEEPALIVE_SIZE
  56. opts.keepalive_timeout = t.keepalive_timeout or DEFAULT_T1K_KEEPALIVE_TIMEOUT
  57. if t.remote_addr then
  58. local var, idx = utils.to_var_idx(t.remote_addr)
  59. opts.remote_addr_var = var
  60. opts.remote_addr_idx = idx
  61. end
  62. ok, err, result = request.do_request(opts)
  63. if not ok then
  64. return ok, err, result
  65. end
  66. if handle and opts.mode == consts.MODE_BLOCK then
  67. ok, err = _M.do_handle(result)
  68. end
  69. return ok, err, result
  70. end
  71. function _M.do_handle(t)
  72. local ok, err = handler.handle(t)
  73. return ok, err
  74. end
  75. function _M.do_header_filter()
  76. filter.do_header_filter()
  77. end
  78. return _M