@woodger/t-invest-node-sdk 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (415) hide show
  1. package/CHANGELOG.md +317 -524
  2. package/NOTICE +8 -8
  3. package/dist/application/dto/t-invest-options.d.ts +8 -6
  4. package/dist/application/dto/t-invest-options.js +4 -4
  5. package/dist/application/dto/t-invest-services.d.ts +26 -1
  6. package/dist/application/dto/t-invest-services.js +2 -1
  7. package/dist/application/errors/sdk-error.d.ts +21 -7
  8. package/dist/application/errors/sdk-error.js +20 -17
  9. package/dist/application/reports/accounts.report.d.ts +7 -2
  10. package/dist/application/reports/accrued-interests.report.d.ts +8 -2
  11. package/dist/application/reports/asset.report.d.ts +5 -0
  12. package/dist/application/reports/bond-coupons.report.d.ts +3 -1
  13. package/dist/application/reports/bond.report.d.ts +3 -1
  14. package/dist/application/reports/brands.report.d.ts +4 -1
  15. package/dist/application/reports/broker-report.report.d.ts +14 -2
  16. package/dist/application/reports/candles.report.d.ts +4 -1
  17. package/dist/application/reports/close-prices.report.d.ts +7 -2
  18. package/dist/application/reports/currency.report.d.ts +4 -1
  19. package/dist/application/reports/dividends-foreign-issuer.report.d.ts +12 -1
  20. package/dist/application/reports/dividends.report.d.ts +4 -1
  21. package/dist/application/reports/find-instrument.report.d.ts +3 -1
  22. package/dist/application/reports/future.report.d.ts +3 -1
  23. package/dist/application/reports/futures-margin.report.d.ts +10 -3
  24. package/dist/application/reports/instrument.report.d.ts +7 -2
  25. package/dist/application/reports/last-prices.report.d.ts +7 -2
  26. package/dist/application/reports/last-trades.report.d.ts +4 -2
  27. package/dist/application/reports/margin-attributes.report.d.ts +6 -2
  28. package/dist/application/reports/operations-by-cursor.report.d.ts +7 -2
  29. package/dist/application/reports/option.report.d.ts +4 -1
  30. package/dist/application/reports/order-book.report.d.ts +1 -1
  31. package/dist/application/reports/order-mutation.report.d.ts +6 -2
  32. package/dist/application/reports/portfolio.report.d.ts +4 -1
  33. package/dist/application/reports/sandbox-account.report.d.ts +6 -0
  34. package/dist/application/reports/stop-orders.report.d.ts +3 -1
  35. package/dist/application/reports/trading-schedules.report.d.ts +12 -4
  36. package/dist/application/reports/trading-status.report.d.ts +3 -1
  37. package/dist/application/reports/trading-statuses.report.d.ts +4 -1
  38. package/dist/application/reports/user-tariff.report.d.ts +2 -0
  39. package/dist/application/reports/withdraw-limits.report.d.ts +4 -1
  40. package/dist/application/services/unary-limiter.d.ts +18 -14
  41. package/dist/application/services/unary-limiter.js +91 -33
  42. package/dist/bootstrap/args/command-options.d.ts +5 -0
  43. package/dist/bootstrap/args/command-options.js +24 -15
  44. package/dist/bootstrap/args/instrument-id-options.d.ts +12 -6
  45. package/dist/bootstrap/args/instrument-id-options.js +4 -2
  46. package/dist/bootstrap/args/instruments-args.d.ts +2 -2
  47. package/dist/bootstrap/args/instruments-args.js +2 -1
  48. package/dist/bootstrap/args/sdk-options.d.ts +7 -3
  49. package/dist/bootstrap/args/sdk-options.js +3 -3
  50. package/dist/bootstrap/args/side-effect-args.js +7 -3
  51. package/dist/bootstrap/cli/contract.d.ts +2 -1
  52. package/dist/bootstrap/cli/contract.js +2 -1
  53. package/dist/bootstrap/cli/domains.d.ts +13 -10
  54. package/dist/bootstrap/cli/domains.js +8 -3
  55. package/dist/bootstrap/cli/error.d.ts +7 -1
  56. package/dist/bootstrap/cli/error.js +11 -3
  57. package/dist/bootstrap/cli/help-catalog.d.ts +4 -1
  58. package/dist/bootstrap/cli/help-catalog.js +5 -0
  59. package/dist/bootstrap/cli/help.d.ts +5 -4
  60. package/dist/bootstrap/cli/help.js +4 -3
  61. package/dist/bootstrap/cli/registry.d.ts +288 -287
  62. package/dist/bootstrap/cli/registry.js +4 -2
  63. package/dist/bootstrap/cli/runner.js +1 -1
  64. package/dist/bootstrap/cli/version.d.ts +2 -1
  65. package/dist/bootstrap/cli/version.js +2 -1
  66. package/dist/bootstrap/commands/accounts/cli.d.ts +6 -5
  67. package/dist/bootstrap/commands/accounts/cli.js +17 -22
  68. package/dist/bootstrap/commands/accounts/reporter.d.ts +4 -2
  69. package/dist/bootstrap/commands/accounts/reporter.js +2 -1
  70. package/dist/bootstrap/commands/accrued-interests/cli.d.ts +16 -15
  71. package/dist/bootstrap/commands/accrued-interests/cli.js +14 -21
  72. package/dist/bootstrap/commands/accrued-interests/reporter.d.ts +4 -2
  73. package/dist/bootstrap/commands/accrued-interests/reporter.js +2 -1
  74. package/dist/bootstrap/commands/asset/cli.d.ts +13 -12
  75. package/dist/bootstrap/commands/asset/cli.js +14 -21
  76. package/dist/bootstrap/commands/asset/reporter.d.ts +4 -2
  77. package/dist/bootstrap/commands/asset/reporter.js +2 -1
  78. package/dist/bootstrap/commands/assets/cli.d.ts +16 -15
  79. package/dist/bootstrap/commands/assets/cli.js +14 -21
  80. package/dist/bootstrap/commands/assets/reporter.d.ts +4 -2
  81. package/dist/bootstrap/commands/assets/reporter.js +2 -1
  82. package/dist/bootstrap/commands/bond/cli.d.ts +6 -5
  83. package/dist/bootstrap/commands/bond/cli.js +19 -24
  84. package/dist/bootstrap/commands/bond/reporter.d.ts +4 -2
  85. package/dist/bootstrap/commands/bond/reporter.js +5 -2
  86. package/dist/bootstrap/commands/bond-coupons/cli.d.ts +16 -15
  87. package/dist/bootstrap/commands/bond-coupons/cli.js +14 -21
  88. package/dist/bootstrap/commands/bond-coupons/reporter.d.ts +4 -2
  89. package/dist/bootstrap/commands/bond-coupons/reporter.js +2 -1
  90. package/dist/bootstrap/commands/bonds/cli.d.ts +6 -5
  91. package/dist/bootstrap/commands/bonds/cli.js +19 -24
  92. package/dist/bootstrap/commands/bonds/reporter.d.ts +4 -2
  93. package/dist/bootstrap/commands/bonds/reporter.js +2 -1
  94. package/dist/bootstrap/commands/brand/cli.d.ts +13 -12
  95. package/dist/bootstrap/commands/brand/cli.js +14 -21
  96. package/dist/bootstrap/commands/brand/reporter.d.ts +4 -2
  97. package/dist/bootstrap/commands/brand/reporter.js +2 -1
  98. package/dist/bootstrap/commands/brands/cli.d.ts +6 -5
  99. package/dist/bootstrap/commands/brands/cli.js +17 -22
  100. package/dist/bootstrap/commands/brands/reporter.d.ts +4 -2
  101. package/dist/bootstrap/commands/brands/reporter.js +2 -1
  102. package/dist/bootstrap/commands/broker-report/cli.d.ts +25 -24
  103. package/dist/bootstrap/commands/broker-report/cli.js +14 -21
  104. package/dist/bootstrap/commands/broker-report/reporter.d.ts +4 -2
  105. package/dist/bootstrap/commands/broker-report/reporter.js +2 -1
  106. package/dist/bootstrap/commands/cancel-order/cli.d.ts +10 -9
  107. package/dist/bootstrap/commands/cancel-order/cli.js +28 -35
  108. package/dist/bootstrap/commands/cancel-order/reporter.d.ts +4 -2
  109. package/dist/bootstrap/commands/cancel-order/reporter.js +2 -1
  110. package/dist/bootstrap/commands/cancel-stop-order/cli.d.ts +16 -15
  111. package/dist/bootstrap/commands/cancel-stop-order/cli.js +16 -22
  112. package/dist/bootstrap/commands/cancel-stop-order/reporter.d.ts +4 -2
  113. package/dist/bootstrap/commands/cancel-stop-order/reporter.js +2 -1
  114. package/dist/bootstrap/commands/candles/cli.d.ts +22 -21
  115. package/dist/bootstrap/commands/candles/cli.js +14 -21
  116. package/dist/bootstrap/commands/candles/reporter.d.ts +4 -2
  117. package/dist/bootstrap/commands/candles/reporter.js +2 -1
  118. package/dist/bootstrap/commands/close-prices/cli.d.ts +13 -12
  119. package/dist/bootstrap/commands/close-prices/cli.js +14 -21
  120. package/dist/bootstrap/commands/close-prices/reporter.d.ts +4 -2
  121. package/dist/bootstrap/commands/close-prices/reporter.js +2 -1
  122. package/dist/bootstrap/commands/compile-proto/cli.d.ts +2 -1
  123. package/dist/bootstrap/commands/compile-proto/cli.js +2 -1
  124. package/dist/bootstrap/commands/countries/cli.d.ts +6 -5
  125. package/dist/bootstrap/commands/countries/cli.js +17 -22
  126. package/dist/bootstrap/commands/countries/reporter.d.ts +4 -2
  127. package/dist/bootstrap/commands/countries/reporter.js +2 -1
  128. package/dist/bootstrap/commands/currencies/cli.d.ts +6 -5
  129. package/dist/bootstrap/commands/currencies/cli.js +19 -24
  130. package/dist/bootstrap/commands/currencies/reporter.d.ts +4 -2
  131. package/dist/bootstrap/commands/currencies/reporter.js +2 -1
  132. package/dist/bootstrap/commands/currency/cli.d.ts +6 -5
  133. package/dist/bootstrap/commands/currency/cli.js +19 -24
  134. package/dist/bootstrap/commands/currency/reporter.d.ts +4 -2
  135. package/dist/bootstrap/commands/currency/reporter.js +2 -1
  136. package/dist/bootstrap/commands/dividends/cli.d.ts +16 -15
  137. package/dist/bootstrap/commands/dividends/cli.js +14 -21
  138. package/dist/bootstrap/commands/dividends/reporter.d.ts +4 -2
  139. package/dist/bootstrap/commands/dividends/reporter.js +2 -1
  140. package/dist/bootstrap/commands/dividends-foreign-issuer/cli.d.ts +25 -24
  141. package/dist/bootstrap/commands/dividends-foreign-issuer/cli.js +14 -21
  142. package/dist/bootstrap/commands/dividends-foreign-issuer/reporter.d.ts +4 -2
  143. package/dist/bootstrap/commands/dividends-foreign-issuer/reporter.js +2 -1
  144. package/dist/bootstrap/commands/edit-favorites/cli.d.ts +13 -12
  145. package/dist/bootstrap/commands/edit-favorites/cli.js +16 -22
  146. package/dist/bootstrap/commands/edit-favorites/reporter.d.ts +2 -1
  147. package/dist/bootstrap/commands/etf/cli.d.ts +6 -5
  148. package/dist/bootstrap/commands/etf/cli.js +19 -24
  149. package/dist/bootstrap/commands/etf/reporter.d.ts +4 -2
  150. package/dist/bootstrap/commands/etf/reporter.js +5 -2
  151. package/dist/bootstrap/commands/etfs/cli.d.ts +6 -5
  152. package/dist/bootstrap/commands/etfs/cli.js +19 -24
  153. package/dist/bootstrap/commands/etfs/reporter.d.ts +4 -2
  154. package/dist/bootstrap/commands/etfs/reporter.js +2 -1
  155. package/dist/bootstrap/commands/favorites/cli.d.ts +6 -5
  156. package/dist/bootstrap/commands/favorites/cli.js +17 -22
  157. package/dist/bootstrap/commands/favorites/reporter.d.ts +4 -2
  158. package/dist/bootstrap/commands/favorites/reporter.js +2 -1
  159. package/dist/bootstrap/commands/find-instrument/cli.d.ts +22 -21
  160. package/dist/bootstrap/commands/find-instrument/cli.js +14 -21
  161. package/dist/bootstrap/commands/find-instrument/reporter.d.ts +4 -2
  162. package/dist/bootstrap/commands/find-instrument/reporter.js +2 -1
  163. package/dist/bootstrap/commands/future/cli.d.ts +6 -5
  164. package/dist/bootstrap/commands/future/cli.js +19 -24
  165. package/dist/bootstrap/commands/future/reporter.d.ts +4 -2
  166. package/dist/bootstrap/commands/future/reporter.js +2 -1
  167. package/dist/bootstrap/commands/futures/cli.d.ts +6 -5
  168. package/dist/bootstrap/commands/futures/cli.js +19 -24
  169. package/dist/bootstrap/commands/futures/reporter.d.ts +4 -2
  170. package/dist/bootstrap/commands/futures/reporter.js +2 -1
  171. package/dist/bootstrap/commands/futures-margin/cli.d.ts +10 -9
  172. package/dist/bootstrap/commands/futures-margin/cli.js +14 -21
  173. package/dist/bootstrap/commands/futures-margin/reporter.d.ts +4 -2
  174. package/dist/bootstrap/commands/futures-margin/reporter.js +8 -2
  175. package/dist/bootstrap/commands/help/cli.js +1 -4
  176. package/dist/bootstrap/commands/instrument/cli.d.ts +6 -5
  177. package/dist/bootstrap/commands/instrument/cli.js +19 -24
  178. package/dist/bootstrap/commands/instrument/reporter.d.ts +4 -2
  179. package/dist/bootstrap/commands/instrument/reporter.js +5 -2
  180. package/dist/bootstrap/commands/last-prices/cli.d.ts +13 -12
  181. package/dist/bootstrap/commands/last-prices/cli.js +14 -21
  182. package/dist/bootstrap/commands/last-prices/reporter.d.ts +4 -2
  183. package/dist/bootstrap/commands/last-prices/reporter.js +2 -1
  184. package/dist/bootstrap/commands/last-trades/cli.d.ts +19 -18
  185. package/dist/bootstrap/commands/last-trades/cli.js +14 -21
  186. package/dist/bootstrap/commands/last-trades/reporter.d.ts +4 -2
  187. package/dist/bootstrap/commands/last-trades/reporter.js +2 -1
  188. package/dist/bootstrap/commands/margin-attributes/cli.d.ts +13 -12
  189. package/dist/bootstrap/commands/margin-attributes/cli.js +14 -21
  190. package/dist/bootstrap/commands/margin-attributes/reporter.d.ts +4 -2
  191. package/dist/bootstrap/commands/margin-attributes/reporter.js +2 -1
  192. package/dist/bootstrap/commands/operations/cli.d.ts +22 -21
  193. package/dist/bootstrap/commands/operations/cli.js +42 -47
  194. package/dist/bootstrap/commands/operations/reporter.d.ts +4 -2
  195. package/dist/bootstrap/commands/operations/reporter.js +2 -1
  196. package/dist/bootstrap/commands/operations/request.mapper.d.ts +6 -6
  197. package/dist/bootstrap/commands/operations-by-cursor/cli.d.ts +44 -43
  198. package/dist/bootstrap/commands/operations-by-cursor/cli.js +63 -75
  199. package/dist/bootstrap/commands/operations-by-cursor/reporter.d.ts +4 -2
  200. package/dist/bootstrap/commands/operations-by-cursor/reporter.js +2 -1
  201. package/dist/bootstrap/commands/operations-by-cursor/request.mapper.d.ts +8 -7
  202. package/dist/bootstrap/commands/operations-by-cursor/request.mapper.js +10 -4
  203. package/dist/bootstrap/commands/option/cli.d.ts +6 -5
  204. package/dist/bootstrap/commands/option/cli.js +19 -24
  205. package/dist/bootstrap/commands/option/reporter.d.ts +4 -2
  206. package/dist/bootstrap/commands/option/reporter.js +2 -1
  207. package/dist/bootstrap/commands/options-by/cli.d.ts +16 -15
  208. package/dist/bootstrap/commands/options-by/cli.js +14 -21
  209. package/dist/bootstrap/commands/options-by/reporter.d.ts +4 -2
  210. package/dist/bootstrap/commands/options-by/reporter.js +2 -1
  211. package/dist/bootstrap/commands/order-book/cli.d.ts +22 -21
  212. package/dist/bootstrap/commands/order-book/cli.js +18 -28
  213. package/dist/bootstrap/commands/order-book/reporter.d.ts +4 -2
  214. package/dist/bootstrap/commands/order-book/reporter.js +11 -2
  215. package/dist/bootstrap/commands/order-state/cli.d.ts +10 -9
  216. package/dist/bootstrap/commands/order-state/cli.js +26 -34
  217. package/dist/bootstrap/commands/order-state/reporter.d.ts +4 -2
  218. package/dist/bootstrap/commands/order-state/reporter.js +2 -1
  219. package/dist/bootstrap/commands/orders/cli.d.ts +8 -7
  220. package/dist/bootstrap/commands/orders/cli.js +22 -30
  221. package/dist/bootstrap/commands/orders/reporter.d.ts +4 -2
  222. package/dist/bootstrap/commands/orders/reporter.js +2 -1
  223. package/dist/bootstrap/commands/portfolio/cli.d.ts +12 -11
  224. package/dist/bootstrap/commands/portfolio/cli.js +27 -35
  225. package/dist/bootstrap/commands/portfolio/reporter.d.ts +4 -2
  226. package/dist/bootstrap/commands/portfolio/reporter.js +2 -1
  227. package/dist/bootstrap/commands/portfolio/request.mapper.d.ts +6 -5
  228. package/dist/bootstrap/commands/portfolio/request.mapper.js +2 -1
  229. package/dist/bootstrap/commands/positions/cli.d.ts +8 -7
  230. package/dist/bootstrap/commands/positions/cli.js +22 -30
  231. package/dist/bootstrap/commands/positions/reporter.d.ts +4 -2
  232. package/dist/bootstrap/commands/positions/reporter.js +11 -2
  233. package/dist/bootstrap/commands/post-order/cli.d.ts +18 -17
  234. package/dist/bootstrap/commands/post-order/cli.js +49 -56
  235. package/dist/bootstrap/commands/post-order/reporter.d.ts +4 -2
  236. package/dist/bootstrap/commands/post-order/reporter.js +2 -1
  237. package/dist/bootstrap/commands/post-order/request.mapper.d.ts +9 -9
  238. package/dist/bootstrap/commands/post-stop-order/cli.d.ts +34 -33
  239. package/dist/bootstrap/commands/post-stop-order/cli.js +18 -23
  240. package/dist/bootstrap/commands/post-stop-order/reporter.d.ts +4 -2
  241. package/dist/bootstrap/commands/post-stop-order/reporter.js +2 -1
  242. package/dist/bootstrap/commands/replace-order/cli.d.ts +16 -15
  243. package/dist/bootstrap/commands/replace-order/cli.js +45 -52
  244. package/dist/bootstrap/commands/replace-order/reporter.d.ts +4 -2
  245. package/dist/bootstrap/commands/replace-order/reporter.js +2 -1
  246. package/dist/bootstrap/commands/replace-order/request.mapper.d.ts +4 -4
  247. package/dist/bootstrap/commands/sandbox-accounts/cli.d.ts +6 -6
  248. package/dist/bootstrap/commands/sandbox-accounts/cli.js +17 -26
  249. package/dist/bootstrap/commands/sandbox-cancel-order/cli.d.ts +10 -44
  250. package/dist/bootstrap/commands/sandbox-cancel-order/cli.js +28 -39
  251. package/dist/bootstrap/commands/sandbox-close-account/cli.d.ts +13 -12
  252. package/dist/bootstrap/commands/sandbox-close-account/cli.js +16 -22
  253. package/dist/bootstrap/commands/sandbox-close-account/reporter.d.ts +4 -2
  254. package/dist/bootstrap/commands/sandbox-close-account/reporter.js +2 -1
  255. package/dist/bootstrap/commands/sandbox-open-account/cli.d.ts +6 -6
  256. package/dist/bootstrap/commands/sandbox-open-account/cli.js +19 -28
  257. package/dist/bootstrap/commands/sandbox-open-account/reporter.d.ts +4 -2
  258. package/dist/bootstrap/commands/sandbox-open-account/reporter.js +2 -1
  259. package/dist/bootstrap/commands/sandbox-operations/cli.d.ts +18 -64
  260. package/dist/bootstrap/commands/sandbox-operations/cli.js +36 -48
  261. package/dist/bootstrap/commands/sandbox-operations-by-cursor/cli.d.ts +32 -94
  262. package/dist/bootstrap/commands/sandbox-operations-by-cursor/cli.js +57 -69
  263. package/dist/bootstrap/commands/sandbox-order-state/cli.d.ts +10 -41
  264. package/dist/bootstrap/commands/sandbox-order-state/cli.js +26 -38
  265. package/dist/bootstrap/commands/sandbox-orders/cli.d.ts +8 -35
  266. package/dist/bootstrap/commands/sandbox-orders/cli.js +22 -34
  267. package/dist/bootstrap/commands/sandbox-pay-in/cli.d.ts +22 -21
  268. package/dist/bootstrap/commands/sandbox-pay-in/cli.js +16 -22
  269. package/dist/bootstrap/commands/sandbox-pay-in/reporter.d.ts +4 -2
  270. package/dist/bootstrap/commands/sandbox-pay-in/reporter.js +2 -1
  271. package/dist/bootstrap/commands/sandbox-portfolio/cli.d.ts +14 -46
  272. package/dist/bootstrap/commands/sandbox-portfolio/cli.js +27 -39
  273. package/dist/bootstrap/commands/sandbox-positions/cli.d.ts +8 -35
  274. package/dist/bootstrap/commands/sandbox-positions/cli.js +22 -34
  275. package/dist/bootstrap/commands/sandbox-post-order/cli.d.ts +22 -80
  276. package/dist/bootstrap/commands/sandbox-post-order/cli.js +49 -60
  277. package/dist/bootstrap/commands/sandbox-replace-order/cli.d.ts +18 -72
  278. package/dist/bootstrap/commands/sandbox-replace-order/cli.js +45 -56
  279. package/dist/bootstrap/commands/sandbox-withdraw-limits/cli.d.ts +8 -35
  280. package/dist/bootstrap/commands/sandbox-withdraw-limits/cli.js +22 -34
  281. package/dist/bootstrap/commands/share/cli.d.ts +6 -5
  282. package/dist/bootstrap/commands/share/cli.js +19 -24
  283. package/dist/bootstrap/commands/share/reporter.d.ts +4 -2
  284. package/dist/bootstrap/commands/share/reporter.js +5 -2
  285. package/dist/bootstrap/commands/shares/cli.d.ts +6 -5
  286. package/dist/bootstrap/commands/shares/cli.js +19 -24
  287. package/dist/bootstrap/commands/shares/reporter.d.ts +4 -2
  288. package/dist/bootstrap/commands/shares/reporter.js +2 -1
  289. package/dist/bootstrap/commands/stop-orders/cli.d.ts +13 -12
  290. package/dist/bootstrap/commands/stop-orders/cli.js +14 -21
  291. package/dist/bootstrap/commands/stop-orders/reporter.d.ts +4 -2
  292. package/dist/bootstrap/commands/stop-orders/reporter.js +2 -1
  293. package/dist/bootstrap/commands/stream-run/cli.d.ts +6 -4
  294. package/dist/bootstrap/commands/stream-run/cli.js +7 -7
  295. package/dist/bootstrap/commands/stream-run/config.d.ts +18 -1
  296. package/dist/bootstrap/commands/stream-run/config.js +5 -3
  297. package/dist/bootstrap/commands/stream-run/reporter.d.ts +6 -1
  298. package/dist/bootstrap/commands/stream-run/request.mapper.js +15 -5
  299. package/dist/bootstrap/commands/stream-run/stream-session.d.ts +14 -0
  300. package/dist/bootstrap/commands/stream-run/stream-session.js +7 -2
  301. package/dist/bootstrap/commands/trading-schedules/cli.d.ts +19 -18
  302. package/dist/bootstrap/commands/trading-schedules/cli.js +14 -21
  303. package/dist/bootstrap/commands/trading-schedules/reporter.d.ts +4 -2
  304. package/dist/bootstrap/commands/trading-schedules/reporter.js +11 -2
  305. package/dist/bootstrap/commands/trading-status/cli.d.ts +13 -12
  306. package/dist/bootstrap/commands/trading-status/cli.js +14 -21
  307. package/dist/bootstrap/commands/trading-status/reporter.d.ts +4 -2
  308. package/dist/bootstrap/commands/trading-status/reporter.js +2 -1
  309. package/dist/bootstrap/commands/trading-statuses/cli.d.ts +13 -12
  310. package/dist/bootstrap/commands/trading-statuses/cli.js +14 -21
  311. package/dist/bootstrap/commands/trading-statuses/reporter.d.ts +4 -2
  312. package/dist/bootstrap/commands/trading-statuses/reporter.js +2 -1
  313. package/dist/bootstrap/commands/user-info/cli.d.ts +6 -5
  314. package/dist/bootstrap/commands/user-info/cli.js +17 -22
  315. package/dist/bootstrap/commands/user-info/reporter.d.ts +4 -2
  316. package/dist/bootstrap/commands/user-info/reporter.js +2 -1
  317. package/dist/bootstrap/commands/user-tariff/cli.d.ts +6 -5
  318. package/dist/bootstrap/commands/user-tariff/cli.js +17 -22
  319. package/dist/bootstrap/commands/user-tariff/reporter.d.ts +4 -2
  320. package/dist/bootstrap/commands/user-tariff/reporter.js +17 -2
  321. package/dist/bootstrap/commands/withdraw-limits/cli.d.ts +12 -7
  322. package/dist/bootstrap/commands/withdraw-limits/cli.js +29 -30
  323. package/dist/bootstrap/commands/withdraw-limits/reporter.d.ts +4 -2
  324. package/dist/bootstrap/commands/withdraw-limits/reporter.js +2 -1
  325. package/dist/bootstrap/generated-exports.d.ts +1 -1
  326. package/dist/bootstrap/generated-exports.js +14 -11
  327. package/dist/bootstrap/index.js +5 -2
  328. package/dist/bootstrap/proto/compile-proto.d.ts +4 -2
  329. package/dist/bootstrap/proto/compile-proto.js +11 -6
  330. package/dist/bootstrap/sdk-config.d.ts +9 -7
  331. package/dist/bootstrap/sdk-config.js +8 -7
  332. package/dist/bootstrap/t-invest-node-sdk.d.ts +26 -6
  333. package/dist/bootstrap/t-invest-node-sdk.js +48 -23
  334. package/dist/bootstrap/unary-limit-config.d.ts +13 -14
  335. package/dist/bootstrap/unary-limit-config.js +12 -13
  336. package/dist/config.d.ts +13 -11
  337. package/dist/config.js +13 -11
  338. package/dist/config.types.d.ts +18 -19
  339. package/dist/config.types.js +6 -6
  340. package/dist/generated/common.d.ts +1 -0
  341. package/dist/generated/common.js +3 -2
  342. package/dist/generated/google/api/field_behavior.d.ts +1 -0
  343. package/dist/generated/google/api/field_behavior.js +3 -2
  344. package/dist/generated/google/protobuf/descriptor.d.ts +1 -0
  345. package/dist/generated/google/protobuf/descriptor.js +26 -16
  346. package/dist/generated/google/protobuf/timestamp.d.ts +1 -0
  347. package/dist/generated/google/protobuf/timestamp.js +20 -2
  348. package/dist/generated/instruments.d.ts +1 -0
  349. package/dist/generated/instruments.js +59 -55
  350. package/dist/generated/marketdata.d.ts +1 -0
  351. package/dist/generated/marketdata.js +10 -7
  352. package/dist/generated/operations.d.ts +1 -0
  353. package/dist/generated/operations.js +10 -7
  354. package/dist/generated/orders.d.ts +5 -2
  355. package/dist/generated/orders.js +29 -7
  356. package/dist/generated/sandbox.d.ts +1 -0
  357. package/dist/generated/sandbox.js +3 -2
  358. package/dist/generated/signals.d.ts +1 -0
  359. package/dist/generated/signals.js +3 -2
  360. package/dist/generated/stoporders.d.ts +1 -0
  361. package/dist/generated/stoporders.js +3 -2
  362. package/dist/generated/users.d.ts +1 -0
  363. package/dist/generated/users.js +9 -6
  364. package/dist/infrastructure/interceptor/warning-interceptor.d.ts +3 -1
  365. package/dist/infrastructure/interceptor/warning-interceptor.js +4 -3
  366. package/dist/infrastructure/report-values.js +8 -2
  367. package/dist/infrastructure/transport/grpc/call-callback-boundary.d.ts +23 -0
  368. package/dist/infrastructure/transport/grpc/call-callback-boundary.js +56 -0
  369. package/dist/infrastructure/transport/grpc/sdk-call-error.js +2 -2
  370. package/dist/infrastructure/transport/grpc/sdk-channel.d.ts +5 -5
  371. package/dist/infrastructure/transport/grpc/sdk-channel.js +5 -5
  372. package/dist/infrastructure/transport/grpc/sdk-client.d.ts +4 -3
  373. package/dist/infrastructure/transport/grpc/sdk-client.js +4 -3
  374. package/dist/infrastructure/transport/grpc/sdk-middleware.d.ts +20 -11
  375. package/dist/infrastructure/transport/grpc/sdk-middleware.js +96 -109
  376. package/dist/infrastructure/transport/grpc/unary-limit-resolver.d.ts +21 -3
  377. package/dist/infrastructure/transport/grpc/unary-limit-resolver.js +22 -6
  378. package/docs/architecture.md +93 -116
  379. package/docs/bundled-ca.md +31 -48
  380. package/docs/clean-architecture/adapters.md +14 -14
  381. package/docs/clean-architecture/api-commands.md +106 -102
  382. package/docs/clean-architecture/application.md +78 -94
  383. package/docs/clean-architecture/cli-output-boundaries.md +109 -119
  384. package/docs/clean-architecture/dto.md +18 -18
  385. package/docs/clean-architecture/index.md +9 -34
  386. package/docs/cli-reference.md +38 -30
  387. package/docs/cli-stream-configuration.md +57 -41
  388. package/docs/cli-stream-reference.md +51 -83
  389. package/docs/examples/custom-unary-limiter.md +454 -0
  390. package/docs/examples/deprecated-fields.md +27 -0
  391. package/docs/examples/errors-and-lifecycle.md +180 -0
  392. package/docs/examples/getting-started.md +45 -0
  393. package/docs/examples/index.md +43 -0
  394. package/docs/examples/instrument-lookup.md +38 -0
  395. package/docs/examples/market-data-recovery.md +327 -0
  396. package/docs/examples/operations-pagination.md +47 -0
  397. package/docs/examples/order-state-stream.md +39 -0
  398. package/docs/examples/sandbox-orders.md +85 -0
  399. package/docs/examples/streams-and-cancellation.md +218 -0
  400. package/docs/examples/testing-with-service-definitions.md +79 -0
  401. package/docs/examples/unary-calls.md +156 -0
  402. package/docs/examples/unary-limits.md +96 -0
  403. package/docs/index.md +23 -48
  404. package/docs/limits-policy.md +26 -48
  405. package/docs/roadmap.md +54 -54
  406. package/docs/tls-policy.md +39 -21
  407. package/package.json +8 -8
  408. package/readme.md +29 -214
  409. package/docs/guides/custom-unary-limiter.md +0 -500
  410. package/docs/guides/errors-and-lifecycle.md +0 -184
  411. package/docs/guides/getting-started.md +0 -86
  412. package/docs/guides/index.md +0 -32
  413. package/docs/guides/streams-and-cancellation.md +0 -162
  414. package/docs/guides/testing-with-service-definitions.md +0 -102
  415. package/docs/guides/unary-calls.md +0 -181
