Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,13 @@ $(EXAMPLES_BINARIES): $(BUILD_DIR)/%: $(SOURCE_FILES) $(EXAMPLES_SOURCE_FILES) \
$(EXAMPLES_DIR)/example.mk $(EXAMPLES_DIR)/%/Makefile | $(BUILD_DIR)
BUILD_DIR=$(mkfile_path)$(BUILD_DIR) $(MAKE) -C $(EXAMPLES_DIR)/$*

# TODO(ponylang/ponyc#7139): pony-lint reports nothing for a package nested
# inside another one, even when it is named next to `.`, so lint
# github_rest_api/request on its own. Remove that line once the issue is fixed.
lint:
$(GET_DEPENDENCIES_WITH)
$(LINT_WITH) .
$(LINT_WITH) github_rest_api/request

clean:
$(CLEAN_DEPENDENCIES_WITH)
Expand Down
1 change: 1 addition & 0 deletions github_rest_api/request/_github_request_headers.pony
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// pony-lint: allow style/file-naming
use http_client = "http_client"

primitive _GitHubRequestHeaders
Expand Down
20 changes: 11 additions & 9 deletions github_rest_api/request/_test.pony
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,10 @@ class \nodoc\ _TestQueryParamsMultiple is UnitTest
fun name(): String => "request/query-params/multiple"

fun ref apply(h: TestHelper) =>
let params = recover val
[("state", "open"); ("labels", "bug")]
end
let params =
recover val
[("state", "open"); ("labels", "bug")]
end
h.assert_eq[String]("?state=open&labels=bug", QueryParams(params))

