fast_curl 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d01979b9bff516a526b66220807d7d325846eb507815dcfe46810daa14f5f782
4
+ data.tar.gz: d9ff4cb707451f4d3516426e84f22798d89ff8b7fdc549addb4e68fc22e55f3b
5
+ SHA512:
6
+ metadata.gz: 354b9d90daaa884f6bc31819a7377a10946874d945add791c61e5801c4c65fe618bb364ea0cc25e8bc155afddf07c9cb7dc0593accff7be33559a7c71b23cf1d
7
+ data.tar.gz: a6a87dae54ce7c8fb52aa5f7f5780df2943767b46a9c87f582fa20bb76475736eac3f4feb360b5cacf5edaad11e6eee2c81ecc7632248ef80b8154a6e6b88c27
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Haydarov Roman
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # fast_curl
2
+
3
+ Ultra-fast parallel HTTP client for Ruby. C extension built on libcurl `curl_multi` API.
4
+
5
+ ## Features
6
+
7
+ - **Parallel requests** via `curl_multi` — no threads, no fibers needed
8
+ - **GVL release** — `rb_thread_call_without_gvl` during I/O, other Ruby threads keep running
9
+ - **Fiber scheduler compatible** — works inside `Async do ... end` without blocking other fibers
10
+ - **Three modes**: execute (all), first_execute (first N), stream_execute (yield as ready)
11
+ - **Zero dependencies** — only libcurl (available everywhere)
12
+
13
+ ## Installation
14
+
15
+ **Requirements**: Ruby >= 3.0 (for Fiber scheduler support)
16
+
17
+ ```ruby
18
+ gem 'fast_curl'
19
+ ```
20
+
21
+ Requires libcurl development headers:
22
+
23
+ ```bash
24
+ # macOS
25
+ brew install curl
26
+
27
+ # Ubuntu/Debian
28
+ apt-get install libcurl4-openssl-dev
29
+
30
+ # Alpine
31
+ apk add curl-dev
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ ### Basic GET
37
+
38
+ ```ruby
39
+ results = FastCurl.get([
40
+ { url: "https://api.example.com/users" },
41
+ { url: "https://api.example.com/posts" }
42
+ ], connections: 20, timeout: 30)
43
+
44
+ results.each do |index, response|
45
+ puts "#{index}: #{response[:status]} — #{response[:body]}"
46
+ end
47
+ ```
48
+
49
+ ### POST with body and headers
50
+
51
+ ```ruby
52
+ FastCurl.post([
53
+ {
54
+ url: "https://api.example.com/users",
55
+ headers: { "Authorization" => "Bearer token" },
56
+ body: { name: "John" }
57
+ }
58
+ ])
59
+ ```
60
+
61
+ ### First N responses (cancel the rest)
62
+
63
+ ```ruby
64
+ result = FastCurl.first_get([
65
+ { url: "https://mirror1.example.com/file" },
66
+ { url: "https://mirror2.example.com/file" },
67
+ { url: "https://mirror3.example.com/file" }
68
+ ], count: 1)
69
+ ```
70
+
71
+ ### Stream responses as they arrive
72
+
73
+ ```ruby
74
+ FastCurl.stream_get(urls, connections: 50) do |index, response|
75
+ puts "Got response #{index}: #{response[:status]}"
76
+ end
77
+ ```
78
+
79
+ ### Inside Async
80
+
81
+ ```ruby
82
+ require "async"
83
+
84
+ Async do
85
+ # fast_curl detects the fiber scheduler and yields
86
+ # to other fibers during I/O instead of blocking
87
+ results = FastCurl.get(urls, connections: 20)
88
+ end
89
+ ```
90
+
91
+ ## Response format
92
+
93
+ ```ruby
94
+ [index, {
95
+ status: 200, # HTTP status code (0 on error)
96
+ headers: { "Key" => "Value" },
97
+ body: "response body"
98
+ }]
99
+ ```
100
+
101
+ ## Available methods
102
+
103
+ | Method | Description |
104
+ |---|---|
105
+ | `FastCurl.get(requests, **opts)` | GET all, wait for all |
106
+ | `FastCurl.post(requests, **opts)` | POST all, wait for all |
107
+ | `FastCurl.put(requests, **opts)` | PUT all, wait for all |
108
+ | `FastCurl.delete(requests, **opts)` | DELETE all, wait for all |
109
+ | `FastCurl.patch(requests, **opts)` | PATCH all, wait for all |
110
+ | `FastCurl.first_get(requests, count: 1, **opts)` | GET, return first N |
111
+ | `FastCurl.stream_get(requests, **opts) { \|i, r\| }` | GET, yield each |
112
+ | `FastCurl.execute(requests, **opts)` | Raw execute |
113
+ | `FastCurl.first_execute(requests, count: 1, **opts)` | Raw first N |
114
+ | `FastCurl.stream_execute(requests, **opts) { \|pair\| }` | Raw stream |
115
+
116
+ ## Options
117
+
118
+ | Option | Default | Description |
119
+ |---|---|---|
120
+ | `connections` | 20 | Max parallel connections |
121
+ | `timeout` | 30 | Per-request timeout in seconds |
122
+
123
+ ## Performance
124
+
125
+ Benchmark results (`bundle exec ruby benchmark/local_bench.rb`):
126
+
127
+ | Method | 4 parallel | 10 parallel | 20 parallel | 200 parallel |
128
+ |--------|------------|-------------|--------------|---------------|
129
+ | Net::HTTP sequential | 7.93s (+2.1 MB) | 24.20s (+0.3 MB) | 48.58s (+1.2 MB) | - |
130
+ | fast_curl (thread) | 2.09s (+0.7 MB) | 3.73s (+0.9 MB) | 3.76s (+0.0 MB) | 5.88s (+2.3 MB) |
131
+ | fast_curl (fiber) | 1.96s (+0.4 MB) | 4.86s (+0.0 MB) | 3.71s (+0.2 MB) | 9.60s (+1.6 MB) |
132
+ | Async::HTTP | 2.54s (+0.3 MB) | 4.27s (+0.4 MB) | 9.16s (+0.5 MB) | 22.44s (+10.7 MB) |
133
+
134
+ Additional scenarios:
135
+ - Stream execute (5 requests): 5.99s (+0.0 MB)
136
+ - First execute (first 1 of 5): 2.40s (+0.0 MB)
137
+ - Error handling (timeout=2s): 2.01s (+0.0 MB)
138
+
139
+ ## License
140
+
141
+ MIT
@@ -0,0 +1,14 @@
1
+ require "mkmf"
2
+
3
+ abort "libcurl is required" unless have_library("curl", "curl_multi_init")
4
+ abort "curl/curl.h is required" unless have_header("curl/curl.h")
5
+
6
+ have_header("ruby/thread.h")
7
+ have_header("ruby/fiber/scheduler.h")
8
+
9
+ have_func("rb_fiber_scheduler_current", "ruby.h")
10
+ have_func("rb_io_wait", "ruby.h")
11
+
12
+ $CFLAGS << " -std=c99 -O2 -Wall -Wextra -Wno-unused-parameter"
13
+
14
+ create_makefile("fast_curl/fast_curl")
@@ -0,0 +1,653 @@
1
+ #include <ruby.h>
2
+ #include <ruby/io.h>
3
+ #include <ruby/thread.h>
4
+ #ifdef HAVE_RUBY_FIBER_SCHEDULER_H
5
+ #include <ruby/fiber/scheduler.h>
6
+ #endif
7
+ #include <curl/curl.h>
8
+ #include <stdlib.h>
9
+ #include <string.h>
10
+
11
+ #define MAX_RESPONSE_SIZE (100 * 1024 * 1024)
12
+ #define MAX_REDIRECTS 5
13
+ #define MAX_TIMEOUT 300
14
+
15
+ typedef struct {
16
+ char *data;
17
+ size_t len;
18
+ size_t cap;
19
+ size_t max_size;
20
+ } buffer_t;
21
+
22
+ static void buffer_init(buffer_t *buf) {
23
+ buf->data = NULL;
24
+ buf->len = 0;
25
+ buf->cap = 0;
26
+ buf->max_size = MAX_RESPONSE_SIZE;
27
+ }
28
+
29
+ static void buffer_free(buffer_t *buf) {
30
+ if (buf->data) {
31
+ free(buf->data);
32
+ buf->data = NULL;
33
+ }
34
+ buf->len = 0;
35
+ buf->cap = 0;
36
+ }
37
+
38
+ static size_t write_callback(char *ptr, size_t size, size_t nmemb,
39
+ void *userdata) {
40
+ buffer_t *buf = (buffer_t *)userdata;
41
+ size_t total = size * nmemb;
42
+
43
+ if (buf->len + total > buf->max_size) {
44
+ return 0;
45
+ }
46
+
47
+ if (buf->len + total >= buf->cap) {
48
+ size_t new_cap = (buf->cap == 0) ? 4096 : buf->cap;
49
+ while (new_cap <= buf->len + total)
50
+ new_cap *= 2;
51
+
52
+ if (new_cap > buf->max_size) {
53
+ new_cap = buf->max_size;
54
+ }
55
+
56
+ char *new_data = realloc(buf->data, new_cap);
57
+ if (!new_data)
58
+ return 0;
59
+ buf->data = new_data;
60
+ buf->cap = new_cap;
61
+ }
62
+
63
+ memcpy(buf->data + buf->len, ptr, total);
64
+ buf->len += total;
65
+ return total;
66
+ }
67
+
68
+ typedef struct {
69
+ char **entries;
70
+ int count;
71
+ int cap;
72
+ } header_list_t;
73
+
74
+ static void header_list_init(header_list_t *h) {
75
+ h->entries = NULL;
76
+ h->count = 0;
77
+ h->cap = 0;
78
+ }
79
+
80
+ static void header_list_free(header_list_t *h) {
81
+ for (int i = 0; i < h->count; i++)
82
+ free(h->entries[i]);
83
+ free(h->entries);
84
+ h->entries = NULL;
85
+ h->count = 0;
86
+ h->cap = 0;
87
+ }
88
+
89
+ static size_t header_callback(char *ptr, size_t size, size_t nmemb,
90
+ void *userdata) {
91
+ header_list_t *h = (header_list_t *)userdata;
92
+ size_t total = size * nmemb;
93
+
94
+ if (total <= 2)
95
+ return total;
96
+
97
+ if (h->count >= h->cap) {
98
+ int new_cap = (h->cap == 0) ? 16 : h->cap * 2;
99
+ char **new_entries = realloc(h->entries, sizeof(char *) * new_cap);
100
+ if (!new_entries)
101
+ return 0;
102
+ h->entries = new_entries;
103
+ h->cap = new_cap;
104
+ }
105
+
106
+ char *entry = malloc(total + 1);
107
+ if (!entry)
108
+ return 0;
109
+ memcpy(entry, ptr, total);
110
+
111
+ while (total > 0 && (entry[total - 1] == '\r' || entry[total - 1] == '\n'))
112
+ total--;
113
+ entry[total] = '\0';
114
+ h->entries[h->count++] = entry;
115
+ return size * nmemb;
116
+ }
117
+
118
+ typedef struct {
119
+ CURL *easy;
120
+ int index;
121
+ buffer_t body;
122
+ header_list_t headers;
123
+ struct curl_slist *req_headers;
124
+ int done;
125
+ } request_ctx_t;
126
+
127
+ static void request_ctx_init(request_ctx_t *ctx, int index) {
128
+ ctx->easy = curl_easy_init();
129
+ ctx->index = index;
130
+ buffer_init(&ctx->body);
131
+ header_list_init(&ctx->headers);
132
+ ctx->req_headers = NULL;
133
+ ctx->done = 0;
134
+ }
135
+
136
+ static void request_ctx_free(request_ctx_t *ctx) {
137
+ if (ctx->easy) {
138
+ curl_easy_cleanup(ctx->easy);
139
+ ctx->easy = NULL;
140
+ }
141
+ buffer_free(&ctx->body);
142
+ header_list_free(&ctx->headers);
143
+ if (ctx->req_headers) {
144
+ curl_slist_free_all(ctx->req_headers);
145
+ ctx->req_headers = NULL;
146
+ }
147
+ }
148
+
149
+ typedef struct {
150
+ CURLM *multi;
151
+ request_ctx_t *requests;
152
+ int count;
153
+ int still_running;
154
+ long timeout_ms;
155
+ int max_connections;
156
+ } multi_session_t;
157
+
158
+ static VALUE build_response(request_ctx_t *ctx) {
159
+ long status = 0;
160
+ curl_easy_getinfo(ctx->easy, CURLINFO_RESPONSE_CODE, &status);
161
+
162
+ VALUE headers_hash = rb_hash_new();
163
+ for (int i = 0; i < ctx->headers.count; i++) {
164
+ char *colon = strchr(ctx->headers.entries[i], ':');
165
+ if (colon) {
166
+ VALUE key =
167
+ rb_str_new(ctx->headers.entries[i], colon - ctx->headers.entries[i]);
168
+ char *val_start = colon + 1;
169
+ while (*val_start == ' ' || *val_start == '\t')
170
+ val_start++;
171
+
172
+ char *val_end = ctx->headers.entries[i] + strlen(ctx->headers.entries[i]);
173
+ while (val_end > val_start &&
174
+ (*(val_end - 1) == ' ' || *(val_end - 1) == '\t' ||
175
+ *(val_end - 1) == '\r' || *(val_end - 1) == '\n')) {
176
+ val_end--;
177
+ }
178
+
179
+ size_t val_len = val_end - val_start;
180
+ VALUE val = rb_str_new(val_start, val_len);
181
+ rb_hash_aset(headers_hash, key, val);
182
+ }
183
+ }
184
+
185
+ VALUE body_str = ctx->body.data ? rb_str_new(ctx->body.data, ctx->body.len)
186
+ : rb_str_new_cstr("");
187
+
188
+ VALUE result = rb_hash_new();
189
+ rb_hash_aset(result, ID2SYM(rb_intern("status")), LONG2NUM(status));
190
+ rb_hash_aset(result, ID2SYM(rb_intern("headers")), headers_hash);
191
+ rb_hash_aset(result, ID2SYM(rb_intern("body")), body_str);
192
+
193
+ return result;
194
+ }
195
+
196
+ static VALUE build_error_response(const char *message) {
197
+ VALUE result = rb_hash_new();
198
+ rb_hash_aset(result, ID2SYM(rb_intern("status")), INT2NUM(0));
199
+ rb_hash_aset(result, ID2SYM(rb_intern("headers")), Qnil);
200
+ rb_hash_aset(result, ID2SYM(rb_intern("body")), rb_str_new_cstr(message));
201
+ return result;
202
+ }
203
+
204
+ static int is_valid_url(const char *url);
205
+ static VALUE build_error_response_with_code(const char *message,
206
+ int error_code);
207
+
208
+ #define CURL_SETOPT_CHECK(handle, option, value) \
209
+ do { \
210
+ CURLcode res = curl_easy_setopt(handle, option, value); \
211
+ if (res != CURLE_OK) { \
212
+ return res; \
213
+ } \
214
+ } while (0)
215
+
216
+ static CURLcode setup_basic_options(CURL *easy, const char *url_str,
217
+ long timeout_sec, request_ctx_t *ctx) {
218
+
219
+ CURL_SETOPT_CHECK(easy, CURLOPT_URL, url_str);
220
+ CURL_SETOPT_CHECK(easy, CURLOPT_WRITEFUNCTION, write_callback);
221
+ CURL_SETOPT_CHECK(easy, CURLOPT_WRITEDATA, &ctx->body);
222
+ CURL_SETOPT_CHECK(easy, CURLOPT_HEADERFUNCTION, header_callback);
223
+ CURL_SETOPT_CHECK(easy, CURLOPT_HEADERDATA, &ctx->headers);
224
+ CURL_SETOPT_CHECK(easy, CURLOPT_TIMEOUT, timeout_sec);
225
+ CURL_SETOPT_CHECK(easy, CURLOPT_NOSIGNAL, 1L);
226
+ CURL_SETOPT_CHECK(easy, CURLOPT_FOLLOWLOCATION, 1L);
227
+ CURL_SETOPT_CHECK(easy, CURLOPT_MAXREDIRS, MAX_REDIRECTS);
228
+ CURL_SETOPT_CHECK(easy, CURLOPT_ACCEPT_ENCODING, "");
229
+ CURL_SETOPT_CHECK(easy, CURLOPT_PRIVATE, (char *)ctx);
230
+
231
+ return CURLE_OK;
232
+ }
233
+
234
+ static CURLcode setup_security_options(CURL *easy) {
235
+
236
+ CURL_SETOPT_CHECK(easy, CURLOPT_SSL_VERIFYPEER, 1L);
237
+ CURL_SETOPT_CHECK(easy, CURLOPT_SSL_VERIFYHOST, 2L);
238
+
239
+ #ifdef CURLOPT_PROTOCOLS_STR
240
+ CURL_SETOPT_CHECK(easy, CURLOPT_PROTOCOLS_STR, "http,https");
241
+ CURL_SETOPT_CHECK(easy, CURLOPT_REDIR_PROTOCOLS_STR, "http,https");
242
+ #else
243
+
244
+ CURL_SETOPT_CHECK(easy, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
245
+ CURL_SETOPT_CHECK(easy, CURLOPT_REDIR_PROTOCOLS,
246
+ CURLPROTO_HTTP | CURLPROTO_HTTPS);
247
+ #endif
248
+
249
+ return CURLE_OK;
250
+ }
251
+
252
+ static CURLcode setup_method_and_body(CURL *easy, VALUE method, VALUE body) {
253
+ if (!NIL_P(method)) {
254
+ const char *m = StringValueCStr(method);
255
+ if (strcmp(m, "POST") == 0) {
256
+ CURL_SETOPT_CHECK(easy, CURLOPT_POST, 1L);
257
+ } else if (strcmp(m, "PUT") == 0) {
258
+ CURL_SETOPT_CHECK(easy, CURLOPT_CUSTOMREQUEST, "PUT");
259
+ } else if (strcmp(m, "DELETE") == 0) {
260
+ CURL_SETOPT_CHECK(easy, CURLOPT_CUSTOMREQUEST, "DELETE");
261
+ } else if (strcmp(m, "PATCH") == 0) {
262
+ CURL_SETOPT_CHECK(easy, CURLOPT_CUSTOMREQUEST, "PATCH");
263
+ } else if (strcmp(m, "GET") != 0) {
264
+
265
+ CURL_SETOPT_CHECK(easy, CURLOPT_CUSTOMREQUEST, m);
266
+ }
267
+ }
268
+
269
+ if (!NIL_P(body)) {
270
+ CURL_SETOPT_CHECK(easy, CURLOPT_POSTFIELDS, StringValuePtr(body));
271
+ CURL_SETOPT_CHECK(easy, CURLOPT_POSTFIELDSIZE, RSTRING_LEN(body));
272
+ }
273
+
274
+ return CURLE_OK;
275
+ }
276
+
277
+ static int setup_easy_handle(request_ctx_t *ctx, VALUE request,
278
+ long timeout_sec) {
279
+ VALUE url = rb_hash_aref(request, ID2SYM(rb_intern("url")));
280
+ VALUE method = rb_hash_aref(request, ID2SYM(rb_intern("method")));
281
+ VALUE headers = rb_hash_aref(request, ID2SYM(rb_intern("headers")));
282
+ VALUE body = rb_hash_aref(request, ID2SYM(rb_intern("body")));
283
+
284
+ if (NIL_P(url)) {
285
+ return 0;
286
+ }
287
+
288
+ const char *url_str = StringValueCStr(url);
289
+
290
+ if (!is_valid_url(url_str)) {
291
+ rb_raise(rb_eArgError, "Invalid URL: %s", url_str);
292
+ }
293
+
294
+ CURLcode res;
295
+
296
+ res = setup_basic_options(ctx->easy, url_str, timeout_sec, ctx);
297
+ if (res != CURLE_OK)
298
+ return 0;
299
+
300
+ res = setup_security_options(ctx->easy);
301
+ if (res != CURLE_OK)
302
+ return 0;
303
+
304
+ res = setup_method_and_body(ctx->easy, method, body);
305
+ if (res != CURLE_OK)
306
+ return 0;
307
+
308
+ if (!NIL_P(headers) && rb_obj_is_kind_of(headers, rb_cHash)) {
309
+ VALUE keys = rb_funcall(headers, rb_intern("keys"), 0);
310
+ long hlen = RARRAY_LEN(keys);
311
+ for (long i = 0; i < hlen; i++) {
312
+ VALUE key = rb_ary_entry(keys, i);
313
+ VALUE val = rb_hash_aref(headers, key);
314
+ VALUE header_line;
315
+
316
+ if (NIL_P(val) || RSTRING_LEN(rb_String(val)) == 0) {
317
+ header_line = rb_sprintf("%" PRIsVALUE ";", key);
318
+ } else {
319
+ header_line = rb_sprintf("%" PRIsVALUE ": %" PRIsVALUE, key, val);
320
+ }
321
+
322
+ ctx->req_headers =
323
+ curl_slist_append(ctx->req_headers, StringValueCStr(header_line));
324
+ if (!ctx->req_headers) {
325
+ return 0;
326
+ }
327
+ }
328
+
329
+ res = curl_easy_setopt(ctx->easy, CURLOPT_HTTPHEADER, ctx->req_headers);
330
+ if (res != CURLE_OK)
331
+ return 0;
332
+ }
333
+
334
+ return 1;
335
+ }
336
+
337
+ static void *perform_without_gvl(void *arg) {
338
+ multi_session_t *session = (multi_session_t *)arg;
339
+
340
+ while (session->still_running > 0) {
341
+ CURLMcode mc = curl_multi_perform(session->multi, &session->still_running);
342
+ if (mc != CURLM_OK)
343
+ break;
344
+
345
+ if (session->still_running > 0) {
346
+ int numfds = 0;
347
+ mc = curl_multi_poll(session->multi, NULL, 0, 100, &numfds);
348
+ if (mc != CURLM_OK)
349
+ break;
350
+ }
351
+ }
352
+
353
+ return NULL;
354
+ }
355
+
356
+ static void *poll_without_gvl(void *arg) {
357
+ multi_session_t *session = (multi_session_t *)arg;
358
+ int numfds = 0;
359
+ curl_multi_poll(session->multi, NULL, 0, 100, &numfds);
360
+ curl_multi_perform(session->multi, &session->still_running);
361
+ return NULL;
362
+ }
363
+
364
+ static void unblock_perform(void *arg) {
365
+ multi_session_t *session = (multi_session_t *)arg;
366
+ (void)session;
367
+ }
368
+
369
+ static int has_fiber_scheduler(void) {
370
+ #ifdef HAVE_RB_FIBER_SCHEDULER_CURRENT
371
+ VALUE scheduler = rb_fiber_scheduler_current();
372
+ return scheduler != Qnil && scheduler != Qfalse;
373
+ #else
374
+ return 0;
375
+ #endif
376
+ }
377
+
378
+ typedef struct {
379
+ VALUE results;
380
+ int completed;
381
+ int target;
382
+ int stream;
383
+ } completion_ctx_t;
384
+
385
+ static int process_completed(multi_session_t *session, completion_ctx_t *cctx) {
386
+ CURLMsg *msg;
387
+ int msgs_left;
388
+
389
+ while ((msg = curl_multi_info_read(session->multi, &msgs_left))) {
390
+ if (msg->msg != CURLMSG_DONE)
391
+ continue;
392
+
393
+ request_ctx_t *ctx = NULL;
394
+ curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char **)&ctx);
395
+ if (!ctx || ctx->done)
396
+ continue;
397
+ ctx->done = 1;
398
+
399
+ VALUE response;
400
+ if (msg->data.result == CURLE_OK) {
401
+ response = build_response(ctx);
402
+ } else {
403
+
404
+ response = build_error_response_with_code(
405
+ curl_easy_strerror(msg->data.result), (int)msg->data.result);
406
+ }
407
+
408
+ VALUE pair = rb_ary_new_from_args(2, INT2NUM(ctx->index), response);
409
+
410
+ if (cctx->stream) {
411
+ rb_yield(pair);
412
+ } else if (!NIL_P(cctx->results)) {
413
+ rb_ary_store(cctx->results, ctx->index, pair);
414
+ }
415
+
416
+ cctx->completed++;
417
+
418
+ if (cctx->target > 0 && cctx->completed >= cctx->target) {
419
+ return 1;
420
+ }
421
+ }
422
+
423
+ return 0;
424
+ }
425
+
426
+ static VALUE build_error_response_with_code(const char *message,
427
+ int error_code) {
428
+ VALUE result = rb_hash_new();
429
+ rb_hash_aset(result, ID2SYM(rb_intern("status")), INT2NUM(0));
430
+ rb_hash_aset(result, ID2SYM(rb_intern("headers")), Qnil);
431
+ rb_hash_aset(result, ID2SYM(rb_intern("body")), rb_str_new_cstr(message));
432
+ rb_hash_aset(result, ID2SYM(rb_intern("error_code")), INT2NUM(error_code));
433
+ return result;
434
+ }
435
+
436
+ static int is_valid_url(const char *url) {
437
+ if (!url || strlen(url) == 0)
438
+ return 0;
439
+
440
+ size_t url_len = strlen(url);
441
+
442
+ if (url_len > 2048) {
443
+ return 0;
444
+ }
445
+
446
+ if (strncmp(url, "http://", 7) != 0 && strncmp(url, "https://", 8) != 0) {
447
+ return 0;
448
+ }
449
+
450
+ if (strncmp(url, "file://", 7) == 0 || strncmp(url, "ftp://", 6) == 0 ||
451
+ strncmp(url, "gopher://", 9) == 0 || strncmp(url, "ldap://", 7) == 0 ||
452
+ strncmp(url, "dict://", 7) == 0 || strncmp(url, "tftp://", 7) == 0) {
453
+ return 0;
454
+ }
455
+
456
+ return 1;
457
+ }
458
+
459
+ static VALUE parse_options(VALUE options, long *timeout, int *max_conn) {
460
+ *timeout = 30;
461
+ *max_conn = 20;
462
+
463
+ if (!NIL_P(options) && rb_obj_is_kind_of(options, rb_cHash)) {
464
+ VALUE t = rb_hash_aref(options, ID2SYM(rb_intern("timeout")));
465
+ VALUE c = rb_hash_aref(options, ID2SYM(rb_intern("connections")));
466
+
467
+ if (!NIL_P(t)) {
468
+ long timeout_val = NUM2LONG(t);
469
+
470
+ if (timeout_val > MAX_TIMEOUT) {
471
+ timeout_val = MAX_TIMEOUT;
472
+ } else if (timeout_val <= 0) {
473
+ timeout_val = 30;
474
+ }
475
+ *timeout = timeout_val;
476
+ }
477
+
478
+ if (!NIL_P(c)) {
479
+ int conn_val = NUM2INT(c);
480
+
481
+ if (conn_val > 100) {
482
+ conn_val = 100;
483
+ } else if (conn_val <= 0) {
484
+ conn_val = 20;
485
+ }
486
+ *max_conn = conn_val;
487
+ }
488
+ }
489
+
490
+ return Qnil;
491
+ }
492
+
493
+ static VALUE internal_execute(VALUE requests, VALUE options, int target,
494
+ int stream) {
495
+ Check_Type(requests, T_ARRAY);
496
+ int count = (int)RARRAY_LEN(requests);
497
+ if (count == 0)
498
+ return rb_ary_new();
499
+
500
+ long timeout_sec;
501
+ int max_conn;
502
+ parse_options(options, &timeout_sec, &max_conn);
503
+
504
+ multi_session_t session;
505
+ session.multi = curl_multi_init();
506
+ session.count = count;
507
+ session.timeout_ms = timeout_sec * 1000;
508
+ session.max_connections = max_conn;
509
+
510
+ curl_multi_setopt(session.multi, CURLMOPT_MAXCONNECTS, (long)max_conn);
511
+ curl_multi_setopt(session.multi, CURLMOPT_MAX_TOTAL_CONNECTIONS,
512
+ (long)max_conn);
513
+
514
+ session.requests = calloc(count, sizeof(request_ctx_t));
515
+ if (!session.requests) {
516
+ curl_multi_cleanup(session.multi);
517
+ rb_raise(rb_eNoMemError, "failed to allocate request contexts");
518
+ }
519
+
520
+ int valid_requests = 0;
521
+ for (int i = 0; i < count; i++) {
522
+ VALUE req = rb_ary_entry(requests, i);
523
+ request_ctx_init(&session.requests[i], i);
524
+
525
+ if (!setup_easy_handle(&session.requests[i], req, timeout_sec)) {
526
+
527
+ session.requests[i].done = 1;
528
+ continue;
529
+ }
530
+
531
+ CURLMcode mc =
532
+ curl_multi_add_handle(session.multi, session.requests[i].easy);
533
+ if (mc != CURLM_OK) {
534
+ session.requests[i].done = 1;
535
+ continue;
536
+ }
537
+
538
+ valid_requests++;
539
+ }
540
+
541
+ if (valid_requests == 0) {
542
+ session.still_running = 0;
543
+ }
544
+
545
+ completion_ctx_t cctx;
546
+ cctx.results = stream ? Qnil : rb_ary_new2(count);
547
+ cctx.completed = 0;
548
+ cctx.target = target;
549
+ cctx.stream = stream;
550
+
551
+ if (!stream) {
552
+ for (int i = 0; i < count; i++)
553
+ rb_ary_store(cctx.results, i, Qnil);
554
+ }
555
+
556
+ if (has_fiber_scheduler()) {
557
+ while (session.still_running > 0 || 1) {
558
+ CURLMcode mc = curl_multi_perform(session.multi, &session.still_running);
559
+ if (mc != CURLM_OK)
560
+ break;
561
+ if (process_completed(&session, &cctx))
562
+ break;
563
+ if (session.still_running == 0)
564
+ break;
565
+
566
+ int numfds = 0;
567
+ curl_multi_poll(session.multi, NULL, 0, 1, &numfds);
568
+ rb_thread_schedule();
569
+ }
570
+
571
+ process_completed(&session, &cctx);
572
+ } else {
573
+ if (stream || target > 0) {
574
+ curl_multi_perform(session.multi, &session.still_running);
575
+ while (session.still_running > 0) {
576
+ rb_thread_call_without_gvl(poll_without_gvl, &session, unblock_perform,
577
+ &session);
578
+ if (process_completed(&session, &cctx))
579
+ break;
580
+ }
581
+ process_completed(&session, &cctx);
582
+ } else {
583
+ session.still_running = 1;
584
+ curl_multi_perform(session.multi, &session.still_running);
585
+ rb_thread_call_without_gvl(perform_without_gvl, &session, unblock_perform,
586
+ &session);
587
+ process_completed(&session, &cctx);
588
+ }
589
+ }
590
+
591
+ if (!stream) {
592
+ for (int i = 0; i < count; i++) {
593
+ if (session.requests[i].done && rb_ary_entry(cctx.results, i) == Qnil) {
594
+
595
+ VALUE error_response =
596
+ build_error_response("Invalid request configuration");
597
+ VALUE pair = rb_ary_new_from_args(2, INT2NUM(i), error_response);
598
+ rb_ary_store(cctx.results, i, pair);
599
+ }
600
+ }
601
+ }
602
+
603
+ for (int i = 0; i < count; i++) {
604
+ curl_multi_remove_handle(session.multi, session.requests[i].easy);
605
+ request_ctx_free(&session.requests[i]);
606
+ }
607
+ free(session.requests);
608
+ curl_multi_cleanup(session.multi);
609
+
610
+ return stream ? Qnil : cctx.results;
611
+ }
612
+
613
+ static VALUE rb_fast_curl_execute(int argc, VALUE *argv, VALUE self) {
614
+ VALUE requests, options;
615
+ rb_scan_args(argc, argv, "1:", &requests, &options);
616
+ return internal_execute(requests, options, -1, 0);
617
+ }
618
+
619
+ static VALUE rb_fast_curl_first_execute(int argc, VALUE *argv, VALUE self) {
620
+ VALUE requests, options;
621
+ rb_scan_args(argc, argv, "1:", &requests, &options);
622
+
623
+ int count = 1;
624
+ if (!NIL_P(options)) {
625
+ VALUE c = rb_hash_aref(options, ID2SYM(rb_intern("count")));
626
+ if (!NIL_P(c))
627
+ count = NUM2INT(c);
628
+ }
629
+
630
+ return internal_execute(requests, options, count, 0);
631
+ }
632
+
633
+ static VALUE rb_fast_curl_stream_execute(int argc, VALUE *argv, VALUE self) {
634
+ VALUE requests, options;
635
+ rb_scan_args(argc, argv, "1:", &requests, &options);
636
+
637
+ if (!rb_block_given_p())
638
+ rb_raise(rb_eArgError, "stream_execute requires a block");
639
+
640
+ return internal_execute(requests, options, -1, 1);
641
+ }
642
+
643
+ void Init_fast_curl(void) {
644
+ curl_global_init(CURL_GLOBAL_ALL);
645
+
646
+ VALUE mFastCurl = rb_define_module("FastCurl");
647
+
648
+ rb_define_module_function(mFastCurl, "execute", rb_fast_curl_execute, -1);
649
+ rb_define_module_function(mFastCurl, "first_execute",
650
+ rb_fast_curl_first_execute, -1);
651
+ rb_define_module_function(mFastCurl, "stream_execute",
652
+ rb_fast_curl_stream_execute, -1);
653
+ }
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FastCurl
4
+ VERSION = "0.1.0"
5
+ end
data/lib/fast_curl.rb ADDED
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require_relative "fast_curl/version"
5
+ require_relative "fast_curl/fast_curl"
6
+
7
+ module FastCurl
8
+ class Error < StandardError; end
9
+ class TimeoutError < Error; end
10
+
11
+ DEFAULT_OPTIONS = {
12
+ connections: 20,
13
+ timeout: 30
14
+ }.freeze
15
+
16
+ METHODS = %i[get post put delete patch].freeze
17
+ BODY_METHODS = %i[post put patch].freeze
18
+
19
+ class << self
20
+ METHODS.each do |method|
21
+ define_method(method) do |requests, **options|
22
+ execute(build_requests(requests, method), **DEFAULT_OPTIONS.merge(options))
23
+ end
24
+
25
+ define_method(:"first_#{method}") do |requests, count: 1, **options|
26
+ first_execute(build_requests(requests, method), count: count, **DEFAULT_OPTIONS.merge(options))
27
+ end
28
+
29
+ define_method(:"stream_#{method}") do |requests, **options, &block|
30
+ stream_execute(build_requests(requests, method), **DEFAULT_OPTIONS.merge(options), &block)
31
+ end
32
+ end
33
+
34
+ private
35
+
36
+ def build_requests(requests, method)
37
+ requests.map do |req|
38
+ r = { url: req[:url], method: method.to_s.upcase }
39
+ r[:headers] = req[:headers] if req[:headers]
40
+ if req[:body] && BODY_METHODS.include?(method)
41
+ r[:body] = req[:body].is_a?(Hash) ? req[:body].to_json : req[:body].to_s
42
+ r[:headers] = (r[:headers] || {}).merge("Content-Type" => "application/json") if req[:body].is_a?(Hash)
43
+ end
44
+ r
45
+ end
46
+ end
47
+ end
48
+ end
metadata ADDED
@@ -0,0 +1,136 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fast_curl
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - roman-haidarov
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-03-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: json
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '13.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '13.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake-compiler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.2'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.2'
55
+ - !ruby/object:Gem::Dependency
56
+ name: minitest
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '5.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '5.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: benchmark-ips
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '2.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '2.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: webrick
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '1.8'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '1.8'
97
+ description: Parallel HTTP requests via libcurl curl_multi API. Releases GVL during
98
+ I/O, compatible with Async gem and Fiber scheduler. Supports execute (all), first_execute
99
+ (first N), stream_execute (yield as ready).
100
+ email:
101
+ - roman.haidarov@gmail.com
102
+ executables: []
103
+ extensions:
104
+ - ext/fast_curl/extconf.rb
105
+ extra_rdoc_files: []
106
+ files:
107
+ - LICENSE.txt
108
+ - README.md
109
+ - ext/fast_curl/extconf.rb
110
+ - ext/fast_curl/fast_curl.c
111
+ - lib/fast_curl.rb
112
+ - lib/fast_curl/version.rb
113
+ homepage: https://github.com/roman-haidarov/fast_curl
114
+ licenses:
115
+ - MIT
116
+ metadata: {}
117
+ post_install_message:
118
+ rdoc_options: []
119
+ require_paths:
120
+ - lib
121
+ required_ruby_version: !ruby/object:Gem::Requirement
122
+ requirements:
123
+ - - ">="
124
+ - !ruby/object:Gem::Version
125
+ version: 3.0.0
126
+ required_rubygems_version: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - ">="
129
+ - !ruby/object:Gem::Version
130
+ version: '0'
131
+ requirements: []
132
+ rubygems_version: 3.3.27
133
+ signing_key:
134
+ specification_version: 4
135
+ summary: Ultra-fast parallel HTTP client as Ruby C extension on libcurl multi
136
+ test_files: []