@@ -1,500 +0,0 @@
1
- # Собственная реализация unary limiter-а
2
-
3
- > Type: Consumer Guide. Здесь подробно разобран публичный port для Consumer-owned ожидания unary-квоты. Руководство показывает отдельный класс решений и не навязывает конкретный алгоритм или готовую реализацию SDK.
4
-
5
- ## Граница ответственности
6
-
7
- SDK владеет знаниями о T-Invest API:
8
-
9
- - сопоставляет полный gRPC method path с service fallback или более точным method rule;
10
- - объединяет методы, расходующие общую квоту, одним `bucket`;
11
- - передаёт исходные `maxRequests` и `windowMs` без нормализации секундного окна в минутное;
12
- - объединяет отмену конкретного RPC с закрытием SDK instance.
13
-
14
- Consumer-owned limiter владеет механизмом выдачи permit:
15
-
16
- - выбирает алгоритм ожидания;
17
- - хранит или координирует состояние;
18
- - определяет границу process, host или deployment;
19
- - прекращает ожидание по `AbortSignal`;
20
- - определяет поведение при отказе собственного backend-а.
21
-
22
- SDK не передаёт limiter-у OAuth token, request payload, metadata или service client. Эти данные не нужны для управления готовой квотой и не должны становиться неявными ключами внешнего хранилища.
23
-
24
- ## Публичные типы
25
-
26
- Импортируйте все типы из корня пакета:
27
-
28
- ```ts
29
- import type {
30
- TInvestUnaryLimit,
31
- TInvestUnaryLimitContext,
32
- TInvestUnaryLimiter,
33
- TInvestUnaryLimits,
34
- TInvestUnaryQuota
35
- } from '@woodger/t-invest-node-sdk';
36
- ```
37
-
38
- Контракт выглядит так:
39
-
40
- ```ts
41
- interface TInvestUnaryLimit {
42
- readonly maxRequests: number;
43
- readonly windowMs: number;
44
- }
45
-
46
- type TInvestUnaryLimits = Record<string, TInvestUnaryLimit>;
47
-
48
- interface TInvestUnaryQuota extends TInvestUnaryLimit {
49
- readonly bucket: string;
50
- }
51
-
52
- interface TInvestUnaryLimitContext {
53
- readonly path: string;
54
- readonly quota: TInvestUnaryQuota;
55
- readonly signal: AbortSignal;
56
- }
57
-
58
- interface TInvestUnaryLimiter {
59
- acquire(context: TInvestUnaryLimitContext): Promise<void>;
60
- }
61
- ```
62
-
63
- В `TInvestOptions.unaryLimiter` можно передать любой объект, который структурно реализует `TInvestUnaryLimiter`. Не нужно наследоваться от SDK-класса или регистрировать plugin.
64
-
65
- ## Когда вызывается `acquire()`
66
-
67
- Для каждого unary RPC SDK выполняет шаги в таком порядке:
68
-
69
- ```text
70
- проверка lifecycle SDK
71
- -> разрешение path в quota
72
- -> unaryLimiter.acquire(context)
73
- -> повторная проверка lifecycle и AbortSignal
74
- -> передача request в gRPC transport
75
- ```
76
-
77
- Инварианты вызова:
78
-
79
- 1. `acquire()` вызывается ровно один раз непосредственно перед каждой попыткой передать unary request transport-у.
80
- 2. Успешный `Promise<void>` означает, что limiter выдал permit. Сразу после этого SDK может начать transport call.
81
- 3. Если Promise отклонён, SDK не отправляет request и возвращает ошибку limiter-а Consumer-у без преобразования в transport `SdkError`.
82
- 4. Server-side и bidirectional streams через этот port не проходят. Их соединения и subscriptions имеют отдельную политику.
83
- 5. Если `unaryLimiter` не передан, SDK не создаёт скрытый limiter и сразу передаёт unary-вызов transport-у.
84
-
85
- Limiter работает в transport middleware, поэтому любой публичный service client использует один и тот же контракт. Успешный `acquire()` лишь разрешает SDK продолжить вызов и не означает, что provider уже принял request.
86
-
87
- ## Семантика полей контекста
88
-
89
- ### `path`
90
-
91
- `path` — полный путь вызываемого RPC, например:
92
-
93
- ```text
94
- /tinkoff.public.invest.api.contract.v1.MarketDataService/GetCandles
95
- ```
96
-
97
- Используйте поле для диагностики, метрик и дополнительной Consumer-owned policy. Не вычисляйте по нему квоту заново: SDK уже передал готовое правило в `quota`.
98
-
99
- ### `quota.bucket`
100
-
101
- `bucket` — непрозрачный идентификатор общего временного состояния. Одинаковые значения означают, что вызовы должны учитывать одну очередь или один счётчик. Например, несколько methods формирования отчётов могут получить общий bucket.
102
-
103
- Consumer должен:
104
-
105
- - использовать значение целиком;
106
- - сравнивать его только на равенство;
107
- - не разбирать prefixes и segments;
108
- - не связывать с ним бизнес-смысл или формат persisted data;
109
- - добавлять собственный scope отдельным полем или внешним prefix, если один backend обслуживает несколько пользователей, environments или endpoints.
110
-
111
- Считайте набор buckets частью лимитной policy конкретной версии SDK, а не вечным идентификатором. Если одновременно работают разные версии пакета, Consumer должен проверить совместимость их quota policy.
112
-
113
- ### `quota.maxRequests` и `quota.windowMs`
114
-
115
- Пара задаёт максимум запросов в исходном временном окне. Например:
116
-
117
- ```ts
118
- {
119
- bucket: '...',
120
- maxRequests: 15,
121
- windowMs: 1_000
122
- }
123
- ```
124
-
125
- означает 15 запросов за секунду. Представление не превращает эту квоту в 900 запросов за минуту, поскольку такие записи допускают разную burst-семантику.
126
-
127
- SDK передаёт конечные положительные значения из статической package policy с учётом `TInvestOptions.unaryLimits`. Они не заменяют актуальный тариф пользователя. Limiter может применить более строгую Consumer-owned policy и учесть `x-ratelimit-*` metadata или данные `getUserTariff()`, не меняя переданный объект.
128
-
129
- Один вызов получает одно наиболее специфичное правило. Оно не моделирует одновременно все возможные service-, user- и IP-ограничения provider-а. Дополнительные ограничения принадлежат реализации Consumer-а.
130
-
131
- ### `signal`
132
-
133
- SDK отменяет `signal` вместе с конкретным вызовом или при `sdk.close()`. Signal может быть результатом `AbortSignal.any()`, поэтому не сравнивайте его identity с signal из call options.
134
-
135
- Реализация должна:
136
-
137
- - проверить `signal.aborted` до постановки в очередь;
138
- - удалить незавершённое ожидание после события `abort`;
139
- - отклонить Promise значением `signal.reason`, если оно доступно;
140
- - удалить event listener при любом завершении;
141
- - не выдавать permit после отмены.
142
-
143
- Если limiter игнорирует signal и не завершает Promise, SDK не сможет остановить его внутреннее ожидание. Pending RPC продолжит ждать limiter даже после `sdk.close()`.
144
-
145
- SDK преобразует call-level отмену в публичный `SdkErrorCode.Cancelled` с `source: 'abort'`, а при закрытии сохраняет lifecycle error. Остальные ошибки limiter-а проходят без маскировки под gRPC failures.
146
-
147
- ## Ownership и время жизни
148
-
149
- Limiter принадлежит коду, который его создал:
150
-
151
- - `TInvestNodeSDK.close()` не вызывает у него `close()`, `dispose()` или иной lifecycle method;
152
- - один limiter можно передать нескольким SDK instances, если они должны делить состояние;
153
- - разные объекты limiter-а не делят состояние автоматически;
154
- - Consumer закрывает внешние connections и workers после завершения всех SDK instances, которые используют limiter.
155
-
156
- Пример общего process-local ownership:
157
-
158
- ```ts
159
- import {
160
- TInvestNodeSDK,
161
- type TInvestUnaryLimiter
162
- } from '@woodger/t-invest-node-sdk';
163
-
164
- declare const unaryLimiter: TInvestUnaryLimiter;
165
-
166
- const firstSdk = new TInvestNodeSDK({
167
- token,
168
- endpoint,
169
- unaryLimiter
170
- });
171
-
172
- const secondSdk = new TInvestNodeSDK({
173
- token,
174
- endpoint,
175
- unaryLimiter
176
- });
177
-
178
- try {
179
- await Promise.all([
180
- firstSdk.marketData.getCandles(firstRequest),
181
- secondSdk.marketData.getCandles(secondRequest)
182
- ]);
183
- }
184
- finally {
185
- firstSdk.close();
186
- secondSdk.close();
187
- }
188
- ```
189
-
190
- Если instances используют разные `unaryLimits`, один bucket может получить разные параметры. Заранее выберите явную policy: отклонять конфликт, использовать наиболее строгую квоту или разделять scopes. Не принимайте молча последнее значение.
191
-
192
- ## Полный process-local пример
193
-
194
- Ниже — самостоятельная rolling-window реализация. Это пример Consumer-кода, а не универсальный алгоритм. Он допускает burst в пределах окна и хранит состояние только в текущем процессе. При `maxRequests >= 1` размер burst консервативно округляется вниз. При `maxRequests < 1` один permit выдаётся за увеличенное окно `windowMs / maxRequests`: квота `0.5` за `100` мс допускает один permit каждые `200` мс.
195
-
196
- ```ts
197
- import type {
198
- TInvestUnaryLimitContext,
199
- TInvestUnaryLimiter,
200
- TInvestUnaryQuota
201
- } from '@woodger/t-invest-node-sdk';
202
-
203
- interface BucketState {
204
- readonly maxRequests: number;
205
- readonly windowMs: number;
206
- readonly issuedAt: number[];
207
- }
208
-
209
- const maxTimerDelayMs = 2_147_483_647;
210
-
211
- export class RollingWindowUnaryLimiter implements TInvestUnaryLimiter {
212
- private readonly buckets = new Map<string, BucketState>();
213
-
214
- async acquire(context: TInvestUnaryLimitContext): Promise<void> {
215
- const state = this.getBucket(context.quota);
216
- const maxRequests = Math.max(1, Math.floor(state.maxRequests));
217
- const windowMs = state.maxRequests < 1
218
- ? state.windowMs / state.maxRequests
219
- : state.windowMs;
220
-
221
- while (true) {
222
- throwIfAborted(context.signal);
223
-
224
- const now = performance.now();
225
-
226
- this.removeExpired(state, now, windowMs);
227
-
228
- if (state.issuedAt.length < maxRequests) {
229
- state.issuedAt.push(now);
230
-
231
- return;
232
- }
233
-
234
- const oldestPermit = state.issuedAt[0];
235
-
236
- if (oldestPermit === undefined) {
237
- continue;
238
- }
239
-
240
- await wait(
241
- Math.max(0, oldestPermit + windowMs - now),
242
- context.signal
243
- );
244
- }
245
- }
246
-
247
- private getBucket(quota: TInvestUnaryQuota): BucketState {
248
- const current = this.buckets.get(quota.bucket);
249
-
250
- if (current !== undefined) {
251
- if (
252
- current.maxRequests !== quota.maxRequests
253
- || current.windowMs !== quota.windowMs
254
- ) {
255
- throw new Error(`Conflicting quota for bucket ${quota.bucket}`);
256
- }
257
-
258
- return current;
259
- }
260
-
261
- const created: BucketState = {
262
- maxRequests: quota.maxRequests,
263
- windowMs: quota.windowMs,
264
- issuedAt: []
265
- };
266
-
267
- this.buckets.set(quota.bucket, created);
268
-
269
- return created;
270
- }
271
-
272
- private removeExpired(state: BucketState, now: number, windowMs: number): void {
273
- const threshold = now - windowMs;
274
- let expired = 0;
275
-
276
- while (
277
- expired < state.issuedAt.length
278
- && (state.issuedAt[expired] ?? Number.POSITIVE_INFINITY) <= threshold
279
- ) {
280
- expired += 1;
281
- }
282
-
283
- if (expired > 0) {
284
- state.issuedAt.splice(0, expired);
285
- }
286
- }
287
- }
288
-
289
- async function wait(delayMs: number, signal: AbortSignal): Promise<void> {
290
- let remainingMs = delayMs;
291
-
292
- while (remainingMs > 0) {
293
- throwIfAborted(signal);
294
-
295
- const startedAt = performance.now();
296
-
297
- await waitOnce(Math.min(remainingMs, maxTimerDelayMs), signal);
298
- remainingMs -= performance.now() - startedAt;
299
- }
300
- }
301
-
302
- function waitOnce(delayMs: number, signal: AbortSignal): Promise<void> {
303
- return new Promise<void>((resolve, reject) => {
304
- if (signal.aborted) {
305
- reject(abortReason(signal));
306
-
307
- return;
308
- }
309
-
310
- const onAbort = () => {
311
- clearTimeout(timer);
312
- signal.removeEventListener('abort', onAbort);
313
- reject(abortReason(signal));
314
- };
315
- const timer = setTimeout(() => {
316
- signal.removeEventListener('abort', onAbort);
317
- resolve();
318
- }, delayMs);
319
-
320
- signal.addEventListener('abort', onAbort, { once: true });
321
- });
322
- }
323
-
324
- function throwIfAborted(signal: AbortSignal): void {
325
- if (signal.aborted) {
326
- throw abortReason(signal);
327
- }
328
- }
329
-
330
- function abortReason(signal: AbortSignal): unknown {
331
- if (signal.reason !== undefined) {
332
- return signal.reason;
333
- }
334
-
335
- const error = new Error('The operation was aborted');
336
-
337
- error.name = 'AbortError';
338
-
339
- return error;
340
- }
341
- ```
342
-
343
- Создайте один объект на нужный scope и передайте его всем соответствующим SDK instances:
344
-
345
- ```ts
346
- import { TInvestNodeSDK } from '@woodger/t-invest-node-sdk';
347
-
348
- const unaryLimiter = new RollingWindowUnaryLimiter();
349
-
350
- const sdk = new TInvestNodeSDK({
351
- token,
352
- endpoint,
353
- unaryLimiter
354
- });
355
- ```
356
-
357
- Для production-реализации также продумайте наблюдаемость, предел очереди, fairness, поведение при перегрузке и очистку неиспользуемых buckets. Эти решения зависят от приложения и не входят в минимальный port SDK.
358
-
359
- ## Межпроцессная реализация
360
-
361
- Один JavaScript-объект объединяет SDK instances только внутри процесса. Для нескольких процессов сделайте `acquire()` тонким adapter-ом к отдельно запущенному coordinator-у:
362
-
363
- ```ts
364
- import type {
365
- TInvestUnaryLimitContext,
366
- TInvestUnaryLimiter
367
- } from '@woodger/t-invest-node-sdk';
368
-
369
- interface CoordinatorClient {
370
- acquire(
371
- request: {
372
- readonly scope: string;
373
- readonly bucket: string;
374
- readonly maxRequests: number;
375
- readonly windowMs: number;
376
- },
377
- signal: AbortSignal
378
- ): Promise<void>;
379
- }
380
-
381
- class CoordinatorUnaryLimiter implements TInvestUnaryLimiter {
382
- constructor(
383
- private readonly client: CoordinatorClient,
384
- private readonly scope: string
385
- ) {}
386
-
387
- async acquire(context: TInvestUnaryLimitContext): Promise<void> {
388
- await this.client.acquire({
389
- scope: this.scope,
390
- bucket: context.quota.bucket,
391
- maxRequests: context.quota.maxRequests,
392
- windowMs: context.quota.windowMs
393
- }, context.signal);
394
- }
395
- }
396
- ```
397
-
398
- Для такого решения заранее определите:
399
-
400
- - кто запускает и завершает coordinator;
401
- - какие processes входят в один `scope`;
402
- - как выполняются atomic permit reservations;
403
- - удаляется ли ещё не выданный request при cancellation или disconnect;
404
- - применяется ли fail-closed при недоступности coordinator-а;
405
- - как обрабатывается cold start после потери неперсистентного состояния;
406
- - что происходит при разных версиях SDK или несовместимых квотах одного bucket;
407
- - какие integration-тесты воспроизводят concurrency, crash и restart.
408
-
409
- Не возвращайте permit после ошибки или отмены RPC: request уже мог достичь provider-а и попасть в квоту.
410
-
411
- SDK не требует конкретного coordinator protocol, IPC transport или базы данных. Consumer выбирает подходящую своей архитектуре границу без новой runtime dependency внутри SDK.
412
-
413
- ## Per-instance overrides
414
-
415
- Через `unaryLimits` можно заменить package rule для конкретного SDK instance. Укажите оба параметра окна:
416
-
417
- ```ts
418
- import {
419
- defineUnaryLimits,
420
- TInvestNodeSDK,
421
- type TInvestUnaryLimiter
422
- } from '@woodger/t-invest-node-sdk';
423
-
424
- declare const unaryLimiter: TInvestUnaryLimiter;
425
-
426
- const sdk = new TInvestNodeSDK({
427
- token,
428
- endpoint,
429
- unaryLimiter,
430
- unaryLimits: defineUnaryLimits({
431
- UsersService: {
432
- default: {
433
- maxRequests: 50,
434
- windowMs: 60_000
435
- }
436
- },
437
- OrdersService: {
438
- methods: {
439
- PostOrder: {
440
- maxRequests: 10,
441
- windowMs: 1_000
442
- }
443
- }
444
- }
445
- })
446
- });
447
- ```
448
-
449
- Остальные rules SDK берёт из `defaultConfig.unaryLimits`. Если изменить один method rule, SDK отсоединит его от package quota group, чтобы общий bucket не получил разные параметры. Одинаковое изменение всех methods группы сохранит общий bucket.
450
-
451
- SDK проверяет overrides при создании instance даже без limiter-а. Сами по себе они не добавляют ожидание: для этого нужен `unaryLimiter`.
452
-
453
- ## Необязательная реализация пакета
454
-
455
- Если нужен небольшой готовый вариант, пакет экспортирует `createInMemoryUnaryLimiter()`:
456
-
457
- ```ts
458
- import {
459
- createInMemoryUnaryLimiter,
460
- TInvestNodeSDK
461
- } from '@woodger/t-invest-node-sdk';
462
-
463
- const sdk = new TInvestNodeSDK({
464
- token,
465
- endpoint,
466
- unaryLimiter: createInMemoryUnaryLimiter()
467
- });
468
- ```
469
-
470
- Эта реализация равномерно разносит permits, использует монотонное время и поддерживает cancellation. Ожидающие requests обслуживаются в порядке FIFO; удаление отменённого request из очереди выполняется за O(1), без поиска и сдвига остальных элементов. Один объект может делить состояние между SDK instances одного процесса. Несовпадающие параметры одного bucket она отклоняет как конфликт конфигурации. Реализация не координирует разные процессы или hosts, не обновляет квоты из тарифа и не моделирует stream limits. Consumer может выбрать другой limiter или вовсе обойтись без него.
471
-
472
- ### Статическая доля квоты
473
-
474
- Если число независимых owners заранее известно, каждому limiter instance можно выделить фиксированную долю исходных квот:
475
-
476
- ```ts
477
- const unaryLimiter = createInMemoryUnaryLimiter({
478
- quotaShare: 0.5
479
- });
480
- ```
481
-
482
- `quotaShare` принимает конечное число в диапазоне `[0.2, 1]`; значение по умолчанию — `1`. Нижняя граница сохраняет не меньше одного permit в исходном окне для минимальной package-квоты `5` запросов в минуту. При доле меньше единицы limiter вычисляет `maxRequests * quotaShare` отдельно для каждой переданной квоты. Результат от единицы и выше округляется вниз: например, `600` запросов за `60_000` мс превращаются в `300`, а `15` запросов за `1_000` мс — в `7`. Если Consumer override даёт значение меньше единицы, limiter сохраняет его как дробную скорость и увеличивает интервал между целыми permits: `1 * 0.2` означает один permit каждые `300_000` мс. Поэтому низкая пользовательская квота не приводит к ошибке во время RPC.
483
-
484
- Эта настройка не меняет `TInvestUnaryLimitContext`: custom limiter по-прежнему получает исходные `maxRequests` и `windowMs` T-Invest. Она также не обнаруживает другие процессы и не синхронизирует их. При двух независимо настроенных процессах значение `0.5` делит известные квоты поровну; один оставшийся процесс использует только половину, а третий процесс нарушает сделанное предположение. Если несколько SDK instances используют один общий объект limiter-а, они уже делят его counters и дополнительное уменьшение доли для них не требуется.
485
-
486
- ## Проверочный список собственной реализации
487
-
488
- - `acquire()` разрешается только после фактической выдачи permit.
489
- - Все callers с одинаковыми `bucket` используют одно состояние в выбранном scope.
490
- - `maxRequests` и `windowMs` применяются как пара без смены единиц.
491
- - Неиспользованные ожидания удаляются по `signal` без listener leaks.
492
- - После выдачи permit нет автоматического refund.
493
- - Конфликт квот одного bucket обрабатывается явно.
494
- - Ошибка backend-а не включает незаметный локальный fallback.
495
- - Streams не считаются unary-вызовами.
496
- - Limiter не ожидает OAuth token или request payload от SDK.
497
- - Lifecycle limiter-а остаётся у Consumer-а.
498
- - Multi-process координация проверена отдельным integration-тестом, если она заявлена реализацией.
499
-
500
- Официальные значения и ограничения package policy смотрите в [лимитной политике](../limits-policy.md), а варианты межпроцессной архитектуры и их trade-offs — в [roadmap](../roadmap.md).
@@ -1,184 +0,0 @@
1
- # Ошибки и lifecycle
2
-
3
- > Type: Guide. Здесь показано, как разбирать `SdkError` по стабильным полям и не привязывать Consumer к transport error classes.
4
-
5
- ## Сужение типа по коду и источнику
6
-
7
- Один `code` не всегда определяет причину ошибки. Например, `CANCELLED` может прийти от локального `AbortSignal` или от provider-а. Когда это влияет на решение Consumer-а, проверяйте сочетание `code` и `source`.
8
-
9
- ```ts
10
- import {
11
- isSdkError,
12
- SdkErrorCode,
13
- TInvestNodeSDK
14
- } from '@woodger/t-invest-node-sdk';
15
-
16
- type RequiredEnvironmentVariable =
17
- | 'T_INVEST_TOKEN'
18
- | 'T_INVEST_ENDPOINT';
19
-
20
- function requireEnvironment(name: RequiredEnvironmentVariable): string {
21
- const value = process.env[name]?.trim();
22
-
23
- if (!value) {
24
- throw new Error(`Environment variable ${name} is required`);
25
- }
26
-
27
- return value;
28
- }
29
-
30
- async function main(): Promise<void> {
31
- const sdk = new TInvestNodeSDK({
32
- token: requireEnvironment('T_INVEST_TOKEN'),
33
- endpoint: requireEnvironment('T_INVEST_ENDPOINT')
34
- });
35
- const deadline = AbortSignal.timeout(5_000);
36
-
37
- try {
38
- const response = await sdk.users.getAccounts(
39
- {},
40
- {
41
- signal: deadline
42
- }
43
- );
44
-
45
- console.log(response.accounts);
46
- }
47
- catch (error: unknown) {
48
- if (
49
- isSdkError(error, SdkErrorCode.Unavailable)
50
- && error.source === 'tls'
51
- ) {
52
- console.error(
53
- 'T-Invest TLS certificate verification failed. '
54
- + 'Check the endpoint and the SDK CA configuration.'
55
- );
56
- process.exitCode = 1;
57
- return;
58
- }
59
-
60
- if (
61
- isSdkError(error, SdkErrorCode.Cancelled)
62
- && error.source === 'abort'
63
- && deadline.aborted
64
- ) {
65
- console.error('The local request deadline expired');
66
- return;
67
- }
68
-
69
- if (
70
- isSdkError(error, SdkErrorCode.Unauthenticated)
71
- && error.source === 'grpc'
72
- ) {
73
- console.error('The provider rejected the supplied credentials', {
74
- path: error.path
75
- });
76
- process.exitCode = 1;
77
- return;
78
- }
79
-
80
- if (
81
- isSdkError(error, SdkErrorCode.ResourceExhausted)
82
- && error.source === 'sdk'
83
- ) {
84
- console.error('Ответ превысил локальный лимит размера gRPC-сообщения', {
85
- path: error.path
86
- });
87
-
88
- throw error;
89
- }
90
-
91
- if (
92
- isSdkError(error, SdkErrorCode.ResourceExhausted)
93
- && error.source === 'grpc'
94
- ) {
95
- console.error('The provider quota was exhausted', {
96
- path: error.path,
97
- details: error.details
98
- });
99
-
100
- throw error;
101
- }
102
-
103
- throw error;
104
- }
105
- finally {
106
- sdk.close();
107
- }
108
- }
109
-
110
- void main().catch((error: unknown) => {
111
- console.error(error);
112
- process.exitCode = 1;
113
- });
114
- ```
115
-
116
- ## Коды ошибок
117
-
118
- SDK преобразует gRPC statuses в одноимённые стабильные `SdkErrorCode`.
119
-
120
- Для ошибки с `source: 'grpc'` поле `code` содержит символьное имя стандартного non-OK gRPC status. Например:
121
-
122
- ```ts
123
- SdkErrorCode.InvalidArgument; // 'INVALID_ARGUMENT'
124
- SdkErrorCode.NotFound; // 'NOT_FOUND'
125
- SdkErrorCode.Unauthenticated; // 'UNAUTHENTICATED'
126
- SdkErrorCode.ResourceExhausted; // 'RESOURCE_EXHAUSTED'
127
- ```
128
-
129
- Error contract не включает `OK`; полный набор значений задаёт экспортируемый enum `SdkErrorCode`. `SdkErrorCode.SdkClosed` и `SdkErrorCode.UnknownUnaryLimit` относятся к SDK, а не к gRPC. Поле `code` само по себе не указывает источник ошибки, поэтому при необходимости проверяйте его вместе с `source`.
130
-
131
- ## Интерпретация источника
132
-
133
- | `source` | Значение |
134
- | --- | --- |
135
- | `grpc` | Ошибка получена от transport/provider boundary |
136
- | `tls` | Transport не прошел проверку цепочки сертификатов или hostname |
137
- | `abort` | Вызов отменен Consumer-ом через `AbortSignal` |
138
- | `lifecycle` | SDK уже закрыт |
139
- | `sdk` | SDK отклонил локальную конфигурацию, request или runtime state |
140
-
141
- `SdkErrorCode.InvalidArgument` получает `source: 'grpc'` при provider validation и `source: 'sdk'` при локальной ошибке конфигурации. Поэтому определяйте источник не только по code.
142
-
143
- Не каждая unknown runtime error — это `SdkError`. Сначала вызовите `isSdkError()`, а неизвестную ошибку сохраните или передайте дальше без принудительного приведения типа. Например, SDK не оборачивает в `SdkError` синхронное исключение application callback-а `onHeader` или `onTrailer`.
144
-
145
- SDK помечает однозначные ошибки проверки цепочки сертификатов и hostname как `SdkErrorCode.Unavailable` с `source: 'tls'`. Обычный provider или network `UNAVAILABLE` сохраняет `source: 'grpc'`. Поля `path`, `details` и `cause` остаются доступными для диагностики, а для надёжной классификации используйте `source`.
146
-
147
- Если входящее gRPC-сообщение превышает внутренний лимит SDK, ошибка получает `SdkErrorCode.ResourceExhausted` и `source: 'sdk'`. Исчерпанная квота провайдера возвращает тот же code с `source: 'grpc'`. В обоих случаях SDK сохраняет исходные `path`, `details` и `cause`; различайте причины по `source`, а не по диагностическому тексту.
148
-
149
- Локальные ошибки сериализации request и разбора response получают `SdkErrorCode.Internal` с `source: 'sdk'`, а provider-side `INTERNAL` сохраняет `source: 'grpc'`. SDK оставляет `path`, `details` и `cause` для диагностики; для классификации достаточно `source`.
150
-
151
- ## Диагностические поля
152
-
153
- - `path` содержит gRPC method path, когда он известен.
154
- - `details` содержит диагностический текст transport/provider-а. Это не стабильный provider business code, поэтому не разбирайте его регулярным выражением.
155
- - `cause` сохраняет исходную ошибку, но остается transport-specific диагностикой. Business logic не должна зависеть от класса ошибки `nice-grpc`.
156
-
157
- Однозначные certificate trust и hostname verification failures получают `SdkErrorCode.Unavailable` с `source: 'tls'`. DNS failures, connection refusal/reset, timeout и обычный provider `UNAVAILABLE` сохраняют `source: 'grpc'`. По `source` можно сразу завершить вызов при ошибке TLS, не разбирая `details` и не запуская общий availability retry.
158
-
159
- Ошибки сериализации request и разбора response получают `SdkErrorCode.Internal` с `source: 'sdk'`, а provider-side `INTERNAL` сохраняет `source: 'grpc'`. Для различения достаточно `source`; используйте исходные `path`, `details` и `cause` только для диагностики.
160
-
161
- Brand guard распознает совместимый `SdkError` из другой физической копии пакета в том же JavaScript realm. После JSON, IPC или worker serialization нужен отдельный application protocol.
162
-
163
- ## Закрытие SDK
164
-
165
- `sdk.close()` можно вызывать повторно. Первый вызов:
166
-
167
- - запрещает новые service getters и calls через ранее полученные clients;
168
- - отменяет операции, которые еще ждут локальную unary-квоту;
169
- - закрывает shared channel.
170
-
171
- `sdk.close()` не ждёт операции, уже переданные transport-у. Для предсказуемого shutdown отмените их собственный `AbortSignal`, дождитесь settlement и только затем закройте SDK. Stream lifecycle подробно разобран в руководстве [Потоки и отмена](./streams-and-cancellation.md).
172
-
173
- ## Граница повторных попыток
174
-
175
- SDK намеренно не считает ошибку retryable только по gRPC status. Перед повтором проверьте:
176
-
177
- - idempotent ли операция;
178
- - мог ли provider уже применить side effect;
179
- - присутствует ли retry/rate-limit metadata;
180
- - какой backoff и общий deadline допустимы для приложения.
181
-
182
- Особенно это относится к `ResourceExhausted`, `Unavailable`, `DeadlineExceeded` и mutation RPC. Универсальный retry interceptor на уровне SDK скрыл бы эти различия.
183
-
184
- Для `ResourceExhausted` сначала проверяйте `source`. Значение `sdk` означает, что входящее сообщение превысило внутренний транспортный лимит SDK; повтор того же вызова ничего не изменит. Значение `grpc` указывает на ответ провайдера, но тоже не даёт достаточных оснований для повтора без учёта metadata, idempotency и backoff.