Skip to content
This repository was archived by the owner on Mar 16, 2022. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,9 @@ lazy val docs = (project in file("docs"))
"extref.jsdoc.base_url" -> ".../user/lang/javascript/api/module-cloudstate.%s",
"cloudstate.version" -> "0.4.3", // hardcode, otherwise we'll end up with the wrong version in the docs
"cloudstate.java-support.version" -> "0.4.3",
"cloudstate.node-support.version" -> "0.0.1"
"cloudstate.node-support.version" -> "0.0.1",
"cloudstate.go-support.version" -> "0.1.0",
"cloudstate.go.version" -> "1.13"
),
paradoxNavigationDepth := 3,
inConfig(Test)(
Expand Down
1 change: 1 addition & 0 deletions docs/src/main/paradox/developer/language-support/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ This is achieved by having a gRPC based protocol between the Proxy and the User

* Java
* JavaScript
* Go

## Creating language support libraries

Expand Down
3 changes: 3 additions & 0 deletions docs/src/main/paradox/user/lang/go/api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Go API docs

The Go API docs can be found [here](https://godoc.org/github.com/cloudstateio/go-support/cloudstate).
6 changes: 6 additions & 0 deletions docs/src/main/paradox/user/lang/go/crdt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Conflict-free Replicated Data Types

* Explain how to use the CRDT API
* Explain how to use CrdtFactory and where it comes from
* Explain how to handle streamed calls
* Explain the APIs for each different CRDT
5 changes: 5 additions & 0 deletions docs/src/main/paradox/user/lang/go/effects.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Forwarding and effects

* Explain the ServiceCallFactory interface
* Explain how to forward replies to another service.
* Explain how to emit effects.
118 changes: 118 additions & 0 deletions docs/src/main/paradox/user/lang/go/eventsourced.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Event sourcing

This page documents how to implement Cloudstate event sourced entities in Go. For information on what Cloudstate event sourced entities are, please read the general @ref[Event sourcing](../../features/eventsourced.md) documentation first.

An event sourced entity can be created by embedding the `cloudstate.EventEmitter` type and also implementing the `cloudstate.Entity` interface.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #entity-type }

Then by composing the Cloudstate entity with an `cloudstate.EventSourcedEntity` and register it with `CloudState.Register()`, your entity gets configured to be an event sourced entity and handled by the Cloudstate instance for now on.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/eventsourced.go) { #event-sourced-entity-type }

The `ServiceName` is the fully qualified name of the gRPC service that implements this entities interface. Setting it is mandatory.

The `PersistenceID` is used to namespace events in the journal, useful for when you share the same database between multiple entities. It is recommended to be the name for the entity type (in this case, `ShoppingCart`) and is set to be mandatory.

The `SnapshotEvery` parameter controls how often snapshots are taken, so that the entity doesn't need to be recovered from the whole journal each time it's loaded. If left unset, it defaults to 100. Setting it to a negative number will result in snapshots never being taken.

The `EntityFunc` is a factory method which generates a new Entity whenever Cloudstate has to initialize a new entity.

## Persistence types and serialization

Event sourced entities persist events and snapshots, and these need to be serialized when persisted. The most straight forward way to persist events and snapshots is to use protobufs. Cloudstate will automatically detect if an emitted event is a protobuf, and serialize it as such. For other serialization options, including JSON, see @ref:[Serialization](serialization.md).

While protobufs are the recommended format for persisting events, it is recommended that you do not persist your services protobuf messages, rather, you should create new messages, even if they are identical to the services. While this may introduce some overhead in needing to convert from one type to the other, the reason for doing this is that it will allow the services public interface to evolve independently from its data storage format, which should be private.

For our shopping cart example, we'll create a new file called `domain.proto`, the name domain is selected to indicate that these are my applications domain objects:

@@snip [domain.proto](/docs/src/test/proto/domain.proto)

## State

Each entity should store its state locally in a mutable variable, either a mutable field or a multiple structure such as an array type or slice. For our shopping cart, the state is a slice of products, so we'll create a slice of LineItems to contain that:

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #entity-state }

## Constructing

The Cloudstate Go Support Library needs to know how to construct and initialize entities. For this, an entity has to provide a factory function, `EntityFunc`, which is set during registration of the event sourced entity.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #register }

The entity factory function returns a `cloudstate.Entity` which is composed of two interfaces to handle commands and events.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #constructing }

## Handling commands

An event sourced entity implements the composed `cloudstate.Entity` interface. `cloudstate.Entity` embeds the `cloudstate.EventHandler` interface and therefore entities implementing it get commands from Cloudstate through the event handlers `HandleCommand` method.

The command types received by an event sourced entity are declared by the gRPC Server interface which is generated from the protobuf definitions. The Cloudstate Go Support library together with the registered `cloudstate.EventSourcedEntity` is then able to dispatch commands it gets from the Cloudstate proxy to the event sourced entity.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #handle-command }

The return type of the command handler is by definition of the service interface, the output type for the gRPC service call, this will be sent as the reply.

The following shows the implementation of the `GetCart` command handler. This command handler is a read-only command handler, it doesn't emit any events, it just returns some state:

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #get-cart }

### Emitting events

Commands that modify the state may do so by emitting events.

@@@ warning
The **only** way a command handler may modify its state is by emitting an event. Any modifications made directly to the state from the command handler will not be persisted, and when the entity is passivated and next reloaded, those modifications will not be present.
@@@

A command handler may emit an event by using the embedded `cloudstate.EventEmitter` and invoking the `Emit` method on it. Calling `Emit` will immediately invoke the associated event handler for that event - this both validates that the event can be applied to the current state, as well as updates the state so that subsequent processing in the command handler can use it.

Here's an example of a command handler that emits an event:

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #add-item }

This command handler also validates the command, ensuring the quantity items added is greater than zero. Returning a `error` fails the command and the support library takes care of signaling that back to the requesting proxy as a `Failure` reply.

## Handling events

Event handlers are invoked at two points, when restoring entities from the journal, before any commands are handled, and each time a new event is emitted. An event handlers responsibility is to update the state of the entity according to the event. Event handlers are the only place where its safe to mutate the state of the entity at all.

Event handlers are declared by implementing the `cloudstate.EventHandler` interface.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/event.go) { #event-handler }

Emitted events by command handlers get dispatched to the implemented event handler which then decides how to proceed with the event.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #handle-event }

Here's an example of a concrete event handler for the `ItemAdded` event.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #item-added }

## Producing and handling snapshots
Comment thread
marcellanz marked this conversation as resolved.

Snapshots are an important optimisation for event sourced entities that may contain many events, to ensure that they can be loaded quickly even when they have very long journals. To produce a snapshot, the `cloudstate.Snapshotter` interface has to be implemented that must return a snapshot of the current state in serializable form.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it should be optional to implement this interface, as otherwise by default users might get poor performance and not knowing why. Is that the case?

Copy link
Copy Markdown
Contributor Author

@marcellanz marcellanz Oct 24, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. The text here is a 1:1 from the documentation in the java support.

Implementation wise we might probably ensure an entity implements this interface otherwise a compilation error would be raised, similar to the EventHandler and the CommandHandler in the case of this support library.

The spec says:

// If present the entity should initialise its state using this snapshot.
    EventSourcedSnapshot snapshot = 3;

so far. Though, this should be implemented the same over different support libraries. I have not checked if others raise a runtime check exception or the like.


@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/event.go) { #snapshotter }

Here is an example of the TCK shopping cart example creating snapshots for the current `domain.Cart` state of the shopping cart.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #snapshotter }

When the entity is loaded again, the snapshot will first be loaded before any other events are received, and passed to a snapshot handler. Snapshot handlers are declared by implementing the `cloudstate.SnapshotHandler` interface.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/event.go) { #snapshot-handler }

A snapshot handler then can type-switch over types the corresponding `cloudstate.Snapshotter` interface has implemented.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #handle-snapshot }

## Registering the entity

Once you've created your entity, you can register it with the `cloudstate.Cloudstate` server, by invoking the `Register` method of an Cloudstate instance. In addition to passing your entity type and service name, you also need to pass any descriptors that you use for persisting events, for example, the `domain.proto` descriptor.

During registration the optional ServiceName and the ServiceVersion can be configured.
(TODO: give an example on how to pick values for these after the spec defines semantics )

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #register }
78 changes: 78 additions & 0 deletions docs/src/main/paradox/user/lang/go/gettingstarted.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Getting started with stateful services in Go

## Prerequisites

Go version
: Cloudstate Go support requires at least Go $cloudstate.go.version$

Build tool
: Cloudstate does not require any particular build tool, you can select your own.

protoc
: Since Cloudstate is based on gRPC, you need a protoc compiler to compile gRPC protobuf descriptors. This can be done manually through the [Protocol Buffer Compiler project](https://github.com/protocolbuffers/protobuf#protocol-compiler-installation).

docker
: Cloudstate runs in Kubernetes with [Docker](https://www.docker.com), hence you will need Docker to build a container that you can deploy to Kubernetes. Most popular build tools have plugins that assist in building Docker images.

In addition to the above, you will need to install the Cloudstate Go support library by issuing `go get -u github.com/cloudstateio/go-support/cloudstate` or with Go module support let the dependency be downloaded by `go [build|run|test]`.

By using the Go module support your go.mod file will reference the latest version of the support library or you can define which version you like to use.

go get
: @@@vars
```text
go get -u github.com/cloudstateio/go-support/cloudstate
```
@@@

import path
: @@@vars
```text
import "github.com/cloudstateio/go-support/cloudstate"
```
@@@

go.mod
: @@@vars
```
module example.com/yourpackage
require (
github.com/cloudstateio/go-support $cloudstate.go-support.version$
)
go $cloudstate.go.version$
```
@@@

## Protobuf files

The Cloudstate Go Support Library provides no dedicated tool beside the protoc compiler to build your protobuf files. The Cloudstate protocol protobuf files as well as the shopping cart example application protobuf files are provided by the Cloudstate Repository.

In addition to the protoc compiler, the gRPC Go plugin is needed to compile the protobuf file to *.pb.go files. Please follow the instructions at the [Go support for Protocol Buffers](https://github.com/golang/protobuf) project page to install the protoc compiler as well as the `protoc-gen-go` plugin which also includes the Google standard protobuf types.

To build the example shopping cart application shown earlier in @ref:[gRPC descriptors](../../features/grpc.md), you could simply paste that protobuf into `protos/shoppingcart.proto`. You may wish to also define the Go package using the `go_package` proto option, to ensure the package name used conforms to Go package naming conventions

```proto
option go_package = "example/shoppingcart";
```

Now if you place your protobuf files under protobuf/ and run `protoc --go_out=. --proto_path=protobuf ./protobuf/*.proto`, you'll find your generated protobuf files in `example/shoppingcart`.

## Creating a main package

Your main package will be responsible for creating the Cloudstate gRPC server, registering the entities for it to serve, and starting it. To do this, you can use the CloudState server type, for example:
Comment thread
marcellanz marked this conversation as resolved.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/shoppingcart.go) { #shopping-cart-main }

We will see more details on registering entities in the coming pages.

## Interfaces to be implemented

Cloudstate entities in Go work by implementing interfaces and composing types.

To get support for the Cloudstate event emission the Cloudstate entity should embed the `cloudstate.EventEmitter` type. The EventEmitter allows the entity to emit events during the handling of commands.

Second, during registration of the entity, an entity factory function has to be provided so Cloudstate gets to know how to create and initialize an event sourced entity.

@@snip [shoppingcart.go](/docs/src/main/paradox/user/lang/go/src/eventsourced.go) { #event-sourced-entity-func }

This entity factory function returns an `cloudstate.Entity` which itself is a composite interface of a `cloudstate.CommandHandler` and a `cloudstate.EventHandler`. Every event sourced entity has to implement these two interfaces.
16 changes: 16 additions & 0 deletions docs/src/main/paradox/user/lang/go/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Go

Cloudstate offers an idiomatic Go support library for writing stateful services.

@@toc { depth=1 }

@@@ index

* [Getting started](gettingstarted.md)
* [Event sourcing](eventsourced.md)
* [Conflict-free Replicated Data Types](crdt.md)
* [Forwarding and effects](effects.md)
* [Serialization](serialization.md)
* [API docs](api.md)

@@@
37 changes: 37 additions & 0 deletions docs/src/main/paradox/user/lang/go/serialization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Serialization

Cloudstate functions serve gRPC interfaces, and naturally the input messages and output messages are protobuf messages that get serialized to the protobuf wire format. However, in addition to these messages, there are a number of places where Cloudstate needs to serialize other objects, for persistence and replication. This includes:

* Event sourced @ref[events and snapshots](eventsourced.md#persistence-types-and-serialization).
* CRDT @ref[map keys and set elements](crdt.md), and @ref[LWWRegister values](crdt.md).

Cloudstate supports a number of types and serialization options for these values.

## Primitive types

Cloudstate supports serializing the following primitive types:

| Protobuf type | Go type |
|---------------|-------------|
| string | string |
| bytes | []byte |
| int32 | int32 |
| int64 | int64 |
| float | float32 |
| double | float64 |
| bool | bool |

The details of how these are serialized can be found @ref[here](../../../developer/language-support/serialization.md#primitive-values).

@@@ note { title=Important }
Go has a set of [predeclared numeric](https://golang.org/ref/spec#Numeric_types) types with implementation-specific sizes. One of them is `int` which would be an int64 on 64-bit systems CPU architectures. Cloudstate does not support implicit conversion between an `int` and the corresponding `int64` as an input type for the serialization. The main reason not to support it is, that an `int` is not the same type as an `int64` and therefore a de-serialized value would have to be converted back to an `int` as it is of type `int64` during its serialized state.
@@@

## JSON

Cloudstate uses the standard library package [`encoding/json`](https://golang.org/pkg/encoding/json/) to serialize JSON. Any type that has a field declared with a string literal tag ``json:"fieldname"`` will be serialized to and from JSON using the [Marshaller and Unmarshaller](https://golang.org/pkg/encoding/json/#Marshal) from the Go standard library package `encoding/json`.

The details of how these are serialized can be found @ref[here](../../../developer/language-support/serialization.md#json-values).

Note that if you are using JSON values in CRDT sets or maps, the serialization of these values **must** be stable. This means you must not use maps or sets in your value, and you should define an explicit ordering for the fields in your objects.
**(TODO: mention the ordering of fields here by the Go standard library implementation).**
Loading