Giter Site home page Giter Site logo

lpgauth / shackle Goto Github PK

View Code? Open in Web Editor NEW
187.0 21.0 45.0 4.78 MB

High-Performance Erlang Network Client Framework

License: MIT License

Makefile 1.03% Erlang 97.25% Shell 0.73% Elixir 1.00%
high-performance erlang client framework tcp udp ssl

shackle's Introduction

shackle

High-Performance Erlang Network Client Framework

Build Status

Requirements

  • Erlang 19.0+

Features

  • Backpressure via backlog (OOM protection)
  • Fast pool implementation (random, round_robin)
  • Managed timeouts
  • Multi-protocol support (SSL / TCP / UDP)
  • Performance-optimized
  • Request pipelining
  • Smart reconnect mechanism (exponential backoff)

Framework goals

  • Reusability
  • Speed
  • Concurrency
  • Safety

How-to

Implementing a client

-behavior(shackle_client).
-export([
    init/0,
    setup/2,
    handle_request/2,
    handle_data/2,
    terminate/1
]).

-record(state, {
    buffer =       <<>> :: binary(),
    request_counter = 0 :: non_neg_integer()
}).

-spec init(Options :: term()) ->
    {ok, State :: term()} |
    {error, Reason :: term()}.

init(_Options) ->
    {ok, #state {}}.

-spec setup(Socket :: inet:socket(), State :: term()) ->
    {ok, State :: term()} |
    {error, Reason :: term(), State :: term()}.

setup(Socket, State) ->
    case gen_tcp:send(Socket, <<"INIT">>) of
        ok ->
            case gen_tcp:recv(Socket, 0) of
                {ok, <<"OK">>} ->
                    {ok, State};
                {error, Reason} ->
                    {error, Reason, State}
            end;
        {error, Reason} ->
            {error, Reason, State}
    end.

-spec handle_request(Request :: term(), State :: term()) ->
    {ok, RequestId :: external_request_id(), Data :: iodata(), State :: term()}.

handle_request(noop,  State) ->
    Data = arithmetic_protocol:request(0, noop, 0, 0),

    {ok, undefined, Data, State};
handle_request({Operation, A, B}, #state {
        request_counter = RequestCounter
    } = State) ->

    RequestId = request_id(RequestCounter),
    Data = request(RequestId, Operation, A, B),

    {ok, RequestId, Data, State#state {
        request_counter = RequestCounter + 1
    }}.

-spec handle_data(Data :: binary(), State :: term()) ->
    {ok, [{RequestId :: external_request_id(), Reply :: term()}], State :: term()}.

handle_data(Data, #state {
        buffer = Buffer
    } = State) ->

    Data2 = <<Buffer/binary, Data/binary>>,
    {Replies, Buffer2} = parse_replies(Data2, []),

    {ok, Replies, State#state {
        buffer = Buffer2
    }}.

-spec terminate(State :: term()) -> ok.

terminate(_State) -> ok.

Starting client pool

shackle_pool:start(shackle_pool:name(), client(), client_options(), pool_options())
client_options:
Name Type Default Description
address inet:ip_address() | inet:hostname() "127.0.0.1" server address (formerly ip)
port inet:port_number() undefined server port
protocol shackle_tcp | shackle_udp | shackle_ssl shackle_tcp server protocol
reconnect boolean() true reconnect closed connections
reconnect_time_max pos_integer() | infinity 120000 maximum reconnect time in milliseconds
reconnect_time_min pos_integer() 1000 minimum reconnect time in milliseconds
socket_options [gen_tcp:connect_option() | gen_udp:option()] [] options passed to the socket
pool_options:
Name Type Default Description
backlog_size pos_integer() | infinity 1024 maximum number of concurrent requests per connection
max_retries non_neg_integer() 3 maximum number of tries to find an active server
pool_size pos_integer() 16 number of connections
pool_strategy random | round_robin random connection selection strategy

Calling / Casting client

1> shackle:call(pool_name, {get, <<"test">>}).
{ok, <<"bar">>}

