Skip to content
This repository has been archived by the owner on Mar 11, 2022. It is now read-only.

Commit

Permalink
Merge pull request #26 from cloudstateio/doc/user_support_lib_doc
Browse files Browse the repository at this point in the history
Go user language support documentation using cloudstate paradox plugin
  • Loading branch information
marcellanz authored Jun 2, 2020
2 parents faaff6d + 2b76e01 commit 7bd8eb4
Show file tree
Hide file tree
Showing 15 changed files with 382 additions and 9 deletions.
34 changes: 26 additions & 8 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,31 @@
language: go
os:
- linux
- osx
- windows
go:
- 1.13.x
before_install:
- go get -t -v ./...
script:
- go test -v -race -coverprofile=coverage.txt -covermode=atomic -bench=. ./...
after_success:
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then bash <(curl -s https://codecov.io/bash); fi

jobs:
include:
- stage: build
before_install:
- go get -t -v ./...
script:
- go test -v -race -coverprofile=coverage.txt -covermode=atomic -bench=. ./...
after_success:
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then bash <(curl -s https://codecov.io/bash); fi

- stage: deploy docs
name: deploy release docs to cloudstate.io
if: tag =~ ^v
language: scala
script: cd docs && sbt deploy
- stage: deploy docs
name: deploy snapshot docs to cloudstate.io
if: branch = master AND type = push
language: scala
script: cd docs && sbt deploy

env:
global:
# encrypted with: travis encrypt --pro -r cloudstateio/go-support DEPLOY_DOCS_TOKEN=<token>
secure: "L1uMy3mR5U+0HFmjJwSD6i/av667T187DkzIlRwfTnEGPG6LoZ5EwyGC/IxbKbV2EyUmxt7zDO+OXvsiZx0l0mXZ5ozAKdTB7eb/ujhinwnvB82OtKu8ejvZqI0ooPO+D1RlxqZF5HCX69L0DfTjhytkqLUIlN4CTtSO4ElJ/1Ottg0c3qiNUYvNdFqsKsF7Dq7EJU8G/vZ6o1WCUJzawLshOGDQ9jSL14QnKquFr/cMXHcg3GgiPVl2NFWAld0fOuNpYqUy2X3O7V4/FOJGe+btOao4xQyVsn9V/1VFsqRCyp1uy+kPbQbA0f+fBY3CnDpLKHrhYv8TDdfP9tbUEIhGikc+aqYeGOP6+4vPK/Xi/p2pZEZErPcBfc7CoJECNG4csMjq0GGdhp6UYJO1JPMVrLFZsWLoxPiXTkreQ+Gj4+Jgia20xfcUR/tkZrCQMnkySfFPHK48g2VOadfIZNz6hbdMGrZUarMrWC/hi3DIUdoT0Wn6y5LuP8goAbIBI/+KXvECIdiqTHu7WIwtdesTIZJvHhdp44zec8Teb0Bo6uYoIrKXvfTQbgvTzMzZO8DZ1L21OL7EKD9H6rvFabZXz5I2i9695Q6gkQYmK6Twg6CK1p/aZXmJWN8QXceXPavl3iNvC2fMSFxZvHBuqAjknCQlmTH7/BKyEw5AQ/Q="
12 changes: 12 additions & 0 deletions cloudstate/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,18 +86,30 @@ func (e *eventEmitter) Clear() {
e.events = make([]interface{}, 0)
}

//#event-handler
type EventHandler interface {
HandleEvent(ctx context.Context, event interface{}) (handled bool, err error)
}

//#event-handler

//#command-handler
type CommandHandler interface {
HandleCommand(ctx context.Context, command interface{}) (handled bool, reply interface{}, err error)
}

//#command-handler

//#snapshotter
type Snapshotter interface {
Snapshot() (snapshot interface{}, err error)
}

//#snapshotter

//#snapshot-handler
type SnapshotHandler interface {
HandleSnapshot(snapshot interface{}) (handled bool, err error)
}

//#snapshot-handler
5 changes: 5 additions & 0 deletions cloudstate/eventsourced.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const snapshotEveryDefault = 100

// EventSourcedEntity captures an Entity, its ServiceName and PersistenceID.
// It is used to be registered as an event sourced entity on a CloudState instance.
//#event-sourced-entity-type
type EventSourcedEntity struct {
// ServiceName is the fully qualified name of the service that implements this entities interface.
// Setting it is mandatory.
Expand All @@ -58,12 +59,16 @@ type EventSourcedEntity struct {
SnapshotEvery int64

// EntityFactory is a factory method which generates a new Entity.
//#event-sourced-entity-func
EntityFunc func() Entity
//#event-sourced-entity-func

// internal
registerOnce sync.Once
}

//#event-sourced-entity-type

// init get its Entity type and Zero-Value it to
// something we can use as an initializer.
func (e *EventSourcedEntity) init() error {
Expand Down
23 changes: 23 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Cloudstate Go documentation

Documentation source for Cloudstate Go, published to https://cloudstate.io/docs/go/current/

To build the docs with [sbt](https://www.scala-sbt.org):

```
sbt paradox
```

Can also first start the sbt interactive shell with `sbt`, then run commands.

The documentation can be viewed locally by opening the generated pages:

```
open target/paradox/site/main/index.html
```

To watch files for changes and rebuild docs automatically:

```
sbt ~paradox
```
12 changes: 12 additions & 0 deletions docs/build.sbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
lazy val docs = project
.in(file("."))
.enablePlugins(CloudstateParadoxPlugin)
.settings(
deployModule := "go",
paradoxProperties in Compile ++= Map(
"cloudstate.go.version" -> "1.14",
"cloudstate.go.lib.version" -> { if (isSnapshot.value) previousStableVersion.value.getOrElse("0.0.0") else version.value },
"extref.cloudstate.base_url" -> "https://cloudstate.io/docs/core/current/%s",
"snip.base.base_dir" -> s"${(baseDirectory in ThisBuild).value.getAbsolutePath}/../",
)
)
1 change: 1 addition & 0 deletions docs/project/build.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sbt.version=1.3.12
2 changes: 2 additions & 0 deletions docs/project/plugins.sbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
addSbtPlugin("com.dwijnand" % "sbt-dynver" % "4.0.0")
addSbtPlugin("io.cloudstate" % "sbt-cloudstate-paradox" % "0.1.2")
3 changes: 3 additions & 0 deletions docs/src/main/paradox/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://pkg.go.dev/github.com/cloudstateio/go-support/cloudstate).
6 changes: 6 additions & 0 deletions docs/src/main/paradox/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/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/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 @extref[Event sourcing](cloudstate:user/features/eventsourced.html) 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]($base$/tck/cmd/tck_shoppingcart/shoppingcart.go) { #entity-type }

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

@@snip [shoppingcart.go]($base$/cloudstate/eventsourced.go) { #event-sourced-entity-type }

The `ServiceName` is the fully qualified name of the gRPC service that implements this entity's 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`). Setting it is 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 straightforward 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 @extref:[Serialization](cloudstate:developer/language-support/serialization.html).

While protobufs are the recommended format for persisting events, it is recommended that you do not persist your service's protobuf messages, rather, you should create new messages, even if they are identical to the service's. 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 service's 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 application's domain objects:

@@snip [domain.proto]($base$/protobuf/example/shoppingcart/persistence/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]($base$/tck/cmd/tck_shoppingcart/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]($base$/tck/cmd/tck_shoppingcart/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]($base$/tck/cmd/tck_shoppingcart/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 handler's `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]($base$/tck/cmd/tck_shoppingcart/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]($base$/tck/cmd/tck_shoppingcart/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]($base$/tck/cmd/tck_shoppingcart/shoppingcart.go) { #add-item }

This command handler also validates the command, ensuring the quantity of items added is greater than zero. Returning an `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 handler's responsibility is to update the state of the entity according to the event. Event handlers are the only place where it's safe to mutate the state of the entity at all.

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

@@snip [shoppingcart.go]($base$/cloudstate/event.go) { #event-handler }

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

@@snip [shoppingcart.go]($base$/tck/cmd/tck_shoppingcart/shoppingcart.go) { #handle-event }

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

@@snip [shoppingcart.go]($base$/tck/cmd/tck_shoppingcart/shoppingcart.go) { #item-added }

## Producing and handling snapshots

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.

@@snip [shoppingcart.go]($base$/cloudstate/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]($base$/tck/cmd/tck_shoppingcart/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]($base$/cloudstate/event.go) { #snapshot-handler }

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

@@snip [shoppingcart.go]($base$/tck/cmd/tck_shoppingcart/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 a 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]($base$/tck/cmd/tck_shoppingcart/shoppingcart.go) { #register }
78 changes: 78 additions & 0 deletions docs/src/main/paradox/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#user-content-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.lib.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 @extref:[gRPC descriptors](cloudstate:user/features/grpc.html), 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:

@@snip [shoppingcart.go]($base$/tck/cmd/tck_shoppingcart/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]($base$/cloudstate/eventsourced.go) { #event-sourced-entity-func }

This entity factory function returns a `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.
18 changes: 18 additions & 0 deletions docs/src/main/paradox/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Cloudstate 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)

@@@

Link to @extref:[Cloudstate Documentation](cloudstate:index.html)
Loading

0 comments on commit 7bd8eb4

Please sign in to comment.