• Stars
    star
    3,030
  • Rank 14,885 (Top 0.3 %)
  • Language
    C++
  • License
    Apache License 2.0
  • Created about 10 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Wangle is a framework providing a set of common client/server abstractions for building services in a consistent, modular, and composable way.

Support Ukraine Travis Build Status CI Status

Wangle

C++ networking library

Wangle is a library that makes it easy to build protocols, application clients, and application servers.

It's like Netty + Finagle smooshed together, but in C++

Building and Installing

The main dependencies are:

Once folly is installed, run the following inside the wangle directory to build, test, and install wangle:

cmake .
make
ctest
sudo make install

Tutorial

There is a tutorial here that explains the basics of Wangle and shows how to build an echo server/client.

Examples

See the examples/ directory for some example Wangle servers and clients

License

Wangle is Apache 2.0-licensed.

Contributing

See the CONTRIBUTING file for how to help out.

Documentation

Wangle interfaces are asynchronous. Interfaces are currently based on Futures, but we're also exploring how to support fibers

Client / Server abstraction #

You're probably familiar with Java's Netty, or Python's twisted, or similar libraries.

It is built on top of folly/async/io, so it's one level up the stack from that (or similar abstractions like boost::asio)

ServerBootstrap - easily manage creation of threadpools and pipelines

ClientBootstrap - the same for clients

Pipeline - set up a series of handlers that modify your socket data

Request / Response abstraction #

This is roughly equivalent to the Finagle library.

Aims to provide easy testing, load balancing, client pooling, retry logic, etc. for any request/response type service - i.e. thrift, http, etc.

Service - a matched interface between client/server. A server will implement this interface, and a client will call in to it. These are protocol-specific

ServiceFilter - a generic filter on a service. Examples: stats, request timeouts, rate limiting

ServiceFactory - A factory that creates client connections. Any protocol specific setup code goes here

ServiceFactoryFilter - Generic filters that control how connections are created. Client examples: load balancing, pooling, idle timeouts, markdowns, etc.

ServerBootstrap

Easily create a new server

ServerBootstrap does the work to set up one or multiple acceptor threads, and one or multiple sets of IO threads. The thread pools can be the same. SO_REUSEPORT is automatically supported for multiple accept threads. tcp is most common, although udp is also supported.

Methods #

childPipeline(PipelineFactory<Pipeline>)

Sets the pipeline factory for each new connection. One pipeline per connection will be created.

group(IOThreadPoolExecutor accept, IOThreadPoolExecutor io)

Sets the thread pools for accept and io thread pools. If more than one thread is in the accept group, SO_REUSEPORT is used. Defaults to a single accept thread, and one io thread per core.

bind(SocketAddress),bind(port)

Binds to a port. Automatically starts to accept after bind.

stop()

Stops listening on all sockets.

join()

Joins all threadpools - all current reads and writes will be completed before this method returns.

NOTE: however that both accept and io thread pools will be stopped using this method, so the thread pools can't be shared, or care must be taken using shared pools during shutdown.

waitForStop()

Waits for stop() to be called from another thread.

Other methods #

channelFactory(ServerSocketFactory)

Sets up the type of server. Defaults to TCP AsyncServerSocket, but AsyncUDPServerSocket is also supported to receive udp messages. In practice, ServerBootstrap is only useful for udp if you need to multiplex the messages across many threads, or have TCP connections going on at the same time, etc. Simple usages of AsyncUDPSocket probably don't need the complexity of ServerBootstrap.

pipeline(PipelineFactory<AcceptPipeline>)

This pipeline method is used to get the accepted socket (or udp message) before it has been handed off to an IO thread. This can be used to steer the accept thread to a particular thread, or for logging.

See also AcceptRoutingHandler and RoutingDataHandler for additional help in reading data off of the accepted socket before it gets attached to an IO thread. These can be used to hash incoming sockets to specific threads.

childHandler(AcceptorFactory)

Previously facebook had lots of code that used AcceptorFactories instead of Pipelines, this is a method to support this code and be backwards compatible. The AcceptorFactory is responsible for creating acceptors, setting up pipelines, setting up AsyncSocket read callbacks, etc.

Examples #

A simple example:

