-
Notifications
You must be signed in to change notification settings - Fork 42
/
world_context.go
239 lines (194 loc) · 7.17 KB
/
world_context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package cardinal
import (
"math/rand"
"reflect"
"time"
"github.com/rotisserie/eris"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"pkg.world.dev/world-engine/cardinal/gamestate"
"pkg.world.dev/world-engine/cardinal/receipt"
"pkg.world.dev/world-engine/cardinal/txpool"
"pkg.world.dev/world-engine/cardinal/types"
"pkg.world.dev/world-engine/cardinal/worldstage"
"pkg.world.dev/world-engine/sign"
)
// interface guard
var _ WorldContext = (*worldContext)(nil)
//go:generate mockgen -source=context.go -package mocks -destination=mocks/context.go
type WorldContext interface {
// Timestamp returns the UNIX timestamp of the tick in milliseconds.
// Millisecond is used to provide precision when working with subsecond tick intervals.
Timestamp() uint64
// CurrentTick returns the current tick.
CurrentTick() uint64
// Logger returns the logger that can be used to log messages from within system or query.
Logger() *zerolog.Logger
// EmitEvent emits an event that will be broadcast to all websocket subscribers.
EmitEvent(map[string]any) error
// EmitStringEvent emits a string event that will be broadcast to all websocket subscribers.
// This method is provided for backwards compatability. EmitEvent should be used for most cases.
EmitStringEvent(string) error
// Namespace returns the namespace of the world.
Namespace() string
// Rand returns a random number generator that is seeded specifically for a current tick.
Rand() *rand.Rand
// ScheduleTickTask schedules a task to be executed after the specified tickDelay.
// The given Task must have been registered using RegisterTask.
ScheduleTickTask(uint64, Task) error
// ScheduleTimeTask schedules a task to be executed after the specified duration (in wall clock time).
// The given Task must have been registered using RegisterTask.
ScheduleTimeTask(time.Duration, Task) error
// Private methods for internal use.
setLogger(logger zerolog.Logger)
addMessageError(id types.TxHash, err error)
setMessageResult(id types.TxHash, a any)
getComponentByName(name string) (types.ComponentMetadata, error)
getMessageByType(mType reflect.Type) (types.Message, bool)
getTransactionReceipt(id types.TxHash) (any, []error, bool)
getSignerForPersonaTag(personaTag string, tick uint64) (addr string, err error)
getTransactionReceiptsForTick(tick uint64) ([]receipt.Receipt, error)
receiptHistorySize() uint64
addTransaction(id types.MessageID, v any, sig *sign.Transaction) (uint64, types.TxHash)
isWorldReady() bool
storeReader() gamestate.Reader
storeManager() gamestate.Manager
getTxPool() *txpool.TxPool
isReadOnly() bool
}
type worldContext struct {
world *World
txPool *txpool.TxPool
logger *zerolog.Logger
readOnly bool
rand *rand.Rand
}
func newWorldContextForTick(world *World, txPool *txpool.TxPool) WorldContext {
return &worldContext{
world: world,
txPool: txPool,
logger: &log.Logger,
readOnly: false,
//nolint:gosec // we require manual in the rng which crypto/rand doesn't have, but math/rand does.
rand: rand.New(rand.NewSource(int64(world.timestamp.Load()))),
}
}
func NewWorldContext(world *World) WorldContext {
return &worldContext{
world: world,
txPool: nil,
logger: &log.Logger,
readOnly: false,
rand: nil,
}
}
func NewReadOnlyWorldContext(world *World) WorldContext {
return &worldContext{
world: world,
txPool: nil,
logger: &log.Logger,
readOnly: true,
rand: nil,
}
}
// -----------------------------------------------------------------------------
// Public methods
// -----------------------------------------------------------------------------
func (ctx *worldContext) ScheduleTickTask(tickDelay uint64, task Task) error {
triggerAtTick := ctx.CurrentTick() + tickDelay
return createTickTask(ctx, triggerAtTick, task)
}
func (ctx *worldContext) ScheduleTimeTask(duration time.Duration, task Task) error {
if duration.Milliseconds() < 0 {
return eris.New("duration value must be positive")
}
triggerAtTimestamp := ctx.Timestamp() + uint64(duration.Milliseconds())
return createTimestampTask(ctx, triggerAtTimestamp, task)
}
func (ctx *worldContext) EmitEvent(event map[string]any) error {
return ctx.world.tickResults.AddEvent(event)
}
func (ctx *worldContext) EmitStringEvent(e string) error {
return ctx.world.tickResults.AddStringEvent(e)
}
func (ctx *worldContext) Timestamp() uint64 {
return ctx.world.timestamp.Load()
}
func (ctx *worldContext) CurrentTick() uint64 {
return ctx.world.CurrentTick()
}
func (ctx *worldContext) Logger() *zerolog.Logger {
return ctx.logger
}
func (ctx *worldContext) Rand() *rand.Rand {
if ctx.rand == nil {
// a panic is thrown here instead of returning an error to maintain method chaining.
// ex: wCtx.rand().Int63()
panic(eris.New("rand is only useable on a context generated by newWorldContextForTick"))
}
return ctx.rand
}
func (ctx *worldContext) Namespace() string {
return ctx.world.Namespace()
}
// -----------------------------------------------------------------------------
// Private methods
// -----------------------------------------------------------------------------
func (ctx *worldContext) getMessageByType(mType reflect.Type) (types.Message, bool) {
return ctx.world.GetMessageByType(mType)
}
func (ctx *worldContext) setLogger(logger zerolog.Logger) {
ctx.logger = &logger
}
func (ctx *worldContext) getComponentByName(name string) (types.ComponentMetadata, error) {
return ctx.world.GetComponentByName(name)
}
func (ctx *worldContext) addMessageError(id types.TxHash, err error) {
// TODO(scott): i dont trust exposing this to the users. this should be fully abstracted away.
ctx.world.receiptHistory.AddError(id, err)
}
func (ctx *worldContext) setMessageResult(id types.TxHash, a any) {
// TODO(scott): i dont trust exposing this to the users. this should be fully abstracted away.
ctx.world.receiptHistory.SetResult(id, a)
}
func (ctx *worldContext) getTransactionReceipt(id types.TxHash) (any, []error, bool) {
rec, ok := ctx.world.receiptHistory.GetReceipt(id)
if !ok {
return nil, nil, false
}
return rec.Result, rec.Errs, true
}
func (ctx *worldContext) getSignerForPersonaTag(personaTag string, tick uint64) (addr string, err error) {
return ctx.world.GetSignerForPersonaTag(personaTag, tick)
}
func (ctx *worldContext) getTransactionReceiptsForTick(tick uint64) ([]receipt.Receipt, error) {
return ctx.world.GetTransactionReceiptsForTick(tick)
}
func (ctx *worldContext) receiptHistorySize() uint64 {
return ctx.world.receiptHistory.Size()
}
func (ctx *worldContext) addTransaction(id types.MessageID, v any, sig *sign.Transaction) (uint64, types.TxHash) {
return ctx.world.AddTransaction(id, v, sig)
}
func (ctx *worldContext) getTxPool() *txpool.TxPool {
return ctx.txPool
}
func (ctx *worldContext) isReadOnly() bool {
return ctx.readOnly
}
func (ctx *worldContext) storeManager() gamestate.Manager {
return ctx.world.entityStore
}
func (ctx *worldContext) storeReader() gamestate.Reader {
sm := ctx.storeManager()
if ctx.isReadOnly() {
return sm.ToReadOnly()
}
return sm
}
func (ctx *worldContext) isWorldReady() bool {
stage := ctx.world.worldStage.Current()
return stage == worldstage.Ready ||
stage == worldstage.Running ||
stage == worldstage.Recovering
}