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

Support TTL for transient data. #575

Merged
merged 3 commits into from
Oct 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions api_signaling.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"net/url"
"sort"
"strings"
"time"

"github.com/golang-jwt/jwt/v4"
)
Expand Down Expand Up @@ -847,6 +848,7 @@ type TransientDataClientMessage struct {

Key string `json:"key,omitempty"`
Value *json.RawMessage `json:"value,omitempty"`
TTL time.Duration `json:"ttl,omitempty"`
}

func (m *TransientDataClientMessage) CheckValid() error {
Expand Down
14 changes: 7 additions & 7 deletions backend_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,8 @@ func TestBackendServer_RoomDisinviteDifferentRooms(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err := client2.RunUntilHello(ctx); err != nil {
hello2, err := client2.RunUntilHello(ctx)
if err != nil {
t.Fatal(err)
}

Expand All @@ -635,16 +636,14 @@ func TestBackendServer_RoomDisinviteDifferentRooms(t *testing.T) {
if _, err := client1.JoinRoom(ctx, roomId1); err != nil {
t.Fatal(err)
}
if err := client1.RunUntilJoined(ctx, hello1.Hello); err != nil {
t.Error(err)
}
roomId2 := "test-room2"
if _, err := client2.JoinRoom(ctx, roomId2); err != nil {
t.Fatal(err)
}

// Ignore "join" events.
if err := client1.DrainMessages(ctx); err != nil {
t.Error(err)
}
if err := client2.DrainMessages(ctx); err != nil {
if err := client2.RunUntilJoined(ctx, hello2.Hello); err != nil {
t.Error(err)
}

Expand Down Expand Up @@ -702,6 +701,7 @@ func TestBackendServer_RoomDisinviteDifferentRooms(t *testing.T) {
UserIds: []string{
testDefaultUserId,
},
Properties: (*json.RawMessage)(&testRoomProperties),
},
}

Expand Down
7 changes: 5 additions & 2 deletions docs/standalone-signaling-api-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -817,14 +817,17 @@ Message format (Client -> Server):
"transient": {
"type": "set",
"key": "sample-key",
"value": "any-json-object"
"value": "any-json-object",
"ttl": "optional-ttl"
}
}

- The `key` must be a string.
- The `value` can be of any type (i.e. string, number, array, object, etc.).
- The `ttl` is the time to live in nanoseconds. The value will be removed after
that time (if it is still present).
- Requests to set a value that is already present for the key are silently
ignored.
ignored. Any TTL value will be updated / removed.


Message format (Server -> Client):
Expand Down
4 changes: 2 additions & 2 deletions hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -1965,9 +1965,9 @@ func (h *Hub) processTransientMsg(client *Client, message *ClientMessage) {
}

if msg.Value == nil {
room.SetTransientData(msg.Key, nil)
room.SetTransientDataTTL(msg.Key, nil, msg.TTL)
} else {
room.SetTransientData(msg.Key, *msg.Value)
room.SetTransientDataTTL(msg.Key, *msg.Value, msg.TTL)
}
case "remove":
if !isAllowedToUpdateTransientData(session) {
Expand Down
4 changes: 4 additions & 0 deletions room.go
Original file line number Diff line number Diff line change
Expand Up @@ -1059,6 +1059,10 @@ func (r *Room) SetTransientData(key string, value interface{}) {
r.transientData.Set(key, value)
}

func (r *Room) SetTransientDataTTL(key string, value interface{}, ttl time.Duration) {
r.transientData.SetTTL(key, value, ttl)
}

func (r *Room) RemoveTransientData(key string) {
r.transientData.Remove(key)
}
3 changes: 2 additions & 1 deletion testclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ func (c *TestClient) SendInternalRemoveSession(msg *RemoveSessionInternalClientM
return c.WriteJSON(message)
}

func (c *TestClient) SetTransientData(key string, value interface{}) error {
func (c *TestClient) SetTransientData(key string, value interface{}, ttl time.Duration) error {
payload, err := json.Marshal(value)
if err != nil {
c.t.Fatal(err)
Expand All @@ -591,6 +591,7 @@ func (c *TestClient) SetTransientData(key string, value interface{}) error {
Type: "set",
Key: key,
Value: (*json.RawMessage)(&payload),
TTL: ttl,
},
}
return c.WriteJSON(message)
Expand Down
89 changes: 78 additions & 11 deletions transient_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ package signaling
import (
"reflect"
"sync"
"time"
)

type TransientListener interface {
Expand All @@ -34,6 +35,8 @@ type TransientData struct {
mu sync.Mutex
data map[string]interface{}
listeners map[TransientListener]bool
timers map[string]*time.Timer
ttlCh chan<- struct{}
}

// NewTransientData creates a new transient data container.
Expand Down Expand Up @@ -99,9 +102,59 @@ func (t *TransientData) RemoveListener(listener TransientListener) {
delete(t.listeners, listener)
}

func (t *TransientData) updateTTL(key string, value interface{}, ttl time.Duration) {
if ttl <= 0 {
delete(t.timers, key)
} else {
t.removeAfterTTL(key, value, ttl)
}
}

func (t *TransientData) removeAfterTTL(key string, value interface{}, ttl time.Duration) {
if ttl <= 0 {
return
}

if old, found := t.timers[key]; found {
old.Stop()
}

timer := time.AfterFunc(ttl, func() {
t.mu.Lock()
defer t.mu.Unlock()

t.compareAndRemove(key, value)
if t.ttlCh != nil {
select {
case t.ttlCh <- struct{}{}:
default:
}
}
})
if t.timers == nil {
t.timers = make(map[string]*time.Timer)
}
t.timers[key] = timer
}

func (t *TransientData) doSet(key string, value interface{}, prev interface{}, ttl time.Duration) {
if t.data == nil {
t.data = make(map[string]interface{})
}
t.data[key] = value
t.notifySet(key, prev, value)
t.removeAfterTTL(key, value, ttl)
}

// Set sets a new value for the given key and notifies listeners
// if the value has been changed.
func (t *TransientData) Set(key string, value interface{}) bool {
return t.SetTTL(key, value, 0)
}

// SetTTL sets a new value for the given key with a time-to-live and notifies
// listeners if the value has been changed.
func (t *TransientData) SetTTL(key string, value interface{}, ttl time.Duration) bool {
if value == nil {
return t.Remove(key)
}
Expand All @@ -111,20 +164,24 @@ func (t *TransientData) Set(key string, value interface{}) bool {

prev, found := t.data[key]
if found && reflect.DeepEqual(prev, value) {
t.updateTTL(key, value, ttl)
return false
}

if t.data == nil {
t.data = make(map[string]interface{})
}
t.data[key] = value
t.notifySet(key, prev, value)
t.doSet(key, value, prev, ttl)
return true
}

// CompareAndSet sets a new value for the given key only for a given old value
// and notifies listeners if the value has been changed.
func (t *TransientData) CompareAndSet(key string, old, value interface{}) bool {
return t.CompareAndSetTTL(key, old, value, 0)
}

// CompareAndSetTTL sets a new value for the given key with a time-to-live,
// only for a given old value and notifies listeners if the value has been
// changed.
func (t *TransientData) CompareAndSetTTL(key string, old, value interface{}, ttl time.Duration) bool {
if value == nil {
return t.CompareAndRemove(key, old)
}
Expand All @@ -139,11 +196,19 @@ func (t *TransientData) CompareAndSet(key string, old, value interface{}) bool {
return false
}

t.data[key] = value
t.notifySet(key, prev, value)
t.doSet(key, value, prev, ttl)
return true
}

func (t *TransientData) doRemove(key string, prev interface{}) {
delete(t.data, key)
if old, found := t.timers[key]; found {
old.Stop()
delete(t.timers, key)
}
t.notifyDeleted(key, prev)
}

// Remove deletes the value with the given key and notifies listeners
// if the key was removed.
func (t *TransientData) Remove(key string) bool {
Expand All @@ -155,8 +220,7 @@ func (t *TransientData) Remove(key string) bool {
return false
}

delete(t.data, key)
t.notifyDeleted(key, prev)
t.doRemove(key, prev)
return true
}

Expand All @@ -166,13 +230,16 @@ func (t *TransientData) CompareAndRemove(key string, old interface{}) bool {
t.mu.Lock()
defer t.mu.Unlock()

return t.compareAndRemove(key, old)
}

func (t *TransientData) compareAndRemove(key string, old interface{}) bool {
prev, found := t.data[key]
if !found || !reflect.DeepEqual(prev, old) {
return false
}

delete(t.data, key)
t.notifyDeleted(key, prev)
t.doRemove(key, prev)
return true
}

Expand Down
Loading
Loading