Ballerina (programming language)

From HandWiki
Ballerina
Ballerina Language
Designed bySanjiva Weerawarana, James Clark, Sameera Jayasoma, Hasitha Aravinda, Srinath Perera, Frank Leymann and WSO2[1]
DeveloperWSO2
First appeared2017; 7 years ago (2017)
Typing disciplineStructural, strong, static, inferred
Implementation languageJava, Ballerina, TypeScript[2]
OSCross-platform
LicenseApache License 2.0[3]
Websiteballerina.io
Influenced by
Java, Javascript, Go, Rust, C#[4]

Ballerina is an open source general-purpose programming language designed by WSO2 for cloud-era application programmers.[2]

The project started in 2015 by architects from WSO2 as a code-based alternative to the configuration-based integration tools such as EAI, ESB, and workflow products.[5][6]

It has various constructs geared toward cloud-native development including support for various data formats and protocols, reliability, distributed transactions, APIs, and event streams.[7][8][9]

History

Ballerina was first publicly announced in 2017 and version 1.0 was released on September 10, 2019.[10]

Design

Ballerina is a general-purpose language with a familiar syntax along with a direct graphical representation of the code in the form of sequence diagrams. It has fundamental abstractions designed to make integration problems easier to program.[11] Ballerina was designed by WSO2 to improve productivity for application developers that have to work with distributed computing. It is easy to write and modify and is suitable for application programmers.[12][13][14]

The designers, who provided enterprise integration products for over 10 years, used their knowledge of the industry when designing the language,[15][16] says WSO2 director and Ballerina founder James Clark.

Examples

Hello World

The regular Hello World program:

import ballerina/io;

public function main() {
    io:println("Hello World!");
}

To execute the above program, place the source code in a .bal file and provide the path of the file to the bal run command.

$ ballerina run hello_world.bal
Hello World!

The service version of the Hello World program:

import ballerina/http;

service /greet on new http:Listener(9090) {
    resource function get . () returns string {
        return "Hello World!";
    }
}

Services are executed in the same manner, except they don't terminate like regular programs do. Once the service is up and running, one can use an HTTP client to invoke the service. For example, the above service can be invoked using the following cURL command:

$ curl http://localhost:9090/greet 
Hello World!

[17]

REST API

import ballerina/http;

service on new http:Listener(9090) {
    resource function post factorial(@http:Payload string payload) returns http:Ok|http:BadRequest {
        int|error num = int:fromString(payload);

        if num is error {
            return <http:BadRequest>{body: "Invalid integer: " + payload};
        }

        if num < 0 {
            return <http:BadRequest>{body: "Integer should be >= 0"};
        }

        int result = 1;

        foreach int i in 2 ... num {
            result *= i;
        }

        return <http:Ok>{body: result};
    }
}
$ curl http://localhost:9090/factorial -d 5
120

GraphQL API

import ballerina/graphql;

service /stocks on new graphql:Listener(4000) {
    resource function get quote() returns StockQuote {
        return {
            ticker: "EXPO",
            price: 287.5,
            open: 285,
            prevClose: 285.5,
            low: 276.25,
            high: 297
        };
    }
}

type StockQuote record {|
    string ticker;
    float price;
    float open;
    float prevClose;
    float low;
    float high;
|};
$ curl -H "Content-type: application/json" -d '{"query": "{ quote { ticker, price } }" }' 'http://localhost:4000/stocks' 
{"data":{"quote":{"ticker":"EXPO", "price":287.5}}}

Sequence diagram

The generated sequence diagram is a canonical representation of the source code. The two representations can be used interchangeably. The diagram support is provided through the Ballerina VS Code plugin. The following are a couple of such generated sequence diagrams, compared with its associated code.

A sample program for retrieving and processing COVID-19 data:

Working-with-data-code+diagram.png

A sample program for creating a report out of pull request data retrieved from GitHub:

Consuming-services-code+diagram.png

JSON support

The language provides support for working with JSON values. The builtin type `json` is defined as the following union: ()|boolean|int|float|decimal|string|json[]|map<json>

import ballerina/io;

public function main() returns error {
    // Syntax for `json` object values is very similar to the syntax of JSON
    json person = {name: "John Doe", age: 25};

    // Serialized `json` values conforms to the JSON specification 
    io:println(person);

    // The fields of the `json` value can be accessed as follows
    string name = check person.name;
    int age = check person.age;
}

Code to cloud

Docker and Kubernetes artifacts required for deploying the code to the cloud can be generated when building the code. Values required for these artifacts are derived from the code. Additionally, one can override these values as well using the Cloud.toml file. To enable generation of the cloud artifacts, the users can use the cloud build option in the Ballerina.toml file. Use docker to generate just the Docker image and the Dockerfile and use k8s to generate Kubernetes artifacts as well. Minimal sample config TOML files would look something like the following:

Ballerina.toml file:

[package]
distribution = "2201.0.0"

[build-options]
cloud="k8s"

Cloud.toml file:

[container.image]
repository="bal_user"
name="greet"
tag="v0.1.0"

Workers

