From b9a4494de74b825901062bc2b546f04bae918373 Mon Sep 17 00:00:00 2001 From: "Sean T. Allen" Date: Fri, 4 Dec 2026 03:31:03 -0500 Subject: [PATCH] Add a typed failure reason to RequestError A caller that wanted to retry connection timeouts had to compare RequestError.message with "Connection timed out", because a timeout and a TLS handshake failure both gave status 0 and an empty body. Any change to the wording silently changed what the caller did. RequestError now has a reason: one of net's ConnectionFailureReason values when the connection could not be opened, or a primitive for each other kind of failure. The documentation says for each reason whether a retry is safe. A connection that closes before any of the request is written is now reported as RequestNotSent, separate from one that closes after the request went out. Per-reason constructors replace RequestError.create, and the receiver interfaces get the RequestError instead of its fields. Closes #225 --- .release-notes/next-release.md | 2 +- .release-notes/request-failure-reason.md | 55 +++++ .../settle-promises-on-premature-close.md | 2 +- README.md | 8 +- examples/README.md | 2 +- examples/get-repository-oo/main.pony | 14 +- examples/get-repository/get_repository.pony | 3 +- examples/get-repository/main.pony | 14 +- github_rest_api/_test.pony | 2 + .../_test_model_template_invalid_url.pony | 30 +++ .../_test_operation_request_lines.pony | 4 +- github_rest_api/_test_premature_close.pony | 109 +++++++--- github_rest_api/_test_redirect_origin.pony | 158 +++++++++----- github_rest_api/_test_request_actors.pony | 176 ++++++++------- github_rest_api/_test_result_receivers.pony | 33 +-- github_rest_api/_test_tls_verification.pony | 46 ++-- github_rest_api/commit.pony | 2 +- github_rest_api/gist.pony | 22 +- github_rest_api/gist_comment.pony | 10 +- github_rest_api/issue.pony | 6 +- github_rest_api/issue_comment.pony | 6 +- github_rest_api/label.pony | 6 +- github_rest_api/paginated_list.pony | 14 +- github_rest_api/pull_request.pony | 3 +- github_rest_api/pull_request_file.pony | 3 +- github_rest_api/release.pony | 3 +- github_rest_api/repository.pony | 30 +-- github_rest_api/request/_redirect_origin.pony | 28 +-- github_rest_api/request/_test.pony | 1 + .../request/_test_redirect_origin.pony | 16 +- .../request/_test_request_error.pony | 47 ++++ github_rest_api/request/check_requester.pony | 34 +-- github_rest_api/request/credentials.pony | 6 +- github_rest_api/request/json.pony | 2 +- github_rest_api/request/json_requester.pony | 46 ++-- .../request/linked_json_requester.pony | 44 ++-- .../request/linked_result_receiver.pony | 2 +- .../request/no_content_requester.pony | 47 ++-- github_rest_api/request/request.pony | 19 +- github_rest_api/request/request_error.pony | 202 ++++++++++++++++-- github_rest_api/search.pony | 14 +- 41 files changed, 882 insertions(+), 389 deletions(-) create mode 100644 .release-notes/request-failure-reason.md create mode 100644 github_rest_api/_test_model_template_invalid_url.pony create mode 100644 github_rest_api/request/_test_request_error.pony diff --git a/.release-notes/next-release.md b/.release-notes/next-release.md index a369628..cffdadb 100644 --- a/.release-notes/next-release.md +++ b/.release-notes/next-release.md @@ -25,7 +25,7 @@ use "json" actor MyReceiver is req.LinkedResultReceiver be success(json: JSONNav, link_header: String) => None - be failure(status: U16, response_body: String, message: String) => None + be failure(err: req.RequestError) => None ``` The same change applies to calls: `gh.LinkedJSONRequester(creds, url, receiver)` becomes `req.LinkedJSONRequester(creds, url, receiver)`. diff --git a/.release-notes/request-failure-reason.md b/.release-notes/request-failure-reason.md new file mode 100644 index 0000000..d05c2c9 --- /dev/null +++ b/.release-notes/request-failure-reason.md @@ -0,0 +1,55 @@ +## Add a typed failure reason to RequestError + +`RequestError` has a new `reason` field that says what failed, so code can decide what to do without comparing `message` strings. Before, telling a connection timeout from a TLS handshake failure meant matching `message` against `"Connection timed out"`, and a change to that wording silently changed the result. + +`reason` is a `RequestFailureReason`: one of the `net` package's `ConnectionFailureReason` values (`ConnectionFailedDNS`, `ConnectionFailedTCP`, `ConnectionFailedSSL`, `ConnectionFailedTimeout`, `ConnectionFailedTimerError`) when the connection could not be opened, or one of `InvalidURL`, `RequestNotSent`, `ConnectionClosedEarly`, `InvalidHTTPResponse`, `UnexpectedStatus`, `RedirectRefused`, `InvalidJSON`, and `ConversionFailed`. The `RequestFailureReason` documentation, and the documentation of each reason this package defines, say whether retrying is safe. `status`, `response_body`, and `message` are unchanged. + +Before: + +```pony +| let e: RequestError => + if e.message == "Connection timed out" then retry() end +``` + +After: + +```pony +use "net" + +| let e: RequestError => + match e.reason + | ConnectionFailedTimeout => retry() + end +``` + +`RequestError` no longer has a `create` constructor. Code that builds a `RequestError`, such as a test fake for an operation, uses the constructor for the reason it needs, for example `RequestError.unexpected_status(404, body)` or `RequestError.connection_failed(ConnectionFailedTimeout)`. + +Before: + +```pony +let err = RequestError(404, body) +``` + +After: + +```pony +let err = RequestError.unexpected_status(404, body) +``` + +The receiver interfaces that the request actors report to (`JSONRequesterResultReceiver`, `LinkedResultReceiver`, `DeleteResultReceiver`, and `CheckResultReceiver`) now receive a `RequestError` in `failure`: + +Before: + +```pony +be failure(status: U16, response_body: String, message: String) => + ... +``` + +After: + +```pony +be failure(err: RequestError) => + ... +``` + +Code that calls `failure` on one of the library's own receivers, such as `ResultReceiver` or `PaginatedResultReceiver`, now passes a `RequestError` too, for example `receiver.failure(RequestError.unexpected_status(404, body))`. diff --git a/.release-notes/settle-promises-on-premature-close.md b/.release-notes/settle-promises-on-premature-close.md index 8e499a9..9a71317 100644 --- a/.release-notes/settle-promises-on-premature-close.md +++ b/.release-notes/settle-promises-on-premature-close.md @@ -2,4 +2,4 @@ Previously, request actors did not notify their receivers when a server closed the connection before completing a response, when an established connection reached the 60-second idle timeout, or when sending the HTTP request failed. High-level API operations left their `Promise` unsettled. -Now, every request actor reports a failure with status `0` to its receiver in each case. When a connection closes early, times out after the TLS handshake, or closes before the actor sends the request, the error message is `"Connection closed before response completed"`. High-level API operations fulfill their `Promise` with a `RequestError` that contains that status and message. +Now, every request actor reports a failure with status `0` to its receiver in each case. When a connection closes early or times out after the actor sends the request, the error's `reason` is `ConnectionClosedEarly` and its message is `"Connection closed before response completed"`. When the connection closes before the actor sends the request, or sending fails, the `reason` is `RequestNotSent` and the message is `"Failed to send request"`. High-level API operations fulfill their `Promise` with a `RequestError` that contains that reason, status, and message. diff --git a/README.md b/README.md index 44bc02f..232bea9 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,13 @@ primitive PrintRepository | let repo: Repository => out.print(repo.full_name) | let err: RequestError => - out.print(err.message) + match err.reason + | ConnectionFailedTimeout => out.print("timed out; try again") + | UnexpectedStatus => + out.print("GitHub returned status " + err.status.string()) + else + out.print(err.message) + end end ``` diff --git a/examples/README.md b/examples/README.md index 6f14fe5..b00e5fa 100644 --- a/examples/README.md +++ b/examples/README.md @@ -23,7 +23,7 @@ Each example has its own `Makefile`. Build with `make ssl=3.0.x` (or the SSL ver | Example | Style | Description | |---------|-------|-------------| -| `get-repository` | Functional | Fetch a repository by owner and name | +| `get-repository` | Functional | Fetch a repository by owner and name, and handle a failure by its reason | | `get-repository-oo` | OO | Same as `get-repository`, using `GitHub.get_repo()` | | `get-repository-labels` | Functional | List labels for a repository with pagination | diff --git a/examples/get-repository-oo/main.pony b/examples/get-repository-oo/main.pony index cfdd0f7..a9ca511 100644 --- a/examples/get-repository-oo/main.pony +++ b/examples/get-repository-oo/main.pony @@ -81,7 +81,15 @@ primitive PrintRepository out.print(repo.html_url) | let e: RequestError => out.print("Unable to retrieve repository") - out.print(e.status.string()) - out.print(e.response_body) - out.print(e.message) + match e.reason + | ConnectionFailedTimeout => + out.print("The connection timed out. Retrying is safe.") + | UnexpectedStatus if e.status == 404 => + out.print("No such repository, or no access to it.") + | UnexpectedStatus => + out.print("GitHub returned status " + e.status.string()) + out.print(e.response_body) + else + out.print(e.message) + end end diff --git a/examples/get-repository/get_repository.pony b/examples/get-repository/get_repository.pony index 934e9eb..b1f6a6f 100644 --- a/examples/get-repository/get_repository.pony +++ b/examples/get-repository/get_repository.pony @@ -1,3 +1,4 @@ """ -Demonstrates fetching information about a GitHub repository. +Demonstrates fetching information about a GitHub repository, and choosing +what to do about a failure by matching on its reason. """ diff --git a/examples/get-repository/main.pony b/examples/get-repository/main.pony index a7c7b36..d878fec 100644 --- a/examples/get-repository/main.pony +++ b/examples/get-repository/main.pony @@ -81,7 +81,15 @@ primitive PrintRepository out.print(repo.html_url) | let e: RequestError => out.print("Unable to retrieve repository") - out.print(e.status.string()) - out.print(e.response_body) - out.print(e.message) + match e.reason + | ConnectionFailedTimeout => + out.print("The connection timed out. Retrying is safe.") + | UnexpectedStatus if e.status == 404 => + out.print("No such repository, or no access to it.") + | UnexpectedStatus => + out.print("GitHub returned status " + e.status.string()) + out.print(e.response_body) + else + out.print(e.message) + end end diff --git a/github_rest_api/_test.pony b/github_rest_api/_test.pony index 7f403fa..e98b203 100644 --- a/github_rest_api/_test.pony +++ b/github_rest_api/_test.pony @@ -99,6 +99,7 @@ actor \nodoc\ Main is TestList test(_TestLinkedWithLink) test(_TestLinkedNoLink) test(_TestLinkedFailure) + test(_TestLinkedRequesterInvalidJSON) test(_TestBearerTokenSent) test(_TestNoTokenNoAuthHeader) test(_TestSearchConverterExtractsLinks) @@ -115,6 +116,7 @@ actor \nodoc\ Main is TestList test(_TestRepositoryGetIssuesSendsQuery) test(_TestRepositoryGetIssuesDefaultQuery) _OperationRequestLineTests.tests(test) + test(_TestModelTemplateInvalidURL) test(_TestJSONRequesterSendsGitHubHeaders) test(_TestNoContentRequesterSendsGitHubHeaders) test(_TestCheckRequesterSendsGitHubHeaders) diff --git a/github_rest_api/_test_model_template_invalid_url.pony b/github_rest_api/_test_model_template_invalid_url.pony new file mode 100644 index 0000000..8dbbf1c --- /dev/null +++ b/github_rest_api/_test_model_template_invalid_url.pony @@ -0,0 +1,30 @@ +use "json" +use "pony_test" +use req = "request" + +class \nodoc\ _TestModelTemplateInvalidURL is UnitTest + """ + A URL template from GitHub data that does not parse gives a `RequestError` + with reason `InvalidURL`, without opening a connection. + """ + fun name(): String => "request-error/model-template-invalid-url" + + fun ref apply(h: TestHelper) ? => + let creds = _TestDummyCredentials(h) + let json = + _TestRepositoryJSON("x").update("labels_url", "https://example{.com") + let repo = RepositoryJSONConverter(JSONNav(json), creds)? + h.long_test(2_000_000_000) + repo.create_label("bug").next[None]( + {(result: LabelOrError) => + match \exhaustive\ result + | let _: Label => + h.fail("expected a RequestError") + h.complete(false) + | let e: req.RequestError => + h.assert_true( + e.reason is req.InvalidURL, "reason should be InvalidURL") + h.assert_eq[U16](0, e.status) + h.complete(true) + end + }) diff --git a/github_rest_api/_test_operation_request_lines.pony b/github_rest_api/_test_operation_request_lines.pony index dc3a373..b0a1085 100644 --- a/github_rest_api/_test_operation_request_lines.pony +++ b/github_rest_api/_test_operation_request_lines.pony @@ -234,9 +234,9 @@ primitive \nodoc\ _OperationRequestLineTests "2024-01-01T00:00:00Z", per_page) | let _: ct.ValidationFailure => + // MakePerPage(50) cannot fail; this arm only satisfies the match. Promise[(PaginatedList[Issue] | req.RequestError)] - .> apply(req.RequestError( - where message' = "MakePerPage(50) should succeed")) + .> apply(req.RequestError.invalid_url("MakePerPage(50) failed")) end } val)) diff --git a/github_rest_api/_test_premature_close.pony b/github_rest_api/_test_premature_close.pony index 634f81d..8479df2 100644 --- a/github_rest_api/_test_premature_close.pony +++ b/github_rest_api/_test_premature_close.pony @@ -24,10 +24,10 @@ actor \nodoc\ _TestOneCheckSuccessReceiver _h.assert_eq[Bool](_expected, value) _count() - be failure(status: U16, response_body: String, message: String) => + be failure(err: req.RequestError) => _h.fail( - "Expected success, got failure: status=" + status.string() + - " body=" + response_body + " msg=" + message) + "Expected success, got failure: status=" + err.status.string() + + " body=" + err.response_body + " msg=" + err.message) _count() fun ref _count() => @@ -44,10 +44,11 @@ actor \nodoc\ _TestOneCheckFailureReceiver is (req.CheckResultReceiver & _TestGraceTarget) """ Fails the test unless it gets exactly one callback: a failure with the given - status, body, and message. Completes the test 300 ms after the first + reason, status, body, and message. Completes the test 300 ms after the first callback, so a second callback in that window fails the test. """ let _h: TestHelper + let _reason: req.RequestFailureReason let _status: U16 let _message: String let _expected_body: String @@ -56,11 +57,13 @@ actor \nodoc\ _TestOneCheckFailureReceiver new create( h: TestHelper, + reason: req.RequestFailureReason, status: U16, message: String, expected_body: String = "") => _h = h + _reason = reason _status = status _message = message _expected_body = expected_body @@ -70,10 +73,11 @@ actor \nodoc\ _TestOneCheckFailureReceiver _h.fail("Expected a failure, got success: " + value.string()) _count() - be failure(status: U16, response_body: String, message: String) => - _h.assert_eq[U16](_status, status) - _h.assert_eq[String](_expected_body, response_body) - _h.assert_eq[String](_message, message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is _reason, "wrong reason") + _h.assert_eq[U16](_status, err.status) + _h.assert_eq[String](_expected_body, err.response_body) + _h.assert_eq[String](_message, err.message) _count() fun ref _count() => @@ -98,7 +102,10 @@ class \nodoc\ _TestJSONRequesterPrematureCloseBeforeStatus is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "" } val h.long_test(5_000_000_000) let listener = @@ -125,7 +132,10 @@ class \nodoc\ _TestLinkedRequesterPrematureCloseBeforeStatus is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneLinkedFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "" } val h.long_test(5_000_000_000) let listener = @@ -152,7 +162,10 @@ class \nodoc\ _TestNoContentRequesterPrematureCloseBeforeStatus is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneDeleteFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "" } val h.long_test(5_000_000_000) let listener = @@ -179,7 +192,10 @@ class \nodoc\ _TestCheckRequesterPrematureCloseBeforeStatus is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneCheckFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "" } val h.long_test(5_000_000_000) let listener = @@ -206,7 +222,10 @@ class \nodoc\ _TestJSONRequesterPrematureCloseMidHeaders is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "HTTP/1.1 200 OK\r\nContent-Type: application/json" @@ -236,7 +255,10 @@ class \nodoc\ _TestJSONRequesterPrematureCloseTruncatedBody is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{\"a\":" @@ -266,7 +288,10 @@ class \nodoc\ _TestJSONRequesterPrematureCloseIncompleteChunked is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhel" @@ -296,7 +321,10 @@ class \nodoc\ _TestLinkedRequesterPrematureCloseTruncatedBody is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneLinkedFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{\"a\":" @@ -326,7 +354,10 @@ class \nodoc\ _TestNoContentRequesterPrematureCloseTruncatedBody is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneDeleteFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\nerr" @@ -356,7 +387,10 @@ class \nodoc\ _TestCheckRequesterPrematureCloseTruncatedBody is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneCheckFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String): String => "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\nerr" @@ -388,7 +422,10 @@ class \nodoc\ _TestJSONRequesterRedirectThenPrematureClose is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String)(target): String => if request.at("GET /start HTTP/1.1\r\n", 0) then @@ -426,7 +463,10 @@ class \nodoc\ _TestLinkedRequesterRedirectThenPrematureClose is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneLinkedFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String)(target): String => if request.at("GET /start HTTP/1.1\r\n", 0) then @@ -464,7 +504,10 @@ class \nodoc\ _TestNoContentRequesterRedirectThenPrematureClose is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneDeleteFailureReceiver( - h, 0, "Connection closed before response completed") + h, + req.ConnectionClosedEarly, + 0, + "Connection closed before response completed") let responder: _Responder = {(request: String)(target): String => if request.at("DELETE /start HTTP/1.1\r\n", 0) then @@ -553,7 +596,9 @@ class \nodoc\ _TestNoContentRequesterCloseDelimitedFailure is UnitTest let url = _TestURL(_TestHost(), port, "/close-delimited") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneDeleteFailureReceiver(h, 403, "", "forbidden") + let receiver = + _TestOneDeleteFailureReceiver( + h, req.UnexpectedStatus, 403, "", "forbidden") let responder: _Responder = {(request: String): String => "HTTP/1.1 403 Forbidden\r\n\r\nforbidden" @@ -657,7 +702,9 @@ class \nodoc\ _TestCheckRequesterCloseDelimited500 is UnitTest let url = _TestURL(_TestHost(), port, "/close-delimited") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneCheckFailureReceiver(h, 500, "", "server error") + let receiver = + _TestOneCheckFailureReceiver( + h, req.UnexpectedStatus, 500, "", "server error") let responder: _Responder = {(request: String): String => "HTTP/1.1 500 Internal Server Error\r\n\r\nserver error" @@ -685,7 +732,9 @@ class \nodoc\ _TestJSONRequesterParseErrorSingleDelivery is UnitTest let url = _TestURL(_TestHost(), port, "/bad-http") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneJSONFailureReceiver(h, 0, "HTTP parse error") + let receiver = + _TestOneJSONFailureReceiver( + h, req.InvalidHTTPResponse, 0, "HTTP parse error") let responder: _Responder = {(request: String): String => "NOT HTTP\r\n\r\n" } val h.long_test(5_000_000_000) @@ -711,7 +760,9 @@ class \nodoc\ _TestLinkedRequesterParseErrorSingleDelivery is UnitTest let url = _TestURL(_TestHost(), port, "/bad-http") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneLinkedFailureReceiver(h, 0, "HTTP parse error") + let receiver = + _TestOneLinkedFailureReceiver( + h, req.InvalidHTTPResponse, 0, "HTTP parse error") let responder: _Responder = {(request: String): String => "NOT HTTP\r\n\r\n" } val h.long_test(5_000_000_000) @@ -737,7 +788,9 @@ class \nodoc\ _TestNoContentRequesterParseErrorSingleDelivery is UnitTest let url = _TestURL(_TestHost(), port, "/bad-http") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneDeleteFailureReceiver(h, 0, "HTTP parse error") + let receiver = + _TestOneDeleteFailureReceiver( + h, req.InvalidHTTPResponse, 0, "HTTP parse error") let responder: _Responder = {(request: String): String => "NOT HTTP\r\n\r\n" } val h.long_test(5_000_000_000) @@ -763,7 +816,9 @@ class \nodoc\ _TestCheckRequesterParseErrorSingleDelivery is UnitTest let url = _TestURL(_TestHost(), port, "/bad-http") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneCheckFailureReceiver(h, 0, "HTTP parse error") + let receiver = + _TestOneCheckFailureReceiver( + h, req.InvalidHTTPResponse, 0, "HTTP parse error") let responder: _Responder = {(request: String): String => "NOT HTTP\r\n\r\n" } val h.long_test(5_000_000_000) diff --git a/github_rest_api/_test_redirect_origin.pony b/github_rest_api/_test_redirect_origin.pony index 10919b5..eb31b8d 100644 --- a/github_rest_api/_test_redirect_origin.pony +++ b/github_rest_api/_test_redirect_origin.pony @@ -8,10 +8,11 @@ actor \nodoc\ _TestOneJSONFailureReceiver is (req.JSONRequesterResultReceiver & _TestGraceTarget) """ Fails the test unless it gets exactly one callback: a failure with the given - status, `expected_body`, and the given message. It completes the test 300 ms + reason, status, `expected_body`, and message. It completes the test 300 ms after the first callback, so a second callback in that window fails the test. """ let _h: TestHelper + let _reason: req.RequestFailureReason let _status: U16 let _message: String let _expected_body: String @@ -20,11 +21,13 @@ actor \nodoc\ _TestOneJSONFailureReceiver new create( h: TestHelper, + reason: req.RequestFailureReason, status: U16, message: String, expected_body: String = "") => _h = h + _reason = reason _status = status _message = message _expected_body = expected_body @@ -34,10 +37,11 @@ actor \nodoc\ _TestOneJSONFailureReceiver _h.fail("Expected a failure, got success") _count() - be failure(status: U16, response_body: String, message: String) => - _h.assert_eq[U16](_status, status) - _h.assert_eq[String](_expected_body, response_body) - _h.assert_eq[String](_message, message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is _reason, "wrong reason") + _h.assert_eq[U16](_status, err.status) + _h.assert_eq[String](_expected_body, err.response_body) + _h.assert_eq[String](_message, err.message) _count() fun ref _count() => @@ -54,17 +58,24 @@ actor \nodoc\ _TestOneLinkedFailureReceiver is (req.LinkedResultReceiver & _TestGraceTarget) """ Fails the test unless it gets exactly one callback: a failure with the given - status, an empty body, and the given message. It completes the test 300 ms + reason, status, and message, and an empty body. It completes the test 300 ms after the first callback, so a second callback in that window fails the test. """ let _h: TestHelper + let _reason: req.RequestFailureReason let _status: U16 let _message: String let _timers: Timers = Timers var _calls: USize = 0 - new create(h: TestHelper, status: U16, message: String) => + new create( + h: TestHelper, + reason: req.RequestFailureReason, + status: U16, + message: String) + => _h = h + _reason = reason _status = status _message = message h.dispose_when_done(_timers) @@ -73,10 +84,11 @@ actor \nodoc\ _TestOneLinkedFailureReceiver _h.fail("Expected a failure, got success") _count() - be failure(status: U16, response_body: String, message: String) => - _h.assert_eq[U16](_status, status) - _h.assert_eq[String]("", response_body) - _h.assert_eq[String](_message, message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is _reason, "wrong reason") + _h.assert_eq[U16](_status, err.status) + _h.assert_eq[String]("", err.response_body) + _h.assert_eq[String](_message, err.message) _count() fun ref _count() => @@ -132,7 +144,10 @@ class \nodoc\ _TestJSONRequesterRefusesCrossOriginRedirect is UnitTest where token' = _TestToken("ghp_secret")?, ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 307, "Refused redirect to a different origin: " + target) + h, + req.RedirectRefused, + 307, + "Refused redirect to a different origin: " + target) let responder: _Responder = {(request: String)(location): String => _TestRedirectResponse("307 Temporary Redirect", location) @@ -174,7 +189,10 @@ class \nodoc\ _TestLinkedJSONRequesterRefusesCrossOriginRedirect is UnitTest where token' = _TestToken("ghp_secret")?, ssl_ctx' = sslctx) let receiver = _TestOneLinkedFailureReceiver( - h, 301, "Refused redirect to a different origin: " + target) + h, + req.RedirectRefused, + 301, + "Refused redirect to a different origin: " + target) let responder: _Responder = {(request: String)(location): String => _TestRedirectResponse("301 Moved Permanently", location) @@ -255,7 +273,10 @@ class \nodoc\ _TestJSONRequesterRefusesCrossSchemeRedirect is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 307, "Refused redirect to a different origin: " + target) + h, + req.RedirectRefused, + 307, + "Refused redirect to a different origin: " + target) let responder: _Responder = {(request: String)(h, location): String => if request.contains("GET /x") then @@ -395,7 +416,10 @@ class \nodoc\ _TestJSONRequesterRefusedRedirectIgnoresParseError is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 307, "Refused redirect to a different origin: " + target) + h, + req.RedirectRefused, + 307, + "Refused redirect to a different origin: " + target) let responder: _Responder = {(request: String)(location): String => _TestOversizedRedirectResponse("307 Temporary Redirect", location) @@ -427,7 +451,10 @@ class \nodoc\ _TestLinkedJSONRequesterRefusedRedirectIgnoresParseError req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneLinkedFailureReceiver( - h, 301, "Refused redirect to a different origin: " + target) + h, + req.RedirectRefused, + 301, + "Refused redirect to a different origin: " + target) let responder: _Responder = {(request: String)(location): String => _TestOversizedRedirectResponse("301 Moved Permanently", location) @@ -471,10 +498,10 @@ actor \nodoc\ _TestOneJSONSuccessReceiver end _count() - be failure(status: U16, response_body: String, message: String) => + be failure(err: req.RequestError) => _h.fail( - "Expected success, got failure: status=" + status.string() + - " body=" + response_body + " msg=" + message) + "Expected success, got failure: status=" + err.status.string() + + " body=" + err.response_body + " msg=" + err.message) _count() fun ref _count() => @@ -523,10 +550,10 @@ actor \nodoc\ _TestOneLinkedSuccessReceiver _h.assert_eq[String](_expected_link, link_header) _count() - be failure(status: U16, response_body: String, message: String) => + be failure(err: req.RequestError) => _h.fail( - "Expected success, got failure: status=" + status.string() + - " body=" + response_body + " msg=" + message) + "Expected success, got failure: status=" + err.status.string() + + " body=" + err.response_body + " msg=" + err.message) _count() fun ref _count() => @@ -723,7 +750,9 @@ class \nodoc\ _TestJSONRequesterRefusesTooManyRedirects is UnitTest let url = _TestURL(_TestHost(), port, "/hop/0") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneJSONFailureReceiver(h, 307, "Too many redirects") + let receiver = + _TestOneJSONFailureReceiver( + h, req.RedirectRefused, 307, "Too many redirects") let responder = _TestHopChainResponder(h, "307 Temporary Redirect", 5, false) h.long_test(5_000_000_000) @@ -748,7 +777,9 @@ class \nodoc\ _TestLinkedJSONRequesterRefusesTooManyRedirects is UnitTest let url = _TestURL(_TestHost(), port, "/hop/0") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneLinkedFailureReceiver(h, 307, "Too many redirects") + let receiver = + _TestOneLinkedFailureReceiver( + h, req.RedirectRefused, 307, "Too many redirects") let responder = _TestHopChainResponder(h, "307 Temporary Redirect", 5, false) h.long_test(5_000_000_000) @@ -776,7 +807,7 @@ class \nodoc\ _TestJSONRequesterInvalidRedirectLocation is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 307, "Invalid redirect Location: " + bad_loc) + h, req.RedirectRefused, 307, "Invalid redirect Location: " + bad_loc) let responder: _Responder = {(request: String)(bad_loc): String => _TestRedirectResponse("307 Temporary Redirect", bad_loc) @@ -806,7 +837,7 @@ class \nodoc\ _TestLinkedJSONRequesterInvalidRedirectLocation is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneLinkedFailureReceiver( - h, 301, "Invalid redirect Location: " + bad_loc) + h, req.RedirectRefused, 301, "Invalid redirect Location: " + bad_loc) let responder: _Responder = {(request: String)(bad_loc): String => _TestRedirectResponse("301 Moved Permanently", bad_loc) @@ -841,10 +872,10 @@ actor \nodoc\ _TestOneDeleteSuccessReceiver be success() => _count() - be failure(status: U16, response_body: String, message: String) => + be failure(err: req.RequestError) => _h.fail( - "Expected success, got failure: status=" + status.string() + - " body=" + response_body + " msg=" + message) + "Expected success, got failure: status=" + err.status.string() + + " body=" + err.response_body + " msg=" + err.message) _count() fun ref _count() => @@ -861,10 +892,11 @@ actor \nodoc\ _TestOneDeleteFailureReceiver is (req.DeleteResultReceiver & _TestGraceTarget) """ Fails the test unless it gets exactly one callback: a failure with the given - status, `expected_body`, and the given message. It completes the test 300 ms + reason, status, `expected_body`, and message. It completes the test 300 ms after the first callback, so a second callback in that window fails the test. """ let _h: TestHelper + let _reason: req.RequestFailureReason let _status: U16 let _message: String let _expected_body: String @@ -873,11 +905,13 @@ actor \nodoc\ _TestOneDeleteFailureReceiver new create( h: TestHelper, + reason: req.RequestFailureReason, status: U16, message: String, expected_body: String = "") => _h = h + _reason = reason _status = status _message = message _expected_body = expected_body @@ -887,10 +921,11 @@ actor \nodoc\ _TestOneDeleteFailureReceiver _h.fail("Expected a failure, got success") _count() - be failure(status: U16, response_body: String, message: String) => - _h.assert_eq[U16](_status, status) - _h.assert_eq[String](_expected_body, response_body) - _h.assert_eq[String](_message, message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is _reason, "wrong reason") + _h.assert_eq[U16](_status, err.status) + _h.assert_eq[String](_expected_body, err.response_body) + _h.assert_eq[String](_message, err.message) _count() fun ref _count() => @@ -1081,7 +1116,8 @@ class \nodoc\ _TestJSONRequesterPostDoesNotFollow301 is UnitTest let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestOneJSONFailureReceiver(h, 301, "", """{"message":"Moved"}""") + _TestOneJSONFailureReceiver( + h, req.UnexpectedStatus, 301, "", """{"message":"Moved"}""") let responder = _TestNonFollowedResponder(h, "301 Moved Permanently") h.long_test(5_000_000_000) let listener = @@ -1106,7 +1142,8 @@ class \nodoc\ _TestJSONRequesterPostDoesNotFollow302 is UnitTest let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestOneJSONFailureReceiver(h, 302, "", """{"message":"Moved"}""") + _TestOneJSONFailureReceiver( + h, req.UnexpectedStatus, 302, "", """{"message":"Moved"}""") let responder = _TestNonFollowedResponder(h, "302 Found") h.long_test(5_000_000_000) let listener = @@ -1131,7 +1168,8 @@ class \nodoc\ _TestJSONRequesterPostDoesNotFollow303 is UnitTest let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestOneJSONFailureReceiver(h, 303, "", """{"message":"Moved"}""") + _TestOneJSONFailureReceiver( + h, req.UnexpectedStatus, 303, "", """{"message":"Moved"}""") let responder = _TestNonFollowedResponder(h, "303 See Other") h.long_test(5_000_000_000) let listener = @@ -1161,7 +1199,10 @@ class \nodoc\ _TestJSONRequesterPostRefusesCrossOrigin307 is UnitTest where token' = _TestToken("ghp_secret")?, ssl_ctx' = sslctx) let receiver = _TestOneJSONFailureReceiver( - h, 307, "Refused redirect to a different origin: " + target) + h, + req.RedirectRefused, + 307, + "Refused redirect to a different origin: " + target) let responder: _Responder = {(request: String)(location): String => _TestRedirectResponse("307 Temporary Redirect", location) @@ -1197,7 +1238,9 @@ class \nodoc\ _TestJSONRequesterPostRefusesTooMany307 is UnitTest let url = _TestURL(_TestHost(), port, "/hop/0") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneJSONFailureReceiver(h, 307, "Too many redirects") + let receiver = + _TestOneJSONFailureReceiver( + h, req.RedirectRefused, 307, "Too many redirects") let responder = _TestHopChainResponder( h, "307 Temporary Redirect", 5, false where method = "POST") @@ -1267,7 +1310,8 @@ class \nodoc\ _TestJSONRequesterPatchDoesNotFollow302 is UnitTest let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestOneJSONFailureReceiver(h, 302, "", """{"message":"Moved"}""") + _TestOneJSONFailureReceiver( + h, req.UnexpectedStatus, 302, "", """{"message":"Moved"}""") let responder = _TestNonFollowedResponder(h, "302 Found") h.long_test(5_000_000_000) let listener = @@ -1366,7 +1410,9 @@ class \nodoc\ _TestNoContentDeleteRefusesTooManyRedirects is UnitTest let url = _TestURL(_TestHost(), port, "/hop/0") let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneDeleteFailureReceiver(h, 307, "Too many redirects") + let receiver = + _TestOneDeleteFailureReceiver( + h, req.RedirectRefused, 307, "Too many redirects") let responder = _TestHopChainResponder( h, "307 Temporary Redirect", 5, false where method = "DELETE") @@ -1398,7 +1444,10 @@ class \nodoc\ _TestNoContentDeleteRefusesCrossOrigin307 is UnitTest where token' = _TestToken("ghp_secret")?, ssl_ctx' = sslctx) let receiver = _TestOneDeleteFailureReceiver( - h, 307, "Refused redirect to a different origin: " + target) + h, + req.RedirectRefused, + 307, + "Refused redirect to a different origin: " + target) let responder: _Responder = {(request: String)(location): String => _TestRedirectResponse("307 Temporary Redirect", location) @@ -1438,7 +1487,10 @@ class \nodoc\ _TestNoContentDeleteRefusedRedirectIgnoresParseError is UnitTest req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = _TestOneDeleteFailureReceiver( - h, 307, "Refused redirect to a different origin: " + target) + h, + req.RedirectRefused, + 307, + "Refused redirect to a different origin: " + target) let responder: _Responder = {(request: String)(location): String => _TestOversizedRedirectResponse("307 Temporary Redirect", location) @@ -1499,7 +1551,8 @@ class \nodoc\ _TestNoContentDeleteDoesNotFollow301 is UnitTest let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestOneDeleteFailureReceiver(h, 301, "", """{"message":"Moved"}""") + _TestOneDeleteFailureReceiver( + h, req.UnexpectedStatus, 301, "", """{"message":"Moved"}""") let responder = _TestNonFollowedResponder(h, "301 Moved Permanently") h.long_test(5_000_000_000) let listener = @@ -1524,7 +1577,8 @@ class \nodoc\ _TestNoContentDeleteDoesNotFollow302 is UnitTest let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestOneDeleteFailureReceiver(h, 302, "", """{"message":"Moved"}""") + _TestOneDeleteFailureReceiver( + h, req.UnexpectedStatus, 302, "", """{"message":"Moved"}""") let responder = _TestNonFollowedResponder(h, "302 Found") h.long_test(5_000_000_000) let listener = @@ -1549,7 +1603,8 @@ class \nodoc\ _TestNoContentDeleteDoesNotFollow303 is UnitTest let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestOneDeleteFailureReceiver(h, 303, "", """{"message":"Moved"}""") + _TestOneDeleteFailureReceiver( + h, req.UnexpectedStatus, 303, "", """{"message":"Moved"}""") let responder = _TestNonFollowedResponder(h, "303 See Other") h.long_test(5_000_000_000) let listener = @@ -1607,7 +1662,8 @@ class \nodoc\ _TestNoContentPutDoesNotFollow301 is UnitTest let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestOneDeleteFailureReceiver(h, 301, "", """{"message":"Moved"}""") + _TestOneDeleteFailureReceiver( + h, req.UnexpectedStatus, 301, "", """{"message":"Moved"}""") let responder = _TestNonFollowedResponder(h, "301 Moved Permanently") h.long_test(5_000_000_000) let listener = @@ -1632,7 +1688,9 @@ class \nodoc\ _TestJSONRequesterPostMissingLocation307 is UnitTest let body = """{"error":"no location"}""" let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneJSONFailureReceiver(h, 307, "", body) + let receiver = + _TestOneJSONFailureReceiver( + h, req.UnexpectedStatus, 307, "", body) let responder: _Responder = {(request: String)(body): String => "HTTP/1.1 307 Temporary Redirect\r\n" + @@ -1663,7 +1721,9 @@ class \nodoc\ _TestNoContentDeleteMissingLocation307 is UnitTest let body = """{"error":"no location"}""" let creds = req.Credentials(TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) - let receiver = _TestOneDeleteFailureReceiver(h, 307, "", body) + let receiver = + _TestOneDeleteFailureReceiver( + h, req.UnexpectedStatus, 307, "", body) let responder: _Responder = {(request: String)(body): String => "HTTP/1.1 307 Temporary Redirect\r\n" + diff --git a/github_rest_api/_test_request_actors.pony b/github_rest_api/_test_request_actors.pony index f2579d9..074550d 100644 --- a/github_rest_api/_test_request_actors.pony +++ b/github_rest_api/_test_request_actors.pony @@ -29,30 +29,29 @@ actor \nodoc\ _TestJSONSuccessReceiver is req.JSONRequesterResultReceiver _h.complete(false) end - be failure( - status: U16, - response_body: String, - message: String) - => + be failure(err: req.RequestError) => _h.fail( "Expected success, got failure: status=" + - status.string() + " body=" + response_body + - " msg=" + message) + err.status.string() + " body=" + err.response_body + + " msg=" + err.message) _h.complete(false) actor \nodoc\ _TestJSONFailureReceiver is req.JSONRequesterResultReceiver let _h: TestHelper + let _reason: req.RequestFailureReason let _expected_status: U16 let _expected_body: String let _expected_message: String new create( h: TestHelper, + reason: req.RequestFailureReason, expected_status: U16, expected_body: String, expected_message: String) => _h = h + _reason = reason _expected_status = expected_status _expected_body = expected_body _expected_message = expected_message @@ -61,14 +60,11 @@ actor \nodoc\ _TestJSONFailureReceiver is req.JSONRequesterResultReceiver _h.fail("Expected failure, got success") _h.complete(false) - be failure( - status: U16, - response_body: String, - message: String) - => - _h.assert_eq[U16](_expected_status, status) - _h.assert_eq[String](_expected_body, response_body) - _h.assert_eq[String](_expected_message, message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is _reason, "wrong reason") + _h.assert_eq[U16](_expected_status, err.status) + _h.assert_eq[String](_expected_body, err.response_body) + _h.assert_eq[String](_expected_message, err.message) _h.complete(true) actor \nodoc\ _TestDeleteSuccessReceiver is req.DeleteResultReceiver @@ -80,30 +76,29 @@ actor \nodoc\ _TestDeleteSuccessReceiver is req.DeleteResultReceiver be success() => _h.complete(true) - be failure( - status: U16, - response_body: String, - message: String) - => + be failure(err: req.RequestError) => _h.fail( "Expected success, got failure: status=" + - status.string() + " body=" + response_body + - " msg=" + message) + err.status.string() + " body=" + err.response_body + + " msg=" + err.message) _h.complete(false) actor \nodoc\ _TestDeleteFailureReceiver is req.DeleteResultReceiver let _h: TestHelper + let _reason: req.RequestFailureReason let _expected_status: U16 let _expected_body: String let _expected_message: String new create( h: TestHelper, + reason: req.RequestFailureReason, expected_status: U16, expected_body: String, expected_message: String = "") => _h = h + _reason = reason _expected_status = expected_status _expected_body = expected_body _expected_message = expected_message @@ -112,14 +107,11 @@ actor \nodoc\ _TestDeleteFailureReceiver is req.DeleteResultReceiver _h.fail("Expected failure, got success") _h.complete(false) - be failure( - status: U16, - response_body: String, - message: String) - => - _h.assert_eq[U16](_expected_status, status) - _h.assert_eq[String](_expected_body, response_body) - _h.assert_eq[String](_expected_message, message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is _reason, "wrong reason") + _h.assert_eq[U16](_expected_status, err.status) + _h.assert_eq[String](_expected_body, err.response_body) + _h.assert_eq[String](_expected_message, err.message) _h.complete(true) actor \nodoc\ _TestCheckSuccessReceiver is req.CheckResultReceiver @@ -134,30 +126,29 @@ actor \nodoc\ _TestCheckSuccessReceiver is req.CheckResultReceiver _h.assert_eq[Bool](_expected, value) _h.complete(true) - be failure( - status: U16, - response_body: String, - message: String) - => + be failure(err: req.RequestError) => _h.fail( "Expected success(" + _expected.string() + - "), got failure: status=" + status.string() + - " body=" + response_body + " msg=" + message) + "), got failure: status=" + err.status.string() + + " body=" + err.response_body + " msg=" + err.message) _h.complete(false) actor \nodoc\ _TestCheckFailureReceiver is req.CheckResultReceiver let _h: TestHelper + let _reason: req.RequestFailureReason let _expected_status: U16 let _expected_body: String let _expected_message: String new create( h: TestHelper, + reason: req.RequestFailureReason, expected_status: U16, expected_body: String, expected_message: String = "") => _h = h + _reason = reason _expected_status = expected_status _expected_body = expected_body _expected_message = expected_message @@ -168,14 +159,11 @@ actor \nodoc\ _TestCheckFailureReceiver is req.CheckResultReceiver value.string() + ")") _h.complete(false) - be failure( - status: U16, - response_body: String, - message: String) - => - _h.assert_eq[U16](_expected_status, status) - _h.assert_eq[String](_expected_body, response_body) - _h.assert_eq[String](_expected_message, message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is _reason, "wrong reason") + _h.assert_eq[U16](_expected_status, err.status) + _h.assert_eq[String](_expected_body, err.response_body) + _h.assert_eq[String](_expected_message, err.message) _h.complete(true) actor \nodoc\ _TestLinkedSuccessReceiver is req.LinkedResultReceiver @@ -206,30 +194,29 @@ actor \nodoc\ _TestLinkedSuccessReceiver is req.LinkedResultReceiver _h.complete(false) end - be failure( - status: U16, - response_body: String, - message: String) - => + be failure(err: req.RequestError) => _h.fail( "Expected success, got failure: status=" + - status.string() + " body=" + response_body + - " msg=" + message) + err.status.string() + " body=" + err.response_body + + " msg=" + err.message) _h.complete(false) actor \nodoc\ _TestLinkedFailureReceiver is req.LinkedResultReceiver let _h: TestHelper + let _reason: req.RequestFailureReason let _expected_status: U16 let _expected_body: String let _expected_message: String new create( h: TestHelper, + reason: req.RequestFailureReason, expected_status: U16, expected_body: String, expected_message: String = "") => _h = h + _reason = reason _expected_status = expected_status _expected_body = expected_body _expected_message = expected_message @@ -238,14 +225,11 @@ actor \nodoc\ _TestLinkedFailureReceiver is req.LinkedResultReceiver _h.fail("Expected failure, got success") _h.complete(false) - be failure( - status: U16, - response_body: String, - message: String) - => - _h.assert_eq[U16](_expected_status, status) - _h.assert_eq[String](_expected_body, response_body) - _h.assert_eq[String](_expected_message, message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is _reason, "wrong reason") + _h.assert_eq[U16](_expected_status, err.status) + _h.assert_eq[String](_expected_body, err.response_body) + _h.assert_eq[String](_expected_message, err.message) _h.complete(true) // --- Test classes --- @@ -299,7 +283,7 @@ class \nodoc\ _TestJSONRequesterGetFailure is UnitTest where ssl_ctx' = sslctx) let receiver = _TestJSONFailureReceiver( - h, 404, "not found here", "") + h, req.UnexpectedStatus, 404, "not found here", "") let responder: _Responder = {(request: String): String => let body = "not found here" @@ -419,7 +403,7 @@ class \nodoc\ _TestJSONRequesterGetParseError is UnitTest where ssl_ctx' = sslctx) let receiver = _TestJSONFailureReceiver( - h, 200, "", "Failed to parse response") + h, req.InvalidJSON, 200, "", "Failed to parse response") let responder: _Responder = {(request: String): String => let body = "this is not json{{" @@ -441,6 +425,43 @@ class \nodoc\ _TestJSONRequesterGetParseError is UnitTest } val) h.dispose_when_done(listener) +class \nodoc\ _TestLinkedRequesterInvalidJSON is UnitTest + fun name(): String => + "request-actors/linked-requester/invalid-json" + + fun ref apply(h: TestHelper) ? => + let sslctx = _TestSSLContext(h)? + let host = _TestHost() + let port: String = "48241" + let url = _TestURL(host, port, "/bad-json") + let creds = + req.Credentials( + TCPConnectAuth(h.env.root) + where ssl_ctx' = sslctx) + let receiver = + _TestLinkedFailureReceiver( + h, req.InvalidJSON, 200, "", "Failed to parse response") + let responder: _Responder = + {(request: String): String => + let body = "this is not json{{" + "HTTP/1.1 200 OK\r\n" + + "Content-Length: " + body.size().string() + + "\r\n" + + "\r\n" + + body + } val + h.long_test(5_000_000_000) + let listener = + _MockHTTPListener( + h, + port, + sslctx, + responder, + {()(creds, url, receiver) => + req.LinkedJSONRequester(creds, url, receiver) + } val) + h.dispose_when_done(listener) + class \nodoc\ _TestNoContentDeleteSuccess is UnitTest fun name(): String => "request-actors/no-content-requester/delete-success" @@ -494,7 +515,7 @@ class \nodoc\ _TestNoContentDeleteFailure is UnitTest TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestDeleteFailureReceiver(h, 403, "forbidden") + _TestDeleteFailureReceiver(h, req.UnexpectedStatus, 403, "forbidden") let responder: _Responder = {(request: String): String => let body = "forbidden" @@ -603,7 +624,7 @@ class \nodoc\ _TestCheckRequesterOther is UnitTest TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestCheckFailureReceiver(h, 500, "server error") + _TestCheckFailureReceiver(h, req.UnexpectedStatus, 500, "server error") let responder: _Responder = {(request: String): String => let body = "server error" @@ -718,7 +739,7 @@ class \nodoc\ _TestLinkedFailure is UnitTest where ssl_ctx' = sslctx) let receiver = _TestLinkedFailureReceiver( - h, 500, "internal error") + h, req.UnexpectedStatus, 500, "internal error") let responder: _Responder = {(request: String): String => let body = "internal error" @@ -831,7 +852,8 @@ class \nodoc\ iso _TestNoContentRequesterInvalidURL is UnitTest h.long_test(5_000_000_000) let creds = req.Credentials(TCPConnectAuth(h.env.root)) let receiver = - _TestDeleteFailureReceiver(h, 0, "", "Unable to parse URL") + _TestDeleteFailureReceiver( + h, req.InvalidURL, 0, "", "Unable to parse URL") req.NoContentRequester.delete(creds, "/no-authority", receiver) class \nodoc\ iso _TestCheckRequesterInvalidURL is UnitTest @@ -841,7 +863,7 @@ class \nodoc\ iso _TestCheckRequesterInvalidURL is UnitTest h.long_test(5_000_000_000) let creds = req.Credentials(TCPConnectAuth(h.env.root)) let receiver = - _TestCheckFailureReceiver(h, 0, "", "Unable to parse URL") + _TestCheckFailureReceiver(h, req.InvalidURL, 0, "", "Unable to parse URL") req.CheckRequester(creds, "/no-authority", receiver) class \nodoc\ iso _TestJSONRequesterRejectsControlCharsURL is UnitTest @@ -852,7 +874,7 @@ class \nodoc\ iso _TestJSONRequesterRejectsControlCharsURL is UnitTest let url = _TestURL(_TestHost(), "1", "/a\r\nX-Injected: 1") let creds = req.Credentials(TCPConnectAuth(h.env.root)) let receiver = - _TestJSONFailureReceiver(h, 0, "", "Unable to parse URL") + _TestJSONFailureReceiver(h, req.InvalidURL, 0, "", "Unable to parse URL") req.JSONRequester.get(creds, url, receiver) class \nodoc\ iso _TestLinkedRequesterRejectsControlCharsURL is UnitTest @@ -863,7 +885,8 @@ class \nodoc\ iso _TestLinkedRequesterRejectsControlCharsURL is UnitTest let url = _TestURL(_TestHost(), "1", "/a\r\nX-Injected: 1") let creds = req.Credentials(TCPConnectAuth(h.env.root)) let receiver = - _TestLinkedFailureReceiver(h, 0, "", "Unable to parse URL") + _TestLinkedFailureReceiver( + h, req.InvalidURL, 0, "", "Unable to parse URL") req.LinkedJSONRequester(creds, url, receiver) class \nodoc\ iso _TestNoContentRequesterRejectsControlCharsURL is UnitTest @@ -875,7 +898,8 @@ class \nodoc\ iso _TestNoContentRequesterRejectsControlCharsURL is UnitTest let url = _TestURL(_TestHost(), "1", "/a\r\nX-Injected: 1") let creds = req.Credentials(TCPConnectAuth(h.env.root)) let receiver = - _TestDeleteFailureReceiver(h, 0, "", "Unable to parse URL") + _TestDeleteFailureReceiver( + h, req.InvalidURL, 0, "", "Unable to parse URL") req.NoContentRequester.delete(creds, url, receiver) class \nodoc\ iso _TestCheckRequesterRejectsControlCharsURL is UnitTest @@ -886,7 +910,7 @@ class \nodoc\ iso _TestCheckRequesterRejectsControlCharsURL is UnitTest let url = _TestURL(_TestHost(), "1", "/a\r\nX-Injected: 1") let creds = req.Credentials(TCPConnectAuth(h.env.root)) let receiver = - _TestCheckFailureReceiver(h, 0, "", "Unable to parse URL") + _TestCheckFailureReceiver(h, req.InvalidURL, 0, "", "Unable to parse URL") req.CheckRequester(creds, url, receiver) class \nodoc\ iso _TestJSONRequesterRejectsHTTPURL is UnitTest @@ -905,7 +929,7 @@ class \nodoc\ iso _TestJSONRequesterRejectsHTTPURL is UnitTest TCPConnectAuth(h.env.root) where ssl_ctx' = sslctx) let receiver = - _TestJSONFailureReceiver(h, 0, "", "Unable to parse URL") + _TestJSONFailureReceiver(h, req.InvalidURL, 0, "", "Unable to parse URL") let responder: _Responder = {(request: String): String => h.fail("The requester connected for an http URL") @@ -931,7 +955,8 @@ class \nodoc\ iso _TestLinkedRequesterRejectsHTTPURL is UnitTest let url: String val = "http://" + _TestHost() + ":1/x" let creds = req.Credentials(TCPConnectAuth(h.env.root)) let receiver = - _TestLinkedFailureReceiver(h, 0, "", "Unable to parse URL") + _TestLinkedFailureReceiver( + h, req.InvalidURL, 0, "", "Unable to parse URL") req.LinkedJSONRequester(creds, url, receiver) class \nodoc\ iso _TestNoContentRequesterRejectsHTTPURL is UnitTest @@ -942,7 +967,8 @@ class \nodoc\ iso _TestNoContentRequesterRejectsHTTPURL is UnitTest let url: String val = "http://" + _TestHost() + ":1/x" let creds = req.Credentials(TCPConnectAuth(h.env.root)) let receiver = - _TestDeleteFailureReceiver(h, 0, "", "Unable to parse URL") + _TestDeleteFailureReceiver( + h, req.InvalidURL, 0, "", "Unable to parse URL") req.NoContentRequester.delete(creds, url, receiver) class \nodoc\ iso _TestCheckRequesterRejectsHTTPURL is UnitTest @@ -953,7 +979,7 @@ class \nodoc\ iso _TestCheckRequesterRejectsHTTPURL is UnitTest let url: String val = "http://" + _TestHost() + ":1/x" let creds = req.Credentials(TCPConnectAuth(h.env.root)) let receiver = - _TestCheckFailureReceiver(h, 0, "", "Unable to parse URL") + _TestCheckFailureReceiver(h, req.InvalidURL, 0, "", "Unable to parse URL") req.CheckRequester(creds, url, receiver) // --- URL helper --- diff --git a/github_rest_api/_test_result_receivers.pony b/github_rest_api/_test_result_receivers.pony index d52b6ad..7c844e9 100644 --- a/github_rest_api/_test_result_receivers.pony +++ b/github_rest_api/_test_result_receivers.pony @@ -46,12 +46,13 @@ class \nodoc\ _TestDeletedResultReceiverFailure is UnitTest h.assert_eq[U16](404, e.status) h.assert_eq[String]( "not found", e.response_body) - h.assert_eq[String]("msg", e.message) + h.assert_eq[String]("", e.message) + h.assert_true(e.reason is req.UnexpectedStatus) h.complete(true) end }) let receiver = req.DeletedResultReceiver(p) - receiver.failure(404, "not found", "msg") + receiver.failure(req.RequestError.unexpected_status(404, "not found")) class \nodoc\ _TestBoolResultReceiverSuccessTrue is UnitTest fun name(): String => @@ -117,14 +118,14 @@ class \nodoc\ _TestBoolResultReceiverFailure is UnitTest h.assert_eq[U16](422, e.status) h.assert_eq[String]( "unprocessable", e.response_body) - h.assert_eq[String]( - "validation failed", e.message) + h.assert_eq[String]("", e.message) + h.assert_true(e.reason is req.UnexpectedStatus) h.complete(true) end }) let receiver = req.BoolResultReceiver(p) receiver.failure( - 422, "unprocessable", "validation failed") + req.RequestError.unexpected_status(422, "unprocessable")) class \nodoc\ _TestResultReceiverSuccess is UnitTest fun name(): String => @@ -174,6 +175,7 @@ class \nodoc\ _TestResultReceiverConverterError is UnitTest h.assert_eq[String]("", e.response_body) h.assert_eq[String]( "Unable to convert json response", e.message) + h.assert_true(e.reason is req.ConversionFailed) h.assert_false( e.message.contains("private-body"), "message copies the response: " + e.message) @@ -207,8 +209,8 @@ class \nodoc\ _TestResultReceiverFailure is UnitTest h.assert_eq[U16](500, e.status) h.assert_eq[String]( "server error", e.response_body) - h.assert_eq[String]( - "internal", e.message) + h.assert_eq[String]("", e.message) + h.assert_true(e.reason is req.UnexpectedStatus) h.complete(true) end }) @@ -219,7 +221,7 @@ class \nodoc\ _TestResultReceiverFailure is UnitTest req.ResultReceiver[String]( creds, p, _TestStringConverter) receiver.failure( - 500, "server error", "internal") + req.RequestError.unexpected_status(500, "server error")) class \nodoc\ _TestPaginatedResultReceiverSuccess is UnitTest fun name(): String => @@ -291,6 +293,7 @@ class \nodoc\ _TestPaginatedResultReceiverConverterError is UnitTest h.assert_eq[String]("", e.response_body) h.assert_eq[String]( "Unable to convert json response", e.message) + h.assert_true(e.reason is req.ConversionFailed) h.assert_false( e.message.contains("private-body"), "message copies the response: " + e.message) @@ -336,6 +339,7 @@ class \nodoc\ _TestPaginatedResultReceiverNotAnArray is UnitTest h.assert_eq[String]("", e.response_body) h.assert_eq[String]( "Unable to convert json response", e.message) + h.assert_true(e.reason is req.ConversionFailed) h.assert_false( e.message.contains("private-body"), "message copies the response: " + e.message) @@ -378,8 +382,8 @@ class \nodoc\ _TestPaginatedResultReceiverFailure is UnitTest h.assert_eq[U16](403, e.status) h.assert_eq[String]( "forbidden", e.response_body) - h.assert_eq[String]( - "auth failed", e.message) + h.assert_eq[String]("", e.message) + h.assert_true(e.reason is req.UnexpectedStatus) h.complete(true) end }) @@ -393,7 +397,7 @@ class \nodoc\ _TestPaginatedResultReceiverFailure is UnitTest PaginatedResultReceiver[String]( creds, p, converter) receiver.failure( - 403, "forbidden", "auth failed") + req.RequestError.unexpected_status(403, "forbidden")) class \nodoc\ _TestSearchResultReceiverSuccess is UnitTest fun name(): String => @@ -470,6 +474,7 @@ class \nodoc\ _TestSearchResultReceiverConverterError is UnitTest h.assert_eq[String]("", e.response_body) h.assert_eq[String]( "Unable to convert json response", e.message) + h.assert_true(e.reason is req.ConversionFailed) h.assert_false( e.message.contains("private-body"), "message copies the response: " + e.message) @@ -512,8 +517,8 @@ class \nodoc\ _TestSearchResultReceiverFailure is UnitTest h.assert_eq[U16](401, e.status) h.assert_eq[String]( "unauthorized", e.response_body) - h.assert_eq[String]( - "bad token", e.message) + h.assert_eq[String]("", e.message) + h.assert_true(e.reason is req.UnexpectedStatus) h.complete(true) end }) @@ -527,4 +532,4 @@ class \nodoc\ _TestSearchResultReceiverFailure is UnitTest SearchResultReceiver[String]( creds, p, converter) receiver.failure( - 401, "unauthorized", "bad token") + req.RequestError.unexpected_status(401, "unauthorized")) diff --git a/github_rest_api/_test_tls_verification.pony b/github_rest_api/_test_tls_verification.pony index 2b1092a..025eb38 100644 --- a/github_rest_api/_test_tls_verification.pony +++ b/github_rest_api/_test_tls_verification.pony @@ -26,10 +26,11 @@ actor \nodoc\ _TestSSLRejectedDeleteReceiver is req.DeleteResultReceiver _h.fail("Expected an SSL handshake failure, got success") _h.complete(false) - be failure(status: U16, response_body: String, message: String) => - _h.assert_eq[U16](0, status) - _h.assert_eq[String]("", response_body) - _h.assert_eq[String]("SSL handshake failed", message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is ConnectionFailedSSL, "wrong reason") + _h.assert_eq[U16](0, err.status) + _h.assert_eq[String]("", err.response_body) + _h.assert_eq[String]("SSL handshake failed", err.message) _h.complete(true) actor \nodoc\ _TestSSLRejectedCheckReceiver is req.CheckResultReceiver @@ -42,10 +43,11 @@ actor \nodoc\ _TestSSLRejectedCheckReceiver is req.CheckResultReceiver _h.fail("Expected an SSL handshake failure, got success") _h.complete(false) - be failure(status: U16, response_body: String, message: String) => - _h.assert_eq[U16](0, status) - _h.assert_eq[String]("", response_body) - _h.assert_eq[String]("SSL handshake failed", message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is ConnectionFailedSSL, "wrong reason") + _h.assert_eq[U16](0, err.status) + _h.assert_eq[String]("", err.response_body) + _h.assert_eq[String]("SSL handshake failed", err.message) _h.complete(true) actor \nodoc\ _TestSSLRejectedLinkedReceiver is req.LinkedResultReceiver @@ -58,10 +60,11 @@ actor \nodoc\ _TestSSLRejectedLinkedReceiver is req.LinkedResultReceiver _h.fail("Expected an SSL handshake failure, got success") _h.complete(false) - be failure(status: U16, response_body: String, message: String) => - _h.assert_eq[U16](0, status) - _h.assert_eq[String]("", response_body) - _h.assert_eq[String]("SSL handshake failed", message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is ConnectionFailedSSL, "wrong reason") + _h.assert_eq[U16](0, err.status) + _h.assert_eq[String]("", err.response_body) + _h.assert_eq[String]("SSL handshake failed", err.message) _h.complete(true) class \nodoc\ _TestDefaultSSLJSONRequesterRejectsUntrustedCert is UnitTest @@ -74,7 +77,9 @@ class \nodoc\ _TestDefaultSSLJSONRequesterRejectsUntrustedCert is UnitTest let url = _TestURL(_TestHost(), port, "/tls") let creds = req.Credentials(TCPConnectAuth(h.env.root), _TestToken("test-token")?) - let receiver = _TestJSONFailureReceiver(h, 0, "", "SSL handshake failed") + let receiver = + _TestJSONFailureReceiver( + h, ConnectionFailedSSL, 0, "", "SSL handshake failed") let body = """{"greeting":"hello"}""" let responder = _TestUnverifiedRequestResponder( @@ -190,10 +195,11 @@ actor \nodoc\ _TestSSLRejectedMultiJSONReceiver _h.fail("Expected an SSL handshake failure, got success") _h.complete(false) - be failure(status: U16, response_body: String, message: String) => - _h.assert_eq[U16](0, status) - _h.assert_eq[String]("", response_body) - _h.assert_eq[String]("SSL handshake failed", message) + be failure(err: req.RequestError) => + _h.assert_true(err.reason is ConnectionFailedSSL, "wrong reason") + _h.assert_eq[U16](0, err.status) + _h.assert_eq[String]("", err.response_body) + _h.assert_eq[String]("SSL handshake failed", err.message) _failures = _failures + 1 if _failures == _expected then _h.complete(true) @@ -261,8 +267,8 @@ actor \nodoc\ _TestDefaultSSLGitHubReceiver is req.JSONRequesterResultReceiver be success(json: JSONNav) => _h.complete(true) - be failure(status: U16, response_body: String, message: String) => + be failure(err: req.RequestError) => _h.fail( - "Request to api.github.com failed: status=" + status.string() + - " message=" + message + " body=" + response_body) + "Request to api.github.com failed: status=" + err.status.string() + + " message=" + err.message + " body=" + err.response_body) _h.complete(false) diff --git a/github_rest_api/commit.pony b/github_rest_api/commit.pony index dd3484f..5afd745 100644 --- a/github_rest_api/commit.pony +++ b/github_rest_api/commit.pony @@ -62,7 +62,7 @@ primitive GetCommit by_url(u, creds) | let e: ut.URITemplateParseError => Promise[CommitOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( diff --git a/github_rest_api/gist.pony b/github_rest_api/gist.pony index 53792c6..bf51d70 100644 --- a/github_rest_api/gist.pony +++ b/github_rest_api/gist.pony @@ -186,7 +186,7 @@ primitive GetGist by_url(u, creds) | let e: ut.URITemplateParseError => Promise[GistOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -292,7 +292,7 @@ primitive UpdateGist by_url(u, files, creds, description) | let e: ut.URITemplateParseError => Promise[GistOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -364,7 +364,7 @@ primitive DeleteGist by_url(u, creds) | let e: ut.URITemplateParseError => Promise[req.DeletedOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -452,7 +452,7 @@ primitive GetUsernameGists | let e: ut.URITemplateParseError => Promise[(PaginatedList[Gist] | req.RequestError)] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end primitive GetGistRevision @@ -480,7 +480,7 @@ primitive GetGistRevision GetGist.by_url(u, creds) | let e: ut.URITemplateParseError => Promise[GistOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end primitive ForkGist @@ -505,7 +505,7 @@ primitive ForkGist by_url(u, creds) | let e: ut.URITemplateParseError => Promise[GistOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -547,7 +547,7 @@ primitive GetGistForks | let e: ut.URITemplateParseError => Promise[(PaginatedList[Gist] | req.RequestError)] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end primitive GetGistCommits @@ -575,7 +575,7 @@ primitive GetGistCommits | let e: ut.URITemplateParseError => Promise[(PaginatedList[GistCommit] | req.RequestError)] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -619,7 +619,7 @@ primitive StarGist by_url(u, creds) | let e: ut.URITemplateParseError => Promise[req.DeletedOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -656,7 +656,7 @@ primitive UnstarGist by_url(u, creds) | let e: ut.URITemplateParseError => Promise[req.DeletedOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -694,7 +694,7 @@ primitive CheckGistStar by_url(u, creds) | let e: ut.URITemplateParseError => Promise[req.BoolOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, diff --git a/github_rest_api/gist_comment.pony b/github_rest_api/gist_comment.pony index 47c2126..630b1f0 100644 --- a/github_rest_api/gist_comment.pony +++ b/github_rest_api/gist_comment.pony @@ -78,7 +78,7 @@ primitive GetGistComment by_url(u, creds) | let e: ut.URITemplateParseError => Promise[GistCommentOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -122,7 +122,7 @@ primitive GetGistComments | let e: ut.URITemplateParseError => Promise[(PaginatedList[GistComment] | req.RequestError)] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -167,7 +167,7 @@ primitive CreateGistComment by_url(u, body, creds) | let e: ut.URITemplateParseError => Promise[GistCommentOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -215,7 +215,7 @@ primitive UpdateGistComment by_url(u, body, creds) | let e: ut.URITemplateParseError => Promise[GistCommentOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, @@ -261,7 +261,7 @@ primitive DeleteGistComment by_url(u, creds) | let e: ut.URITemplateParseError => Promise[req.DeletedOrError] .> apply( - req.RequestError(where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url(url: String, diff --git a/github_rest_api/issue.pony b/github_rest_api/issue.pony index 4f78bc1..76aa48d 100644 --- a/github_rest_api/issue.pony +++ b/github_rest_api/issue.pony @@ -200,8 +200,7 @@ primitive GetIssue by_url(u, creds) | let e: ut.URITemplateParseError => Promise[IssueOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( @@ -339,8 +338,7 @@ primitive GetRepositoryIssues Promise[ (PaginatedList[Issue] | req.RequestError) ] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( diff --git a/github_rest_api/issue_comment.pony b/github_rest_api/issue_comment.pony index 972c3a4..db7e087 100644 --- a/github_rest_api/issue_comment.pony +++ b/github_rest_api/issue_comment.pony @@ -60,8 +60,7 @@ primitive CreateIssueComment by_url(u', comment, creds) | let e: ut.URITemplateParseError => Promise[IssueCommentOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( @@ -110,8 +109,7 @@ primitive GetIssueComments by_url(u', creds) | let e: ut.URITemplateParseError => Promise[IssueCommentsOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( diff --git a/github_rest_api/label.pony b/github_rest_api/label.pony index f9307aa..ef06b9a 100644 --- a/github_rest_api/label.pony +++ b/github_rest_api/label.pony @@ -80,8 +80,7 @@ primitive CreateLabel by_url(u, name, creds, color, description) | let e: ut.URITemplateParseError => Promise[LabelOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( @@ -146,8 +145,7 @@ primitive DeleteLabel by_url(u, name, creds) | let e: ut.URITemplateParseError => Promise[req.DeletedOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( diff --git a/github_rest_api/paginated_list.pony b/github_rest_api/paginated_list.pony index 6ccf411..5e94e71 100644 --- a/github_rest_api/paginated_list.pony +++ b/github_rest_api/paginated_list.pony @@ -46,7 +46,7 @@ class val PaginatedList[A: Any val] package, such as `https://api.github.com/repositories/1/issues?page=2`. For any other target, such as a relative one, it opens no connection, and - the Promise resolves to `RequestError(0, "", "Unable to parse URL")`. + the Promise resolves to a `RequestError` whose `reason` is `InvalidURL`. """ match \exhaustive\ _prev_link | let prev: String => @@ -72,7 +72,7 @@ class val PaginatedList[A: Any val] package, such as `https://api.github.com/repositories/1/issues?page=2`. For any other target, such as a relative one, it opens no connection, and - the Promise resolves to `RequestError(0, "", "Unable to parse URL")`. + the Promise resolves to a `RequestError` whose `reason` is `InvalidURL`. """ match \exhaustive\ _next_link | let next: String => @@ -156,12 +156,8 @@ actor PaginatedResultReceiver[A: Any val] try _p(_converter(json, link_header, _creds)?) else - _p(req.RequestError(where message' = "Unable to convert json response")) + _p(req.RequestError.conversion_failed()) end - be failure( - status: U16, - response_body: String, - message: String) - => - _p(req.RequestError(status, response_body, message)) + be failure(err: req.RequestError) => + _p(err) diff --git a/github_rest_api/pull_request.pony b/github_rest_api/pull_request.pony index c7e4bdf..06c269d 100644 --- a/github_rest_api/pull_request.pony +++ b/github_rest_api/pull_request.pony @@ -83,8 +83,7 @@ primitive GetPullRequest by_url(u, creds) | let e: ut.URITemplateParseError => Promise[PullRequestOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( diff --git a/github_rest_api/pull_request_file.pony b/github_rest_api/pull_request_file.pony index 9c082c6..dd125c9 100644 --- a/github_rest_api/pull_request_file.pony +++ b/github_rest_api/pull_request_file.pony @@ -50,8 +50,7 @@ primitive GetPullRequestFiles by_url(u, creds) | let e: ut.URITemplateParseError => Promise[PullRequestFilesOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( diff --git a/github_rest_api/release.pony b/github_rest_api/release.pony index 3c06c8d..0c6a114 100644 --- a/github_rest_api/release.pony +++ b/github_rest_api/release.pony @@ -134,8 +134,7 @@ primitive CreateRelease prerelease) | let e: ut.URITemplateParseError => Promise[ReleaseOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( diff --git a/github_rest_api/repository.pony b/github_rest_api/repository.pony index 5ee9e42..26b95d5 100644 --- a/github_rest_api/repository.pony +++ b/github_rest_api/repository.pony @@ -258,8 +258,7 @@ class val Repository label_description) | let e: ut.URITemplateParseError => Promise[LabelOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun create_release( @@ -288,8 +287,7 @@ class val Repository prerelease) | let e: ut.URITemplateParseError => Promise[ReleaseOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun delete_label(label_name: String) @@ -306,8 +304,7 @@ class val Repository DeleteLabel.by_url(u, label_name, _creds) | let e: ut.URITemplateParseError => Promise[req.DeletedOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun get_commit(sha: String): Promise[CommitOrError] => @@ -322,8 +319,7 @@ class val Repository GetCommit.by_url(u, _creds) | let e: ut.URITemplateParseError => Promise[CommitOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun get_issue(number: I64): Promise[IssueOrError] => @@ -338,8 +334,7 @@ class val Repository GetIssue.by_url(u, _creds) | let e: ut.URITemplateParseError => Promise[IssueOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun get_issues( @@ -389,8 +384,7 @@ class val Repository | let e: ut.URITemplateParseError => Promise[(PaginatedList[Issue] | req.RequestError)] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun get_pull_request(number: I64) @@ -408,8 +402,7 @@ class val Repository GetPullRequest.by_url(u, _creds) | let e: ut.URITemplateParseError => Promise[PullRequestOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end primitive GetRepository @@ -444,8 +437,7 @@ primitive GetRepository by_url(u, creds) | let e: ut.URITemplateParseError => Promise[RepositoryOrError] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( @@ -500,8 +492,7 @@ primitive GetRepositoryLabels | let e: ut.URITemplateParseError => Promise[(PaginatedList[Label] | req.RequestError)] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( @@ -555,8 +546,7 @@ primitive GetOrganizationRepositories Promise[ (PaginatedList[Repository] | req.RequestError)] .> apply( - req.RequestError( - where message' = e.message)) + req.RequestError.invalid_url(e.message)) end fun by_url( diff --git a/github_rest_api/request/_redirect_origin.pony b/github_rest_api/request/_redirect_origin.pony index 379905d..970c4b0 100644 --- a/github_rest_api/request/_redirect_origin.pony +++ b/github_rest_api/request/_redirect_origin.pony @@ -45,7 +45,7 @@ class val _FollowRedirect url = url' remaining = remaining' -class val _RedirectRefused +class val _RefusedRedirect """ Failure returned when a redirect has an invalid `Location`, crosses origins, or exceeds the redirect hop limit. @@ -62,63 +62,63 @@ primitive _ResolveRedirect resolved URI uses http or https with a non-empty host, stays on `origin`, and has no userinfo, and that `remaining_hops` is greater than zero. Returns `_FollowRedirect` with the resolved URL and decremented hop budget, or - `_RedirectRefused`. + `_RefusedRedirect`. """ fun apply( origin: http_client.Origin, request_path: String, location: String, remaining_hops: USize) - : (_FollowRedirect | _RedirectRefused) + : (_FollowRedirect | _RefusedRedirect) => if _HasControlOrWhitespace(location) then - return _RedirectRefused("Invalid redirect Location: " + location) + return _RefusedRedirect("Invalid redirect Location: " + location) end let base = match \exhaustive\ uri.ParseURI(origin.string() + request_path) | let u: uri.URI val => u | let _: uri.URIParseError val => - return _RedirectRefused("Invalid redirect Location: " + location) + return _RefusedRedirect("Invalid redirect Location: " + location) end let reference = match \exhaustive\ uri.ParseURI(location) | let u: uri.URI val => u | let _: uri.URIParseError val => - return _RedirectRefused("Invalid redirect Location: " + location) + return _RefusedRedirect("Invalid redirect Location: " + location) end let resolved = match \exhaustive\ uri.ResolveURI(base, reference) | let u: uri.URI val => u | let _: uri.ResolveURIError val => - return _RedirectRefused("Invalid redirect Location: " + location) + return _RefusedRedirect("Invalid redirect Location: " + location) end match \exhaustive\ resolved.scheme | let s: String => let lower = s.lower() if (lower != "http") and (lower != "https") then - return _RedirectRefused("Invalid redirect Location: " + location) + return _RefusedRedirect("Invalid redirect Location: " + location) end | None => - return _RedirectRefused("Invalid redirect Location: " + location) + return _RefusedRedirect("Invalid redirect Location: " + location) end let auth = match \exhaustive\ resolved.authority | let a: uri.URIAuthority => a | None => - return _RedirectRefused("Invalid redirect Location: " + location) + return _RefusedRedirect("Invalid redirect Location: " + location) end let target = http_client.Origin.from_uri(resolved) if target.host.size() == 0 then - return _RedirectRefused("Invalid redirect Location: " + location) + return _RefusedRedirect("Invalid redirect Location: " + location) end if target != origin then - return _RedirectRefused( + return _RefusedRedirect( "Refused redirect to a different origin: " + target.string()) end if not (auth.userinfo is None) then - return _RedirectRefused("Invalid redirect Location: " + location) + return _RefusedRedirect("Invalid redirect Location: " + location) end if remaining_hops == 0 then - return _RedirectRefused("Too many redirects") + return _RefusedRedirect("Too many redirects") end _FollowRedirect(resolved.string(), remaining_hops - 1) diff --git a/github_rest_api/request/_test.pony b/github_rest_api/request/_test.pony index 1feb899..baa8372 100644 --- a/github_rest_api/request/_test.pony +++ b/github_rest_api/request/_test.pony @@ -55,6 +55,7 @@ actor \nodoc\ Main is TestList test(_TestDefaultConnectionTimeout) test(_TestConnectionTimeoutStalledHandshake) test(_TestConnectionFailureMessage) + test(_TestRequestErrorConstructors) class \nodoc\ _TestQueryParamsEmpty is UnitTest fun name(): String => "request/query-params/empty" diff --git a/github_rest_api/request/_test_redirect_origin.pony b/github_rest_api/request/_test_redirect_origin.pony index c3d42b6..b1d5fec 100644 --- a/github_rest_api/request/_test_redirect_origin.pony +++ b/github_rest_api/request/_test_redirect_origin.pony @@ -12,7 +12,7 @@ primitive \nodoc\ _TestAuthority primitive \nodoc\ _AssertFollow fun apply( h: TestHelper, - result: (_FollowRedirect | _RedirectRefused), + result: (_FollowRedirect | _RefusedRedirect), expected_url: String, expected_remaining: USize) => @@ -20,20 +20,20 @@ primitive \nodoc\ _AssertFollow | let next: _FollowRedirect => h.assert_eq[String](expected_url, next.url) h.assert_eq[USize](expected_remaining, next.remaining) - | let err: _RedirectRefused => + | let err: _RefusedRedirect => h.fail("Expected _FollowRedirect, got refusal: " + err.message) end primitive \nodoc\ _AssertRefused fun apply( h: TestHelper, - result: (_FollowRedirect | _RedirectRefused), + result: (_FollowRedirect | _RefusedRedirect), expected_message: String) => match \exhaustive\ result | let next: _FollowRedirect => - h.fail("Expected _RedirectRefused, got follow: " + next.url) - | let err: _RedirectRefused => + h.fail("Expected _RefusedRedirect, got follow: " + next.url) + | let err: _RefusedRedirect => h.assert_eq[String](expected_message, err.message) end @@ -179,7 +179,7 @@ class \nodoc\ iso _TestResolveRedirectFollowedURLParses is UnitTest | let e: _InvalidRequestURL => h.fail("Followed " + location + " but " + e.message) end - | let err: _RedirectRefused => + | let err: _RefusedRedirect => h.fail("Expected to follow " + location + ", got: " + err.message) end end @@ -325,7 +325,7 @@ class \nodoc\ iso _TestResolveRedirectRelativeProperty is UnitTest | let err: _InvalidRequestURL => h.fail("Resolved URL failed _ParseRequestURL: " + err.message) end - | let err: _RedirectRefused => + | let err: _RefusedRedirect => h.fail("Expected follow for " + location + ", got: " + err.message) end end @@ -357,7 +357,7 @@ class \nodoc\ iso _TestResolveRedirectCrossOriginPortProperty is UnitTest match \exhaustive\ _ResolveRedirect(origin, "/start", location, hops) | let next: _FollowRedirect => h.fail("Expected refusal for " + location + ", got: " + next.url) - | let err: _RedirectRefused => + | let err: _RefusedRedirect => h.assert_eq[String](expected, err.message) end })? diff --git a/github_rest_api/request/_test_request_error.pony b/github_rest_api/request/_test_request_error.pony new file mode 100644 index 0000000..07ef150 --- /dev/null +++ b/github_rest_api/request/_test_request_error.pony @@ -0,0 +1,47 @@ +use "net" +use "pony_test" + +primitive \nodoc\ _TestRequestErrorFields + """ + Checks every field of `err`. + """ + fun apply( + h: TestHelper, + err: RequestError, + reason: RequestFailureReason, + status: U16, + response_body: String, + message: String) + => + h.assert_true(err.reason is reason, "wrong reason") + h.assert_eq[U16](status, err.status) + h.assert_eq[String](response_body, err.response_body) + h.assert_eq[String](message, err.message) + +class \nodoc\ _TestRequestErrorConstructors is UnitTest + fun name(): String => "request/request-error/constructors" + + fun ref apply(h: TestHelper) => + _TestRequestErrorFields(h, RequestError.connection_failed( + ConnectionFailedTimeout), ConnectionFailedTimeout, 0, "", + "Connection timed out") + _TestRequestErrorFields(h, RequestError.connection_failed( + ConnectionFailedSSL), ConnectionFailedSSL, 0, "", + "SSL handshake failed") + _TestRequestErrorFields(h, RequestError.invalid_url("bad"), + InvalidURL, 0, "", "bad") + _TestRequestErrorFields(h, RequestError.request_not_sent(), + RequestNotSent, 0, "", "Failed to send request") + _TestRequestErrorFields(h, RequestError.connection_closed_early(), + ConnectionClosedEarly, 0, "", + "Connection closed before response completed") + _TestRequestErrorFields(h, RequestError.invalid_http_response(), + InvalidHTTPResponse, 0, "", "HTTP parse error") + _TestRequestErrorFields(h, RequestError.unexpected_status(404, "gone"), + UnexpectedStatus, 404, "gone", "") + _TestRequestErrorFields(h, RequestError.redirect_refused(301, "why"), + RedirectRefused, 301, "", "why") + _TestRequestErrorFields(h, RequestError.invalid_json(200), + InvalidJSON, 200, "", "Failed to parse response") + _TestRequestErrorFields(h, RequestError.conversion_failed(), + ConversionFailed, 0, "", "Unable to convert json response") diff --git a/github_rest_api/request/check_requester.pony b/github_rest_api/request/check_requester.pony index 2b7de51..609575e 100644 --- a/github_rest_api/request/check_requester.pony +++ b/github_rest_api/request/check_requester.pony @@ -9,7 +9,7 @@ interface tag CheckResultReceiver their answer via status code rather than a response body. """ be success(value: Bool) - be failure(status: U16, response_body: String, message: String) + be failure(err: RequestError) type BoolOrError is (Bool | RequestError) @@ -26,8 +26,8 @@ actor BoolResultReceiver be success(value: Bool) => _p(value) - be failure(status: U16, response_body: String, message: String) => - _p(RequestError(status, response_body, message)) + be failure(err: RequestError) => + _p(err) actor CheckRequester is http_client.HTTPClientConnectionActor """ @@ -42,6 +42,7 @@ actor CheckRequester is http_client.HTTPClientConnectionActor let _receiver: CheckResultReceiver var _request_path: String = "" var _done: Bool = false + var _sent: Bool = false var _status: U16 = 0 new create(creds: Credentials, @@ -76,17 +77,21 @@ actor CheckRequester is http_client.HTTPClientConnectionActor _request_path, consume hdrs) match \exhaustive\ _http.send_request(request) - | http_client.SendRequestOK => None + | http_client.SendRequestOK => + // After a write error, on_closed can run inside send_request and still + // be followed by SendRequestOK. It then reads _sent as false and reports + // RequestNotSent; _done makes this assignment harmless. + _sent = true | http_client.ConnectionClosed => if not _done then _done = true - _receiver.failure(0, "", "Connection closed before response completed") + _receiver.failure(RequestError.request_not_sent()) end | http_client.ResponsePending => if not _done then _done = true _http.close() - _receiver.failure(0, "", "Failed to send request") + _receiver.failure(RequestError.request_not_sent()) end end @@ -112,27 +117,32 @@ actor CheckRequester is http_client.HTTPClientConnectionActor try let response = _collector.build()? let body_str = String.from_array(response.body) - _receiver.failure(_status, consume body_str, "") + _receiver.failure( + RequestError.unexpected_status(_status, consume body_str)) else - _receiver.failure(_status, "", "") + _receiver.failure(RequestError.invalid_http_response()) end end fun ref on_connection_failure(reason: ConnectionFailureReason) => if _done then return end _done = true - _receiver.failure(0, "", _ConnectionFailureMessage(reason)) + _receiver.failure(RequestError.connection_failed(reason)) fun ref on_parse_error(err: http_client.ParseError) => if _done then return end _done = true _http.close() - _receiver.failure(0, "", "HTTP parse error") + _receiver.failure(RequestError.invalid_http_response()) fun ref on_closed() => if _done then return end _done = true - _receiver.failure(0, "", "Connection closed before response completed") + if _sent then + _receiver.failure(RequestError.connection_closed_early()) + else + _receiver.failure(RequestError.request_not_sent()) + end be _fail(message: String) => - _receiver.failure(0, "", message) + _receiver.failure(RequestError.invalid_url(message)) diff --git a/github_rest_api/request/credentials.pony b/github_rest_api/request/credentials.pony index d40e668..f3a8557 100644 --- a/github_rest_api/request/credentials.pony +++ b/github_rest_api/request/credentials.pony @@ -97,8 +97,8 @@ actor ResultReceiver[A: Any val] try _p(_converter(json, _creds)?) else - _p(RequestError(where message' = "Unable to convert json response")) + _p(RequestError.conversion_failed()) end - be failure(status: U16, response_body: String, message: String) => - _p(RequestError(status, response_body, message)) + be failure(err: RequestError) => + _p(err) diff --git a/github_rest_api/request/json.pony b/github_rest_api/request/json.pony index 39b9907..af42c82 100644 --- a/github_rest_api/request/json.pony +++ b/github_rest_api/request/json.pony @@ -14,7 +14,7 @@ interface val JSONConverter[A: Any #share] Raises an error when `json` lacks a field the value needs or a field has the wrong JSON type. When the converter an operation uses raises, the - request fails with a `RequestError` whose `status` is `0`. + request fails with a `RequestError` whose `reason` is `ConversionFailed`. """ primitive JSONTypeString diff --git a/github_rest_api/request/json_requester.pony b/github_rest_api/request/json_requester.pony index ce17299..6df6561 100644 --- a/github_rest_api/request/json_requester.pony +++ b/github_rest_api/request/json_requester.pony @@ -5,10 +5,10 @@ use "net" interface tag JSONRequesterResultReceiver """ Receives the result of a JSON API request: either a parsed JSON response - on success, or status/body/message details on failure. + on success, or a `RequestError` on failure. """ be success(json: JSONNav) - be failure(status: U16, response_body: String, message: String) + be failure(err: RequestError) actor JSONRequester is http_client.HTTPClientConnectionActor """ @@ -20,10 +20,9 @@ actor JSONRequester is http_client.HTTPClientConnectionActor reports them as failures. The requester resolves relative `Location` values against the request URL. If a redirect crosses origins, has an invalid `Location`, or exceeds the 5-redirect limit, the requester stops and reports - a failure with the redirect's status, an empty body, and an error message. On - success, the requester parses the response body as JSON and delivers it to - the receiver; on failure, the requester delivers the status code, raw - response body, and an error message. + a `RedirectRefused` failure. On success, the requester parses the response + body as JSON and delivers it to the receiver; on failure, it delivers a + `RequestError`. """ var _http: http_client.HTTPClientConnection = http_client.HTTPClientConnection.none() var _collector: http_client.ResponseCollector = http_client.ResponseCollector @@ -35,6 +34,7 @@ actor JSONRequester is http_client.HTTPClientConnectionActor let _remaining_redirects: USize var _request_path: String = "" var _done: Bool = false + var _sent: Bool = false var _origin: http_client.Origin = http_client.Origin(true, "", "443") var _status: U16 = 0 @@ -132,17 +132,21 @@ actor JSONRequester is http_client.HTTPClientConnectionActor | None => None end) match \exhaustive\ _http.send_request(request) - | http_client.SendRequestOK => None + | http_client.SendRequestOK => + // After a write error, on_closed can run inside send_request and still + // be followed by SendRequestOK. It then reads _sent as false and reports + // RequestNotSent; _done makes this assignment harmless. + _sent = true | http_client.ConnectionClosed => if not _done then _done = true - _receiver.failure(0, "", "Connection closed before response completed") + _receiver.failure(RequestError.request_not_sent()) end | http_client.ResponsePending => if not _done then _done = true _http.close() - _receiver.failure(0, "", "Failed to send request") + _receiver.failure(RequestError.request_not_sent()) end end @@ -165,8 +169,9 @@ actor JSONRequester is http_client.HTTPClientConnectionActor _body, _receiver, next.remaining) - | let refused: _RedirectRefused => - _receiver.failure(_status, "", refused.message) + | let refused: _RefusedRedirect => + _receiver.failure( + RequestError.redirect_refused(_status, refused.message)) end return end @@ -189,31 +194,36 @@ actor JSONRequester is http_client.HTTPClientConnectionActor | let json: JSONValue => _receiver.success(JSONNav(json)) | let _: JSONParseError => - _receiver.failure(_status, "", "Failed to parse response") + _receiver.failure(RequestError.invalid_json(_status)) end else let body_str = String.from_array(response.body) - _receiver.failure(_status, consume body_str, "") + _receiver.failure( + RequestError.unexpected_status(_status, consume body_str)) end else - _receiver.failure(0, "", "Failed to build response") + _receiver.failure(RequestError.invalid_http_response()) end fun ref on_connection_failure(reason: ConnectionFailureReason) => if _done then return end _done = true - _receiver.failure(0, "", _ConnectionFailureMessage(reason)) + _receiver.failure(RequestError.connection_failed(reason)) fun ref on_parse_error(err: http_client.ParseError) => if _done then return end _done = true _http.close() - _receiver.failure(0, "", "HTTP parse error") + _receiver.failure(RequestError.invalid_http_response()) fun ref on_closed() => if _done then return end _done = true - _receiver.failure(0, "", "Connection closed before response completed") + if _sent then + _receiver.failure(RequestError.connection_closed_early()) + else + _receiver.failure(RequestError.request_not_sent()) + end be _fail(message: String) => - _receiver.failure(0, "", message) + _receiver.failure(RequestError.invalid_url(message)) diff --git a/github_rest_api/request/linked_json_requester.pony b/github_rest_api/request/linked_json_requester.pony index 15b041c..4538e78 100644 --- a/github_rest_api/request/linked_json_requester.pony +++ b/github_rest_api/request/linked_json_requester.pony @@ -9,8 +9,8 @@ actor LinkedJSONRequester header to a `LinkedResultReceiver`. Follows up to 5 same-origin 301, 302, 307, or 308 redirects, resolving relative `Location` values against the request URL. If a redirect crosses origins, has an invalid `Location`, or - exceeds the 5-redirect limit, the requester stops and reports a failure with - the redirect's status, an empty body, and an error message. + exceeds the 5-redirect limit, the requester stops and reports a + `RedirectRefused` failure. """ var _http: http_client.HTTPClientConnection = http_client.HTTPClientConnection.none() @@ -21,6 +21,7 @@ actor LinkedJSONRequester let _remaining_redirects: USize var _request_path: String = "" var _done: Bool = false + var _sent: Bool = false var _origin: http_client.Origin = http_client.Origin(true, "", "443") var _status: U16 = 0 var _link_header: String = "" @@ -68,8 +69,8 @@ actor LinkedJSONRequester fun ref on_connected() => """ - Sends the GET request, or reports a status-0 failure to the receiver if - sending fails. + Sends the GET request, or reports a `RequestNotSent` failure to the + receiver if the request cannot be sent. """ if _done then return end let hdrs = _GitHubRequestHeaders(_creds) @@ -79,17 +80,21 @@ actor LinkedJSONRequester _request_path, consume hdrs) match \exhaustive\ _http.send_request(request) - | http_client.SendRequestOK => None + | http_client.SendRequestOK => + // After a write error, on_closed can run inside send_request and still + // be followed by SendRequestOK. It then reads _sent as false and reports + // RequestNotSent; _done makes this assignment harmless. + _sent = true | http_client.ConnectionClosed => if not _done then _done = true - _receiver.failure(0, "", "Connection closed before response completed") + _receiver.failure(RequestError.request_not_sent()) end | http_client.ResponsePending => if not _done then _done = true _http.close() - _receiver.failure(0, "", "Failed to send request") + _receiver.failure(RequestError.request_not_sent()) end end @@ -118,8 +123,9 @@ actor LinkedJSONRequester | let next: _FollowRedirect => LinkedJSONRequester._redirect( _creds, next.url, _receiver, next.remaining) - | let refused: _RedirectRefused => - _receiver.failure(_status, "", refused.message) + | let refused: _RefusedRedirect => + _receiver.failure( + RequestError.redirect_refused(_status, refused.message)) end return end @@ -145,35 +151,37 @@ actor LinkedJSONRequester _receiver.success( JSONNav(json), _link_header) | let _: JSONParseError => - _receiver.failure( - _status, "", "Failed to parse response") + _receiver.failure(RequestError.invalid_json(_status)) end else let body_str = String.from_array(response.body) _receiver.failure( - _status, consume body_str, "") + RequestError.unexpected_status(_status, consume body_str)) end else - _receiver.failure( - 0, "", "Failed to build response") + _receiver.failure(RequestError.invalid_http_response()) end fun ref on_connection_failure(reason: ConnectionFailureReason) => if _done then return end _done = true - _receiver.failure(0, "", _ConnectionFailureMessage(reason)) + _receiver.failure(RequestError.connection_failed(reason)) fun ref on_parse_error(err: http_client.ParseError) => if _done then return end _done = true _http.close() - _receiver.failure(0, "", "HTTP parse error") + _receiver.failure(RequestError.invalid_http_response()) fun ref on_closed() => if _done then return end _done = true - _receiver.failure(0, "", "Connection closed before response completed") + if _sent then + _receiver.failure(RequestError.connection_closed_early()) + else + _receiver.failure(RequestError.request_not_sent()) + end be _fail(message: String) => - _receiver.failure(0, "", message) + _receiver.failure(RequestError.invalid_url(message)) diff --git a/github_rest_api/request/linked_result_receiver.pony b/github_rest_api/request/linked_result_receiver.pony index 00444c7..a237a2b 100644 --- a/github_rest_api/request/linked_result_receiver.pony +++ b/github_rest_api/request/linked_result_receiver.pony @@ -10,7 +10,7 @@ interface tag LinkedResultReceiver Called when the request succeeds with parsed JSON. """ - be failure(status: U16, response_body: String, message: String) + be failure(err: RequestError) """ Called when the request fails. """ diff --git a/github_rest_api/request/no_content_requester.pony b/github_rest_api/request/no_content_requester.pony index b0ece5c..37fe193 100644 --- a/github_rest_api/request/no_content_requester.pony +++ b/github_rest_api/request/no_content_requester.pony @@ -9,7 +9,7 @@ interface tag DeleteResultReceiver a gist. """ be success() - be failure(status: U16, response_body: String, message: String) + be failure(err: RequestError) type DeletedOrError is (Deleted | RequestError) @@ -26,8 +26,8 @@ actor DeletedResultReceiver be success() => _p(Deleted) - be failure(status: U16, response_body: String, message: String) => - _p(RequestError(status, response_body, message)) + be failure(err: RequestError) => + _p(err) primitive Deleted """ @@ -41,10 +41,10 @@ actor NoContentRequester is http_client.HTTPClientConnectionActor resending the same method and resolving relative `Location` values against the request URL. Does not follow 301, 302, or 303 responses and reports them as failures. If a redirect crosses origins, has an invalid `Location`, or - exceeds the 5-redirect limit, the requester stops and reports a failure with - the redirect's status, an empty body, and an error message. On success, calls - `receiver.success()`; on any other status or connection failure, calls - `receiver.failure()` with details. + exceeds the 5-redirect limit, the requester stops and reports a + `RedirectRefused` failure. On success, calls `receiver.success()`; on any + other status or connection failure, calls `receiver.failure()` with a + `RequestError`. """ var _http: http_client.HTTPClientConnection = http_client.HTTPClientConnection.none() var _collector: http_client.ResponseCollector = http_client.ResponseCollector @@ -54,6 +54,7 @@ actor NoContentRequester is http_client.HTTPClientConnectionActor let _remaining_redirects: USize var _request_path: String = "" var _done: Bool = false + var _sent: Bool = false var _origin: http_client.Origin = http_client.Origin(true, "", "443") var _status: U16 = 0 @@ -120,17 +121,21 @@ actor NoContentRequester is http_client.HTTPClientConnectionActor _request_path, consume hdrs) match \exhaustive\ _http.send_request(request) - | http_client.SendRequestOK => None + | http_client.SendRequestOK => + // After a write error, on_closed can run inside send_request and still + // be followed by SendRequestOK. It then reads _sent as false and reports + // RequestNotSent; _done makes this assignment harmless. + _sent = true | http_client.ConnectionClosed => if not _done then _done = true - _receiver.failure(0, "", "Connection closed before response completed") + _receiver.failure(RequestError.request_not_sent()) end | http_client.ResponsePending => if not _done then _done = true _http.close() - _receiver.failure(0, "", "Failed to send request") + _receiver.failure(RequestError.request_not_sent()) end end @@ -147,8 +152,9 @@ actor NoContentRequester is http_client.HTTPClientConnectionActor | let next: _FollowRedirect => NoContentRequester._redirect( _creds, next.url, _method, _receiver, next.remaining) - | let refused: _RedirectRefused => - _receiver.failure(_status, "", refused.message) + | let refused: _RefusedRedirect => + _receiver.failure( + RequestError.redirect_refused(_status, refused.message)) end return end @@ -170,27 +176,32 @@ actor NoContentRequester is http_client.HTTPClientConnectionActor try let response = _collector.build()? let body_str = String.from_array(response.body) - _receiver.failure(_status, consume body_str, "") + _receiver.failure( + RequestError.unexpected_status(_status, consume body_str)) else - _receiver.failure(_status, "", "") + _receiver.failure(RequestError.invalid_http_response()) end end fun ref on_connection_failure(reason: ConnectionFailureReason) => if _done then return end _done = true - _receiver.failure(0, "", _ConnectionFailureMessage(reason)) + _receiver.failure(RequestError.connection_failed(reason)) fun ref on_parse_error(err: http_client.ParseError) => if _done then return end _done = true _http.close() - _receiver.failure(0, "", "HTTP parse error") + _receiver.failure(RequestError.invalid_http_response()) fun ref on_closed() => if _done then return end _done = true - _receiver.failure(0, "", "Connection closed before response completed") + if _sent then + _receiver.failure(RequestError.connection_closed_early()) + else + _receiver.failure(RequestError.request_not_sent()) + end be _fail(message: String) => - _receiver.failure(0, "", message) + _receiver.failure(RequestError.invalid_url(message)) diff --git a/github_rest_api/request/request.pony b/github_rest_api/request/request.pony index 409da2f..4b51c04 100644 --- a/github_rest_api/request/request.pony +++ b/github_rest_api/request/request.pony @@ -19,14 +19,19 @@ Every request actor in this package sends `X-GitHub-Api-Version: 2026-03-10`. A request URL must be an absolute `https` URL with a host and without userinfo, such as `https://api.github.com/repos/ponylang/ponyc`, and must not contain ASCII whitespace or control characters. For a URL that breaks these rules, the -request actor does not connect and reports status `0` with the message -`Unable to parse URL`. The message does not include the URL. +request actor does not connect and reports a `RequestError` whose `reason` is +`InvalidURL`, with the message `Unable to parse URL`. The message does not +include the URL. If a connection does not finish the TCP connect and the TLS handshake within -30 seconds, the request actor reports status `0` with the message -`Connection timed out`. The DNS lookup is not part of the 30 seconds. Each +30 seconds, the request actor reports a `RequestError` whose `reason` is +`ConnectionFailedTimeout`. The DNS lookup is not part of the 30 seconds. Each redirect hop gets its own 30 seconds. If the connect timer cannot be started, -the request actor reports status `0` with the message `Connect timer failed`. -Once the connection is ready, only the 60-second idle timeout applies: a -server that sends data at least once every 60 seconds is not timed out. +the `reason` is `ConnectionFailedTimerError`. Once the connection is ready, +only the 60-second idle timeout applies: a server that sends data at least +once every 60 seconds is not timed out, and an idle timeout after the request +is sent gives `ConnectionClosedEarly`. + +Every failure reaches the caller as a `RequestError`. Match on its `reason` to +decide what to do; `RequestFailureReason` lists the reasons. """ diff --git a/github_rest_api/request/request_error.pony b/github_rest_api/request/request_error.pony index 4c65592..2e78099 100644 --- a/github_rest_api/request/request_error.pony +++ b/github_rest_api/request/request_error.pony @@ -1,32 +1,198 @@ +use "net" + +primitive InvalidURL + """ + The request was never sent because its URL was not valid: a URI template + did not parse, or a request URL did not meet the package's rules for + request URLs. The URL can come from the caller or from GitHub data, such as + a URL template in a model or a `Link` header target. Retrying the same + request fails the same way. + """ + +primitive RequestNotSent + """ + The connection closed before any of the request was written to the network. + Retrying is safe for every method. + """ + +primitive ConnectionClosedEarly + """ + The connection closed after it took the request and before the response + was complete. The request may have been only partly written, or GitHub may + have acted on it, so retrying a request that changes something, such as a + POST, can repeat the change. The idle timeout, which closes a connection + that receives nothing for 60 seconds after the request is sent, also gives + this reason. + """ + +primitive InvalidHTTPResponse + """ + The response could not be read as HTTP, or it was larger than a limit: + 8 KiB for the status line, 8 KiB for all header lines together, 8 KiB for + all trailer lines together, 128 bytes for a chunk-size line, and 10 MiB for + the body. GitHub received the request and may have acted on it, so retrying + a request that changes something, such as a POST, can repeat the change. + """ + +primitive UnexpectedStatus + """ + The response had a status the operation does not treat as success. + `status` holds it and `response_body` holds the body. A 3xx redirect that + the requester does not follow, such as a 303 or a 301 for a POST, and a + redirect with no `Location` header also give this reason. GitHub received + the request; whether it acted on it depends on the status. A 5xx can follow + a change that did happen, so retrying a request that changes something can + repeat the change. + """ + +primitive RedirectRefused + """ + The response was a redirect of a kind the requester follows for this + method, and the requester refused it because the target is on another + origin, the `Location` is present but not valid, or the request already + used up its redirects. `status` holds the redirect's status and `message` + says why. GitHub answered with a redirect, so it did not act on the + request, and retrying it fails the same way. + """ + +primitive InvalidJSON + """ + The response had the expected status, but its body was not valid JSON. + `status` holds the status. GitHub acted on the request, so retrying a + request that changes something, such as a POST, repeats the change. + """ + +primitive ConversionFailed + """ + The response was valid JSON that did not convert to the expected model, + for example because a required field was missing or had the wrong type. + The response had the expected status, so GitHub acted on the request, and + retrying a request that changes something, such as a POST, repeats the + change. + """ + +type RequestFailureReason is + ( ConnectionFailureReason + | InvalidURL + | RequestNotSent + | ConnectionClosedEarly + | InvalidHTTPResponse + | UnexpectedStatus + | RedirectRefused + | InvalidJSON + | ConversionFailed ) + """ + Why a request failed. The `net` package's `ConnectionFailureReason` values + mean the connection could not be opened: DNS resolution, the TCP connect, + or the TLS handshake failed, the connect and handshake took longer than 30 + seconds (`ConnectionFailedTimeout`), or the connect timer could not be + started. In each case the request was not sent, so retrying is safe for + every method. To handle all five alike, match + `let _: ConnectionFailureReason`. + """ + class val RequestError """ A failed GitHub API request. Every operation fulfills its promise with either its result or a `RequestError`. - `status` is the HTTP status of the response. It is `0` when the failure is - not about the response status: the URL could not be built or parsed; the - request could not be sent; the connection failed, timed out, or closed - before the response was complete; the response was not valid HTTP; or a - response with the expected status had JSON that could not be converted to - the expected model. + `reason` says what failed; match on it to decide what to do. `message` + describes the failure for a person to read, never includes the response + body, and is empty for `UnexpectedStatus`. `status` is the response's HTTP + status for `UnexpectedStatus`, `RedirectRefused`, and `InvalidJSON`, and `0` + for every other reason. `response_body` is the body of the response for + `UnexpectedStatus`, and empty for every other reason. - `response_body` is the body of a response with an unexpected status. It is - empty for every other failure. - - `message` describes the failure for a person to read. It never includes the - response body. It is empty for an unexpected status; `status` and - `response_body` describe that failure instead. A non-zero `status` with a - non-empty `message` means the library refused to follow a redirect, or a - response with the expected status had a body that was not valid JSON. + Code outside the library, such as a test fake for an operation, can create + a `RequestError` with the constructor for the reason it needs. """ + let reason: RequestFailureReason let status: U16 let response_body: String let message: String - new val create(status': U16 = 0, - response_body': String = "", - message': String = "") - => + new val connection_failed(reason': ConnectionFailureReason) => + """ + The connection could not be opened for `reason'`. + """ + reason = reason' + status = 0 + response_body = "" + message = _ConnectionFailureMessage(reason') + + new val invalid_url(message': String) => + """ + The request URL was not valid. `message'` says why. + """ + reason = InvalidURL + status = 0 + response_body = "" + message = message' + + new val request_not_sent() => + """ + The connection closed before any of the request was written to the + network. + """ + reason = RequestNotSent + status = 0 + response_body = "" + message = "Failed to send request" + + new val connection_closed_early() => + """ + The connection closed after it took the request and before the response + was complete. + """ + reason = ConnectionClosedEarly + status = 0 + response_body = "" + message = "Connection closed before response completed" + + new val invalid_http_response() => + """ + The response could not be read as HTTP, or it was larger than a limit. + """ + reason = InvalidHTTPResponse + status = 0 + response_body = "" + message = "HTTP parse error" + + new val unexpected_status(status': U16, response_body': String) => + """ + The response had status `status'`, which the operation does not treat as + success, and body `response_body'`. + """ + reason = UnexpectedStatus status = status' response_body = response_body' + message = "" + + new val redirect_refused(status': U16, message': String) => + """ + The requester refused a redirect with status `status'`. `message'` says + why. + """ + reason = RedirectRefused + status = status' + response_body = "" message = message' + + new val invalid_json(status': U16) => + """ + The response had the expected status `status'`, but its body was not + valid JSON. + """ + reason = InvalidJSON + status = status' + response_body = "" + message = "Failed to parse response" + + new val conversion_failed() => + """ + The response JSON did not convert to the expected model. + """ + reason = ConversionFailed + status = 0 + response_body = "" + message = "Unable to convert json response" diff --git a/github_rest_api/search.pony b/github_rest_api/search.pony index cd2371b..8cdcbcf 100644 --- a/github_rest_api/search.pony +++ b/github_rest_api/search.pony @@ -94,7 +94,7 @@ class val SearchResults[A: Any val] package, such as `https://api.github.com/search/issues?q=bug&page=2`. For any other target, such as a relative one, it opens no connection, and - the Promise resolves to `RequestError(0, "", "Unable to parse URL")`. + the Promise resolves to a `RequestError` whose `reason` is `InvalidURL`. """ match \exhaustive\ _prev_link | let prev: String => @@ -120,7 +120,7 @@ class val SearchResults[A: Any val] package, such as `https://api.github.com/search/issues?q=bug&page=2`. For any other target, such as a relative one, it opens no connection, and - the Promise resolves to `RequestError(0, "", "Unable to parse URL")`. + the Promise resolves to a `RequestError` whose `reason` is `InvalidURL`. """ match \exhaustive\ _next_link | let next: String => @@ -209,12 +209,8 @@ actor SearchResultReceiver[A: Any val] try _p(_converter(json, link_header, _creds)?) else - _p(req.RequestError(where message' = "Unable to convert json response")) + _p(req.RequestError.conversion_failed()) end - be failure( - status: U16, - response_body: String, - message: String) - => - _p(req.RequestError(status, response_body, message)) + be failure(err: req.RequestError) => + _p(err)