Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update for 1.0 and implement basic awakeables #2

Merged
merged 13 commits into from
Jul 8, 2024
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
[![Go Reference](https://pkg.go.dev/badge/github.com/restatedev/sdk-go.svg)](https://pkg.go.dev/github.com/restatedev/sdk-go)
[![Go](https://github.com/restatedev/sdk-go/actions/workflows/test.yaml/badge.svg)](https://github.com/restatedev/sdk-go/actions/workflows/test.yaml)

> This only works with Restate version 0.8

# Restate Go SDK

[Restate](https://restate.dev/) is a system for easily building resilient applications using *distributed durable async/await*. This repository contains the Restate SDK for writing services in **Golang**.
Expand Down
2 changes: 0 additions & 2 deletions proto/buf.yaml → buf.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
version: v1
deps:
- buf.build/restatedev/proto
breaking:
use:
- FILE
Expand Down
Binary file removed descriptor.binpb
Binary file not shown.
138 changes: 3 additions & 135 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,140 +8,8 @@ import (
type Code uint16

const (
/**
* The operation was cancelled, typically by the caller.
* HTTP 408
*/
CANCELLED Code = 1
/**
* Unknown error. For example, this error may be returned when a
* Status value received from another address space belongs to an error
* space that is not known in this address space. Also errors raised by APIs
* that do not return enough error information may be converted to this
* error.
* HTTP 500
*/
UNKNOWN Code = 2
/**
* The client specified an invalid argument. Note that
* this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates
* arguments that are problematic regardless of the state of the system
* (e.g., a malformed file name).
* HTTP 400
*/
INVALID_ARGUMENT Code = 3
/**
* The deadline expired before the operation could
* complete. For operations that change the state of the system, this error
* may be returned even if the operation has completed successfully. For
* example, a successful response from a server could have been delayed
* long.
* HTTP 408
*/
DEADLINE_EXCEEDED Code = 4
/**
* Some requested entity (e.g., file or directory) was not
* found. Note to server developers: if a request is denied for an entire
* class of users, such as gradual feature rollout or undocumented
* allowlist, NOT_FOUND may be used. If a request is denied for some users
* within a class of users, such as user-based access control,
* PERMISSION_DENIED must be used.
* HTTP 404
*/
NOT_FOUND Code = 5
/**
* The entity that a client attempted to create (e.g., file
* or directory) already exists.
* HTTP 409
*/
ALREADY_EXISTS Code = 6
/**
* The caller does not have permission to execute the
* specified operation. PERMISSION_DENIED must not be used for rejections
* caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for
* those errors). PERMISSION_DENIED must not be used if the caller can not
* be identified (use UNAUTHENTICATED instead for those errors). This error
* code does not imply the request is valid or the requested entity exists
* or satisfies other pre-conditions.
* HTTP 403
*/
PERMISSION_DENIED Code = 7
/**
* Some resource has been exhausted, perhaps a per-user
* quota, or perhaps the entire file system is out of space.
* HTTP 413
*/
RESOURCE_EXHAUSTED Code = 8
/**
* The operation was rejected because the system is
* not in a state required for the operation's execution. For example, the
* directory to be deleted is non-empty, an rmdir operation is applied to a
* non-directory, etc. Service implementors can use the following guidelines
* to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use
* UNAVAILABLE if the client can retry just the failing call. (b) Use
* ABORTED if the client should retry at a higher level (e.g., when a
* client-specified test-and-set fails, indicating the client should restart
* a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client
* should not retry until the system state has been explicitly fixed. E.g.,
* if an "rmdir" fails because the directory is non-empty,
* FAILED_PRECONDITION should be returned since the client should not retry
* unless the files are deleted from the directory.
* HTTP 412
*/
FAILED_PRECONDITION Code = 9
/**
* The operation was aborted, typically due to a concurrency issue
* such as a sequencer check failure or transaction abort. See the
* guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and
* UNAVAILABLE.
* HTTP 409
*/
ABORTED Code = 10
/**
* The operation was attempted past the valid range. E.g.,
* seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error
* indicates a problem that may be fixed if the system state changes. For
* example, a 32-bit file system will generate INVALID_ARGUMENT if asked to
* read at an offset that is not in the range [0,2^32-1], but it will
* generate OUT_OF_RANGE if asked to read from an offset past the current
* file size. There is a fair bit of overlap between FAILED_PRECONDITION and
* OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
* when it applies so that callers who are iterating through a space can
* easily look for an OUT_OF_RANGE error to detect when they are done.
* HTTP 400
*/
OUT_OF_RANGE Code = 11
/**
* The operation is not implemented or is not
* supported/enabled in this service.
* HTTP 501
*/
UNIMPLEMENTED Code = 12
/**
* Internal errors. This means that some invariants expected by
* the underlying system have been broken. This error code is reserved for
* serious errors.
* HTTP 500
*/
INTERNAL Code = 13
/**
* The service is currently unavailable. This is most likely a
* transient condition, which can be corrected by retrying with a backoff.
* Note that it is not always safe to retry non-idempotent operations.
* HTTP 503
*/
UNAVAILABLE Code = 14
/**
* Unrecoverable data loss or corruption.
* HTTP 500
*/
DATA_LOSS Code = 15
/**
* The request does not have valid authentication
* credentials for the operation.
* HTTP 401
*/
UNAUTHENTICATED Code = 16
ErrJournalMismatch Code = 570
ErrProtocolViolation Code = 571
)

type codeError struct {
Expand Down Expand Up @@ -224,5 +92,5 @@ func ErrorCode(err error) Code {
return e.code
}

return UNKNOWN
return 500
}
7 changes: 4 additions & 3 deletions error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package restate

import (
"fmt"
"net/http"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -14,10 +15,10 @@ func TestTerminal(t *testing.T) {
require.True(t, IsTerminalError(err))

//terminal with code
err = TerminalError(fmt.Errorf("terminal with code"), INTERNAL)
err = TerminalError(fmt.Errorf("terminal with code"), 500)

require.True(t, IsTerminalError(err))
require.EqualValues(t, INTERNAL, ErrorCode(err))
require.EqualValues(t, 500, ErrorCode(err))
}

func TestCode(t *testing.T) {
Expand All @@ -28,7 +29,7 @@ func TestCode(t *testing.T) {

require.EqualValues(t, 16, code)

require.EqualValues(t, 2, ErrorCode(fmt.Errorf("unknown error")))
require.EqualValues(t, http.StatusInternalServerError, ErrorCode(fmt.Errorf("unknown error")))
}

func TestCombine(t *testing.T) {
Expand Down
6 changes: 3 additions & 3 deletions example/checkout.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"fmt"

"github.com/google/uuid"
"github.com/restatedev/sdk-go"
restate "github.com/restatedev/sdk-go"
"github.com/rs/zerolog/log"
)

Expand Down Expand Up @@ -58,6 +58,6 @@ func payment(ctx restate.Context, request PaymentRequest) (response PaymentRespo
}

var (
Checkout = restate.NewUnKeyedRouter().
Handler("checkout", restate.NewUnKeyedHandler(payment))
Checkout = restate.NewServiceRouter().
Handler("checkout", restate.NewServiceHandler(payment))
)
18 changes: 10 additions & 8 deletions example/ticket_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package main
import (
"errors"

"github.com/restatedev/sdk-go"
restate "github.com/restatedev/sdk-go"
"github.com/rs/zerolog/log"
)

Expand All @@ -15,7 +15,7 @@ const (
TicketSold TicketStatus = 2
)

func reserve(ctx restate.Context, ticketId string, _ restate.Void) (bool, error) {
func reserve(ctx restate.ObjectContext, _ restate.Void) (bool, error) {
status, err := restate.GetAs[TicketStatus](ctx, "status")
if err != nil && !errors.Is(err, restate.ErrKeyNotFound) {
return false, err
Expand All @@ -28,7 +28,8 @@ func reserve(ctx restate.Context, ticketId string, _ restate.Void) (bool, error)
return false, nil
}

func unreserve(ctx restate.Context, ticketId string, _ restate.Void) (void restate.Void, err error) {
func unreserve(ctx restate.ObjectContext, _ restate.Void) (void restate.Void, err error) {
ticketId := ctx.Key()
log.Info().Str("ticket", ticketId).Msg("un-reserving ticket")
status, err := restate.GetAs[TicketStatus](ctx, "status")
if err != nil && !errors.Is(err, restate.ErrKeyNotFound) {
Expand All @@ -42,7 +43,8 @@ func unreserve(ctx restate.Context, ticketId string, _ restate.Void) (void resta
return void, nil
}

func markAsSold(ctx restate.Context, ticketId string, _ restate.Void) (void restate.Void, err error) {
func markAsSold(ctx restate.ObjectContext, _ restate.Void) (void restate.Void, err error) {
ticketId := ctx.Key()
log.Info().Str("ticket", ticketId).Msg("mark ticket as sold")

status, err := restate.GetAs[TicketStatus](ctx, "status")
Expand All @@ -58,8 +60,8 @@ func markAsSold(ctx restate.Context, ticketId string, _ restate.Void) (void rest
}

var (
TicketService = restate.NewKeyedRouter().
Handler("reserve", restate.NewKeyedHandler(reserve)).
Handler("unreserve", restate.NewKeyedHandler(unreserve)).
Handler("markAsSold", restate.NewKeyedHandler(markAsSold))
TicketService = restate.NewObjectRouter().
Handler("reserve", restate.NewObjectHandler(reserve)).
Handler("unreserve", restate.NewObjectHandler(unreserve)).
Handler("markAsSold", restate.NewObjectHandler(markAsSold))
)
32 changes: 17 additions & 15 deletions example/user_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import (
"slices"
"time"

"github.com/restatedev/sdk-go"
restate "github.com/restatedev/sdk-go"
"github.com/rs/zerolog/log"
)

func addTicket(ctx restate.Context, userId, ticketId string) (bool, error) {
func addTicket(ctx restate.ObjectContext, ticketId string) (bool, error) {
userId := ctx.Key()

var success bool
if err := ctx.Service(TicketServiceName).Method("reserve").Do(ticketId, userId, &success); err != nil {
if err := ctx.Object(TicketServiceName, ticketId).Method("reserve").Do(userId, &success); err != nil {
return false, err
}

Expand All @@ -33,14 +34,14 @@ func addTicket(ctx restate.Context, userId, ticketId string) (bool, error) {
return false, err
}

if err := ctx.Service(UserSessionServiceName).Method("expireTicket").Send(userId, ticketId, 15*time.Minute); err != nil {
if err := ctx.Object(UserSessionServiceName, ticketId).Method("expireTicket").Send(ticketId, 15*time.Minute); err != nil {
return false, err
}

return true, nil
}

func expireTicket(ctx restate.Context, _, ticketId string) (void restate.Void, err error) {
func expireTicket(ctx restate.ObjectContext, ticketId string) (void restate.Void, err error) {
tickets, err := restate.GetAs[[]string](ctx, "tickets")
if err != nil && !errors.Is(err, restate.ErrKeyNotFound) {
return void, err
Expand All @@ -62,10 +63,11 @@ func expireTicket(ctx restate.Context, _, ticketId string) (void restate.Void, e
return void, err
}

return void, ctx.Service(TicketServiceName).Method("unreserve").Send(ticketId, nil, 0)
return void, ctx.Object(TicketServiceName, ticketId).Method("unreserve").Send(nil, 0)
}

func checkout(ctx restate.Context, userId string, _ restate.Void) (bool, error) {
func checkout(ctx restate.ObjectContext, _ restate.Void) (bool, error) {
userId := ctx.Key()
tickets, err := restate.GetAs[[]string](ctx, "tickets")
if err != nil && !errors.Is(err, restate.ErrKeyNotFound) {
return false, err
Expand All @@ -78,17 +80,17 @@ func checkout(ctx restate.Context, userId string, _ restate.Void) (bool, error)
}

var response PaymentResponse
if err := ctx.Service(CheckoutServiceName).
if err := ctx.Object(CheckoutServiceName, "").
Method("checkout").
Do("", PaymentRequest{UserID: userId, Tickets: tickets}, &response); err != nil {
Do(PaymentRequest{UserID: userId, Tickets: tickets}, &response); err != nil {
return false, err
}

log.Info().Str("id", response.ID).Int("price", response.Price).Msg("payment details")

call := ctx.Service(TicketServiceName).Method("markAsSold")
for _, ticket := range tickets {
if err := call.Send(ticket, nil, 0); err != nil {
call := ctx.Object(ticket, TicketServiceName).Method("markAsSold")
if err := call.Send(nil, 0); err != nil {
return false, err
}
}
Expand All @@ -97,8 +99,8 @@ func checkout(ctx restate.Context, userId string, _ restate.Void) (bool, error)
}

var (
UserSession = restate.NewKeyedRouter().
Handler("addTicket", restate.NewKeyedHandler(addTicket)).
Handler("expireTicket", restate.NewKeyedHandler(expireTicket)).
Handler("checkout", restate.NewKeyedHandler(checkout))
UserSession = restate.NewObjectRouter().
Handler("addTicket", restate.NewObjectHandler(addTicket)).
Handler("expireTicket", restate.NewObjectHandler(expireTicket)).
Handler("checkout", restate.NewObjectHandler(checkout))
)
1 change: 0 additions & 1 deletion generate.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
package restate

//go:generate buf generate
//go:generate buf build --as-file-descriptor-set -o internal/dynrpc.binbp proto/dynrpc/dynrpc.proto
Loading
Loading