Commit Graph
301 Commits
Author SHA1 Message Date
Jacek Sieka 890687e7e0 Merge branch 'master' into asyncdispatch_stacktrace_port 2026-06-17 09:16:13 +02:00
Jacek Sieka 34d193061e httpclient: add CONNECT proxy / tunnel support (#656)
Using `tunnel`, a general TCP tunnel can be created for any protocol via
a HTTP proxy. This tunnel is typically used for establishing TLS
connections via a proxy but any protocol can be used.

When a tunnel is established, the connection is removed from the session
pool and given to the caller who is now responsible for closing it.

Because the tunnel connection itself can be encrypted, we return an
`AsyncStream` that the caller must close (rather than a
`StreamTransport`).

This PR also moves DNS name resolution to the connection provider - this
has the effect of delaying DNS lookup until the actual connect attempt
is made - earlier, DNS lookups would happen when creating the HTTP
address. The move allows the proxy to perform the name resolution when
relevant - the move also prepares the API for async name resolution.

Callers can still skip name resolution by providing an explicit list of
addresses to connect to.
2026-06-16 10:20:46 +00:00
Jacek Sieka 3c5654c990 http: align with RFC 9112, deprecate pipelining (#653)
The pipelining implementation was incomplete insofar as it only enabled
connection reuse without actually performing pipelining - keep the reuse
but deprecate pipelining.

With pipelining cleaned up, several other RFC 9112-related cleanups can
also be performed:

* clarify "perstistent connections" vs pipelining, where relevant
* in HTTP/1.1, don't send `Connection: keep-alive` (this is the default
in 1.1) - similarly, don't send `Connection: close` in other versions
* in older HTTP versions, disable persistent connections / keep-alive
entirely following RFC recommendations
* decode message body length according to RFC 9112
* prioritise `Transfer-Encoding` over `Content-Length`, per RFC 9112
* document lack of EOF monitoring when using persistent connections
* differentiate "no body" from "body length" tracking, ie a HEAD request
never has a body but might send a Content-Length for use as a length
discovery mechanism
* streamline request body sending code to reuse stream helpers
* fix sending and parsing of CONNECT authority form
* fix processing of `Connection` header - in particular, `Connection:
Keep-Alive` should not be used in HTTP/1.1 since persistent connections
are the default - instead, `Connection: close` should be used when the
connection is _not_ perisistent.
* exclude fragment from request-target
2026-06-16 11:12:14 +02:00
Jacek Sieka b76a78f1da http: add absolute request-target support (fixes #193) (#651)
Using an absolute request URI and a connection provider that connects to
a different server than the http address, generic proxies can be
implemented

* add detail to http connection error
* fix transport/stream leak when http client construction fails
2026-06-15 20:23:04 +02:00
Chrysostomos Nanakos 9620a4691a fix(asyncengine): drain idle callbacks based on event count, not buffer size (#655)
Signed-off-by: Chrysostomos Nanakos <chris@include.gr>
2026-06-11 07:56:46 +00:00
Jacek Sieka 7396b60662 tests: more tls tests (#643) 2026-05-05 14:59:05 +00:00
Shuu c7c1dca747 Add ALPN support to TLSStream (#640)
* Add ALPN support to TLSStream

* Replace {.emit.} workaround with sslEngineSetProtocolNames

* Bump bearssl to 0.2.8
2026-05-05 14:14:24 +02:00
markspanbroek 7cc1ad8079 fix(httpclient): pipelining session handles closed connections (#646)
Before this change, HttpSession tried to reuse connections that
were already closed by the server, leading to stream reading
failures.
2026-05-04 09:45:30 +02:00
Eugene Kabanov b411dd632b Fix TLSStream exception not generated after TLS errors. (#641)
* Fix TLSStream TLSStreamProtocolError exception not generated after TLS checks.
Add more tests.
Update RSA self-signed TLS certificate with CNAME = chronos-test-server.com

* Recover old RSA keys.

* Address review comments.
2026-04-08 14:17:57 +00:00
Jacek Sieka 6080fef1b2 Speed up http client (#633)
The http client currently uses an inefficient byte-by-byte copy in its
`BoundedStreamReader` - the real solution here is to get rid of the
copy completely but until then, we can use bulk-copy the data at least.

Ditto `read`, `readN` and similar helpers - this ~doubles throughput
for bulk reading.

Pre:
```
| Small/small    |    0.070s |   1000 | 14226.009 |    0.031 MB |    0.016 MB |    0.434 MB/s |    0.231 MB/s |
| Medium/small   |    1.834s |   1000 |  545.267 | 1000.000 MB |    0.021 MB |  545.267 MB/s |    0.011 MB/s |
| Small/Medium   |    2.238s |   1000 |  446.735 |    0.031 MB | 1000.000 MB |    0.014 MB/s |  446.735 MB/s |
| Medium/Medium  |    2.583s |   1000 |  387.196 | 1000.000 MB | 1000.000 MB |  387.196 MB/s |  387.196 MB/s |
```

Post:

```
| Small/small    |    0.066s |   1000 | 15038.890 |    0.031 MB |    0.016 MB |    0.459 MB/s |    0.244 MB/s |
| Medium/small   |    0.954s |   1000 | 1048.475 | 1000.000 MB |    0.021 MB | 1048.475 MB/s |    0.022 MB/s |
| Small/Medium   |    1.264s |   1000 |  791.318 |    0.031 MB | 1000.000 MB |    0.024 MB/s |  791.318 MB/s |
| Medium/Medium  |    1.615s |   1000 |  619.083 | 1000.000 MB | 1000.000 MB |  619.083 MB/s |  619.083 MB/s |
```
2026-04-07 19:37:35 +02:00
ShuuandJacek Sieka 3e7b228356 Add client certificate authentication support to TLSStream (#631)
Add support for mTLS client certificate authentication
in `newTLSClientAsyncStream`. Both RSA and EC key types are supported.

* Add EC test

---------

Co-authored-by: Jacek Sieka <jacek@status.im>
2026-04-07 13:42:58 +00:00
Jacek Sieka 495cf9b1ce tests: more asyncTest usage (#638) 2026-04-07 06:39:05 +00:00
Jacek Sieka ec3c85f132 stream test: refactor to use asyncTest (#634) 2026-03-31 21:18:20 +00:00
Jacek Sieka 712f9937e4 fix readLine for partial separator matches (fixes #573) (#605)
Also allows the separator to be empty, in which case characters are
returned one by one
2026-01-12 09:02:21 +01:00
Jacek Sieka 8ed098ef61 ratelimit: fix non-deterministic start time in test (#608) 2025-12-27 16:13:32 +01:00
NagyZoltanPeterandJacek Sieka 85af4db764 Token bucket unification (#582)
* Fix original TokenBucket, consolidate the behaviors of chronos/TokenBucket and waku/TokenBucket (compensating) with no interface change

* TokenBucket extended with waku's strict mode replenish, that does not allow refill just after period boundary elapsed.

* Adjust for new chat-sdk needs, added setState and getAvailableCapacity with small refactoring

* Better comments

* rename for better self explain code, added more explanatory comments upon code review finding

* Document TokenBucket with detailed samples of Balanced mode replenishment algorithm, extended TokenBucket unit test

* Address review comments, renaming the replenish modes, removed old/new algo comparison from documentation, fix Discrete mode update calculation to properly calculate correct last update time by period distance calculation.

* protect from devide by zero, code style fix

* Make (re)setState close pending request before reseting state

* Polishing interface, move discrete mode initial start time setup into ctor and remove resetState to have a cleaner and consistent interface for both usage mode

* Addressing review observation, keep only singel new ctor and leave defaults to match former use.

* Removing leftovers and confirm with coding guideline

* refactor rate limiter implementation

* make sure that `tryConsume` respects queued `consume` requests
* refill tokens the same way regardless of replenish mode and source of
tokens (manual/time-based/cancellation)
* whem manually replenishing, compute budget cap after satisfying queued
requests
* don't run worker if fill duration is 0
* add some docs

* int vs int64

* Fix Discrete mode time window drift, added tests

* wait for sleeper/waiter

---------

Co-authored-by: Jacek Sieka <jacek@status.im>
2025-12-12 15:25:45 +01:00
nitely 994840503f wip 2025-11-29 22:19:19 -03:00
nitely 543e731859 Port asyncdispatch stacktraces improvement 2025-11-29 21:56:55 -03:00
vladopajic dd21dd4a19 feat: add AsyncSemaphore (#586) 2025-11-19 12:03:20 +00:00
Eugene Kabanov a737147849 Fix Windows does not properly handle 0-size UDP datagrams. (#598)
Add test.
2025-11-17 12:57:18 +02:00
Eugene Kabanov 3639e3cc9b Disable flaky test. (#593) 2025-10-28 00:25:20 +02:00
Miran fff013c810 disable leaking broadcast test on macos (#585) 2025-09-16 16:53:41 +02:00
Eugene Kabanov b55e2816eb Allow cancelAndWait() accept multiple Futures for cancellation. (#572)
* Allow cancelAndWait accept multiple Futures for cancellation.
Add tests.

* Add 2 more tests.

* Update test name.

* Fix sporadic test.
2025-03-21 14:46:18 +02:00
Eugene Kabanov 7c5cbf04a6 Fix baseUri should provide correct value for ANY_ADDRESS. (#563) 2025-01-13 18:31:36 +02:00
c-blake 8f609b6c17 Fix tests to be string hash order independent (#551) 2024-07-09 11:42:20 +02:00
Jacek Sieka 4ad38079de pretty-printer for Duration (#547) 2024-06-20 09:52:23 +02:00
Giuliano Mega 7630f39471 Fixes compilation issues in v3 compatibility mode (-d:chronosHandleException) (#545)
* add missing calls to await

* add test run in v3 compatibility

* fix semantics for chronosHandleException so it does not override local raises/handleException annotations

* distinguish between explicit override and default setting; fix test

* re-enable wrongly disabled check

* make implementation simpler/clearer

* update docs

* reflow long line

* word swap
2024-06-10 10:18:42 +02:00
Jacek Sieka c44406594f fix results import 2024-06-07 12:05:15 +02:00
Jacek Sieka 1ff81c60ea avoid warning in noCancel with non-raising future (#540) 2024-05-06 08:56:48 +00:00
Eugene Kabanov 0f0ed1d654 Add wait(deadline future) implementation. (#535)
* Add waitUntil(deadline) implementation.

* Add one more test.

* Fix rare race condition and tests for it.

* Rename waitUntil() to wait().
2024-04-20 03:49:07 +03:00
Eugene Kabanov d184a92227 Fix rare cancellation race issue on timeout for wait/withTimeout. (#536)
Add tests.
2024-04-19 16:43:34 +03:00
Eugene Kabanov e4cb48088c Fix inability to change httpclient's internal buffer size. (#531)
Add test.
Address #529.
2024-04-17 17:27:14 +03:00
Eugene Kabanov 0d050d5823 Add automatic constructors for TCP and UDP transports. (#512)
* Add automatic constructors for TCP and UDP transports.

* Add port number argument.
Add some documentation comments.
Fix tests.

* Make datagram test use request/response scheme.

* Add helper.

* Fix issue with non-zero port setups.
Add test.

* Fix tests to probe ports.

* Attempt to fix MacOS issue.

* Add Opt[IpAddress].
Make IPv4 mapping to IPv6 space automatic.

* Add tests.

* Add stream capabilities.

* Fix Linux issues.

* Make getTransportFlags() available for all OSes.

* Fix one more compilation issue.

* Workaround weird compiler bug.

* Fix forgotten typed version of constructor.

* Make single source for addresses calculation.

* Add one more check into tests.

* Fix flags not being set in transport constructor.

* Fix post-rebase issues with flags not being set.

* Address review comments.
2024-04-13 03:04:42 +03:00
Eugene Kabanov 2d85229dce Add join() operation to wait for future completion. (#525)
* Add `join()` operation to wait for future completion without cancelling it when `join()` got cancelled.

* Start using join() operation.
2024-04-04 00:30:01 +03:00
Jacek Sieka b8b4e1fc47 make Raising compatible with 2.0 (#526)
* make `Raising` compatible with 2.0

See https://github.com/nim-lang/Nim/issues/23432

* Update tests/testfut.nim

* Update tests/testfut.nim
2024-03-25 10:37:42 +01:00
Jacek Sieka 03d82475d9 Avoid ValueError effect in varargs race/one (#520)
We can check at compile-time that at least one parameter is passed

* clean up closure environment explicitly in some callbacks to release
memory earlier
2024-03-06 06:42:22 +01:00
Eugene Kabanov 4ed0cd6be7 Ensure that OwnCancelSchedule flag will not be removed from wait() and withTimeout(). (#519) 2024-03-05 17:34:53 +01:00
Eugene Kabanov 1eb834a2f9 Fix or deadlock issue. (#517)
* Fix `or` should not create future with OwnCancelSchedule flag set.

* Fix `CancelledError` missing from raises list when both futures has empty raises list.

* Fix macros tests.
2024-03-05 17:33:46 +01:00
cheatfate be4923be19 Strip debugging echo in threadsync tests. 2024-02-14 14:09:01 +02:00
Eugene Kabanov a81961a3c6 Fix HTTP server accept() loop exiting under heavy load. (#502)
* Add more specific accept() exceptions raised.
Add some refactoring to HTTP server code.

* Refactor acceptLoop.

* Print GC statistics in every failing test.

* Try to disable failing tests.
2024-02-14 14:05:19 +02:00
Eugene Kabanov 08db79fe63 Disable memory hungry tests in 32bit tests. (#503)
* Disable memory hungry tests in 32bit tests.

* Limit threadsync tests for 32bit.
2024-02-14 00:03:12 +02:00
Jacek Sieka 1021a7d294 check leaks after every test (#487) 2024-01-18 14:34:16 +02:00
Eugene Kabanov b02b9608c3 HTTP server middleware implementation. (#483)
* HTTP server middleware implementation and test.

* Address review comments.

* Address review comments.
2024-01-12 15:27:36 +02:00
Jacek Sieka 1598471ed2 add a test for results.? compatibility (#484)
Finally! (haha)
2023-12-21 15:52:16 +01:00
Eugene Kabanov c41599a6d6 Asyncraises HTTP layer V3 (#482)
* No Critical and Recoverable errors anymore.

* Recover raiseHttpCriticalError()

* Post-rebase fixes.

* Remove deprecated ResponseFence and getResponseFence().

* HttpProcessCallback and 2.

* Fix callback holder.

* Fix test issue.

* Fix backwards compatibility of `HttpResponse.state` field.
2023-12-09 06:50:35 +02:00
Jacek Sieka e38ceb5378 fix v3 backwards compatibility for callbacks (#481)
Because the callback types were used explicitly in some consumers of
chronos, the change of type introduces a backwards incompatibility
preventing a smooth transition to v4 for code that doesn't uses
`raises`.

This PR restores backwards compatibility at the expense of introducing a
new type with a potentially ugly name - that said, there is already
precedence for using numbered names to provide new error handling
strategy in chronos.
2023-12-04 14:19:29 +01:00
Eugene Kabanov 28a100b135 Fix processing callback missing asyncraises. (#479) 2023-11-28 18:57:13 +02:00
Jacek Sieka fa0bf405e6 varargs overloads (#477)
* varargs overloads

for convenience and compatibility

* no parameterless varargs calls with generic overloads
2023-11-20 12:04:28 +02:00
Jacek Sieka f03cdfcc40 futures: sinkify (#475)
This avoids copies here and there throughout the pipeline - ie
`copyString` and friends can often be avoided when moving things into
and out of futures

Annoyingly, one has to sprinkle the codebase liberally with `sink` and
`move` for the pipeline to work well - sink stuff _generally_ works
better in orc/arc

Looking at nim 1.6/refc, sink + local variable + move generates the best
code:

msg directly:
```nim
	T1_ = (*colonenv_).msg1; (*colonenv_).msg1 = copyStringRC1(msg);
```

local copy without move:
```nim
	T60_ = (*colonenv_).localCopy1; (*colonenv_).localCopy1 =
copyStringRC1(msg);
```

local copy with move:
```nim
	asgnRef((void**) (&(*colonenv_).localCopy1), msg);
```

Annoyingly, sink is also broken for refc+literals as it tries to
changes the refcount of the literal as part of the move (which shouldn't
be happening, but here we are), so we have to use a hack to find
literals and avoid moving them.
2023-11-19 18:29:09 +01:00
Jacek Sieka f5ff9e32ca introduce asyncraises in transports/asyncsync (#470)
With these fixes, `transports`/`asyncsync` correctly propagate and document their raises information - generally, most transport functions (send etc) raise `TransportError` and `CancelledError` - `closeWait` is special in that it generally doesn't fail.

This PR introduces the syntax `Future[void].Raises([types])` to create the `InternalRaisesFuture` type with the correct encoding for the types - this allows it to be used in user code while retaining the possibility to change the internal representation down the line.

* introduce raising constraints on stream callbacks - these constraints now give a warning when called with a callback that can raise exceptions (raising callbacks would crash 
* fix fail and its tests, which wasn't always given a good generic match
* work around nim bugs related to macro expansion of generic types
* make sure transports raise only `TransportError`-derived exceptions (and `CancelledError`)
2023-11-15 09:38:48 +01:00