Commit Graph

273 Commits

Author SHA1 Message Date
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
Eugene Kabanov 9c93ab48de
Attempt to fix CI crash at Windows. (#465)
* Attempt to fix CI crash at Windows.
Remove all cast[string] and cast[seq[byte]] from the codebase.

* Address review comments.
2023-11-13 13:14:21 +02:00
Eugene Kabanov 8156e2997a
Fix not enough memory on i386. (#467)
* Fix waitFor() should not exit earlier last callback will be scheduled.

* Tune tests to use less memory.

* Fix `testutils`. There is no more last poll() needed.

* Update chronos/internal/asyncfutures.nim

---------

Co-authored-by: Jacek Sieka <jacek@status.im>
2023-11-10 07:42:36 +01:00
Jacek Sieka 5ebd771d35
per-function `Exception` handling (#457)
This PR replaces the global strict exception mode with an option to
handle `Exception` per function while at the same time enabling strict
exception checking globally by default as has been planned for v4.

`handleException` mode raises `AsyncExceptionError` to distinguish it
from `ValueError` which may originate from user code.

* remove obsolete 1.2 config options
2023-11-08 15:12:32 +01:00
Jacek Sieka cd6369c048
`asyncraises` -> `async: (raises: ..., raw: ...)` (#455)
Per discussion in
https://github.com/status-im/nim-chronos/pull/251#issuecomment-1559233139,
`async: (parameters..)` is introduced as a way to customize the async
transformation instead of relying on separate keywords (like
asyncraises).

Two parameters are available as of now:

`raises`: controls the exception effect tracking
`raw`: disables body transformation

Parameters are added to `async` as a tuple allowing more params to be
added easily in the future:
```nim:
proc f() {.async: (name: value, ...).}`
```
2023-11-07 12:12:59 +02:00
Eugene Kabanov a70b145964
IPv4/IPv6 dualstack (#456)
* Initial commit.

* Fix tests.

* Fix linux compilation issue.

* Add getDomain() implementation.
Add getDomain() tests.
Add datagram tests.

* Fix style errors.

* Deprecate NetFlag.
Deprecate new flags in ServerFlags.
Add isAvailable().
Fix setDualstack() to ignore errors on `Auto`.
Updatetests.

* Deprecate some old procedures.
Improve datagram transport a bit.

* Address review comments, and fix tests.

* Fix setDescriptorBlocking() issue.
Recover connect() dualstack behavior.
Add test for connect() IPv6-[IPv4 mapped] addresses.

* Fix alignment code issue.
Fix TcpNoDelay was not available on Windows.

* Add dualstack support to HTTP/HTTPS client/server.
2023-10-30 15:27:50 +02:00
Jacek Sieka f56d286687
introduce `asyncraises` to core future utilities (#454)
* introduce `asyncraises` to core future utilities

Similar to the introduction of `raises` into a codebase, `asyncraises`
needs to be introduced gradually across all functionality before
deriving benefit.

This is a first introduction along with utilities to manage raises lists
and transform them at compile time.

Several scenarios ensue:

* for trivial cases, adding `asyncraises` is enough and the framework
deduces the rest
* some functions "add" new asyncraises (similar to what `raise` does in
"normal" code) - for example `wait` may raise all exceptions of the
future passed to it and additionally a few of its own - this requires
extending the raises list
* som functions "remove" raises (similar to what `try/except` does) such
as `nocancel` with blocks cancellations and therefore reduce the raising
set

Both of the above cases are currently handled by a macro, but depending
on the situation lead to code organisation issues around return types
and pragma limitations - in particular, to keep `asyncraises`
backwards-compatibility, some code needs to exist in two versions which
somewhat complicates the implementation.

* add `asyncraises` versions for several `asyncfutures` utilities
* when assigning exceptions to a `Future` via `fail`, check at compile
time if possible and at runtime if not that the exception matches
constraints
* fix `waitFor` comments
* move async raises to separate module, implement `or`
2023-10-24 16:21:07 +02:00
Jacek Sieka be9eef7a09
move test data to c file (#448)
* move test data to c file

allows compiling with nlvm

* more nlvm compat
2023-10-17 14:19:20 +02:00
Tanguy a759c11ce4
Raise tracking (#251)
* Exception tracking v2

* some fixes

* Nim 1.2 compat

* simpler things

* Fixes for libp2p

* Fixes for strictException

* better await exception check

* Fix for template async proc

* make async work with procTy

* FuturEx is now a ref object type

* add tests

* update test

* update readme

* Switch to asyncraises pragma

* Address tests review comments

* Rename FuturEx to RaiseTrackingFuture

* Fix typo

* Split asyncraises into async, asyncraises

* Add -d:chronosWarnMissingRaises

* Add comment to RaiseTrackingFuture

* Allow standalone asyncraises

* CheckedFuture.fail type checking

* First cleanup

* Remove useless line

* Review comments

* nimble: Remove #head from unittest2

* Remove implict raises: CancelledError

* Move checkFutureExceptions to asyncfutures2

* Small refacto

* small cleanup

* Complete in closure finally

* cleanup tests, add comment

* bump

* chronos is not compatible with nim 1.2 anymore

* re-add readme modifications

* fix special exception handlers

* also propagate excetion type in `read`

* `RaiseTrackingFuture` -> `InternalRaisesFuture`

Use internal naming scheme for RTF (this type should only be accessed
via asyncraises)

* use `internalError` for error reading

* oops

* 2.0 workarounds

* again

* remove try/finally for non-raising functions

* Revert "remove try/finally for non-raising functions"

This reverts commit 86bfeb5c97.

`finally` is needed if code returns early :/

* fixes

* avoid exposing `newInternalRaisesFuture` in manual macro code
* avoid unnecessary codegen for `Future[void]`
* avoid reduntant block around async proc body
* simplify body generation for forward declarations with comment but no
body
* avoid duplicate `gcsafe` annotiations
* line info for return at end of async proc

* expand tests

* fix comments, add defer test

---------

Co-authored-by: Jacek Sieka <jacek@status.im>
2023-10-17 14:18:14 +02:00
Tanguy 253bc3cfc0
Complete futures in closure finally (fix #415) (#449)
* Complete in closure finally

* cleanup tests, add comment

* handle defects

* don't complete future on defect

* complete future in test to avoid failure

* fix with strict exceptions

* fix regressions

* fix nim 1.6
2023-10-16 10:38:11 +02:00
Eugene Kabanov 2e8551b0d9
Cancellation fixes and tests. (#445)
* Add callTick and stream cancellation tests.

* Fix stepsAsync() test.

* Cancellation changes.

* Update and add more cancellation tests.

* Fix Posix shutdown call to handle ENOTCONN error.

* With new changes to to cancellation its now possible.

* Refactor testsoon.nim to not produce artifacts after tests are finished.

* Debugging MacOS issue.

* Adjust flaky test times.

* Fix issue.

* Add test for issue #334 which was also addressed in this PR.
Avoid `break` in problematic test.

* Add noCancelWait() call which prohibits cancellation.
Fix closeWait() calls to use noCancelWait() predicate.
Adding sleep to flaky MacOS test.

* Remove all debugging echoes.

* Fix cancelAndWait() which now could perform multiple attempts to cancel target Future (mustCancel behavior).

* Fix issues revealed by switch to different cancelAndWait().

* Address review comments.

* Fix testutils compilation warning.

* Rename callTick() to internalCallTick().

* Add some documentation comments.

* Disable flaky ratelimit test.

* Rename noCancelWait() to noCancel().
Address review comments.
2023-09-15 19:38:39 +03:00
Jacek Sieka e706167a53
add connect cancellation test (#444) 2023-09-05 13:41:52 +03:00
Eugene Kabanov 300fbaaf09
HttpAddress errors should be not only critical. (#446)
* Distinguish between resolve errors and check errors.

* Fix issues and add test for getHttpAddress() procedure.

* Address review comments.
2023-09-04 21:49:45 +03:00
Jacek Sieka a7f708bea8
futures: lentify (#413)
sometimes avoid copies when reading from `Future`
2023-08-09 17:27:17 +03:00
Eugene Kabanov 6c2ea67512
Unroll `defer`s and remove `break`s. (#440)
* Unpack `finally/defer` blocks and introduce explicit cleaning of objects.
Add request query to debug information.

* Unroll one more loop to avoid `break`.
Add test for query debug string.

* Fix cancellation behavior.

* Address review comments.
2023-08-09 10:57:49 +03:00
diegomrsantos 466241aa95
Remove reuseaddr (#438)
* Remove hard-coded ports when non-windows

* Remove ReuseAddr from test
2023-08-08 03:11:35 +03:00
diegomrsantos 194226a0e0
Remove hard-coded ports when non-windows (#437) 2023-08-08 03:10:28 +03:00
diegomrsantos c546a4329c
Use random ports (#429) 2023-08-02 21:04:30 +02:00
Eugene Kabanov 6b4f5a1d23
Recover `poll` engine and add tests. (#421)
* Initial commit.

* Fix one more place with deprecated constant.

* Fix testall and nimble file.

* Fix poll issue.

* Workaround Nim's faulty declaration of `poll()` and types on MacOS.

* Fix syntax errors.

* Fix MacOS post-rebase issue.

* Add more conditionals.

* Address review comments.

* Fix Nim 1.2 configuration defaults.
2023-08-01 12:56:08 +03:00
Eugene Kabanov 53e9f75735
Add some helpers for asyncproc. (#424)
* Initial commit.

* Adjust posix tests.

* Fix compilation issue.

* Attempt to fix flaky addProcess() test.
2023-07-28 11:54:53 +03:00
Eugene Kabanov 0277b65be2
Asynchronous thread notification mechanism. (#406)
* Initial commit.

* Some fixes.

* More fixes.

* Add first test.

* Further fixes for MacOS/BSD.

* Fixes for Linux.

* Add proper tests.

* Lower number of tests.

* Add threadsync tests to test suite.

* There is no need to run tests when threads are off.

* Address review comments.
Fix the issue with multiple signals.
Add tests.

* Switch to use socketpair() instead of pipes.
Fix semaphoring issue on MacOS/BSD.
Add tests.

* Add single threaded fire/wait tests.
2023-07-21 15:51:36 +03:00
Eugene Kabanov 155d89450e
Trackers refactoring. (#416)
* Refactor chronos trackers to be more simple.

* Refactor trackers.
Add HTTP server trackers.
Refactor HTTP main processing loop.

* Compatibility fixes.
Add checkLeaks().

* Fix posix test issue.

* Add httpdebug module which introduces HTTP connection dumping helpers.
Add tests for it.

* Recover and deprecate old version of Trackers.

* Make public iterators to iterate over all tracker counters available.
Fix asynctests to use public iterators instead private one.
2023-07-14 13:35:08 +03:00
Jacek Sieka 0a6f5854a7
fix unused result warning on implict return (fixes #414) (#417)
* fix unused result warning on implict return

* describe `{.used.}` tradeoffs

* oops
2023-07-04 01:11:08 +03:00
Eugene Kabanov 73fd1206ab
Disable HTTP/1.1 pipeline support for HTTP/S server by default. (#410)
* Disable HTTP/1.1 pipeline support for HTTP/S server by default.
Add tests.

* Fix tests according to new behavior.
Fix tests to use random assigned OS ports instead of predefined.

* Fix flaky tests in testasyncstream.
2023-06-26 16:28:33 +03:00
Tanguy 47016961f5
Less flaky rate limit tests (#408) 2023-06-23 10:11:14 +02:00
Jacek Sieka 0035f4fa66
Introduce `chronos/futures` (#405)
* move `Future[T]` into its own module along with some basic accessors
* mark all fields internal, exposing only read-only versions under the
old names
* introduce `init`/`completed`/etc as a way of creating a future (vs
newFuture)
* introduce `LocationKind` for `SrcLoc` access
* don't expose `FutureList` unless future tracking is enabled
* introduce `chronosStrictFutureAccess` which controls a number of
additional `Defect` being raised when accessing Future fields in the
wrong state - this will become true in a future version

In this version, `Future[T]` backwards compatibility code remains in
`asyncfutures2` meaning that if only `chronos/futures` is imported, only
"new" API is available.

This branch is a refinement / less invasive / minimal version of
https://github.com/status-im/nim-chronos/pull/373.
2023-06-07 20:04:07 +02:00
Jacek Sieka 1d6c309d77
clean up `Defect` (#404) 2023-06-05 22:21:50 +02:00
Jacek Sieka a6ac5f2213
exception warning fixes (#403) 2023-06-05 13:03:38 +02:00
Jacek Sieka 157ca4fea5
Support implicit returns (#401)
* based on https://github.com/nim-lang/Nim/pull/21898
* also fixes generic Future[T] where T ends up being `void`
2023-06-05 13:02:13 +02:00