Commit Graph

81 Commits

Author SHA1 Message Date
Jacek Sieka 24be151cf3
move docs to docs (#466)
* introduce user guide based on `mdbook`
* set up structure for adding simple `chronos` usage examples
* move most readme content to book
* ci deploys book and api guide automatically
* remove most of existing engine docs (obsolete)
2023-11-15 09:06:37 +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
Jacek Sieka e3c5a86a14
Introduce chronos/internals, move some code (#453)
* Introduce chronos/internals, move some code

This PR breaks the include dependencies between `asyncfutures2` and
`asyncmacros2` by moving the dispatcher and some other code to a new
module.

This step makes it easier to implement `asyncraises` support for future
utilities like `allFutures` etc avoiding the need to play tricks with
include order etc.

Future PR:s may further articulate the difference between "internal"
stuff subject to API breakage and regular public API intended for end
users (rather than advanced integrators).

* names

* windows fix
2023-10-17 20:25:25 +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
Eugene Kabanov 60e6fc55bf
Fix #431. (#441) 2023-08-11 00:31:47 +03: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 e04c042e8a
Add cross-platform shutdown() call and use it for HTTP server. (#420)
* Add cross-platform shutdown() call and use it for httpserver connection processing.

* Fix Posix compilation issues and warnings.
2023-07-19 20:33:28 +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 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
Eugene Kabanov 02fda01bf2
Add facility to emulate signals on Windows. (#357)
* Initial Windows asyncproc part.
Deprecate usage of net/nativesockets in handles, asyncloop.
Introduce primitives with inheritable flag.

* Some posix fixes.

* More duplicate fixes.

* Fix AsyncProcessOption.EchoCommand option.
Remove isMainModule code.
Fix execCommand to use AsyncProcessOption.EvalCommand.

* Initial asyncproc tests commit.

* Some Posix fixes.

* Fix Posix crash.

* Add testsuite.
Fix osnet.nim to use proper declarations.
Fix timer.nim to use proper declarations.
Add Windows environment handling procedures.
Fix createAsyncPipe.
Add leaks tracking for AsyncProcessRef.

* Fix O_CLOEXEC constant value.

* Add file descriptors leak test.

* Remove commented code.
Refactor exceptions.
Fix compilation warnings.

* No exception ioselectors_kqueue initial commit.

* Some BSD fixes.
Linux refactoring of selectors.nim.

* Some fixes to move further.

* Last Linux fixes.

* Fixes for asyncloop to use 2nd version of selectors api.

* Add osutils.nim.

* Some fixes.

* Hardening resumeRead(), resumeWrite() and consumers.
Add ESRCH handling.
Introduce no-exception fromPipe2.

* Make Windows part exception-free and fix zombie race issue.

* createStreamServer() fixes.

* Upgrade asyncproc to use non-exception primitives.
Fix ioselectors_kqueue to use closeFd().

* Refactor accept() and acceptLoop() to be exception free.

* Deprecated some `result` usage.
Last fixes to make stream.nim exception free.
Use closeFd().
Refactor some loops to use handleEintr().

* Fix connect() forgot to unregister socket on error.

* All createAsyncSocket() sockets should be closed with unregisterAndCloseFd().

* Attempt to fix posix bug with incomplete output.

* Change number of runs in big test.

* Refactoring pipes creation. Attempt to fix "write error: Resource temporarily unavailable".

* Fix waitForExit(duration) code.
Fix test exit code.

* Fix Windows missing SIGTERM.

* Fix mistype.

* Fix compilation error.

* Attempt to fix Nim 1.6 issue.

* Eliminate Nim's WideCString usage to avoid any problems in future.

* Deprecate posix usage in osnet.

* Eliminate unused imports.

* Some debugging statements for investigation.

* Remove all the debugging statements.

* Remove testhelpers in favor of unittest2/asynctests.

* Fix flaky test.

* Make test more resilient to timings.

* Add memory size dump to CI.

* Refactor some blocks to use valueOr.
Make waitForExit to use kill() instead of terminate().

* Remove memory dumps.

* Fix peekProcessExitCode() blocks issue.

* Fix Windows issue.

* Add some debugging echoes.

* Fix compilation error.

* Add some debugging echoes.

* Add more helpers.

* Fix compilation error.

* waitForExit() is primary suspect.

* Remove fast-path for waitForExit.
Remove loop for reading signal events.

* Remove all debugging echoes.

* Return one debugging echo.

* Fix futures tests.

* Add test for multiple processes waiting to attempt stress test.

* Refactor ioselectors_epoll for better signalfd and process monitoring.
Add more race condition fixes to waitForExit.
Fix some Nim 1.6 warnings.

* Fix after rebase issues and warnings.

* Fix style issues.
Fix different Nim versions issues.
Workaround `signalfd` style issues.

* Add one more Linux signals workaround.
Add one more multiple processes test.

* Windows fixes.

* Remove unixPlatform define.
Fix WSAECONNABORTED for devel.

* Temporarily disable rate limit tests.
Fix more devel issues.

* Deprecate `hasThreadSupport` for ioselectors_kqueue.
Fix verifySelectParams issue.
Add exit codes test for multiple processes.
Fix osnet PtrToCstringConv warning.

* ioselectors_kqueue refactoring.

* Initial commit.

* Fix 1.2-1.4 compilation issue.

* Fix unused warning for testCtrlC() test.

* Post-rebase fixes.

* Restore master files.

* More fixes.

* Remove duplicates.

* Fix style mistake.

* Add more flexible pragmas.
2023-06-02 01:53:20 +03:00
Eugene Kabanov 148ddf49c2
Asyncproc (Part 3/3) (#374)
* Initial commit.

* Some Linux fixes.

* Address review comments on Windows.

* Fix issues on Linux.

* Fix 1.2 issue and Windows warnings.

* Fix posix compilation issues.
2023-05-23 12:39:35 +02:00
Eugene Kabanov 956ae5af55
Fix import poison regression. (#388)
* Initial commit.

* One more linux fix.

* Eliminate posix from asyncloop.

* Fix Linux warnings.

* Fix MacOS issues.

* Fix BSD issues.

* Fix comma.

* Fix Windows issues.
2023-05-15 19:45:26 +03:00
Eugene Kabanov 3118f8c1b2
Fix cast[pointer] issues on nim-devel. (#381)
* Fix cast[pointer] issues on nim-devel.

* More cast[T] fixes.

* Fix compilation error.

* Add oserrno.nim
Further fixes for Windows and Linux.

* MacOS fixes.

* More Windows fixes and attempt to fix 1.2, 1.4 branches.

* Implicitly import/export oserrno.

* Replace oserrno with osdefs.

* Return back oserrno.

* epoll to oserrno.

* datagram/stream to oserrno.

* common to oserrno.

* test to oserrno.
2023-04-30 08:20:08 +02:00
Jacek Sieka 229de5f842
Compile-time configuration (#371)
This PR moves all compile-time configuration to a single module,
simplifying documentation and access to these features.

Upcomfing features may be enabled either individually, or through a new
`chronosPreviewV4` catch-all designed to allow code to be prepared for
increased strictness in future chronos releases.

`-d:chronosDebug` may be used to enable the existing debugging helpers
together.
2023-03-31 07:35:04 +02:00
Eugene Kabanov 1394c9e049
IOSelectors refactoring to properly support signals and processes. (AsyncProc 2) (#366)
* ioselectors_epoll() refactoring.

* ioselectors_kqueue() refactoring.

* ioselectors_poll() initial refactor.

* Remove `s.count` because it inconsistent and not used in `chronos`.

* Remove Windows version of select() engine.

* Add ability to switch event queue engine via `asyncEventEngine` command line option.

* Make it possible to switch between engines.

* Fix epoll regression.

* Fix poll() engine issues.

* Address review comments.

* Add proper trick.

* Address review comments.

* Bump version to 3.1.0.
2023-03-24 17:52:55 +02:00
Eugene Kabanov 0f70a6b8ee
OS definitions and exceptions changes. (AsyncProc part 1). (#361)
* Initial commit.

* Finalize Windows part.

* Finalize Posix part.

* Fix style issues.

* Move osnet declarations to osdefs.

* Move osnet declarations to osdefs 2.

* Fix Nim 1.2 issues.

* Fix 1.2 compilation issues 2.

* Address review comments.
Fix SignalFdInfo issue.
2023-02-21 11:48:36 +01:00
Tanguy a50ac4f642
Documentation (#311)
* Fix & update asyncloop documentation

* Add cancellation documentation

* Add documentation generation workflow

* pin nim version for doc gen

* update readme

* fix example

* Simplify examples
2023-02-16 21:27:31 +01:00
Jacek Sieka c65cc4c136
`async` `proc` types (#346)
Allow `type = proc(...) {.async.}` for pre-declaring async callback
types - in this case, the macro applies the correct transformation to
the return type and adds the appropriate exception / gcsafe annotations
2023-01-18 15:54:39 +01:00
Eugene Kabanov 6525f4ce1d
Fix some warnings. (#310)
* Fix some warnings messages.

* More warning fixes.

* Address review comments.
Fix MacOS issues.

* More warning fixes.

* More Windows specific fixes.

* Fix macos and windows warnings.

* Fix warnings in timer.nim
Refactor to remove `result`.
Improve performance and behavior of timer to string procedure.
Add tests.
2022-11-02 08:09:15 +01:00
Eugene Kabanov be2352027e
Fix nested waitFor (IndexError defect crash) bug. (#309)
Add IndexError crash test for Linux/MacOS.
Add Sentinel version of fix.
Add GetQueuedCompletionStatusEx() support for Windows, which allows to capture more then one event in single `poll()` call.
2022-09-16 22:34:18 +02:00
Jacek Sieka 746832384a
`Option` -> `Opt` (#307) 2022-09-05 11:08:52 +00:00
Miran 93800879fd
make it more Nim 1.4+ compatible (#296) 2022-08-06 13:56:06 +03:00
Eugene Kabanov 377e197417
waitSignal() helper and tests for it. (#289)
* Add waitForSignal() implementation and tests.

* Fix compilation issues.

* Fix mistype.

* Rename to waitSignal().

* Fix Windows compilation issue.

* Re-export posix signals.

* Remove signal handler on continuation too.
2022-06-29 00:53:09 +03:00
Jacek Sieka bb4c3298f5
fix crash after reading from fd > 1024 (#267)
The socket selector holds a `seq` of per-descriptor data. When a reader
is registered, a pointer to a seq item is stored - when the `seq` grows,
this pointer becomes dangling and causes crashes like
https://github.com/status-im/nimbus-eth2/issues/3521.

It turns out that there already exist two mechanisms for passing user
data around - this PR simply removes one of them, saving on memory usage
and removing the need to store pointers to the `seq` data that become
dangling on resize.
2022-04-11 11:56:30 +02:00
Ștefan Talpalaru 17fed89c99
style fixes (#253)
* style fixes

and disable the cron CI job
2022-01-04 23:14:30 +01:00
Tanguy d926415f42
Fixes for nimdoc (#252) 2022-01-04 18:00:17 +01:00
Zahary Karadjov 7ca85ddadc
Fix compilation errors with --styleCheck:usages --styleCheck:error 2021-12-08 16:58:24 +02:00
Ștefan Talpalaru 4aaaa3379a
Nim-1.6 fixes (#239) 2021-11-20 01:30:23 +01:00
Eugene Kabanov 3bc0bc36f7
Change Future identifier type from `int` to `uint`. (#228)
* Change Future identifier type from `int` to `uint64`.

* Fix compilation error and tests.

* Add integer overflow test, to avoid confusion with next Nim versions, we expect that unsigned integers do not raise any exceptions if overflow happens.

* Switch from `uint64` to `uint` type.

* Add `uint` overflow tests.
2021-10-21 17:22:11 +03:00
Eugene Kabanov d270dba8a3
Fix unused warnings, result, asyncCheck and 80 cpl (#185)
* Fix sources to follow 80 characters per line.
Fix unused compilation warnings.
Refactor (remove result) handles.nim.
Fix tests to use asyncSpawn instead of asyncCheck.

* Fix handles for Unix platforms.
2021-05-07 23:52:24 +03:00
Jacek Sieka 895fc53193
add explicit gcsafe annotations (fixes #174) (#175)
Seems like a variation of https://github.com/nim-lang/Nim/issues/17369
2021-04-03 10:05:08 +02:00
markspanbroek e5d3ecdd01
Ensures that asyncmacro2 does not raise exceptions (#172)
* Ensures that asyncmacro2 does not raise exceptions

* Remove unnecessary include
2021-03-30 16:48:20 +02:00
Kim De Mey c206d2bc19
Add raises annotation to withTimeout callbacks (#168) 2021-03-25 14:20:26 +01:00
Jacek Sieka 4abd7a5645
exception tracking (#166)
* exception tracking

This PR adds minimal exception tracking to chronos, moving the goalpost
one step further.

In particular, it becomes invalid to raise exceptions from `callSoon`
callbacks: this is critical for writing correct error handling because
there's no reasonable way that a user of chronos can possibly _reason_
about exceptions coming out of there: the event loop will be in an
indeterminite state when the loop is executing an _random_ callback.

As expected, there are several issues in the error handling of chronos:
in particular, it will end up in an inconsistent internal state whenever
the selector loop operations fail, because the internal state update
functions are not written in an exception-safe way. This PR turns this
into a Defect, which probably is not the optimal way of handling things
- expect more work to be done here.

Some API have no way of reporting back errors to callers - for example,
when something fails in the accept loop, there's not much it can do, and
no way to report it back to the user of the API - this has been fixed
with the new accept flow - the old one should be deprecated.

Finally, there is information loss in the API: in composite operations
like `poll` and `waitFor` there's no way to differentiate internal
errors from user-level errors originating from callbacks.

* store `CatchableError` in future
* annotate proc's with correct raises information
* `selectors2` to avoid non-CatchableError IOSelectorsException
* `$` should never raise
* remove unnecessary gcsafe annotations
* fix exceptions leaking out of timer waits
* fix some imports
* functions must signal raising the union of all exceptions across all
platforms to enable cross-platform code
* switch to unittest2
* add `selectors2` which supercedes the std library version and fixes
several exception handling issues in there

* fixes

* docs, platform-independent eh specifiers for some functions

* add feature flag for strict exception mode

also bump version to 3.0.0 - _most_ existing code should be compatible
with this version of exception handling but some things might need
fixing - callbacks, existing raises specifications etc.

* fix AsyncCheck for non-void T
2021-03-24 10:08:33 +01:00
cheatfate 13eddf382d Simplification and fixes for TLSStream state machine. 2021-02-18 22:16:04 +02:00
cheatfate e8d2a3ca0a Attempt #5. 2021-02-18 22:16:04 +02:00
cheatfate 49fd70f504 Attempt #4. 2021-02-18 22:16:04 +02:00
cheatfate cf42a5455e Investigation of Linux freezes #2. 2021-02-18 22:16:04 +02:00
Eugene Kabanov 491213dfa0
Add callIdle() primitive. (#148)
* Add callIdle primitive.

* Make single idle callback to be processed by single poll() step.
Add idleAsync() primitive to allow wait for "idle" time.
Refactor some `result` usage.
2021-01-19 13:48:39 +01:00
Jacek Sieka 9a420c6b05
work around overload resolution issues (#146)
it seems that due to a naming conflict from asyncdispatch, callSoon is
deduced to raise exceptions even if it doesn't in modules that import
both, even indirectly - this patch randomly works around the issue with
some more overloads
2021-01-11 22:15:21 +01:00
Eugene Kabanov 0933feaa35
Fix callSoon to raise Defect only. (#145)
* Initial commit.

* Move pragmas to forward declaration.
Add raises to callSoon declaration.

* Fix for IOSelectorsException.
2021-01-11 18:15:23 +01:00
cheatfate 493cb1dbfd Fix behavior of wait() and withTimeout() calls to cancel and wait for result of cancelled Future[T].
Add tests.
2020-11-17 19:28:52 +02:00
Eugene Kabanov b5915ecd29
Small fixes (#134)
* Fix cancellation behavior.
Fix some compilation warnings.

* Fix cancelAndWait() and add proper documentation.

* Add completed(Future) and done(Future) calls to check if Future[T] completed without an error.

* Add stepsAsync() and tests.

* Fix comments.

* Fix new primitive comment, to avoid usage for task switches.
2020-11-13 14:22:58 +02:00
Jacek Sieka 1ffd1cd3dc
release callback memory early (#130)
* release callback memory early

this fixes a memory leak where a deleted callback may keep references
alive until the future is finished.

In particular, when using helpers like `or` which try to remove
themselves from the callback list when a dependent future is completed,
create a reference chain between all futures in the expression - in the
pathological case where one of the futures is completes only rarely (for
example a timeout or a cancellation task), the buildup will be
significant.

* Removing unnecessary asserts, and place comments instead.
2020-09-15 10:55:43 +03:00
Zahary Karadjov e6d50b7736 Revert "some metrics for monitoring futures (#85)"
This reverts commit e45ef32b5b.

Metrics implemented this way, with a lock inside the otherwise tight
event loop are not consistent with the chronos architecture that for
good or bad uses thread local variables to avoid them - the solution
does not have rough consensus behind it, and other avenues should be
explored for this generally useful functionality.
2020-08-16 01:48:25 +03:00
Zahary Karadjov 03f4a26829 Revert "yieldAsync() (#120)"
This reverts commit 284d677815.

There is no rough consensus for how this should be implemented and
whether it's needed indeed - a use case that cannot be solved with
a queue or a lock/event should be identified before pursuing this
functionality.
2020-08-16 01:48:25 +03:00
Ștefan Talpalaru 284d677815
yieldAsync() (#120) 2020-08-10 15:31:21 +02:00
Ștefan Talpalaru e45ef32b5b
some metrics for monitoring futures (#85) 2020-08-06 19:30:53 +02:00