-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathvirtual_objects.rb
More file actions
53 lines (47 loc) · 1.64 KB
/
Copy pathvirtual_objects.rb
File metadata and controls
53 lines (47 loc) · 1.64 KB
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
# frozen_string_literal: true
#
# Example: Virtual Objects
#
# A VirtualObject has a key and durable K/V state scoped to that key.
# Exclusive handlers run with mutual exclusion per key, so state
# updates are safe without external locking. Shared handlers allow
# concurrent reads.
#
# Features:
# - state :name, default: val — declarative state with auto accessors
# - Restate.get / Restate.set — explicit state operations
# - handler (exclusive) — one invocation at a time per key
# - shared (concurrent) — many readers, no writes
#
# Try it:
# curl localhost:8080/Counter/add -H 'content-type: application/json' -d '3'
# curl localhost:8080/Counter/add -H 'content-type: application/json' -d '2'
# curl localhost:8080/Counter/get -H 'content-type: application/json' -d 'null'
# curl localhost:8080/Counter/reset -H 'content-type: application/json' -d 'null'
require 'restate'
class Counter < Restate::VirtualObject
# Exclusive handler — only one runs at a time per key.
# Safe to read-modify-write without races.
handler def add(addend)
current = Restate.get('count') || 0
updated = current + addend
Restate.set('count', updated)
updated
end
# Shared handler — concurrent access allowed.
# Great for reads that don't mutate state.
shared def get
Restate.get('count') || 0
end
# Exclusive handler — clears a single state key.
handler def reset
Restate.clear('count')
'counter reset'
end
# Exclusive handler — lists all keys then wipes everything.
handler def reset_all
keys = Restate.state_keys
Restate.clear_all
{ 'cleared_keys' => keys }
end
end