@woodger/t-invest-node-sdk 0.5.1
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.
- package/CHANGELOG.md +611 -0
- package/LICENSE +21 -0
- package/THIRD_PARTY_NOTICES.md +307 -0
- package/certificates/russian-trusted-root-ca.pem +33 -0
- package/dist/application/dto/t-invest-options.d.ts +30 -0
- package/dist/application/dto/t-invest-options.js +11 -0
- package/dist/application/dto/t-invest-services.d.ts +168 -0
- package/dist/application/dto/t-invest-services.js +12 -0
- package/dist/application/errors/sdk-error.d.ts +47 -0
- package/dist/application/errors/sdk-error.js +84 -0
- package/dist/application/reports/accounts.report.d.ts +26 -0
- package/dist/application/reports/accounts.report.js +11 -0
- package/dist/application/reports/accrued-interests.report.d.ts +22 -0
- package/dist/application/reports/accrued-interests.report.js +11 -0
- package/dist/application/reports/asset.report.d.ts +72 -0
- package/dist/application/reports/asset.report.js +11 -0
- package/dist/application/reports/bond-coupons.report.d.ts +31 -0
- package/dist/application/reports/bond-coupons.report.js +11 -0
- package/dist/application/reports/bond.report.d.ts +82 -0
- package/dist/application/reports/bond.report.js +11 -0
- package/dist/application/reports/brands.report.d.ts +24 -0
- package/dist/application/reports/brands.report.js +11 -0
- package/dist/application/reports/broker-report.report.d.ts +74 -0
- package/dist/application/reports/broker-report.report.js +11 -0
- package/dist/application/reports/cancel-order.report.d.ts +14 -0
- package/dist/application/reports/cancel-order.report.js +11 -0
- package/dist/application/reports/cancel-stop-order.report.d.ts +14 -0
- package/dist/application/reports/cancel-stop-order.report.js +11 -0
- package/dist/application/reports/candles.report.d.ts +26 -0
- package/dist/application/reports/candles.report.js +11 -0
- package/dist/application/reports/close-prices.report.d.ts +20 -0
- package/dist/application/reports/close-prices.report.js +11 -0
- package/dist/application/reports/countries.report.d.ts +20 -0
- package/dist/application/reports/countries.report.js +11 -0
- package/dist/application/reports/currency.report.d.ts +58 -0
- package/dist/application/reports/currency.report.js +11 -0
- package/dist/application/reports/dividends-foreign-issuer.report.d.ts +51 -0
- package/dist/application/reports/dividends-foreign-issuer.report.js +11 -0
- package/dist/application/reports/dividends.report.d.ts +33 -0
- package/dist/application/reports/dividends.report.js +11 -0
- package/dist/application/reports/etf.report.d.ts +62 -0
- package/dist/application/reports/etf.report.js +11 -0
- package/dist/application/reports/favorites.report.d.ts +24 -0
- package/dist/application/reports/favorites.report.js +11 -0
- package/dist/application/reports/find-instrument.report.d.ts +34 -0
- package/dist/application/reports/find-instrument.report.js +11 -0
- package/dist/application/reports/future.report.d.ts +66 -0
- package/dist/application/reports/future.report.js +11 -0
- package/dist/application/reports/futures-margin.report.d.ts +21 -0
- package/dist/application/reports/futures-margin.report.js +11 -0
- package/dist/application/reports/index.d.ts +50 -0
- package/dist/application/reports/index.js +66 -0
- package/dist/application/reports/instrument.report.d.ts +47 -0
- package/dist/application/reports/instrument.report.js +11 -0
- package/dist/application/reports/last-prices.report.d.ts +20 -0
- package/dist/application/reports/last-prices.report.js +11 -0
- package/dist/application/reports/last-trades.report.d.ts +24 -0
- package/dist/application/reports/last-trades.report.js +11 -0
- package/dist/application/reports/margin-attributes.report.d.ts +25 -0
- package/dist/application/reports/margin-attributes.report.js +11 -0
- package/dist/application/reports/money.report.d.ts +15 -0
- package/dist/application/reports/money.report.js +11 -0
- package/dist/application/reports/operations-by-cursor.report.d.ts +65 -0
- package/dist/application/reports/operations-by-cursor.report.js +11 -0
- package/dist/application/reports/operations.report.d.ts +40 -0
- package/dist/application/reports/operations.report.js +11 -0
- package/dist/application/reports/option.report.d.ts +76 -0
- package/dist/application/reports/option.report.js +11 -0
- package/dist/application/reports/order-book.report.d.ts +38 -0
- package/dist/application/reports/order-book.report.js +11 -0
- package/dist/application/reports/order-mutation.report.d.ts +45 -0
- package/dist/application/reports/order-mutation.report.js +11 -0
- package/dist/application/reports/order-state.report.d.ts +12 -0
- package/dist/application/reports/order-state.report.js +11 -0
- package/dist/application/reports/orders.report.d.ts +53 -0
- package/dist/application/reports/orders.report.js +11 -0
- package/dist/application/reports/portfolio.report.d.ts +54 -0
- package/dist/application/reports/portfolio.report.js +11 -0
- package/dist/application/reports/positions.report.d.ts +45 -0
- package/dist/application/reports/positions.report.js +11 -0
- package/dist/application/reports/post-stop-order.report.d.ts +14 -0
- package/dist/application/reports/post-stop-order.report.js +11 -0
- package/dist/application/reports/sandbox-account.report.d.ts +20 -0
- package/dist/application/reports/sandbox-account.report.js +11 -0
- package/dist/application/reports/share.report.d.ts +66 -0
- package/dist/application/reports/share.report.js +11 -0
- package/dist/application/reports/stop-orders.report.d.ts +34 -0
- package/dist/application/reports/stop-orders.report.js +11 -0
- package/dist/application/reports/trading-schedules.report.d.ts +44 -0
- package/dist/application/reports/trading-schedules.report.js +11 -0
- package/dist/application/reports/trading-status.report.d.ts +19 -0
- package/dist/application/reports/trading-status.report.js +11 -0
- package/dist/application/reports/trading-statuses.report.d.ts +12 -0
- package/dist/application/reports/trading-statuses.report.js +11 -0
- package/dist/application/reports/user-info.report.d.ts +16 -0
- package/dist/application/reports/user-info.report.js +11 -0
- package/dist/application/reports/user-tariff.report.d.ts +28 -0
- package/dist/application/reports/user-tariff.report.js +11 -0
- package/dist/application/reports/withdraw-limits.report.d.ts +16 -0
- package/dist/application/reports/withdraw-limits.report.js +11 -0
- package/dist/application/services/unary-limiter.d.ts +44 -0
- package/dist/application/services/unary-limiter.js +138 -0
- package/dist/bootstrap/args/command-options.d.ts +43 -0
- package/dist/bootstrap/args/command-options.js +125 -0
- package/dist/bootstrap/args/index.d.ts +1 -0
- package/dist/bootstrap/args/index.js +5 -0
- package/dist/bootstrap/args/instrument-id-options.d.ts +24 -0
- package/dist/bootstrap/args/instrument-id-options.js +47 -0
- package/dist/bootstrap/args/instruments-args.d.ts +49 -0
- package/dist/bootstrap/args/instruments-args.js +89 -0
- package/dist/bootstrap/args/sdk-options.d.ts +19 -0
- package/dist/bootstrap/args/sdk-options.js +40 -0
- package/dist/bootstrap/args/side-effect-args.d.ts +20 -0
- package/dist/bootstrap/args/side-effect-args.js +50 -0
- package/dist/bootstrap/cli/contract.d.ts +16 -0
- package/dist/bootstrap/cli/contract.js +15 -0
- package/dist/bootstrap/cli/domains.d.ts +260 -0
- package/dist/bootstrap/cli/domains.js +631 -0
- package/dist/bootstrap/cli/error.d.ts +15 -0
- package/dist/bootstrap/cli/error.js +40 -0
- package/dist/bootstrap/cli/help.d.ts +751 -0
- package/dist/bootstrap/cli/help.js +1789 -0
- package/dist/bootstrap/cli/registry.d.ts +2102 -0
- package/dist/bootstrap/cli/registry.js +186 -0
- package/dist/bootstrap/cli/runner.d.ts +10 -0
- package/dist/bootstrap/cli/runner.js +151 -0
- package/dist/bootstrap/cli/version.d.ts +17 -0
- package/dist/bootstrap/cli/version.js +26 -0
- package/dist/bootstrap/commands/accounts/cli.d.ts +63 -0
- package/dist/bootstrap/commands/accounts/cli.js +50 -0
- package/dist/bootstrap/commands/accounts/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/accounts/reporter.js +50 -0
- package/dist/bootstrap/commands/accrued-interests/cli.d.ts +129 -0
- package/dist/bootstrap/commands/accrued-interests/cli.js +80 -0
- package/dist/bootstrap/commands/accrued-interests/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/accrued-interests/reporter.js +43 -0
- package/dist/bootstrap/commands/asset/cli.d.ts +99 -0
- package/dist/bootstrap/commands/asset/cli.js +64 -0
- package/dist/bootstrap/commands/asset/reporter.d.ts +16 -0
- package/dist/bootstrap/commands/asset/reporter.js +122 -0
- package/dist/bootstrap/commands/assets/cli.d.ts +102 -0
- package/dist/bootstrap/commands/assets/cli.js +78 -0
- package/dist/bootstrap/commands/assets/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/assets/reporter.js +27 -0
- package/dist/bootstrap/commands/bond/cli.d.ts +83 -0
- package/dist/bootstrap/commands/bond/cli.js +53 -0
- package/dist/bootstrap/commands/bond/reporter.d.ts +15 -0
- package/dist/bootstrap/commands/bond/reporter.js +123 -0
- package/dist/bootstrap/commands/bond-coupons/cli.d.ts +129 -0
- package/dist/bootstrap/commands/bond-coupons/cli.js +80 -0
- package/dist/bootstrap/commands/bond-coupons/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/bond-coupons/reporter.js +64 -0
- package/dist/bootstrap/commands/bonds/cli.d.ts +73 -0
- package/dist/bootstrap/commands/bonds/cli.js +53 -0
- package/dist/bootstrap/commands/bonds/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/bonds/reporter.js +27 -0
- package/dist/bootstrap/commands/brand/cli.d.ts +99 -0
- package/dist/bootstrap/commands/brand/cli.js +64 -0
- package/dist/bootstrap/commands/brand/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/brand/reporter.js +37 -0
- package/dist/bootstrap/commands/brands/cli.d.ts +63 -0
- package/dist/bootstrap/commands/brands/cli.js +50 -0
- package/dist/bootstrap/commands/brands/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/brands/reporter.js +49 -0
- package/dist/bootstrap/commands/broker-report/cli.d.ts +132 -0
- package/dist/bootstrap/commands/broker-report/cli.js +105 -0
- package/dist/bootstrap/commands/broker-report/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/broker-report/reporter.js +123 -0
- package/dist/bootstrap/commands/cancel-order/cli.d.ts +120 -0
- package/dist/bootstrap/commands/cancel-order/cli.js +71 -0
- package/dist/bootstrap/commands/cancel-order/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/cancel-order/reporter.js +32 -0
- package/dist/bootstrap/commands/cancel-stop-order/cli.d.ts +120 -0
- package/dist/bootstrap/commands/cancel-stop-order/cli.js +71 -0
- package/dist/bootstrap/commands/cancel-stop-order/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/cancel-stop-order/reporter.js +32 -0
- package/dist/bootstrap/commands/candles/cli.d.ts +138 -0
- package/dist/bootstrap/commands/candles/cli.js +104 -0
- package/dist/bootstrap/commands/candles/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/candles/reporter.js +49 -0
- package/dist/bootstrap/commands/close-prices/cli.d.ts +99 -0
- package/dist/bootstrap/commands/close-prices/cli.js +66 -0
- package/dist/bootstrap/commands/close-prices/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/close-prices/reporter.js +43 -0
- package/dist/bootstrap/commands/compile-proto/cli.d.ts +12 -0
- package/dist/bootstrap/commands/compile-proto/cli.js +22 -0
- package/dist/bootstrap/commands/countries/cli.d.ts +63 -0
- package/dist/bootstrap/commands/countries/cli.js +50 -0
- package/dist/bootstrap/commands/countries/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/countries/reporter.js +42 -0
- package/dist/bootstrap/commands/currencies/cli.d.ts +73 -0
- package/dist/bootstrap/commands/currencies/cli.js +53 -0
- package/dist/bootstrap/commands/currencies/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/currencies/reporter.js +27 -0
- package/dist/bootstrap/commands/currency/cli.d.ts +83 -0
- package/dist/bootstrap/commands/currency/cli.js +53 -0
- package/dist/bootstrap/commands/currency/reporter.d.ts +15 -0
- package/dist/bootstrap/commands/currency/reporter.js +104 -0
- package/dist/bootstrap/commands/dividends/cli.d.ts +129 -0
- package/dist/bootstrap/commands/dividends/cli.js +80 -0
- package/dist/bootstrap/commands/dividends/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/dividends/reporter.js +62 -0
- package/dist/bootstrap/commands/dividends-foreign-issuer/cli.d.ts +132 -0
- package/dist/bootstrap/commands/dividends-foreign-issuer/cli.js +105 -0
- package/dist/bootstrap/commands/dividends-foreign-issuer/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/dividends-foreign-issuer/reporter.js +108 -0
- package/dist/bootstrap/commands/edit-favorites/cli.d.ts +129 -0
- package/dist/bootstrap/commands/edit-favorites/cli.js +78 -0
- package/dist/bootstrap/commands/edit-favorites/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/edit-favorites/reporter.js +23 -0
- package/dist/bootstrap/commands/etf/cli.d.ts +83 -0
- package/dist/bootstrap/commands/etf/cli.js +53 -0
- package/dist/bootstrap/commands/etf/reporter.d.ts +15 -0
- package/dist/bootstrap/commands/etf/reporter.js +109 -0
- package/dist/bootstrap/commands/etfs/cli.d.ts +73 -0
- package/dist/bootstrap/commands/etfs/cli.js +53 -0
- package/dist/bootstrap/commands/etfs/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/etfs/reporter.js +27 -0
- package/dist/bootstrap/commands/favorites/cli.d.ts +63 -0
- package/dist/bootstrap/commands/favorites/cli.js +50 -0
- package/dist/bootstrap/commands/favorites/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/favorites/reporter.js +60 -0
- package/dist/bootstrap/commands/find-instrument/cli.d.ts +126 -0
- package/dist/bootstrap/commands/find-instrument/cli.js +88 -0
- package/dist/bootstrap/commands/find-instrument/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/find-instrument/reporter.js +71 -0
- package/dist/bootstrap/commands/future/cli.d.ts +83 -0
- package/dist/bootstrap/commands/future/cli.js +53 -0
- package/dist/bootstrap/commands/future/reporter.d.ts +15 -0
- package/dist/bootstrap/commands/future/reporter.js +116 -0
- package/dist/bootstrap/commands/futures/cli.d.ts +73 -0
- package/dist/bootstrap/commands/futures/cli.js +53 -0
- package/dist/bootstrap/commands/futures/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/futures/reporter.js +27 -0
- package/dist/bootstrap/commands/futures-margin/cli.d.ts +105 -0
- package/dist/bootstrap/commands/futures-margin/cli.js +64 -0
- package/dist/bootstrap/commands/futures-margin/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/futures-margin/reporter.js +40 -0
- package/dist/bootstrap/commands/help/cli.d.ts +13 -0
- package/dist/bootstrap/commands/help/cli.js +26 -0
- package/dist/bootstrap/commands/instrument/cli.d.ts +83 -0
- package/dist/bootstrap/commands/instrument/cli.js +53 -0
- package/dist/bootstrap/commands/instrument/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/instrument/reporter.js +91 -0
- package/dist/bootstrap/commands/last-prices/cli.d.ts +99 -0
- package/dist/bootstrap/commands/last-prices/cli.js +66 -0
- package/dist/bootstrap/commands/last-prices/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/last-prices/reporter.js +43 -0
- package/dist/bootstrap/commands/last-trades/cli.d.ts +123 -0
- package/dist/bootstrap/commands/last-trades/cli.js +82 -0
- package/dist/bootstrap/commands/last-trades/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/last-trades/reporter.js +48 -0
- package/dist/bootstrap/commands/margin-attributes/cli.d.ts +99 -0
- package/dist/bootstrap/commands/margin-attributes/cli.js +64 -0
- package/dist/bootstrap/commands/margin-attributes/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/margin-attributes/reporter.js +51 -0
- package/dist/bootstrap/commands/operations/cli.d.ts +156 -0
- package/dist/bootstrap/commands/operations/cli.js +99 -0
- package/dist/bootstrap/commands/operations/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/operations/reporter.js +78 -0
- package/dist/bootstrap/commands/operations-by-cursor/cli.d.ts +204 -0
- package/dist/bootstrap/commands/operations-by-cursor/cli.js +164 -0
- package/dist/bootstrap/commands/operations-by-cursor/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/operations-by-cursor/reporter.js +107 -0
- package/dist/bootstrap/commands/option/cli.d.ts +83 -0
- package/dist/bootstrap/commands/option/cli.js +53 -0
- package/dist/bootstrap/commands/option/reporter.d.ts +15 -0
- package/dist/bootstrap/commands/option/reporter.js +125 -0
- package/dist/bootstrap/commands/options-by/cli.d.ts +108 -0
- package/dist/bootstrap/commands/options-by/cli.js +68 -0
- package/dist/bootstrap/commands/options-by/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/options-by/reporter.js +27 -0
- package/dist/bootstrap/commands/order-book/cli.d.ts +120 -0
- package/dist/bootstrap/commands/order-book/cli.js +73 -0
- package/dist/bootstrap/commands/order-book/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/order-book/reporter.js +60 -0
- package/dist/bootstrap/commands/order-state/cli.d.ts +111 -0
- package/dist/bootstrap/commands/order-state/cli.js +71 -0
- package/dist/bootstrap/commands/order-state/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/order-state/reporter.js +57 -0
- package/dist/bootstrap/commands/orders/cli.d.ts +99 -0
- package/dist/bootstrap/commands/orders/cli.js +64 -0
- package/dist/bootstrap/commands/orders/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/orders/reporter.js +88 -0
- package/dist/bootstrap/commands/portfolio/cli.d.ts +114 -0
- package/dist/bootstrap/commands/portfolio/cli.js +77 -0
- package/dist/bootstrap/commands/portfolio/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/portfolio/reporter.js +95 -0
- package/dist/bootstrap/commands/positions/cli.d.ts +99 -0
- package/dist/bootstrap/commands/positions/cli.js +64 -0
- package/dist/bootstrap/commands/positions/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/positions/reporter.js +116 -0
- package/dist/bootstrap/commands/post-order/cli.d.ts +192 -0
- package/dist/bootstrap/commands/post-order/cli.js +113 -0
- package/dist/bootstrap/commands/post-order/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/post-order/reporter.js +77 -0
- package/dist/bootstrap/commands/post-stop-order/cli.d.ts +216 -0
- package/dist/bootstrap/commands/post-stop-order/cli.js +145 -0
- package/dist/bootstrap/commands/post-stop-order/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/post-stop-order/reporter.js +31 -0
- package/dist/bootstrap/commands/replace-order/cli.d.ts +180 -0
- package/dist/bootstrap/commands/replace-order/cli.js +99 -0
- package/dist/bootstrap/commands/replace-order/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/replace-order/reporter.js +17 -0
- package/dist/bootstrap/commands/sandbox-accounts/cli.d.ts +64 -0
- package/dist/bootstrap/commands/sandbox-accounts/cli.js +54 -0
- package/dist/bootstrap/commands/sandbox-cancel-order/cli.d.ts +120 -0
- package/dist/bootstrap/commands/sandbox-cancel-order/cli.js +69 -0
- package/dist/bootstrap/commands/sandbox-close-account/cli.d.ts +108 -0
- package/dist/bootstrap/commands/sandbox-close-account/cli.js +66 -0
- package/dist/bootstrap/commands/sandbox-close-account/reporter.d.ts +12 -0
- package/dist/bootstrap/commands/sandbox-close-account/reporter.js +32 -0
- package/dist/bootstrap/commands/sandbox-open-account/cli.d.ts +70 -0
- package/dist/bootstrap/commands/sandbox-open-account/cli.js +57 -0
- package/dist/bootstrap/commands/sandbox-open-account/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/sandbox-open-account/reporter.js +31 -0
- package/dist/bootstrap/commands/sandbox-operations/cli.d.ts +156 -0
- package/dist/bootstrap/commands/sandbox-operations/cli.js +78 -0
- package/dist/bootstrap/commands/sandbox-operations-by-cursor/cli.d.ts +204 -0
- package/dist/bootstrap/commands/sandbox-operations-by-cursor/cli.js +98 -0
- package/dist/bootstrap/commands/sandbox-order-state/cli.d.ts +111 -0
- package/dist/bootstrap/commands/sandbox-order-state/cli.js +67 -0
- package/dist/bootstrap/commands/sandbox-orders/cli.d.ts +99 -0
- package/dist/bootstrap/commands/sandbox-orders/cli.js +63 -0
- package/dist/bootstrap/commands/sandbox-pay-in/cli.d.ts +135 -0
- package/dist/bootstrap/commands/sandbox-pay-in/cli.js +86 -0
- package/dist/bootstrap/commands/sandbox-pay-in/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/sandbox-pay-in/reporter.js +32 -0
- package/dist/bootstrap/commands/sandbox-portfolio/cli.d.ts +114 -0
- package/dist/bootstrap/commands/sandbox-portfolio/cli.js +68 -0
- package/dist/bootstrap/commands/sandbox-positions/cli.d.ts +99 -0
- package/dist/bootstrap/commands/sandbox-positions/cli.js +63 -0
- package/dist/bootstrap/commands/sandbox-post-order/cli.d.ts +192 -0
- package/dist/bootstrap/commands/sandbox-post-order/cli.js +90 -0
- package/dist/bootstrap/commands/sandbox-replace-order/cli.d.ts +180 -0
- package/dist/bootstrap/commands/sandbox-replace-order/cli.js +86 -0
- package/dist/bootstrap/commands/sandbox-withdraw-limits/cli.d.ts +99 -0
- package/dist/bootstrap/commands/sandbox-withdraw-limits/cli.js +63 -0
- package/dist/bootstrap/commands/share/cli.d.ts +83 -0
- package/dist/bootstrap/commands/share/cli.js +53 -0
- package/dist/bootstrap/commands/share/reporter.d.ts +15 -0
- package/dist/bootstrap/commands/share/reporter.js +111 -0
- package/dist/bootstrap/commands/shares/cli.d.ts +73 -0
- package/dist/bootstrap/commands/shares/cli.js +53 -0
- package/dist/bootstrap/commands/shares/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/shares/reporter.js +27 -0
- package/dist/bootstrap/commands/stop-orders/cli.d.ts +99 -0
- package/dist/bootstrap/commands/stop-orders/cli.js +68 -0
- package/dist/bootstrap/commands/stop-orders/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/stop-orders/reporter.js +69 -0
- package/dist/bootstrap/commands/stream-run/cli.d.ts +138 -0
- package/dist/bootstrap/commands/stream-run/cli.js +229 -0
- package/dist/bootstrap/commands/stream-run/config.d.ts +56 -0
- package/dist/bootstrap/commands/stream-run/config.js +468 -0
- package/dist/bootstrap/commands/stream-run/reporter.d.ts +30 -0
- package/dist/bootstrap/commands/stream-run/reporter.js +76 -0
- package/dist/bootstrap/commands/trading-schedules/cli.d.ts +120 -0
- package/dist/bootstrap/commands/trading-schedules/cli.js +79 -0
- package/dist/bootstrap/commands/trading-schedules/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/trading-schedules/reporter.js +58 -0
- package/dist/bootstrap/commands/trading-status/cli.d.ts +99 -0
- package/dist/bootstrap/commands/trading-status/cli.js +65 -0
- package/dist/bootstrap/commands/trading-status/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/trading-status/reporter.js +51 -0
- package/dist/bootstrap/commands/trading-statuses/cli.d.ts +99 -0
- package/dist/bootstrap/commands/trading-statuses/cli.js +64 -0
- package/dist/bootstrap/commands/trading-statuses/reporter.d.ts +14 -0
- package/dist/bootstrap/commands/trading-statuses/reporter.js +44 -0
- package/dist/bootstrap/commands/user-info/cli.d.ts +63 -0
- package/dist/bootstrap/commands/user-info/cli.js +50 -0
- package/dist/bootstrap/commands/user-info/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/user-info/reporter.js +39 -0
- package/dist/bootstrap/commands/user-tariff/cli.d.ts +63 -0
- package/dist/bootstrap/commands/user-tariff/cli.js +50 -0
- package/dist/bootstrap/commands/user-tariff/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/user-tariff/reporter.js +50 -0
- package/dist/bootstrap/commands/version/cli.d.ts +13 -0
- package/dist/bootstrap/commands/version/cli.js +22 -0
- package/dist/bootstrap/commands/withdraw-limits/cli.d.ts +99 -0
- package/dist/bootstrap/commands/withdraw-limits/cli.js +64 -0
- package/dist/bootstrap/commands/withdraw-limits/reporter.d.ts +13 -0
- package/dist/bootstrap/commands/withdraw-limits/reporter.js +59 -0
- package/dist/bootstrap/generated-exports.d.ts +29 -0
- package/dist/bootstrap/generated-exports.js +590 -0
- package/dist/bootstrap/index.d.ts +6 -0
- package/dist/bootstrap/index.js +22 -0
- package/dist/bootstrap/proto/compile-proto.d.ts +18 -0
- package/dist/bootstrap/proto/compile-proto.js +122 -0
- package/dist/bootstrap/sdk-config.d.ts +21 -0
- package/dist/bootstrap/sdk-config.js +152 -0
- package/dist/bootstrap/t-invest-node-sdk.d.ts +42 -0
- package/dist/bootstrap/t-invest-node-sdk.js +115 -0
- package/dist/bootstrap/unary-limit-config.d.ts +38 -0
- package/dist/bootstrap/unary-limit-config.js +130 -0
- package/dist/config.d.ts +160 -0
- package/dist/config.js +173 -0
- package/dist/config.types.d.ts +89 -0
- package/dist/config.types.js +13 -0
- package/dist/generated/common.d.ts +214 -0
- package/dist/generated/common.js +1336 -0
- package/dist/generated/google/api/field_behavior.d.ts +61 -0
- package/dist/generated/google/api/field_behavior.js +126 -0
- package/dist/generated/google/protobuf/descriptor.d.ts +1330 -0
- package/dist/generated/google/protobuf/descriptor.js +5984 -0
- package/dist/generated/google/protobuf/timestamp.d.ts +122 -0
- package/dist/generated/google/protobuf/timestamp.js +102 -0
- package/dist/generated/instruments.d.ts +3230 -0
- package/dist/generated/instruments.js +24246 -0
- package/dist/generated/marketdata.d.ts +1268 -0
- package/dist/generated/marketdata.js +8922 -0
- package/dist/generated/operations.d.ts +1165 -0
- package/dist/generated/operations.js +8625 -0
- package/dist/generated/orders.d.ts +806 -0
- package/dist/generated/orders.js +5639 -0
- package/dist/generated/sandbox.d.ts +356 -0
- package/dist/generated/sandbox.js +603 -0
- package/dist/generated/signals.d.ts +196 -0
- package/dist/generated/signals.js +1261 -0
- package/dist/generated/stoporders.d.ts +328 -0
- package/dist/generated/stoporders.js +1990 -0
- package/dist/generated/users.d.ts +453 -0
- package/dist/generated/users.js +2334 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +30 -0
- package/dist/infrastructure/interceptor/index.d.ts +1 -0
- package/dist/infrastructure/interceptor/index.js +17 -0
- package/dist/infrastructure/interceptor/warning-interceptor.d.ts +23 -0
- package/dist/infrastructure/interceptor/warning-interceptor.js +38 -0
- package/dist/infrastructure/report-values.d.ts +19 -0
- package/dist/infrastructure/report-values.js +50 -0
- package/dist/infrastructure/transport/grpc/index.d.ts +5 -0
- package/dist/infrastructure/transport/grpc/index.js +13 -0
- package/dist/infrastructure/transport/grpc/sdk-channel.d.ts +12 -0
- package/dist/infrastructure/transport/grpc/sdk-channel.js +23 -0
- package/dist/infrastructure/transport/grpc/sdk-client.d.ts +16 -0
- package/dist/infrastructure/transport/grpc/sdk-client.js +33 -0
- package/dist/infrastructure/transport/grpc/sdk-metadata.d.ts +12 -0
- package/dist/infrastructure/transport/grpc/sdk-metadata.js +22 -0
- package/dist/infrastructure/transport/grpc/sdk-middleware.d.ts +22 -0
- package/dist/infrastructure/transport/grpc/sdk-middleware.js +312 -0
- package/dist/infrastructure/transport/grpc/tls-root-certificates.d.ts +10 -0
- package/dist/infrastructure/transport/grpc/tls-root-certificates.js +20 -0
- package/dist/infrastructure/transport/grpc/unary-limit-resolver.d.ts +22 -0
- package/dist/infrastructure/transport/grpc/unary-limit-resolver.js +60 -0
- package/dist/infrastructure/transport/grpc/unary-limits.d.ts +1 -0
- package/dist/infrastructure/transport/grpc/unary-limits.js +7 -0
- package/docs/architecture.md +378 -0
- package/docs/bundled-ca.md +157 -0
- package/docs/clean-architecture/adapters.md +173 -0
- package/docs/clean-architecture/api-commands.md +487 -0
- package/docs/clean-architecture/application.md +137 -0
- package/docs/clean-architecture/cli-output-boundaries.md +256 -0
- package/docs/clean-architecture/dto.md +153 -0
- package/docs/clean-architecture/index.md +89 -0
- package/docs/cli-stream-configuration.md +305 -0
- package/docs/cli-stream-reference.md +195 -0
- package/docs/guides/custom-unary-limiter.md +552 -0
- package/docs/guides/errors-and-lifecycle.md +196 -0
- package/docs/guides/getting-started.md +100 -0
- package/docs/guides/index.md +43 -0
- package/docs/guides/streams-and-cancellation.md +177 -0
- package/docs/guides/testing-with-service-definitions.md +110 -0
- package/docs/guides/unary-calls.md +216 -0
- package/docs/index.md +86 -0
- package/docs/limits-policy.md +201 -0
- package/docs/roadmap.md +204 -0
- package/docs/tls-policy.md +62 -0
- package/package.json +62 -0
- package/readme.md +472 -0
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
# Собственная реализация unary limiter-а
|
|
2
|
+
|
|
3
|
+
> Type: Consumer Guide. Документ описывает публичный port, который позволяет
|
|
4
|
+
> приложению самостоятельно владеть ожиданием unary-квоты. Это отдельный класс
|
|
5
|
+
> архитектурных решений, а не рекомендация использовать конкретный алгоритм или
|
|
6
|
+
> готовую реализацию SDK.
|
|
7
|
+
|
|
8
|
+
## Граница ответственности
|
|
9
|
+
|
|
10
|
+
SDK владеет знаниями о T-Invest API:
|
|
11
|
+
|
|
12
|
+
- сопоставляет полный gRPC method path с service fallback или более точным
|
|
13
|
+
method rule;
|
|
14
|
+
- объединяет методы, расходующие общую квоту, одним `bucket`;
|
|
15
|
+
- передаёт исходные `maxRequests` и `windowMs` без нормализации секундного окна
|
|
16
|
+
в минутное;
|
|
17
|
+
- объединяет отмену конкретного RPC с закрытием SDK instance.
|
|
18
|
+
|
|
19
|
+
Consumer-owned limiter владеет механизмом выдачи permit:
|
|
20
|
+
|
|
21
|
+
- выбирает алгоритм ожидания;
|
|
22
|
+
- хранит или координирует состояние;
|
|
23
|
+
- определяет границу process, host или deployment;
|
|
24
|
+
- прекращает ожидание по `AbortSignal`;
|
|
25
|
+
- определяет поведение при отказе собственного backend-а.
|
|
26
|
+
|
|
27
|
+
SDK не передаёт limiter-у OAuth token, request payload, metadata или service
|
|
28
|
+
client. Эти данные не нужны для управления готовой квотой и не должны
|
|
29
|
+
становиться неявными ключами внешнего хранилища.
|
|
30
|
+
|
|
31
|
+
## Публичные типы
|
|
32
|
+
|
|
33
|
+
Все типы импортируются только из корня пакета:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import type {
|
|
37
|
+
TInvestUnaryLimit,
|
|
38
|
+
TInvestUnaryLimitContext,
|
|
39
|
+
TInvestUnaryLimiter,
|
|
40
|
+
TInvestUnaryLimits,
|
|
41
|
+
TInvestUnaryQuota
|
|
42
|
+
} from '@woodger/t-invest-node-sdk';
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Их контракт имеет следующую форму:
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
interface TInvestUnaryLimit {
|
|
49
|
+
readonly maxRequests: number;
|
|
50
|
+
readonly windowMs: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type TInvestUnaryLimits = Record<string, TInvestUnaryLimit>;
|
|
54
|
+
|
|
55
|
+
interface TInvestUnaryQuota extends TInvestUnaryLimit {
|
|
56
|
+
readonly bucket: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface TInvestUnaryLimitContext {
|
|
60
|
+
readonly path: string;
|
|
61
|
+
readonly quota: TInvestUnaryQuota;
|
|
62
|
+
readonly signal: AbortSignal;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface TInvestUnaryLimiter {
|
|
66
|
+
acquire(context: TInvestUnaryLimitContext): Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`TInvestOptions.unaryLimiter` принимает любой объект, структурно реализующий
|
|
71
|
+
`TInvestUnaryLimiter`. Наследование от SDK-класса и регистрация plugin-а не
|
|
72
|
+
требуются.
|
|
73
|
+
|
|
74
|
+
## Когда вызывается `acquire()`
|
|
75
|
+
|
|
76
|
+
Для каждого unary RPC с настроенным limiter-ом последовательность такова:
|
|
77
|
+
|
|
78
|
+
```text
|
|
79
|
+
проверка lifecycle SDK
|
|
80
|
+
-> разрешение path в quota
|
|
81
|
+
-> unaryLimiter.acquire(context)
|
|
82
|
+
-> повторная проверка lifecycle и AbortSignal
|
|
83
|
+
-> передача request в gRPC transport
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Инварианты вызова:
|
|
87
|
+
|
|
88
|
+
1. `acquire()` вызывается ровно один раз непосредственно перед каждой
|
|
89
|
+
попыткой передать unary request transport-у.
|
|
90
|
+
2. Успешное завершение `Promise<void>` означает выдачу permit. После него SDK
|
|
91
|
+
вправе сразу начать transport call.
|
|
92
|
+
3. Отклонение Promise запрещает отправку request. Обычная ошибка limiter-а
|
|
93
|
+
возвращается Consumer-у без преобразования в transport `SdkError`.
|
|
94
|
+
4. Server-side и bidirectional streams через этот port не проходят. Их
|
|
95
|
+
соединения и subscriptions имеют отдельную политику.
|
|
96
|
+
5. Если `unaryLimiter` не передан, SDK не создаёт скрытый limiter и сразу
|
|
97
|
+
передаёт unary-вызов transport-у.
|
|
98
|
+
|
|
99
|
+
Limiter вызывается на уровне transport middleware, поэтому прямой вызов любого
|
|
100
|
+
публичного service client проходит через тот же контракт. Вызов `acquire()` не
|
|
101
|
+
означает, что provider принял request: он означает только разрешение локальной
|
|
102
|
+
или внешней стратегии продолжить вызов.
|
|
103
|
+
|
|
104
|
+
## Семантика полей контекста
|
|
105
|
+
|
|
106
|
+
### `path`
|
|
107
|
+
|
|
108
|
+
`path` — полный путь вызываемого RPC, например:
|
|
109
|
+
|
|
110
|
+
```text
|
|
111
|
+
/tinkoff.public.invest.api.contract.v1.MarketDataService/GetCandles
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Поле пригодно для диагностики, метрик и дополнительной Consumer-owned policy.
|
|
115
|
+
Не следует заново выводить из него квоту: SDK уже передал разрешённое правило в
|
|
116
|
+
`quota`.
|
|
117
|
+
|
|
118
|
+
### `quota.bucket`
|
|
119
|
+
|
|
120
|
+
`bucket` — непрозрачный идентификатор общего временного состояния. Одинаковые
|
|
121
|
+
значения означают, что вызовы должны учитывать одну очередь или один счётчик.
|
|
122
|
+
Например, несколько methods формирования отчётов могут получить общий bucket.
|
|
123
|
+
|
|
124
|
+
Consumer должен:
|
|
125
|
+
|
|
126
|
+
- использовать значение целиком;
|
|
127
|
+
- сравнивать его только на равенство;
|
|
128
|
+
- не разбирать prefixes и segments;
|
|
129
|
+
- не связывать с ним бизнес-смысл или формат persisted data;
|
|
130
|
+
- добавлять собственный scope отдельным полем или внешним prefix, если один
|
|
131
|
+
backend обслуживает несколько пользователей, environments или endpoints.
|
|
132
|
+
|
|
133
|
+
Состав buckets следует считать частью текущего snapshot лимитной policy SDK,
|
|
134
|
+
а не вечным идентификатором между произвольными версиями пакета. При
|
|
135
|
+
одновременной работе разных версий Consumer должен явно проверить, что их
|
|
136
|
+
quota policy совместима.
|
|
137
|
+
|
|
138
|
+
### `quota.maxRequests` и `quota.windowMs`
|
|
139
|
+
|
|
140
|
+
Пара задаёт максимум запросов в исходном временном окне. Например:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
{
|
|
144
|
+
bucket: '...',
|
|
145
|
+
maxRequests: 15,
|
|
146
|
+
windowMs: 1_000
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
означает 15 запросов за секунду. Представление не превращает эту квоту в 900
|
|
151
|
+
запросов за минуту, поскольку такие записи допускают разную burst-семантику.
|
|
152
|
+
|
|
153
|
+
SDK гарантирует конечные положительные значения. Это статическая package
|
|
154
|
+
policy с учётом `TInvestOptions.unaryLimits`, но не автоматически обновляемый
|
|
155
|
+
тариф пользователя. Limiter может применить более строгую Consumer-owned
|
|
156
|
+
policy, учитывать `x-ratelimit-*` metadata или данные `getUserTariff()`, не
|
|
157
|
+
изменяя переданный объект.
|
|
158
|
+
|
|
159
|
+
Один вызов получает одно наиболее специфичное правило. Оно не моделирует
|
|
160
|
+
одновременно все возможные service-, user- и IP-ограничения provider-а.
|
|
161
|
+
Дополнительные ограничения принадлежат реализации Consumer-а.
|
|
162
|
+
|
|
163
|
+
### `signal`
|
|
164
|
+
|
|
165
|
+
`signal` отменяется при отмене конкретного вызова или при `sdk.close()`. Он
|
|
166
|
+
может быть результатом `AbortSignal.any()`, поэтому нельзя полагаться на
|
|
167
|
+
identity с signal, переданным в call options.
|
|
168
|
+
|
|
169
|
+
Реализация должна:
|
|
170
|
+
|
|
171
|
+
- проверить `signal.aborted` до постановки в очередь;
|
|
172
|
+
- удалить незавершённое ожидание после события `abort`;
|
|
173
|
+
- отклонить Promise значением `signal.reason`, если оно доступно;
|
|
174
|
+
- удалить event listener при любом завершении;
|
|
175
|
+
- не выдавать permit после отмены.
|
|
176
|
+
|
|
177
|
+
Если limiter игнорирует signal и оставляет Promise незавершённым, SDK не может
|
|
178
|
+
принудительно остановить его внутреннее ожидание. В этом случае pending RPC
|
|
179
|
+
останется в ожидании limiter-а даже после `sdk.close()`.
|
|
180
|
+
|
|
181
|
+
Отмена call-level ожидания преобразуется в публичный `SdkErrorCode.Cancelled`
|
|
182
|
+
с `source: 'abort'`. Закрытие SDK сохраняет lifecycle error. Остальные ошибки
|
|
183
|
+
limiter-а не маскируются под gRPC failures.
|
|
184
|
+
|
|
185
|
+
## Ownership и время жизни
|
|
186
|
+
|
|
187
|
+
Limiter принадлежит коду, который его создал:
|
|
188
|
+
|
|
189
|
+
- `TInvestNodeSDK.close()` не вызывает у него `close()`, `dispose()` или иной
|
|
190
|
+
lifecycle method;
|
|
191
|
+
- один limiter можно передать нескольким SDK instances, если они должны делить
|
|
192
|
+
состояние;
|
|
193
|
+
- разные объекты limiter-а не делят состояние автоматически;
|
|
194
|
+
- Consumer закрывает внешние connections и workers после завершения всех SDK
|
|
195
|
+
instances, которые используют limiter.
|
|
196
|
+
|
|
197
|
+
Пример общего process-local ownership:
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
import {
|
|
201
|
+
TInvestNodeSDK,
|
|
202
|
+
type TInvestUnaryLimiter
|
|
203
|
+
} from '@woodger/t-invest-node-sdk';
|
|
204
|
+
|
|
205
|
+
declare const unaryLimiter: TInvestUnaryLimiter;
|
|
206
|
+
|
|
207
|
+
const firstSdk = new TInvestNodeSDK({
|
|
208
|
+
token,
|
|
209
|
+
endpoint,
|
|
210
|
+
unaryLimiter
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
const secondSdk = new TInvestNodeSDK({
|
|
214
|
+
token,
|
|
215
|
+
endpoint,
|
|
216
|
+
unaryLimiter
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
try {
|
|
220
|
+
await Promise.all([
|
|
221
|
+
firstSdk.marketdata.getCandles(firstRequest),
|
|
222
|
+
secondSdk.marketdata.getCandles(secondRequest)
|
|
223
|
+
]);
|
|
224
|
+
}
|
|
225
|
+
finally {
|
|
226
|
+
firstSdk.close();
|
|
227
|
+
secondSdk.close();
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
Если instances используют разные `unaryLimits`, один bucket может прийти с
|
|
232
|
+
разными параметрами. Реализация должна заранее выбрать явную policy: отклонять
|
|
233
|
+
конфликт, использовать наиболее строгую квоту или разделять scopes. Незаметно
|
|
234
|
+
принимать последнее полученное значение небезопасно.
|
|
235
|
+
|
|
236
|
+
## Полный process-local пример
|
|
237
|
+
|
|
238
|
+
Ниже приведена самостоятельная rolling-window реализация. Это пример
|
|
239
|
+
Consumer-кода, а не эталон алгоритма для всех workloads. Она допускает burst в
|
|
240
|
+
пределах окна и хранит состояние только в текущем процессе.
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
import type {
|
|
244
|
+
TInvestUnaryLimitContext,
|
|
245
|
+
TInvestUnaryLimiter,
|
|
246
|
+
TInvestUnaryQuota
|
|
247
|
+
} from '@woodger/t-invest-node-sdk';
|
|
248
|
+
|
|
249
|
+
interface BucketState {
|
|
250
|
+
readonly maxRequests: number;
|
|
251
|
+
readonly windowMs: number;
|
|
252
|
+
readonly issuedAt: number[];
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const maxTimerDelayMs = 2_147_483_647;
|
|
256
|
+
|
|
257
|
+
export class RollingWindowUnaryLimiter implements TInvestUnaryLimiter {
|
|
258
|
+
private readonly buckets = new Map<string, BucketState>();
|
|
259
|
+
|
|
260
|
+
async acquire(context: TInvestUnaryLimitContext): Promise<void> {
|
|
261
|
+
const state = this.getBucket(context.quota);
|
|
262
|
+
|
|
263
|
+
while (true) {
|
|
264
|
+
throwIfAborted(context.signal);
|
|
265
|
+
|
|
266
|
+
const now = performance.now();
|
|
267
|
+
|
|
268
|
+
this.removeExpired(state, now);
|
|
269
|
+
|
|
270
|
+
if (state.issuedAt.length < state.maxRequests) {
|
|
271
|
+
state.issuedAt.push(now);
|
|
272
|
+
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const oldestPermit = state.issuedAt[0];
|
|
277
|
+
|
|
278
|
+
if (oldestPermit === undefined) {
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
await wait(
|
|
283
|
+
Math.max(0, oldestPermit + state.windowMs - now),
|
|
284
|
+
context.signal
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private getBucket(quota: TInvestUnaryQuota): BucketState {
|
|
290
|
+
const current = this.buckets.get(quota.bucket);
|
|
291
|
+
|
|
292
|
+
if (current !== undefined) {
|
|
293
|
+
if (
|
|
294
|
+
current.maxRequests !== quota.maxRequests
|
|
295
|
+
|| current.windowMs !== quota.windowMs
|
|
296
|
+
) {
|
|
297
|
+
throw new Error(`Conflicting quota for bucket ${quota.bucket}`);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return current;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const created: BucketState = {
|
|
304
|
+
maxRequests: quota.maxRequests,
|
|
305
|
+
windowMs: quota.windowMs,
|
|
306
|
+
issuedAt: []
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
this.buckets.set(quota.bucket, created);
|
|
310
|
+
|
|
311
|
+
return created;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private removeExpired(state: BucketState, now: number): void {
|
|
315
|
+
const threshold = now - state.windowMs;
|
|
316
|
+
let expired = 0;
|
|
317
|
+
|
|
318
|
+
while (
|
|
319
|
+
expired < state.issuedAt.length
|
|
320
|
+
&& (state.issuedAt[expired] ?? Number.POSITIVE_INFINITY) <= threshold
|
|
321
|
+
) {
|
|
322
|
+
expired += 1;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (expired > 0) {
|
|
326
|
+
state.issuedAt.splice(0, expired);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async function wait(delayMs: number, signal: AbortSignal): Promise<void> {
|
|
332
|
+
let remainingMs = delayMs;
|
|
333
|
+
|
|
334
|
+
while (remainingMs > 0) {
|
|
335
|
+
throwIfAborted(signal);
|
|
336
|
+
|
|
337
|
+
const startedAt = performance.now();
|
|
338
|
+
|
|
339
|
+
await waitOnce(Math.min(remainingMs, maxTimerDelayMs), signal);
|
|
340
|
+
remainingMs -= performance.now() - startedAt;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function waitOnce(delayMs: number, signal: AbortSignal): Promise<void> {
|
|
345
|
+
return new Promise<void>((resolve, reject) => {
|
|
346
|
+
if (signal.aborted) {
|
|
347
|
+
reject(abortReason(signal));
|
|
348
|
+
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const onAbort = () => {
|
|
353
|
+
clearTimeout(timer);
|
|
354
|
+
signal.removeEventListener('abort', onAbort);
|
|
355
|
+
reject(abortReason(signal));
|
|
356
|
+
};
|
|
357
|
+
const timer = setTimeout(() => {
|
|
358
|
+
signal.removeEventListener('abort', onAbort);
|
|
359
|
+
resolve();
|
|
360
|
+
}, delayMs);
|
|
361
|
+
|
|
362
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function throwIfAborted(signal: AbortSignal): void {
|
|
367
|
+
if (signal.aborted) {
|
|
368
|
+
throw abortReason(signal);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function abortReason(signal: AbortSignal): unknown {
|
|
373
|
+
if (signal.reason !== undefined) {
|
|
374
|
+
return signal.reason;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const error = new Error('The operation was aborted');
|
|
378
|
+
|
|
379
|
+
error.name = 'AbortError';
|
|
380
|
+
|
|
381
|
+
return error;
|
|
382
|
+
}
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
При использовании этого примера один объект нужно создать на требуемый scope и
|
|
386
|
+
передать во все соответствующие SDK instances:
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
import { TInvestNodeSDK } from '@woodger/t-invest-node-sdk';
|
|
390
|
+
|
|
391
|
+
const unaryLimiter = new RollingWindowUnaryLimiter();
|
|
392
|
+
|
|
393
|
+
const sdk = new TInvestNodeSDK({
|
|
394
|
+
token,
|
|
395
|
+
endpoint,
|
|
396
|
+
unaryLimiter
|
|
397
|
+
});
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
Для production-реализации дополнительно определяются наблюдаемость, предел
|
|
401
|
+
очереди, fairness, поведение при перегрузке и очистка неиспользуемых buckets.
|
|
402
|
+
Они зависят от приложения и поэтому не входят в минимальный port SDK.
|
|
403
|
+
|
|
404
|
+
## Межпроцессная реализация
|
|
405
|
+
|
|
406
|
+
Передача одного JavaScript-объекта объединяет только SDK instances одного
|
|
407
|
+
процесса. Для нескольких процессов `acquire()` может быть тонким adapter-ом к
|
|
408
|
+
явно запущенному coordinator-у:
|
|
409
|
+
|
|
410
|
+
```ts
|
|
411
|
+
import type {
|
|
412
|
+
TInvestUnaryLimitContext,
|
|
413
|
+
TInvestUnaryLimiter
|
|
414
|
+
} from '@woodger/t-invest-node-sdk';
|
|
415
|
+
|
|
416
|
+
interface CoordinatorClient {
|
|
417
|
+
acquire(
|
|
418
|
+
request: {
|
|
419
|
+
readonly scope: string;
|
|
420
|
+
readonly bucket: string;
|
|
421
|
+
readonly maxRequests: number;
|
|
422
|
+
readonly windowMs: number;
|
|
423
|
+
},
|
|
424
|
+
signal: AbortSignal
|
|
425
|
+
): Promise<void>;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
class CoordinatorUnaryLimiter implements TInvestUnaryLimiter {
|
|
429
|
+
constructor(
|
|
430
|
+
private readonly client: CoordinatorClient,
|
|
431
|
+
private readonly scope: string
|
|
432
|
+
) {}
|
|
433
|
+
|
|
434
|
+
async acquire(context: TInvestUnaryLimitContext): Promise<void> {
|
|
435
|
+
await this.client.acquire({
|
|
436
|
+
scope: this.scope,
|
|
437
|
+
bucket: context.quota.bucket,
|
|
438
|
+
maxRequests: context.quota.maxRequests,
|
|
439
|
+
windowMs: context.quota.windowMs
|
|
440
|
+
}, context.signal);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
Для такого решения нужно отдельно зафиксировать:
|
|
446
|
+
|
|
447
|
+
- кто запускает и завершает coordinator;
|
|
448
|
+
- какие processes входят в один `scope`;
|
|
449
|
+
- как выполняются atomic permit reservations;
|
|
450
|
+
- удаляется ли ещё не выданный request при cancellation или disconnect;
|
|
451
|
+
- применяется ли fail-closed при недоступности coordinator-а;
|
|
452
|
+
- как обрабатывается cold start после потери неперсистентного состояния;
|
|
453
|
+
- что происходит при разных версиях SDK или несовместимых квотах одного
|
|
454
|
+
bucket;
|
|
455
|
+
- какие integration-тесты воспроизводят concurrency, crash и restart.
|
|
456
|
+
|
|
457
|
+
После выдачи permit его не следует возвращать из-за последующей ошибки или
|
|
458
|
+
отмены RPC: request уже мог достичь provider-а и быть учтён в квоте.
|
|
459
|
+
|
|
460
|
+
SDK не требует конкретного coordinator protocol, IPC transport или базы
|
|
461
|
+
данных. Это позволяет Consumer-у выбрать границу, соответствующую собственной
|
|
462
|
+
архитектуре, без runtime dependency внутри SDK.
|
|
463
|
+
|
|
464
|
+
## Per-instance overrides
|
|
465
|
+
|
|
466
|
+
`unaryLimits` позволяет заменить package rule для конкретного SDK instance.
|
|
467
|
+
Поля окна задаются явно:
|
|
468
|
+
|
|
469
|
+
```ts
|
|
470
|
+
import {
|
|
471
|
+
defineUnaryLimits,
|
|
472
|
+
TInvestNodeSDK,
|
|
473
|
+
type TInvestUnaryLimiter
|
|
474
|
+
} from '@woodger/t-invest-node-sdk';
|
|
475
|
+
|
|
476
|
+
declare const unaryLimiter: TInvestUnaryLimiter;
|
|
477
|
+
|
|
478
|
+
const sdk = new TInvestNodeSDK({
|
|
479
|
+
token,
|
|
480
|
+
endpoint,
|
|
481
|
+
unaryLimiter,
|
|
482
|
+
unaryLimits: defineUnaryLimits({
|
|
483
|
+
UsersService: {
|
|
484
|
+
default: {
|
|
485
|
+
maxRequests: 50,
|
|
486
|
+
windowMs: 60_000
|
|
487
|
+
}
|
|
488
|
+
},
|
|
489
|
+
OrdersService: {
|
|
490
|
+
methods: {
|
|
491
|
+
PostOrder: {
|
|
492
|
+
maxRequests: 10,
|
|
493
|
+
windowMs: 1_000
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
})
|
|
498
|
+
});
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
Остальные rules наследуются из `defaultConfig.unaryLimits`. Изменение одного
|
|
502
|
+
method rule отсоединяет его от package quota group, если иначе у общего bucket
|
|
503
|
+
получились бы разные параметры. Одинаковое изменение всех methods группы
|
|
504
|
+
сохраняет общий bucket.
|
|
505
|
+
|
|
506
|
+
Overrides проверяются при создании SDK независимо от наличия limiter-а. Без
|
|
507
|
+
`unaryLimiter` они не создают ожидание сами по себе.
|
|
508
|
+
|
|
509
|
+
## Необязательная реализация пакета
|
|
510
|
+
|
|
511
|
+
Пакет предоставляет `createInMemoryUnaryLimiter()` как небольшой готовый
|
|
512
|
+
вариант:
|
|
513
|
+
|
|
514
|
+
```ts
|
|
515
|
+
import {
|
|
516
|
+
createInMemoryUnaryLimiter,
|
|
517
|
+
TInvestNodeSDK
|
|
518
|
+
} from '@woodger/t-invest-node-sdk';
|
|
519
|
+
|
|
520
|
+
const sdk = new TInvestNodeSDK({
|
|
521
|
+
token,
|
|
522
|
+
endpoint,
|
|
523
|
+
unaryLimiter: createInMemoryUnaryLimiter()
|
|
524
|
+
});
|
|
525
|
+
```
|
|
526
|
+
|
|
527
|
+
Эта реализация равномерно разносит permits, использует монотонное время,
|
|
528
|
+
поддерживает cancellation и может делить состояние между SDK instances одного
|
|
529
|
+
процесса при передаче одного объекта. Несовпадающие параметры одного bucket
|
|
530
|
+
она отклоняет как конфликт конфигурации. Реализация не координирует разные
|
|
531
|
+
процессы или hosts, не обновляет квоты из тарифа и не моделирует stream limits.
|
|
532
|
+
Consumer может не использовать её вовсе.
|
|
533
|
+
|
|
534
|
+
## Проверочный список собственной реализации
|
|
535
|
+
|
|
536
|
+
- `acquire()` разрешается только после фактической выдачи permit.
|
|
537
|
+
- Все callers с одинаковыми `bucket` используют одно состояние в выбранном
|
|
538
|
+
scope.
|
|
539
|
+
- `maxRequests` и `windowMs` применяются как пара без смены единиц.
|
|
540
|
+
- Неиспользованные ожидания удаляются по `signal` без listener leaks.
|
|
541
|
+
- После выдачи permit нет автоматического refund.
|
|
542
|
+
- Конфликт квот одного bucket обрабатывается явно.
|
|
543
|
+
- Ошибка backend-а не включает незаметный локальный fallback.
|
|
544
|
+
- Streams не считаются unary-вызовами.
|
|
545
|
+
- Limiter не ожидает OAuth token или request payload от SDK.
|
|
546
|
+
- Lifecycle limiter-а остаётся у Consumer-а.
|
|
547
|
+
- Multi-process координация проверена отдельным integration-тестом, если она
|
|
548
|
+
заявлена реализацией.
|
|
549
|
+
|
|
550
|
+
Официальные значения и известные границы package policy описаны отдельно в
|
|
551
|
+
[лимитной политике](../limits-policy.md). Варианты межпроцессной архитектуры и
|
|
552
|
+
их trade-offs сохранены в [roadmap](../roadmap.md).
|