ServerBootstrap<TelnetPipeline> server;                                                                                                      
server.childPipeline(std::make_shared<TelnetPipelineFactory>());                                                                             
server.bind(FLAGS_port);                                                                                                                     
server.waitForStop();

ClientBootstrap

Create clients easily

ClientBootstrap is a thin wrapper around AsyncSocket that provides a future interface to the connect callback, and a Pipeline interface to the read callback.

Methods #

group(IOThreadPoolExecutor)

Sets the thread or group of threads where the IO will take place. Callbacks are also made on this thread.

bind(port)

Optionally bind to a specific port

Future<Pipeline*> connect(SocketAddress)

Connect to the selected address. When the future is complete, the initialized pipeline will be returned.

NOTE: future.cancel() can be called to cancel an outstanding connection attempt.

pipelineFactory(PipelineFactory<Pipeline>)

Set the pipeline factory to use after a connection is successful.

Example #

ClientBootstrap<TelnetPipeline> client;
client.group(std::make_shared<folly::wangle::IOThreadPoolExecutor>(1));
client.pipelineFactory(std::make_shared<TelnetPipelineFactory>());
// synchronously wait for the connect to finish
auto pipeline = client.connect(SocketAddress(FLAGS_host,FLAGS_port)).get();

// close the pipeline when finished pipeline->close();

Pipeline

Send your socket data through a series of tubes

A Pipeline is a series of Handlers that intercept inbound or outbound events, giving full control over how events are handled. Handlers can be added dynamically to the pipeline.

When events are called, a Context* object is passed to the Handler - this means state can be stored in the context object, and a single instantiation of any individual Handler can be used for the entire program.

Netty's documentation: ChannelHandler

Usually, the bottom of the Pipeline is a wangle::AsyncSocketHandler to read/write to a socket, but this isn't a requirement.

A pipeline is templated on the input and output types:

EventBase base_;
Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>> pipeline;
pipeline.addBack(AsyncSocketHandler(AsyncSocket::newSocket(eventBase)));

The above creates a pipeline and adds a single AsyncSocket handler, that will push read events through the pipeline when the socket gets bytes. Let's try handling some socket events:

class MyHandler : public InboundHandler<folly::IOBufQueue&> {
 public:

void read(Context* ctx, folly::IOBufQueue& q) override { IOBufQueue data;
if (q.chainLength() >= 4) { data.append(q.split(4)); ctx->fireRead(data); } } };