class \nodoc\ _TestQueryParamsSpaceEncoding is UnitTest
Expand Down Expand Up @@ -147,13 +148,14 @@ class \nodoc\ _TestQueryParamsStructureProperty is UnitTest
h.for_all[USize](
recover val Generators.usize(1, 10) end)(
{(n, h) =>
let params = recover val
let p = Array[(String, String)]
for i in Range[USize].till(0, n) do
p.push(("k" + i.string(), "v" + i.string()))
let params =
recover val
let p = Array[(String, String)]
for i in Range[USize].till(0, n) do
p.push(("k" + i.string(), "v" + i.string()))
end
p
end
p
end
let result = QueryParams(params)

// Must start with ?
Expand Down
32 changes: 16 additions & 16 deletions github_rest_api/request/_test_github_token.pony
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ use "pony_test"
primitive \nodoc\ _TokenChars
fun apply(): Array[U8] val =>
recover val
let chars = Array[U8]
chars.append("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
chars.append("abcdefghijklmnopqrstuvwxyz")
chars.append("0123456789-._~+/")
chars
Array[U8]
.> append("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
.> append("abcdefghijklmnopqrstuvwxyz")
.> append("0123456789-._~+/")
end

primitive \nodoc\ _AssertTokenAccepted
Expand Down Expand Up @@ -74,8 +73,9 @@ class \nodoc\ iso _TestGitHubTokenRejects is UnitTest
| let m: String =>
h.assert_eq[String](expected, m, "value " + index.string())
| None =>
h.fail("Expected value " + index.string()
+ " to be rejected with one message")
h.fail(
"Expected value " + index.string() +
" to be rejected with one message")
end
end

Expand Down Expand Up @@ -108,8 +108,9 @@ class \nodoc\ iso _TestGitHubTokenAcceptsProperty is UnitTest
| let t: GitHubToken =>
h.assert_eq[String](value, t())
| let _: ct.ValidationFailure =>
h.fail("Expected a token of " + value.size().string()
+ " valid bytes to be accepted")
h.fail(
"Expected a token of " + value.size().string() +
" valid bytes to be accepted")
end
})?

Expand All @@ -134,11 +135,10 @@ class \nodoc\ iso _TestGitHubTokenRejectsOutsideByteProperty is UnitTest
recover val Generators.usize(0, 3) end,
recover val Generators.usize(0, 44) end,
recover val
Generators.frequency[U8]([
(3, Generators.u8().filter(
{(b)(chars) => (b, (not chars.contains(b)) and (b != '='))}))
(1, Generators.one_of[U8](boundary))
])
Generators.frequency[U8](
[ (3, Generators.u8().filter(
{(b)(chars) => (b, (not chars.contains(b)) and (b != '=')) }))
(1, Generators.one_of[U8](boundary)) ])
end)(
{(body, padding, position, bad, h) =>
let value: String val =
Expand All @@ -155,8 +155,8 @@ class \nodoc\ iso _TestGitHubTokenRejectsOutsideByteProperty is UnitTest
end
match \exhaustive\ MakeGitHubToken(value)
| let _: GitHubToken =>
h.fail("Expected a token with byte " + bad.string()
+ " to be rejected")
h.fail(
"Expected a token with byte " + bad.string() + " to be rejected")
| let _: ct.ValidationFailure =>
None
end
Expand Down
9 changes: 4 additions & 5 deletions github_rest_api/request/_test_redirect_origin.pony
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,10 @@ class \nodoc\ iso _TestResolveRedirectCrossOriginPortProperty is UnitTest
let origin = http_client.Origin(true, "api.github.com", "443")
let port_gen =
recover val
Generators.frequency[U16]([
(2, Generators.one_of[U16]([0; 80; 442; 444; 65535]))
(2, Generators.u16(1, 442))
(4, Generators.u16(444, 65535))
])
Generators.frequency[U16](
[ (2, Generators.one_of[U16]([0; 80; 442; 444; 65535]))
(2, Generators.u16(1, 442))
(4, Generators.u16(444, 65535)) ])
end
h.for_all2[USize, U16](
recover val Generators.usize(0, 20) end,
Expand Down
38 changes: 23 additions & 15 deletions github_rest_api/request/check_requester.pony
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,6 @@ use "promises"
use "net"
use "time"

interface tag CheckResultReceiver
"""
Receives the result of an HTTP status check where 204 means true and 404
means false. Used for endpoints like "is this gist starred?" that indicate
their answer via status code rather than a response body.
"""
be success(value: Bool)
be failure(err: RequestError)

type BoolOrError is (Bool | RequestError)

actor BoolResultReceiver
Expand All @@ -36,9 +27,11 @@ actor CheckRequester is
Issues an HTTP GET request and interprets the status code as a boolean: 204
means true, 404 means false, and any other status is treated as a failure.
Used for GitHub API endpoints that answer yes/no questions via status codes
(e.g., checking whether a gist is starred).
(e.g., checking whether a gist is starred). It does not follow redirects,
so a 3xx response is a failure too.
"""
var _http: http_client.HTTPClientConnection = http_client.HTTPClientConnection.none()
var _http: http_client.HTTPClientConnection =
http_client.HTTPClientConnection.none()
var _collector: http_client.ResponseCollector = http_client.ResponseCollector
let _creds: Credentials
let _receiver: CheckResultReceiver
Expand Down Expand Up @@ -108,12 +101,17 @@ actor CheckRequester is
_http

fun ref on_connected() =>
"""
Sends the request, or reports a `RequestNotSent` failure to the receiver
if the request cannot be sent.
"""
if _done then return end
let hdrs = _GitHubRequestHeaders(_creds)
let request = http_client.HTTPRequest(
http_client.GET,
_request_path,
consume hdrs)
let request =
http_client.HTTPRequest(
http_client.GET,
_request_path,
consume hdrs)
match \exhaustive\ _http.send_request(request)
| http_client.SendRequestOK =>
// After a write error, on_closed can run inside send_request and still
Expand All @@ -134,6 +132,9 @@ actor CheckRequester is
end

fun ref on_response(response: http_client.Response val) =>
"""
Records the response status. This requester does not follow redirects.
"""
if _done then return end
_status = response.status
_collector = http_client.ResponseCollector
Expand All @@ -144,6 +145,10 @@ actor CheckRequester is
_collector.add_chunk(data)

fun ref on_response_complete() =>
"""
Reports true to the receiver for a 204 response, false for a 404, and a
failure otherwise.
"""
if _done then return end
_finish()
_http.close()
Expand All @@ -166,6 +171,9 @@ actor CheckRequester is
_receiver.failure(ConnectionFailed(reason))

fun ref on_parse_error(err: http_client.ParseError) =>
"""
Reports an `InvalidHTTPResponse` failure to the receiver.
"""
if _done then return end
_finish()
_http.close()
Expand Down
16 changes: 16 additions & 0 deletions github_rest_api/request/check_result_receiver.pony
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
interface tag CheckResultReceiver
"""
Receives the result of an HTTP status check where 204 means true and 404
means false. Used for endpoints like "is this gist starred?" that indicate
their answer via status code rather than a response body.
The requester calls exactly one of `success` and `failure`, one time.
"""
be success(value: Bool)
"""
Called with true for a 204 response and false for a 404.
"""

be failure(err: RequestError)
"""
Called with the failure when the request fails.
"""
16 changes: 16 additions & 0 deletions github_rest_api/request/delete_result_receiver.pony
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
interface tag DeleteResultReceiver
"""
Receives the result of an HTTP request that expects no response body (204 No
Content). Used for DELETE and PUT operations like deleting a label or starring
a gist.
The requester calls exactly one of `success` and `failure`, one time.
"""
be success()
"""
Called when the request succeeds.
"""

be failure(err: RequestError)
"""
Called with the failure when the request fails.
"""
16 changes: 8 additions & 8 deletions github_rest_api/request/github_token.pony
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,18 @@ primitive GitHubTokenValidator is ct.Validator[String]
end

fun _is_token_char(b: U8): Bool =>
((b >= 'A') and (b <= 'Z'))
or ((b >= 'a') and (b <= 'z'))
or ((b >= '0') and (b <= '9'))
or (b == '-') or (b == '.') or (b == '_') or (b == '~')
or (b == '+') or (b == '/')
((b >= 'A') and (b <= 'Z')) or
((b >= 'a') and (b <= 'z')) or
((b >= '0') and (b <= '9')) or
(b == '-') or (b == '.') or (b == '_') or (b == '~') or
(b == '+') or (b == '/')

fun _failure(): ct.ValidationFailure =>
recover val
ct.ValidationFailure(
"token must be one or more of A-Z, a-z, 0-9, '-', '.', '_', '~', '+', "
+ "'/', followed by zero or more '='; check for a trailing newline "
+ "or space")
"token must be one or more of A-Z, a-z, 0-9, '-', '.', '_', '~', " +
"'+', '/', followed by zero or more '='; check for a trailing " +
"newline or space")
end

type GitHubToken is ct.Constrained[String, GitHubTokenValidator]
Expand Down
45 changes: 28 additions & 17 deletions github_rest_api/request/json_requester.pony
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,6 @@ use "json"
use "net"
use "time"

interface tag JSONRequesterResultReceiver
"""
Receives the result of a JSON API request: either a parsed JSON response
on success, or a `RequestError` on failure.
"""
be success(json: JSONNav)
be failure(err: RequestError)

actor JSONRequester is
(http_client.HTTPClientConnectionActor & _DeadlineTarget)
"""
Expand All @@ -26,7 +18,8 @@ actor JSONRequester is
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 _http: http_client.HTTPClientConnection =
http_client.HTTPClientConnection.none()
var _collector: http_client.ResponseCollector = http_client.ResponseCollector
let _creds: Credentials
let _receiver: JSONRequesterResultReceiver
Expand Down Expand Up @@ -148,20 +141,25 @@ actor JSONRequester is
_http

fun ref on_connected() =>
"""
Sends the request, or reports a `RequestNotSent` failure to the receiver
if the request cannot be sent.
"""
if _done then return end
let hdrs = _GitHubRequestHeaders(_creds)
match _body
| let b: String =>
hdrs.set("Content-Length", b.size().string())
end
let request = http_client.HTTPRequest(
_method,
_request_path,
consume hdrs,
match \exhaustive\ _body
| let b: String => b.array()
| None => None
end)
let request =
http_client.HTTPRequest(
_method,
_request_path,
consume hdrs,
match \exhaustive\ _body
| let b: String => b.array()
| None => None
end)
match \exhaustive\ _http.send_request(request)
| http_client.SendRequestOK =>
// After a write error, on_closed can run inside send_request and still
Expand All @@ -182,6 +180,12 @@ actor JSONRequester is
end

fun ref on_response(response: http_client.Response val) =>
"""
On a 307 or 308 response with a `Location` header, or a 301 or 302 for a
GET, resolves `Location` against the request URL and follows a valid
same-origin redirect within the hop limit, or reports a `RedirectRefused`
failure to the receiver.
"""
if _done then return end
_status = response.status
if _ShouldFollowRedirect(_method, _status) then
Expand Down Expand Up @@ -215,6 +219,10 @@ actor JSONRequester is
_collector.add_chunk(data)

fun ref on_response_complete() =>
"""
Reports the parsed JSON body to the receiver when the response has the
expected status, and a failure otherwise.
"""
if _done then return end
_finish()
_http.close()
Expand All @@ -240,6 +248,9 @@ actor JSONRequester is
_receiver.failure(ConnectionFailed(reason))

fun ref on_parse_error(err: http_client.ParseError) =>
"""
Reports an `InvalidHTTPResponse` failure to the receiver.
"""
if _done then return end
_finish()
_http.close()
Expand Down
17 changes: 17 additions & 0 deletions github_rest_api/request/json_requester_result_receiver.pony
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use "json"

interface tag JSONRequesterResultReceiver
"""
Receives the result of a JSON API request: either a parsed JSON response
on success, or a `RequestError` on failure.
The requester calls exactly one of `success` and `failure`, one time.
"""
be success(json: JSONNav)
"""
Called with the parsed JSON body when the request succeeds.
"""

be failure(err: RequestError)
"""
Called with the failure when the request fails.
"""
Loading
Loading