2> {ok, ReqId} = shackle:cast(pool_name, {get, <<"foo">>}, 500).
{ok, {anchor, anchor_client, #Ref<0.0.0.2407>}}

3> shackle:receive_response(ReqId).
{ok, <<"bar">>}

Telemetry

Shackle integrates with the backend-agnostic telemetry library. See shackle_telemetry for the list of telemetry events that shackle can emit.

Tests

make dialyzer
make eunit
make xref

Performance testing

To run performance testing targets you must first start the server:

./bin/server.sh

Then you can run the bench or profile target:

make bench
make profile

Clients

Name Description
anchor Memcached Client
aspike-node Aerospike Client
buoy HTTP 1.1 Client
flare Kafka Producer
marina Cassandra CQL Client
statsderl StatsD Client

License

The MIT License (MIT)

Copyright (c) 2015-2023 Louis-Philippe Gauthier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

shackle's People

Contributors

fbernier avatar getong avatar haguenau avatar lpgauth avatar pjhades avatar ppikula avatar rkallos avatar tokenrove avatar tsloughter avatar vsavkov avatar weatherman2095 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

shackle's Issues

Request does not timeout when client throws an error

It seems like a call is never timing out if the client throws an error during handle_data or handle_request. Example:

client:

-module(bad_client).

-behavior(shackle_client).

-export([
    init/0,
    setup/2,
    handle_request/2,
    handle_data/2,
    terminate/1
]).

-record(state, {
    req = 0
}).

init() ->
    {ok, #state{}}.

setup(_, State) ->
    {ok, State}.

handle_request(_, #state{req = Requests} = State) ->
    Requests = this_should_error,

    {ok, Requests, <<"does_not_matter">>, State#state{req = Requests + 1}}.

handle_data(_, State) ->
    {ok, [], State}.

terminate(_State) ->
    ok.

pool setting:

2> shackle_pool:start(bad_client, bad_client, [{ip, "127.0.0.1"}, {port, 3000}], [{pool_size, 4}]).
ok
3> shackle:call(bad_client, some_req).

The call never returns

granderl in applications list

granderl isn't included in the applications list of the .app.src file. This will mean it won't be considered a runtime dependency by rebar3 and relx and thus not be included in any releases that rely on shackle.

So it should be added to the list before publishing a new hex package that includes it as a dependency.

Granderl is not currently compiling on osx

Hello,

Granderl is not cross compiling yet and is limiting the usage of your library on OSX.
I see you recently integrated this one. Maybe you can do something to use on osx another library

Silviu

Fix test flakiness

The reconnect tests use sleep and are not fully deterministic. This needs to be addressed so that the test suite doesn't randomly fail all the time (especially on Travis-CI).

Support send and forget messages?

Hi! I see that currently shackle expects all messages to fit into a request-response pattern, would it be possible to add a way to send a message through the client without expecting a reply?

Use-case: you want to send a message to a server, but the server won't send a response. Currently the way to get around the request-response limitation is to implement handle_timeout/2 with a dummy return (for example):

%% at shackle_client
%% won't care about the reply
handle_request({cast, Msg}, State) -> {ok, 0, Msg, State}.

handle_timeout(0, State) -> {ok, {0, ok}, State}.

%% ...

%% at call site
ok = shackle:call(pool, {cast, <<"don't care">>}, 0).

My idea would be to let Client:handle_request/2 return {ok, Data :: iodata(), State :: term()}, signalling that it won't expect a reply for that message. This would avoid storing the a dummy request identifier, and bypass the timeout mechanism.

(I think this what #72 tried to address)

Server shouldn't crash when there's a lookup error

=CRASH REPORT==== 10-Feb-2017::13:49:39 ===
  crasher:
    initial call: shackle_server:init/5
    pid: <0.709.0>
    registered_name: 'googleusercontent.com_80_1'
    exception error: no match of right hand side value {error,nxdomain}
      in function  shackle_server:init/5 (/Users/lpgauth/Git/buoy/_build/default/lib/shackle/src/shackle_server.erl, line 65)
    ancestors: [shackle_sup,<0.67.0>]
    messages: [connect]
    links: [<0.68.0>]
    dictionary: []
    trap_exit: true
    status: running
    heap_size: 610
    stack_size: 27
    reductions: 305
  neighbours:

Any plan to add metrics for the pools ?

Hello do you have any plan to add metrics for the pools ? Like:

  • connections_up (counter)
  • total_requests (counter)
  • finished_requests (counter)
  • running_requests (counter)
  • response_time (histogram)

Kind regards,
Silviu

API changes

Change API to use async_* prefix to be consistent with other Shackle clients.

Add `max_requests` client option

Add an option to limit the number of requests that can be handled per connection (before a reconnect). This is useful for load-balancing when using DNS.

connection closed messages are spamming the logs

Can you please remove : ?WARN(PoolName, "connection closed", []), from the code.

There are http servers that doesnt support persistent connections and are closing your socket after each request. This is spamming the logs when using buoy.

Silviu

Make client name configurable

Currently, the Client name is equal to the Client module name. It would nice to be able to dynamically configure the name.

Publish to hex.pm

Hi,

Just thought I would ask if you could publish this library to hex.pm? There are a number of benefits to having the library on hex, for both Erlang and Elixir projects. Here's the documentation for rebar3, which it already seems you are using: https://hex.pm/docs/rebar3_publish

I would love to contribute by sending a pull request but I imagine this is something you'd rather have full control over. Let me know if I can help in any way!

Thanks!

master failure ets table

I tried the latest master with my project vonnegut and after the first test it starts to fail to start the pool with a badarg on this stacktrace:

[{ets,update_counter,[shackle_pool_index,{metadata,round_robin},[{2,1,2,1}]],[]},{shackle_pool,server_index,3,[{file,"/home/tristan/Devel/vonnegut/_build/default/lib/shackle/src/shackle_pool.erl"},{line,137}]},

With the hex package it passes fine. I'm going to dig in to see if I can find the cause.

cant send data back to sending socket

hI,

hope u are good.
i needed some help with the shackle library.
i have been able to get it to work but am having some difficulties.
i have been trying to use shackle for a tcp client pool.
i am able to process the data received but cant seem to reply back to the sender of the data.
any idea why the recipient doesn't seem to receive the info sent back .
i wanted to know which part of the message also i received should identify the sender so i can send the info back to the sender.
thanks for the library also.

ETS_TAKE being defined despite using OTP 17

shackle tries to call ets:take.

OTP 17 should not have defined ETS_TAKE.
{erl_opts, [ debug_info, {platform_define, "18|19|^2", 'ETS_TAKE'}, {platform_define, "19|^2", 'UDP_HEADER'} ]}.

I am using rebar3 3.10.0

update hex package to 0.5.3

I was going to open an issue asking about a crash I've been seeing where send_after is passed none for the reconnect timeout, but then I noticed maybe it was something fixed between 0.5.1 and 0.5.3? I'll look at the diffs in a minute, but either way, could you publish the latest version to hex? Thanks!

ARM build fails

Due to tokenrove/granderl#13 the ARM build for this (and hence https://github.com/lpgauth/statsderl) is failing. Certainly for statsderl I don't believe that the prng code in granderl is actually needed. Is there any way to work around this at build time eg via some environment/configuration variable so that we can get some functionality working on ARM without granderl issues needing to be resolved?

Support `ssl_closed`

=SUPERVISOR REPORT==== 13-Dec-2017::18:08:11 ===
     Supervisor: {local,shackle_sup}
     Context:    child_terminated
     Reason:     {function_clause,
                     [{shackle_ssl_server,handle_msg,
                          [{ssl_closed,
                               {sslsocket,
                                   {gen_tcp,#Port<0.68243>,tls_connection,
                                       undefined},
                                   <0.1459.0>}},
                           {{state,buoy_client,"sun.com",
                                'https_sun.com_443_1',<0.468.0>,
                                'https_sun.com_443',443,undefined,undefined,
                                [binary,
                                 {packet,line},
                                 {packet,raw},
                                 {send_timeout,50},
                                 {send_timeout_close,true}],
                                undefined},
                            {state,
                                {bin_patterns,
                                    {bm,#Ref<0.10484378.3710517252.3632>},
                                    {bm,#Ref<0.10484378.3710517252.3633>}},
                                <<>>,0,1,undefined}}],
                          [{file,
                               "/Users/lpgauth/Git/buoy/_build/default/lib/shackle/src/shackle_ssl_server.erl"},
                           {line,66}]},
                      {metal,loop,4,
                          [{file,
                               "/Users/lpgauth/Git/buoy/_build/default/lib/metal/src/metal.erl"},
                           {line,88}]}]}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.