Skip to content

Commit

Permalink
reorganises code to follow structure in other examples
Browse files Browse the repository at this point in the history
Signed-off-by: Elena Kolevska <[email protected]>
  • Loading branch information
elena-kolevska committed Nov 26, 2024
1 parent b687e9d commit a10aee3
Show file tree
Hide file tree
Showing 7 changed files with 160 additions and 144 deletions.
6 changes: 3 additions & 3 deletions scheduler-actor-reminders/Dockerfile-server
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@ RUN go mod download
COPY . .

# Build the server app binary
RUN CGO_ENABLED=0 go build -o player-actor ./server/player-actor.go
RUN CGO_ENABLED=0 go build -o player-actor-server ./server

# Final stage
FROM alpine:latest

WORKDIR /server

# Copy binary from the builder stage
COPY --from=builder /server/player-actor .
COPY --from=builder /server/player-actor-server .

EXPOSE 3007

# Start the server
CMD ["/server/player-actor"]
CMD ["/server/player-actor-server"]
96 changes: 6 additions & 90 deletions scheduler-actor-reminders/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@ package api

import (
"context"
"fmt"

"github.com/dapr/go-sdk/actor"
dapr "github.com/dapr/go-sdk/client"
)

const playerActorType = "playerActorType"
const PlayerActorType = "playerActorType"