This handler only handles read (inbound) data, so we can inherit from InboundHandler, and ignore the outbound type (so the ordering of inbound/outbound handlers in your pipeline doesn't matter). It checks if there are at least 4 bytes of data available, and if so, passes them on to the next handler. If there aren't yet four bytes of data available, it does nothing, and waits for more data.

We can add this handler to our pipeline like so:

pipeline.addBack(MyHandler());

and remove it just as easily:

pipeline.remove<MyHandler>();

StaticPipeline #

Instantiating all these handlers and pipelines can hit the allocator pretty hard. There are two ways to try to do fewer allocations. StaticPipeline allows all the handlers, and the pipeline, to be instantiated all in the same memory block, so we only hit the allocator once.

The other option is to allocate the handlers once at startup, and reuse them in many pipelines. This means all state has to be saved in the HandlerContext object instead of the Handler itself, since each handler can be in multiple pipelines. There is one context per pipeline to get around this limitation.

Built-in handlers

The stuff that comes with the box

Byte to byte handlers #

AsyncSocketHandler #

This is almost always the first handler in the pipeline for clients and servers - it connects an AsyncSocket to the pipeline. Having it as a handler is nice, because mocking it out for tests becomes trivial.

OutputBufferingHandler #

Output is buffered and only sent once per event loop. This logic is exactly what is in ThriftServer, and very similar to what exists in proxygen - it can improve throughput for small writes by up to 300%.

EventBaseHandler #

Putting this right after an AsyncSocketHandler means that writes can happen from any thread, and eventBase->runInEventBaseThread() will automatically be called to put them in the correct thread. It doesn't intrinsically make the pipeline thread-safe though, writes from different threads may be interleaved, other handler stages must be only used from one thread or be thread safe, etc.

In addition, reads are still always called on the eventBase thread.

Codecs #

FixedLengthFrameDecoder #

A decoder that splits received IOBufs by a fixed number of bytes. Used for fixed-length protocols

LengthFieldPrepender #

Prepends a fixed-length field length. Field length is configurable.

LengthFieldBasedFrameDecoder #

The receiving portion of LengthFieldPrepender - decodes based on a fixed frame length, with optional header/tailer data sections.

LineBasedFrameDecoder #

Decodes by line (with optional ending detection types), to be used for text-based protocols

StringCodec #

Converts from IOBufs to std::strings and back for text-based protocols. Must be used after one of the above frame decoders

Services

How to add a new protocol

Finagle's documentation on Services is highly recommended

Services #

A Pipeline was read() and write() methods - it streams bytes in one or both directions. write() returns a future, but the future is set when the bytes are successfully written. Using pipeline there is no easy way to match up requests and responses for RPC.

A Service is an RPC abstraction - Both clients and servers implement the interface. Servers implement it by handling the request. Clients implement it by sending the request to the server to complete.

A Dispatcher is the adapter between the Pipeline and Service that matches up the requests and responses. There are several built in Dispatchers, however if you are doing anything advanced, you may need to write your own.

Because both clients and servers implement the same interface, mocking either clients or servers is trivially easy.

ServiceFilters #

ServiceFilters provide a way to wrap filters around every request and response. Things like logging, timeouts, retrying requests, etc. can be implemented as ServiceFilters.

Existing ServiceFilters include:

  • CloseOnReleaseFilter - rejects requests after connection is closed. Often used in conjunction with
  • ExpiringFilter - idle timeout and max connection time (usually used for clients)
  • TimeoutFilter - request timeout time. Usually used on servers. Clients can use future.within to specify timeouts individually.
  • ExecutorFilter - move requests to a different executor.

ServiceFactories #

For some services, a Factory can help instantiate clients. In Finagle, these are frequently provided for easy use with specific protocols, i.e. http, memcache, etc.

ServiceFactoryFilters #

ServiceFactoryFilters provide filters for getting clients. These include most connection-oriented things, like connection pooling, selection, dispatch, load balancing, etc.

Existing ServiceFactoryFilters:

More Repositories

1

react

The library for web and native user interfaces.
JavaScript
227,971
star
2

react-native

A framework for building native applications using React
C++
118,682
star
3

create-react-app

Set up a modern web app by running one command.
JavaScript
101,913
star
4

docusaurus

Easy to maintain open source documentation websites.
TypeScript
56,059
star
5

jest

Delightful JavaScript Testing.
TypeScript
41,554
star
6

rocksdb

A library that provides an embeddable, persistent key-value store for fast storage.
C++
28,328
star
7

folly

An open-source C++ library developed and used at Facebook.
C++
27,122
star
8

zstd

Zstandard - Fast real-time compression algorithm
C
22,448
star
9

flow

Adds static typing to JavaScript to improve developer productivity and code quality.
OCaml
22,068
star
10

lexical

Lexical is an extensible text editor framework that provides excellent reliability, accessibility and performance.
TypeScript
19,616
star
11

relay

Relay is a JavaScript framework for building data-driven React applications.
Rust
18,191
star
12

hhvm

A virtual machine for executing programs written in Hack.
Hack
18,048
star
13

prophet

Tool for producing high quality forecasts for time series data that has multiple seasonality with linear or non-linear growth.
Python
17,943
star
14

fresco

An Android library for managing images and the memory they use.
Java
17,041
star
15

yoga

Yoga is an embeddable layout engine targeting web standards.
C++
16,928
star
16

infer

A static analyzer for Java, C, C++, and Objective-C
OCaml
14,715
star
17

flipper

A desktop debugging platform for mobile developers.
TypeScript
13,221
star
18

watchman

Watches files and records, or triggers actions, when they change.
C++
12,294
star
19

react-devtools

An extension that allows inspection of React component hierarchy in the Chrome and Firefox Developer Tools.
11,030
star
20

hermes

A JavaScript engine optimized for running React Native.
C++
9,388
star
21

jscodeshift

A JavaScript codemod toolkit.
JavaScript
9,270
star
22

chisel

Chisel is a collection of LLDB commands to assist debugging iOS apps.
Python
9,090
star
23

buck

A fast build system that encourages the creation of small, reusable modules over a variety of platforms and languages.
Java
8,568
star
24

stylex

StyleX is the styling system for ambitious user interfaces.
JavaScript
8,333
star
25

proxygen

A collection of C++ HTTP libraries including an easy to use HTTP server.
C++
8,026
star
26

facebook-ios-sdk

Used to integrate the Facebook Platform with your iOS & tvOS apps.
Swift
7,720
star
27

litho

A declarative framework for building efficient UIs on Android.
Java
7,646
star
28

pyre-check

Performant type-checking for python.
OCaml
6,696
star
29

facebook-android-sdk

Used to integrate Android apps with Facebook Platform.
Kotlin
6,066
star
30

redex

A bytecode optimizer for Android apps
C++
5,991
star
31

sapling

A Scalable, User-Friendly Source Control System.
Rust
5,815
star
32

componentkit

A React-inspired view framework for iOS.
Objective-C++
5,746
star
33

fishhook

A library that enables dynamically rebinding symbols in Mach-O binaries running on iOS.
C
5,117
star
34

PathPicker

PathPicker accepts a wide range of input -- output from git commands, grep results, searches -- pretty much anything. After parsing the input, PathPicker presents you with a nice UI to select which files you're interested in. After that you can open them in your favorite editor or execute arbitrary commands.
Python
5,075
star
35

metro

πŸš‡ The JavaScript bundler for React Native
JavaScript
5,061
star
36

prop-types

Runtime type checking for React props and similar objects
JavaScript
4,446
star
37

idb

idb is a flexible command line interface for automating iOS simulators and devices
Objective-C
4,431
star
38

Haxl

A Haskell library that simplifies access to remote data, such as databases or web-based services.
Haskell
4,227
star
39

FBRetainCycleDetector

iOS library to help detecting retain cycles in runtime.
Objective-C++
4,190
star
40

memlab

A framework for finding JavaScript memory leaks and analyzing heap snapshots
TypeScript
4,187
star
41

duckling

Language, engine, and tooling for expressing, testing, and evaluating composable language rules on input strings.
Haskell
4,021
star
42

fbt

A JavaScript Internationalization Framework
JavaScript
3,849
star
43

regenerator

Source transformer enabling ECMAScript 6 generator functions in JavaScript-of-today.
JavaScript
3,817
star
44

buck2

Build system, successor to Buck
Rust
3,307
star
45

mcrouter

Mcrouter is a memcached protocol router for scaling memcached deployments.
C++
3,222
star
46

react-strict-dom

React Strict DOM (RSD) is a subset of React DOM, imperative DOM, and CSS that supports web and native targets
JavaScript
2,922
star
47

wdt

Warp speed Data Transfer (WDT) is an embeddedable library (and command line tool) aiming to transfer data between 2 systems as fast as possible over multiple TCP paths.
C++
2,836
star
48

igl

Intermediate Graphics Library (IGL) is a cross-platform library that commands the GPU. It provides a single low-level cross-platform interface on top of various graphics APIs (e.g. OpenGL, Metal and Vulkan).
C++
2,719
star
49

fbthrift

Facebook's branch of Apache Thrift, including a new C++ server.
C++
2,535
star
50

mysql-5.6

Facebook's branch of the Oracle MySQL database. This includes MyRocks.
C++
2,446
star
51

Ax

Adaptive Experimentation Platform
Python
2,272
star
52

fbjs

A collection of utility libraries used by other Meta JS projects.
JavaScript
1,953
star
53

jsx

The JSX specification is a XML-like syntax extension to ECMAScript.
HTML
1,945
star
54

react-native-website

The React Native website and docs
JavaScript
1,899
star
55

screenshot-tests-for-android

Generate fast deterministic screenshots during Android instrumentation tests
Java
1,733
star
56

idx

Library for accessing arbitrarily nested, possibly nullable properties on a JavaScript object.
JavaScript
1,686
star
57

TextLayoutBuilder

An Android library that allows you to build text layouts more easily.
Java
1,470
star
58

mvfst

An implementation of the QUIC transport protocol.
C++
1,433
star
59

SoLoader

Native code loader for Android
Java
1,300
star
60

facebook-python-business-sdk

Python SDK for Meta Marketing APIs
Python
1,240
star
61

ThreatExchange

Trust & Safety tools for working together to fight digital harms.
C++
1,170
star
62

CacheLib

Pluggable in-process caching engine to build and scale high performance services
C++
1,097
star
63

mariana-trench

A security focused static analysis tool for Android and Java applications.
C++
1,041
star
64

fatal

Fatal is a library for fast prototyping software in modern C++. It provides facilities to enhance the expressive power of C++. The library is heavily based on template meta-programming, while keeping the complexity under-the-hood.
C++
1,000
star
65

transform360

Transform360 is an equirectangular to cubemap transform for 360 video.
C
996
star
66

openr

Distributed platform for building autonomic network functions.
C++
883
star
67

fboss

Facebook Open Switching System Software for controlling network switches.
C++
851
star
68

ktfmt

A program that reformats Kotlin source code to comply with the common community standard for Kotlin code conventions.
Kotlin
818
star
69

facebook-php-business-sdk

PHP SDK for Meta Marketing API
PHP
810
star
70

winterfell

A STARK prover and verifier for arbitrary computations
Rust
728
star
71

pyre2

Python wrapper for RE2
C++
631
star
72

starlark-rust

A Rust implementation of the Starlark language
Rust
623
star
73

openbmc

OpenBMC is an open software framework to build a complete Linux image for a Board Management Controller (BMC).
C
615
star
74

SPARTA

SPARTA is a library of software components specially designed for building high-performance static analyzers based on the theory of Abstract Interpretation.
C++
609
star
75

time

Meta's Time libraries
Go
570
star
76

chef-cookbooks

Open source chef cookbooks.
Ruby
565
star
77

IT-CPE

Meta's Client Platform Engineering tools. Some of the tools we have written to help manage our fleet of client systems.
Ruby
554
star
78

dotslash

Simplified executable deployment
Rust
523
star
79

Rapid

The OpenStreetMap editor driven by open data, AI, and supercharged features
JavaScript
515
star
80

lexical-ios

Lexical iOS is an extensible text editor framework that integrates the APIs and philosophies from Lexical Web with a Swift API built on top of TextKit.
Swift
477
star
81

facebook-sdk-for-unity

The facebook sdk for unity.
C#
474
star
82

facebook-nodejs-business-sdk

Node.js SDK for Meta Marketing APIs
JavaScript
469
star
83

FAI-PEP

Facebook AI Performance Evaluation Platform
Python
384
star
84

facebook-java-business-sdk

Java SDK for Meta Marketing APIs
Java
379
star
85

chef-utils

Utilities related to Chef
Ruby
290
star
86

opaque-ke

An implementation of the OPAQUE password-authenticated key exchange protocol
Rust
275
star
87

dns

Collection of Meta's DNS Libraries
Go
257
star
88

facebook360_dep

Facebook360 Depth Estimation Pipeline - https://facebook.github.io/facebook360_dep
HTML
241
star
89

akd

An implementation of an auditable key directory
Rust
219
star
90

tac_plus

A Tacacs+ Daemon tested on Linux (CentOS) to run AAA via TACACS+ Protocol via IPv4 and IPv6.
C
207
star
91

facebook-ruby-business-sdk

Ruby SDK for Meta Marketing API
Ruby
204
star
92

usort

Safe, minimal import sorting for Python projects.
Python
171
star
93

grocery-delivery

The Grocery Delivery utility for managing cookbook uploads to distributed Chef backends.
Ruby
153
star
94

taste-tester

Software to manage a chef-zero instance and use it to test changes on production servers.
Ruby
146
star
95

TestSlide

A Python test framework
Python
143
star
96

sapp

Post Processor for Facebook Static Analysis Tools.
Python
127
star
97

homebrew-fb

OS X Homebrew formulas to install Meta open source software
Ruby
124
star
98

threat-research

Welcome to the Meta Threat Research Indicator Repository, a dedicated resource for the sharing of Indicators of Compromise (IOCs) and other threat indicators with the external research community
Python
124
star
99

ocamlrep

Sets of libraries and tools to write applications and libraries mixing OCaml and Rust. These libraries will help keeping your types and data structures synchronized, and enable seamless exchange between OCaml and Rust
Rust
121
star
100

squangle

SQuangLe is a C++ API for accessing MySQL servers
C++
121
star