import ballerina/http;
import ballerina/lang.'int;
import ballerina/io;

// Workers interact with each other by sending and receiving messages.
// Ballerina validates every worker interaction (send and receive)
// to avoid deadlocks.
public function main() {
    @strand {thread: "any"}
    worker w1 {
        int w1val = checkpanic calculate("2*3");
        // Sends a message asynchronously to the worker `w2`.
        w1val -> w2;
        // Receives a message from the worker `w2`.
        int w2val = <- w2;
        io:println("[w1] Message from w2: ", w2val);
        // Sends messages synchronously to the worker `w3`. The worker `w1` will wait
        // until the worker `w3` receives the message.
        w1val ->> w3;
        w2val -> w3;
        // Flushes all messages sent asynchronously to the worker `w3`. The worker
        // will halt at this point until all messages are sent or until the worker `w3`
        // fails.
        checkpanic flush w3;
    }

    // A worker can have an explicit return type, or else, if a return type is not mentioned,
    // it is equivalent to returning ().
    @strand {thread: "any"}
    worker w2 {
        int w2val = checkpanic calculate("17*5");
        // Receives a message from the worker `w1`.
        int w1val = <- w1;
        io:println("[w2] Message from w1: ", w1val);
        // Sends a message asynchronously to the worker `w1`.
        w1val + w2val -> w1;
    }

    worker w3 {
        int|error w1val = <- w1;
        int|error w2val = <- w1;
        io:println("[w3] Messages from w1: ", w1val, ", ", w2val);
    }

    // Waits for the worker `w1`to finish.
    wait w1;
}

function calculate(string expr) returns int|error {
    http:Client httpClient = check new ("https://api.mathjs.org");
    string response = check httpClient->get(string `/v4/?expr=${expr}`);
    return check 'int:fromString(response);
}

[18]

References

  1. "Ballerina Language Specification". WSO2. https://ballerina.io/spec/. 
  2. 2.0 2.1 ((Open Source Contributors)) (18 June 2019). "Ballerina source code". GitHub. https://github.com/ballerina-platform/ballerina-lang. 
  3. "WSO2 / LICENSE". WSO2. 2017-03-08. https://github.com/ballerina-platform/ballerina-lang/blob/master/LICENSE. 
  4. Ballerina, A modern programming language focused on integration. pp. 15. https://opensource.ellak.gr/wp-content/uploads/sites/5/2018/06/2018-06-Ballerina-GFOSS.pdf. 
  5. "Ballerina Microservices Programming Language: Introducing the Latest Release and "Ballerina Central"". https://www.infoq.com/articles/ballerina-microservices-language-part-1. 
  6. Earls, Alan (2019-03-01). "How does Ballerina stack up as a cloud-native programming language?". https://searchmicroservices.techtarget.com/tip/How-does-Ballerina-stack-up-as-a-cloud-native-programming-language. 
  7. Doyle, Kerry. "10 of the best programming languages to learn in 2020" (in en-GB). https://searchapparchitecture.techtarget.com/tip/10-of-the-best-programming-languages-to-learn-in-2020. 
  8. Posta, Christian. "Evolution of Integration and Microservices with Service Mesh and Ballerina" (in en-GB). https://www.youtube.com/watch?v=rRrJKM0BAAo. 
  9. Techworld staff. "Top programming languages you should try" (in en-GB). Techworld. https://www.techworld.com/picture-gallery/careers/up-coming-programming-languages-for-developers-get-grips-with-3621455/. 
  10. "Ballerina Reinvents Cloud-Native Middleware as a Programming Language". GlobeNewswire (Press release). 10 September 2019. Retrieved 2020-09-16.
  11. Ratnayake, Dakshitha. "Ballerina Swan Lake: 10 Compelling Language Characteristics for Cloud Native Programming". https://www.infoq.com/articles/ballerina-cloud-native-programming/. 
  12. Jackson, Joab. "Ballerina: An API-First Programming Language" (in en-US). The New Stack. https://thenewstack.io/ballerina-an-api-first-programming-language/. 
  13. Foremski, Tom (2019-03-01). "Technology and the Arts: Celebrating Ballerina, a computer language of integration". https://www.zdnet.com/article/ballerina-a-language-of-integration-of-technology-and-the-arts/. 
  14. Lawton, George (2018-11-01). "Ballerina language promises to improve app integration". https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/Ballerina-language-promises-to-improve-app-integration. 
  15. Clark, James. "Ballerina Programming Language Part 0 - Context" (in en-GB). https://blog.jclark.com/2019/09/ballerina-programming-language-part-0.html. 
  16. Clark, James. "Ballerina Programming Language Part 1 - Concepts" (in en-GB). https://blog.jclark.com/2019/09/ballerina-programming-language-part-1.html. 
  17. Ballerina Team (16 September 2020). "Hello world service". ballerina.io. https://ballerina.io/learn/by-example/hello-world-service.html. 
  18. Ballerina Team (16 September 2020). "Worker interaction". ballerina.io. https://github.com/ballerina-platform/ballerina-distribution/blob/master/examples/worker-interaction/worker_interaction.bal. 

Further reading

External links