thephpleague / statsd

A library for working with StatsD
MIT License
351 stars 56 forks source link

Ability to use TCP connections. #62

Open Angel5a opened 2 years ago

Angel5a commented 2 years ago

Rarely somebody need that feature, but in case if does, here is support for TCP connections in a pull request.

UDP is great. It's fast, it's reliable in local connections and it even doesn't require to have server running.

But in case your StatsD server running on other machine and your network become flooded with packages (i.e. during DDoS attack), your packets will start to get lost and your metrics won't show you the real picture. You want get real count of unique IP addresses of clients. Attendance is falling, mean/percentile looks good, but site isn't going well. That's the problem that I run into.

Of cause it would be better to run local instances of StatsD on each server. But it's also possible to switch on TCP. You still need to set your NAT/firewall properly, cause no any authentication is used, and all your data goes in plane text thru the network.

As far as TCP connections take resources both from client and server, I added destructor and the ability to remove static instance, to free the connection. And because of destructor, magic __clone method is also appeared with a controversial decision. As far as testing with a TCP scheme requires running TCP server and everyone have different workspace, I opted TCP tests with an STATSD_TCP_ADDRESS environment variable that should have 'host:port' of any TCP server (it could be any http-server as well, because we don't need to get any meaningful answer from the server, just an IP SYN and ACK packets). On linux systems you can use nc -lk 127.0.0.1 8125 and set STATSD_TCP_ADDRESS to '127.0.0.1:8125' (IPv6 is also supported if needed).

Tested wit PHP 7.4, 8.0 and 8.1. Laravel integration updated. No breaking changes involved. Only minor changes:

I leave some minor phpDoc changer in separate commit, 'cause it's a controversial topic. Fell free tho throw them out or merge together.