diff --git a/README.md b/README.md index 0ed3be3..26c4eb1 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,17 @@ result.colnames # column names result.data # retrieved data ``` +The vector forms of `kegg_conv`, `kegg_get`, `kegg_link`, and `kegg_list` send +at most 10 entries per request. Set `request_delay` to control the pause between +requests: + +```julia +entries = ["hsa:$id" for id in 10458:10468] +result = kegg_get(entries; request_delay = 0.5) +``` + +The old `timeout` keyword remains available as a deprecated alias. + ## Documentation - [Getting started](https://cvigilv.github.io/KEGGAPI.jl/dev/man/getting-started/) diff --git a/benchmarking/README.md b/benchmarking/README.md index 08f318b..4788c8a 100644 --- a/benchmarking/README.md +++ b/benchmarking/README.md @@ -19,9 +19,9 @@ have no bar for it in the figure. The `conv` case uses `ncbi-geneid` rather than `ncbi-proteinid` because Bio.KEGG.REST only recognises the legacy outside-database names (`ncbi-gi | ncbi-geneid | uniprot`) and rejects the newer ones. -`KEGGAPI.jl`'s chunked `kegg_get` sleeps internally to respect KEGG's rate limit; -the Julia runner passes `timeout = 0.0` so that deliberate delay is not counted -as work, since the runner already spaces its own calls. +`KEGGAPI.jl`'s chunked `kegg_get` waits between requests to respect KEGG's rate +limit. The Julia runner passes `request_delay = 0.0` because the runner already +spaces its own calls and should not include that delay in its timings. Each interface runs every operation inside a **single** process, so what is measured is per-call time rather than interpreter startup. A warm-up call is diff --git a/benchmarking/runners/bench_julia.jl b/benchmarking/runners/bench_julia.jl index cee1b86..b591c74 100644 --- a/benchmarking/runners/bench_julia.jl +++ b/benchmarking/runners/bench_julia.jl @@ -1,17 +1,13 @@ # Julia runner: times KEGGAPI.jl calls and prints one CSV row per replicate. # Usage: julia --project=. runners/bench_julia.jl using KEGGAPI -using Logging const NREPS = length(ARGS) >= 1 ? parse(Int, ARGS[1]) : 5 const PAUSE = length(ARGS) >= 2 ? parse(Float64, ARGS[2]) : 0.4 -# The chunked `kegg_get` methods sleep internally to respect KEGG's rate limit. -# This runner already spaces its own calls, so that sleep is disabled here to -# measure the actual request/parse work; the resulting @warn is silenced. -get_entry(args...) = with_logger(NullLogger()) do - KEGGAPI.kegg_get(args...; timeout = 0.0) -end +# This runner already spaces its calls, so disable the internal batching delay +# to measure request and parsing work only. +get_entry(args...) = KEGGAPI.kegg_get(args...; request_delay = 0.0) # (label, thunk) pairs -- keep in sync with the other runners. const CASES = [ diff --git a/src/Conv.jl b/src/Conv.jl index 029b8e5..5c24583 100644 --- a/src/Conv.jl +++ b/src/Conv.jl @@ -11,9 +11,9 @@ Convert KEGG identifiers to/from outside identifiers. ```julia using KEGGAPI -KEGGAPI.conv("eco", "ncbi-geneid") -KEGGAPI.conv("ncbi-geneid", "eco") -KEGGAPI.conv("genes", "ncbi-geneid:948364") +KEGGAPI.kegg_conv("eco", "ncbi-geneid") +KEGGAPI.kegg_conv("ncbi-geneid", "eco") +KEGGAPI.kegg_conv("genes", "ncbi-geneid:948364") ``` # Extended help @@ -37,7 +37,7 @@ end """ - kegg_conv(target_db::String, dbentries::Vector{String}; [timeout::Float64 = 0.4]) + kegg_conv(target_db::String, dbentries::Vector{String}; request_delay::Real = 0.4, timeout = nothing) Convert KEGG identifiers to/from outside identifiers. @@ -55,27 +55,47 @@ For chemical substance identifiers: # Arguments - `target_db::String`: Target database - `dbentries::Vector{String}`: Database entries of the available databases -- `timeout::Float64`: Time to wait between requests (default: 0.4 seconds) +- `request_delay::Real`: Seconds to wait between batched requests. Defaults to + 0.4. No delay occurs when the input fits in one request. +- `timeout::Real`: Deprecated alias for `request_delay`. If both keywords are + supplied, their values must be equal. + +# Throws +- `ArgumentError`: If a delay is negative or non-finite, or if `request_delay` + and `timeout` conflict. # Examples ```julia using KEGGAPI -KEGGAPI.conv("ncbi-proteinid", ["hsa:10458", "ece:Z5100"]) +KEGGAPI.kegg_conv("ncbi-proteinid", ["hsa:10458", "ece:Z5100"]) ``` """ -function kegg_conv(target_db::String, dbentries::Vector{String}; timeout::Float64 = 0.4) +function kegg_conv( + target_db::String, dbentries::Vector{String}; + request_delay::Union{Nothing, Real} = nothing, + timeout::Union{Nothing, Real} = nothing, + ) + return _kegg_conv(target_db, dbentries, request, sleep; request_delay, timeout) +end + +function _kegg_conv( + target_db::String, dbentries::Vector{String}, requester::F, sleep_function::S; + request_delay::Union{Nothing, Real} = nothing, + timeout::Union{Nothing, Real} = nothing, + ) where {F, S} + request_count = cld(length(dbentries), KEGG_BATCH_SIZE) + delay = resolve_request_delay(request_delay, timeout, :kegg_conv, request_count) urls = String[] data = [] - for chunk in partition(dbentries, 10) + foreach_request_batch(dbentries, delay, sleep_function) do chunk url = "https://rest.kegg.jp/conv/$(target_db)/$(join(chunk, "+"))" push!(urls, url) - response_text = request(url) + response_text = requester(url) for datum in eachline(IOBuffer(response_text)) id, d = split(datum, '\t') .|> String push!(data, [id, d]) end - sleep(timeout) end return KeggTupleList(urls, ["source", target_db], data) end diff --git a/src/Get.jl b/src/Get.jl index 4126c00..a47221a 100644 --- a/src/Get.jl +++ b/src/Get.jl @@ -67,8 +67,8 @@ end # ---------------------------------------------------------------------------- Main function """ - kegg_get(dbentries::Vector{String}, option::Union{Symbol, Nothing} = nothing; timeout::Float64 = 0.4) - kegg_get(dbentry::String, args...; kwargs...) + kegg_get(dbentries::Vector{String}, option::Union{Symbol, Nothing} = nothing; request_delay::Real = 0.4, timeout = nothing) + kegg_get(dbentry::String, option::Union{Symbol, Nothing} = nothing; request_delay::Real = 0.4, timeout = nothing) Retrieve given database entries. @@ -89,8 +89,14 @@ Allowed `option` for retrieval of selected fields: - `dbentries::Vector{String}`: A vector of KEGG database entries to retrieve. - `option::Union{Symbol, Nothing}`: An optional symbol specifying the format of the retrieved data. If `nothing`, the default format is used. -- `timeout::Float64`: A float specifying the time to wait between API requests when retrieving - more than 10 entries. Default is 0.4 seconds. +- `request_delay::Real`: Seconds to wait between batched requests. Defaults to + 0.4. No delay occurs when the input fits in one request. +- `timeout::Real`: Deprecated alias for `request_delay`. If both keywords are + supplied, their values must be equal. + +# Throws +- `ArgumentError`: If a delay is negative or non-finite, or if `request_delay` + and `timeout` conflict. # Returns A tuple containing: @@ -110,9 +116,10 @@ urls, data = kegg_get(dbentries, option) This operation retrieves given database entries in a flat file format or in other formats with `option`. Flat file formats are available for all KEGG databases except brite. The input is limited up to 10 entries; if more are provided the -query will be split into chunks of 10 entries and multiple requests will be made -with a `timeout` between each request (KEGG API indicates that the maximum API -calls per seconds is 3, so a default timeout of 0.4 seconds is set to ensure that). +query is split into chunks of 10 entries. The function waits `request_delay` +seconds between requests, but does not wait after the final request. The default +of 0.4 seconds keeps batched calls below KEGG's limit of three requests per +second. Options allow retrieval of selected fields, including sequence data from genes entries, chemical structure data or GIF image files from compound, glycan and @@ -127,23 +134,35 @@ and to **one pathway entry with the `:image`, `:image2x` or `:kgml` option**. - https://www.kegg.jp/kegg/rest/keggapi.html#get """ -function kegg_get(dbentries::Vector{String}, option::Union{Symbol, Nothing} = nothing; timeout::Float64 = 0.4) +function kegg_get( + dbentries::Vector{String}, option::Union{Symbol, Nothing} = nothing; + request_delay::Union{Nothing, Real} = nothing, + timeout::Union{Nothing, Real} = nothing, + ) + return _kegg_get(dbentries, option, request, sleep; request_delay, timeout) +end + +function _kegg_get( + dbentries::Vector{String}, option::Union{Symbol, Nothing}, requester::F, + sleep_function::S; request_delay::Union{Nothing, Real} = nothing, + timeout::Union{Nothing, Real} = nothing, + ) where {F, S} validate_get_option(option) - timeout < 0.334 && @warn "KEGG API accepts 3 requests per second. Current timeout may lead to API rate limit errors." + request_count = cld(length(dbentries), KEGG_BATCH_SIZE) + delay = resolve_request_delay(request_delay, timeout, :kegg_get, request_count) length(dbentries) > 1 && option == :image && @warn "Using the :image option with kegg_get is limited to one compound/glycan/drug entry" urls = String[] data = [] processor = get_response_processor(option) - for chunk in partition(dbentries, 10) + foreach_request_batch(dbentries, delay, sleep_function) do chunk url = build_kegg_url(chunk, option) push!(urls, url) - response_text = option in KEGGAPI_GET_BINARY_OPTIONS ? request(url, Vector{UInt8}) : request(url) + response_text = option in KEGGAPI_GET_BINARY_OPTIONS ? requester(url, Vector{UInt8}) : requester(url) for datum in processor(response_text) push!(data, datum) end - sleep(timeout) end return (url = urls, data = data) diff --git a/src/KEGGAPI.jl b/src/KEGGAPI.jl index a387e0a..7d3e222 100644 --- a/src/KEGGAPI.jl +++ b/src/KEGGAPI.jl @@ -1,8 +1,8 @@ module KEGGAPI import HTTP: get -import .Iterators: partition +include("utils.jl") include("Conv.jl") include("Ddi.jl") include("Find.jl") diff --git a/src/Link.jl b/src/Link.jl index d76b08d..f7243c8 100644 --- a/src/Link.jl +++ b/src/Link.jl @@ -53,7 +53,7 @@ function kegg_link(target_db::String, source_db::String, option::String = "") end """ - kegg_link(target_db::String, dbentries::Vector{String}, option::String = ""; [timeout::Float64 = 0.4]) + kegg_link(target_db::String, dbentries::Vector{String}, option::String = ""; request_delay::Real = 0.4, timeout = nothing) Find related entries by using database cross-references. @@ -76,19 +76,43 @@ and the available external databases are: (`species | genus | family | order | class | phylum`) for `genome`/`taxonomy` links, or an RDF output format (`turtle | n-triple`) for the `drug`/`atc`/`jtc` databases (in which case the raw response text is returned). -- `timeout::Float64`, time to wait between requests (default: 0.4 seconds) +- `request_delay::Real`, seconds to wait between batched requests. Defaults to + 0.4. No delay occurs when the input fits in one request. +- `timeout::Real`, deprecated alias for `request_delay`. If both keywords are + supplied, their values must be equal. + +# Throws +- `ArgumentError`: If a delay is negative or non-finite, or if `request_delay` + and `timeout` conflict. + +The vector form sends at most 10 entries per request. It waits `request_delay` +seconds between requests, but does not wait after the final request. """ -function kegg_link(target_db::String, dbentries::Vector{String}, option::String = ""; timeout::Float64 = 0.4) +function kegg_link( + target_db::String, dbentries::Vector{String}, option::String = ""; + request_delay::Union{Nothing, Real} = nothing, + timeout::Union{Nothing, Real} = nothing, + ) + return _kegg_link(target_db, dbentries, option, request, sleep; request_delay, timeout) +end + +function _kegg_link( + target_db::String, dbentries::Vector{String}, option::String, requester::F, + sleep_function::S; request_delay::Union{Nothing, Real} = nothing, + timeout::Union{Nothing, Real} = nothing, + ) where {F, S} option_str = isempty(option) ? "" : "/$option" is_rdf = option in KEGG_LINK_RDF_OPTIONS + request_count = cld(length(dbentries), KEGG_BATCH_SIZE) + delay = resolve_request_delay(request_delay, timeout, :kegg_link, request_count) urls = String[] data = [] rdf_text = "" - for chunk in partition(dbentries, 10) + foreach_request_batch(dbentries, delay, sleep_function) do chunk url = "https://rest.kegg.jp/link/$(target_db)/$(join(chunk, "+"))$option_str" push!(urls, url) - response_text = request(url) + response_text = requester(url) if is_rdf rdf_text *= response_text else @@ -97,7 +121,6 @@ function kegg_link(target_db::String, dbentries::Vector{String}, option::String push!(data, [id, d]) end end - sleep(timeout) end is_rdf && return rdf_text diff --git a/src/List.jl b/src/List.jl index 36f5d24..cfab760 100644 --- a/src/List.jl +++ b/src/List.jl @@ -47,12 +47,20 @@ function _kegg_list(query::String, query_type::String, request_function::F) wher end """ - kegg_list(dbentries::Vector{String}; timeout::Float64 = 0.4) -> KeggTupleList + kegg_list(dbentries::Vector{String}; request_delay::Real = 0.4, timeout = nothing) -> KeggTupleList Get a list of entry identifiers and associated names # Arguments - `dbentries::Vector{String}`: The list of entries to list. +- `request_delay::Real`: Seconds to wait between batched requests. Defaults to + 0.4. No delay occurs when the input fits in one request. +- `timeout::Real`: Deprecated alias for `request_delay`. If both keywords are + supplied, their values must be equal. + +# Throws +- `ArgumentError`: If a delay is negative or non-finite, or if `request_delay` + and `timeout` conflict. # Returns - `data::KeggTupleList`: A data structure containing the `url`, the `data` retrieved, @@ -60,20 +68,32 @@ Get a list of entry identifiers and associated names # Extended help -The input is limited up to 10 entries; if more are provided the query will be -split into chunks of 10 entries and multiple requests will be made with a `timeout` -between each request (KEGG API indicates that the maximum API calls per seconds -is 3, so a default timeout of 0.4 seconds is set to ensure that). +The input is limited to 10 entries per request. Larger inputs are split into +batches, with `request_delay` seconds between requests and no wait after the +final request. The default of 0.4 seconds keeps batched calls below KEGG's limit +of three requests per second. """ -function kegg_list(dbentries::Vector{String}; timeout::Float64 = 0.4) +function kegg_list( + dbentries::Vector{String}; request_delay::Union{Nothing, Real} = nothing, + timeout::Union{Nothing, Real} = nothing, + ) + return _kegg_list(dbentries, request, sleep; request_delay, timeout) +end + +function _kegg_list( + dbentries::Vector{String}, requester::F, sleep_function::S; + request_delay::Union{Nothing, Real} = nothing, + timeout::Union{Nothing, Real} = nothing, + ) where {F, S} + request_count = cld(length(dbentries), KEGG_BATCH_SIZE) + delay = resolve_request_delay(request_delay, timeout, :kegg_list, request_count) urls = String[] data = [] - for chunk in partition(dbentries, 10) + foreach_request_batch(dbentries, delay, sleep_function) do chunk url = "https://rest.kegg.jp/list/$(join(chunk, "+"))" push!(urls, url) - response_text = request(url) + response_text = requester(url) append!(data, list_parser(response_text, url).data) - sleep(timeout) end colnames = inferred_list_colnames(data) return KeggTupleList(urls, colnames, data) diff --git a/src/utils.jl b/src/utils.jl new file mode 100644 index 0000000..a12b9bd --- /dev/null +++ b/src/utils.jl @@ -0,0 +1,40 @@ +const DEFAULT_REQUEST_DELAY = 0.4 +const KEGG_REQUEST_INTERVAL = 1 / 3 +const KEGG_BATCH_SIZE = 10 + +function resolve_request_delay( + request_delay::Union{Nothing, Real}, timeout::Union{Nothing, Real}, + function_name::Symbol, request_count::Int, + ) + for delay in (request_delay, timeout) + if !isnothing(delay) && (!isfinite(delay) || delay < 0) + throw(ArgumentError("request delays must be finite and nonnegative")) + end + end + + if !isnothing(request_delay) && !isnothing(timeout) && request_delay != timeout + throw(ArgumentError("request_delay and the deprecated timeout alias must be equal when both are supplied")) + end + + if !isnothing(timeout) + Base.depwarn("The timeout keyword is deprecated; use request_delay instead.", function_name) + end + + delay = something(request_delay, timeout, DEFAULT_REQUEST_DELAY) + if request_count > 1 && delay < KEGG_REQUEST_INTERVAL + @warn "KEGG allows at most three requests per second. A request_delay below one third of a second may cause rate-limit errors." + end + return delay +end + +function foreach_request_batch( + f::F, dbentries::AbstractVector{String}, request_delay::Real, + sleep_function::S, + ) where {F, S} + request_count = cld(length(dbentries), KEGG_BATCH_SIZE) + for (request_index, chunk) in enumerate(Iterators.partition(dbentries, KEGG_BATCH_SIZE)) + f(chunk) + request_index < request_count && sleep_function(request_delay) + end + return nothing +end diff --git a/test/runtests.jl b/test/runtests.jl index 68fd5f6..d09d298 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,5 +1,7 @@ using KEGGAPI using Test +include("test_batching.jl") include("test_list.jl") include("test_requests.jl") +include("test_utils.jl") diff --git a/test/test_batching.jl b/test/test_batching.jl new file mode 100644 index 0000000..b86d0be --- /dev/null +++ b/test/test_batching.jl @@ -0,0 +1,79 @@ +using KEGGAPI +using Test + +function empty_conv(; kwargs...) + return KEGGAPI.kegg_conv("genes", String[]; kwargs...) +end + +function empty_get(; kwargs...) + return KEGGAPI.kegg_get(String[]; kwargs...) +end + +function empty_link(; kwargs...) + return KEGGAPI.kegg_link("pathway", String[]; kwargs...) +end + +function empty_list(; kwargs...) + return KEGGAPI.kegg_list(String[]; kwargs...) +end + +@testset "batched API request delays" begin + empty_calls = (empty_conv, empty_get, empty_link, empty_list) + + @testset "timeout compatibility alias" begin + for call in empty_calls + @test_deprecated r"use request_delay" call(; timeout = 0.4) + end + @test_deprecated r"use request_delay" empty_get(; request_delay = 0.4, timeout = 0.4) + + for call in empty_calls + @test_throws ArgumentError call(; request_delay = 0.4, timeout = 0.5) + end + end + + @testset "invalid delays" begin + for call in empty_calls, delay in (-0.1, Inf, -Inf, NaN) + @test_throws ArgumentError call(; request_delay = delay) + @test_throws ArgumentError call(; timeout = delay) + end + end + + @testset "wrapper batching" begin + batched_calls = ( + (entries, requester, sleeper) -> KEGGAPI._kegg_conv( + "genes", entries, requester, sleeper; request_delay = 0.4 + ), + (entries, requester, sleeper) -> KEGGAPI._kegg_get( + entries, nothing, requester, sleeper; request_delay = 0.4 + ), + (entries, requester, sleeper) -> KEGGAPI._kegg_link( + "pathway", entries, "", requester, sleeper; request_delay = 0.4 + ), + (entries, requester, sleeper) -> KEGGAPI._kegg_list( + entries, requester, sleeper; request_delay = 0.4 + ), + ) + + for call in batched_calls + requested_urls = String[] + sleep_delays = Float64[] + requester = function (url::String, response_type::Type = String) + push!(requested_urls, url) + return response_type === String ? "" : UInt8[] + end + sleeper = delay -> push!(sleep_delays, delay) + + call(["entry-$i" for i in 1:10], requester, sleeper) + @test length(requested_urls) == 1 + @test isempty(sleep_delays) + + empty!(requested_urls) + call(["entry-$i" for i in 1:21], requester, sleeper) + @test length(requested_urls) == 3 + @test sleep_delays == [0.4, 0.4] + end + end + + partition_view = first(Iterators.partition(["hsa:1", "hsa:2", "hsa:3"], 2)) + @test KEGGAPI.build_kegg_url(partition_view, nothing) == "https://rest.kegg.jp/get/hsa:1+hsa:2" +end diff --git a/test/test_requests.jl b/test/test_requests.jl index a033ceb..69bc66d 100644 --- a/test/test_requests.jl +++ b/test/test_requests.jl @@ -254,7 +254,7 @@ import HTTP @test isa(r.data, Vector) sleep(0.4) @test_warn "Using the :image option with kegg_get is limited to one compound/glycan/drug entry" KEGGAPI.kegg_get(["map00010", "map01110"], :image) - @test_warn "KEGG API accepts 3 requests per second. Current timeout may lead to API rate limit errors." KEGGAPI.kegg_get("map00010"; timeout = 0.1) + @test_logs KEGGAPI.kegg_get("map00010"; request_delay = 0.1) # Doubled-size reference-pathway image request r = KEGGAPI.kegg_get("map00010", :image2x) diff --git a/test/test_utils.jl b/test/test_utils.jl new file mode 100644 index 0000000..4127103 --- /dev/null +++ b/test/test_utils.jl @@ -0,0 +1,34 @@ +using KEGGAPI +using Test + +@testset "request delay" begin + @test KEGGAPI.resolve_request_delay(nothing, nothing, :test_function, 2) == 0.4 + @test KEGGAPI.resolve_request_delay(1, nothing, :test_function, 2) == 1 + @test_deprecated r"use request_delay" KEGGAPI.resolve_request_delay(1, 1.0, :test_function, 2) + + for delay in (-0.1, Inf, -Inf, NaN) + @test_throws ArgumentError KEGGAPI.resolve_request_delay(delay, nothing, :test_function, 2) + @test_throws ArgumentError KEGGAPI.resolve_request_delay(nothing, delay, :test_function, 2) + end + @test_throws ArgumentError KEGGAPI.resolve_request_delay(0.4, 0.5, :test_function, 2) + + @test_logs KEGGAPI.resolve_request_delay(0.0, nothing, :test_function, 1) + @test_logs (:warn, r"three requests per second") KEGGAPI.resolve_request_delay(0.0, nothing, :test_function, 2) +end + +@testset "request batches" begin + requested_batches = Vector{Vector{String}}() + sleep_delays = Float64[] + request_batch = chunk -> push!(requested_batches, collect(chunk)) + record_sleep = delay -> push!(sleep_delays, delay) + + KEGGAPI.foreach_request_batch(request_batch, ["entry-$i" for i in 1:10], 0.4, record_sleep) + @test length(requested_batches) == 1 + @test isempty(sleep_delays) + + empty!(requested_batches) + KEGGAPI.foreach_request_batch(request_batch, ["entry-$i" for i in 1:21], 0.4, record_sleep) + @test length(requested_batches) == 3 + @test length.(requested_batches) == [10, 10, 1] + @test sleep_delays == [0.4, 0.4] +end