Skip to content

Commit d816f79

Browse files
committed
Initial commit - FR: realtime event listener for RTDB (#229)
1 parent be821cd commit d816f79

File tree

5 files changed

+484
-0
lines changed

5 files changed

+484
-0
lines changed

cmd/listen/main.go

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// Copyright 2019 Google Inc. All Rights Reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package main
16+
17+
import (
18+
"fmt"
19+
"log"
20+
"os"
21+
22+
"golang.org/x/net/context"
23+
"google.golang.org/api/option"
24+
25+
firebase "firebase.google.com/go"
26+
"firebase.google.com/go/db"
27+
)
28+
29+
func main() {
30+
31+
// opt := option.WithCredentialsFile("c:/users/username/.firebase/firebase.json") // Windows
32+
//
33+
opt := option.WithCredentialsFile("/home/username/.firebase/firebase.json") // Linux, edit 1.
34+
35+
config := &firebase.Config{
36+
DatabaseURL: "https://mydb.firebaseio.com", // edit 2.
37+
}
38+
39+
app, err := firebase.NewApp(context.Background(), config, opt)
40+
if err != nil {
41+
log.Fatal(err)
42+
}
43+
44+
ctx := context.Background()
45+
46+
// DatabaseWithURL
47+
client, err := app.Database(ctx)
48+
49+
if err != nil {
50+
log.Fatal(err)
51+
}
52+
53+
testpath := "user1/path1"
54+
ref := client.NewRef(testpath)
55+
56+
args := os.Args
57+
if len(args) > 1 {
58+
triggerEvent(ctx, client, testpath, args[1])
59+
return // exit app
60+
}
61+
62+
// SnapshotIterator
63+
iter, err := ref.Listen(ctx)
64+
if err != nil {
65+
fmt.Printf(" Error: failed to create Listener %v\n", err)
66+
return
67+
}
68+
69+
fmt.Printf("client app | Ref Path: %s | iter.Snapshot = %v\n", ref.Path, iter.Snapshot)
70+
fmt.Printf(" | Ref Key: %s \n", ref.Key)
71+
72+
defer iter.Stop()
73+
74+
go func() {
75+
for {
76+
event, err := iter.Next()
77+
78+
if err != nil {
79+
break
80+
}
81+
82+
fmt.Printf("client app | Ref Path: %s | event.Path %s | event.Snapshot() = %v\n", ref.Path, event.Path, event.Snapshot())
83+
fmt.Printf("\n")
84+
}
85+
}()
86+
87+
fmt.Printf("\n >>> edit value of any key from %s in firebase console to trigger event\n\n", testpath)
88+
fmt.Printf("\n >>> press <enter> to close http connection\n\n")
89+
fmt.Printf("Waiting for events...\n\n")
90+
91+
fmt.Scanln()
92+
iter.Stop()
93+
94+
fmt.Printf("\n >>> press <enter> to exit app\n\n\n")
95+
fmt.Scanln()
96+
}
97+
98+
func triggerEvent(ctx context.Context, client *db.Client, testpath string, val string) {
99+
100+
ref := client.NewRef(testpath + "/key1")
101+
102+
if err := ref.Set(ctx, val); err != nil {
103+
log.Fatal(err)
104+
} else {
105+
fmt.Printf("OK - Set %s to %v\n", testpath+"/key1", val)
106+
}
107+
}

db/event.go

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Copyright 2019 Google Inc. All Rights Reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package db
16+
17+
import (
18+
"encoding/json"
19+
"errors"
20+
"net/http"
21+
)
22+
23+
// SSE = Sever-Sent Events = ssevent
24+
25+
// EventType ...
26+
type EventType uint
27+
28+
// EventType ...
29+
const (
30+
ChildChanged EventType = iota
31+
ChildAdded // to be implemented
32+
ChildRemoved // to be implemented
33+
ValueChanged // to be implemented
34+
)
35+
36+
// Event Sever-Sent Event object
37+
type Event struct {
38+
EventType EventType // ChildChanged, ValueChanged, ChildAdded, ChildRemoved
39+
40+
Data string // JSON-encoded snapshot
41+
Path string // snapshot path
42+
}
43+
44+
// SnapshotIterator iterator for continuous event
45+
type SnapshotIterator struct {
46+
Snapshot string // initial snapshot, JSON-encoded, returned from http Respoonse, server sent event, data part
47+
SSEDataChan <-chan string // continuous event snapshot, channel receive only, directional channel
48+
resp *http.Response // http connection keep alive
49+
active bool // false when resp is closed, used to prevent channel block, defaults to false
50+
}
51+
52+
// Snapshot ssevent data, data part
53+
func (e *Event) Snapshot() string {
54+
return e.Data // ssevent data (snapshot), snapshot only, data part of ssevent data
55+
}
56+
57+
// Unmarshal current snapshot Event.Data
58+
func (e *Event) Unmarshal(v interface{}) error {
59+
60+
return json.Unmarshal([]byte(e.Data), v)
61+
}
62+
63+
// Next ...
64+
func (i *SnapshotIterator) Next() (*Event, error) {
65+
66+
// prevent channel block
67+
if i.active == false {
68+
return nil, errors.New("SnapshotIterator is not active")
69+
}
70+
71+
sseDataString := <-i.SSEDataChan
72+
73+
// todo: determine EventType
74+
75+
path, ss, err := splitSSEData(sseDataString)
76+
77+
return &Event{
78+
EventType: ChildChanged,
79+
Data: ss, // snapshot
80+
Path: path,
81+
}, err
82+
83+
} // Next()
84+
85+
// Stop ...
86+
func (i *SnapshotIterator) Stop() {
87+
i.active = false
88+
if i.resp != nil {
89+
i.resp.Body.Close()
90+
}
91+
}

0 commit comments

Comments
 (0)