type ClientStub struct {
ActorID string
OnActivate func(context.Context) error
GetUser func(ctx context.Context) (*GetPlayerResponse, error)
Invoke func(context.Context, string) (string, error)
RevivePlayer func(context.Context, string) error
Expand All @@ -20,21 +18,11 @@ type ClientStub struct {
}

func (a *ClientStub) Type() string {
return playerActorType
return PlayerActorType
}

func (a *ClientStub) ID() string {
return "player-1"
}

type PlayerActor struct {
actor.ServerImplBaseCtx
DaprClient dapr.Client
Health int
}

func (p *PlayerActor) Type() string {
return playerActorType
return a.ActorID
}

type GetPlayerRequest struct {
Expand All @@ -48,79 +36,7 @@ type GetPlayerResponse struct {

type ReminderRequest struct {
ReminderName string `json:"reminder_name"`
DueTime string `json:"duration"`
DueTime string `json:"due_time"`
Period string `json:"period"`
Data string `json:"data"`
}

// GetUser retrieving the state of the PlayerActor
func (p *PlayerActor) GetUser(ctx context.Context) (*GetPlayerResponse, error) {
fmt.Printf("Player Actor ID: %s has a health level of: %d\n", p.ID(), p.Health)
return &GetPlayerResponse{
ActorID: p.ID(),
Health: p.Health,
}, nil
}

// Invoke invokes an action on the actor
func (p *PlayerActor) Invoke(ctx context.Context, req string) (string, error) {
fmt.Println("get req = ", req)
return req, nil
}

// RevivePlayer revives the actor players health back to 100
func (p *PlayerActor) RevivePlayer(ctx context.Context, id string) error {
if id == p.ID() {
fmt.Printf("Reviving player: %s\n", id)
p.Health = 100
}

return nil
}

// StartReminder registers a reminder for the actor
func (p *PlayerActor) StartReminder(ctx context.Context, req *ReminderRequest) error {
fmt.Println("Starting reminder:", req.ReminderName)
return p.DaprClient.RegisterActorReminder(ctx, &dapr.RegisterActorReminderRequest{
ActorType: p.Type(),
ActorID: p.ID(),
Name: req.ReminderName,
DueTime: req.DueTime,
Period: req.Period,
Data: []byte(req.Data),
})
}

// StopReminder unregisters a reminder for the actor
func (p *PlayerActor) StopReminder(ctx context.Context, req *ReminderRequest) error {
fmt.Println("Stopping reminder:", req.ReminderName)
return p.DaprClient.RegisterActorReminder(ctx, &dapr.RegisterActorReminderRequest{
ActorType: p.Type(),
ActorID: p.ID(),
Name: req.ReminderName,
})
}

// ReminderCall executes logic to handle what happens when the reminder is triggered
// Dapr automatically calls this method when a reminder fires for the player actor
func (p *PlayerActor) ReminderCall(reminderName string, state []byte, dueTime string, period string) {
fmt.Println("receive reminder = ", reminderName, " state = ", string(state), "duetime = ", dueTime, "period = ", period)
if reminderName == "healthReminder" {
// Increase health if below 100
if p.Health < 100 {
p.Health += 10
if p.Health > 100 {
p.Health = 100
}
fmt.Printf("Player Actor health increased. Current health: %d\n", p.Health)
}
} else if reminderName == "healthDecayReminder" {
// Decrease health
p.Health -= 5
if p.Health < 0 {
fmt.Println("Player Actor died...")
}
fmt.Printf("Health decreased. Current health: %d\n", p.Health)
}

}
12 changes: 6 additions & 6 deletions scheduler-actor-reminders/client/player-actor-client.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ func main() {
log.Fatalf("error waiting for Dapr initialization: %v", err)
}

// implement the actor client stub
myActor := new(api.ClientStub)
// Implement the actor client stub
myActor := &api.ClientStub{
ActorID: "player-1",
}
client.ImplActorClientStub(myActor)

deathSignal := make(chan bool)

// Start monitoring actor player's health
go monitorPlayerHealth(ctx, myActor, deathSignal)
go monitorPlayerHealth(ctx, myActor)

//Start player actor health increase reminder
err = myActor.StartReminder(ctx, &api.ReminderRequest{
Expand Down Expand Up @@ -74,7 +74,7 @@ func main() {

// monitorPlayerHealth continuously checks the player's health every 5 seconds
// and signals via a channel if the player is dead (health <= 0).
func monitorPlayerHealth(ctx context.Context, actor *api.ClientStub, deathSignal chan bool) {
func monitorPlayerHealth(ctx context.Context, actor *api.ClientStub) {
for {
select {
case <-ctx.Done():
Expand Down
6 changes: 2 additions & 4 deletions scheduler-actor-reminders/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@ module test-infra/scheduler-actor-reminders

go 1.23.1

require (
github.com/dapr/go-sdk v1.11.0
github.com/dapr/go-sdk/examples/actor v0.0.0-20240626135542-c417f950fe1d
)
require github.com/dapr/go-sdk v1.11.0

require (
github.com/dapr/dapr v1.14.0 // indirect
github.com/go-chi/chi/v5 v5.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/rogpeppe/go-internal v1.13.1 // indirect
go.opentelemetry.io/otel v1.27.0 // indirect
golang.org/x/net v0.26.0 // indirect
Expand Down
5 changes: 3 additions & 2 deletions scheduler-actor-reminders/go.sum
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/dapr/dapr v1.14.0 h1:SIQsNX1kH31JRDIS4k8IZ6eomM/BAcOP844PhQIT+BQ=
github.com/dapr/dapr v1.14.0/go.mod h1:oDNgaPHQIDZ3G4n4g89TElXWgkluYwcar41DI/oF4gw=
github.com/dapr/go-sdk v1.11.0 h1:clANpOQd6MsfvSa6snaX8MVk6eRx26Vsj5GxGdQ6mpE=
github.com/dapr/go-sdk v1.11.0/go.mod h1:btZ/tX8eYnx0fg3HiJUku8J5QBRXHsp3kAB1BUiTxXY=
github.com/dapr/go-sdk/examples/actor v0.0.0-20240626135542-c417f950fe1d h1:J7u+R5/FXuh1y757FHAnA75g3w8ADzm4idO1kQmKH80=
github.com/dapr/go-sdk/examples/actor v0.0.0-20240626135542-c417f950fe1d/go.mod h1:Vg/MQZ6O3JVTtp6NgNtAGRmyCamXjZDp6OBqkLfF8W8=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
Expand All @@ -18,8 +17,10 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
Expand Down
60 changes: 60 additions & 0 deletions scheduler-actor-reminders/server/player-actor-server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"context"
"log"
http2 "net/http"
"os"
"os/signal"
"syscall"

"github.com/dapr/go-sdk/actor"
dapr "github.com/dapr/go-sdk/client"
"github.com/dapr/go-sdk/service/http"
)

const appPort = ":3007"

func playerActorFactory() actor.ServerContext {
client, err := dapr.NewClient()
if err != nil {
panic(err)
}

return &PlayerActor{
DaprClient: client,
Health: 100, // initial health
}
}

func main() {
_, cancel := context.WithCancel(context.Background())
defer cancel()

daprService := http.NewService(appPort)
// Register actor factory, meaning register actor methods to be called by client
daprService.RegisterActorImplFactoryContext(playerActorFactory)

go func() {
log.Println("Starting Dapr actor runtime...")
if err := daprService.Start(); err != nil && err.Error() != http2.ErrServerClosed.Error() {
log.Fatalf("error starting Dapr actor runtime: %v", err)
}
}()

waitForShutdown(cancel)
if err := daprService.GracefulStop(); err != nil {
log.Fatalf("error stopping Dapr actor runtime: %v", err)
}
}

// waitForShutdown keeps the app alive until an interrupt or termination signal is received
func waitForShutdown(cancelFunc context.CancelFunc) {
sigCh := make(chan os.Signal, 1)
// Notify the channel on Interrupt (Ctrl+C) or SIGTERM (for Docker/K8s graceful shutdown)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
<-sigCh

log.Println("Shutting down...")
cancelFunc()
}
Loading

0 comments on commit a10aee3

Please sign in to comment.