You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

517 line
15 KiB

  1. // Copyright 2018 Google LLC
  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. package firestore
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "log"
  20. "sort"
  21. "time"
  22. "cloud.google.com/go/internal/btree"
  23. "github.com/golang/protobuf/ptypes"
  24. gax "github.com/googleapis/gax-go"
  25. "golang.org/x/net/context"
  26. pb "google.golang.org/genproto/googleapis/firestore/v1beta1"
  27. "google.golang.org/grpc/codes"
  28. "google.golang.org/grpc/status"
  29. )
  30. // LogWatchStreams controls whether watch stream status changes are logged.
  31. // This feature is EXPERIMENTAL and may disappear at any time.
  32. var LogWatchStreams bool = false
  33. // DocumentChangeKind describes the kind of change to a document between
  34. // query snapshots.
  35. type DocumentChangeKind int
  36. const (
  37. DocumentAdded DocumentChangeKind = iota
  38. DocumentRemoved
  39. DocumentModified
  40. )
  41. // A DocumentChange describes the change to a document from one query snapshot to the next.
  42. type DocumentChange struct {
  43. Kind DocumentChangeKind
  44. Doc *DocumentSnapshot
  45. // The zero-based index of the document in the sequence of query results prior to this change,
  46. // or -1 if the document was not present.
  47. OldIndex int
  48. // The zero-based index of the document in the sequence of query results after this change,
  49. // or -1 if the document is no longer present.
  50. NewIndex int
  51. }
  52. // Implementation of realtime updates (a.k.a. watch).
  53. // This code is closely based on the Node.js implementation,
  54. // https://github.com/googleapis/nodejs-firestore/blob/master/src/watch.js.
  55. // The sole target ID for all streams from this client.
  56. // Variable for testing.
  57. var watchTargetID int32 = 'g' + 'o'
  58. var defaultBackoff = gax.Backoff{
  59. // Values from https://github.com/googleapis/nodejs-firestore/blob/master/src/backoff.js.
  60. Initial: 1 * time.Second,
  61. Max: 60 * time.Second,
  62. Multiplier: 1.5,
  63. }
  64. // not goroutine-safe
  65. type watchStream struct {
  66. ctx context.Context
  67. c *Client
  68. lc pb.Firestore_ListenClient // the gRPC stream
  69. target *pb.Target // document or query being watched
  70. backoff gax.Backoff // for stream retries
  71. err error // sticky permanent error
  72. readTime time.Time // time of most recent snapshot
  73. current bool // saw CURRENT, but not RESET; precondition for a snapshot
  74. hasReturned bool // have we returned a snapshot yet?
  75. compare func(a, b *DocumentSnapshot) (int, error) // compare documents according to query
  76. // An ordered tree where DocumentSnapshots are the keys.
  77. docTree *btree.BTree
  78. // Map of document name to DocumentSnapshot for the last returned snapshot.
  79. docMap map[string]*DocumentSnapshot
  80. // Map of document name to DocumentSnapshot for accumulated changes for the current snapshot.
  81. // A nil value means the document was removed.
  82. changeMap map[string]*DocumentSnapshot
  83. }
  84. func newWatchStreamForDocument(ctx context.Context, dr *DocumentRef) *watchStream {
  85. // A single document is always equal to itself.
  86. compare := func(_, _ *DocumentSnapshot) (int, error) { return 0, nil }
  87. return newWatchStream(ctx, dr.Parent.c, compare, &pb.Target{
  88. TargetType: &pb.Target_Documents{
  89. Documents: &pb.Target_DocumentsTarget{Documents: []string{dr.Path}},
  90. },
  91. TargetId: watchTargetID,
  92. })
  93. }
  94. func newWatchStreamForQuery(ctx context.Context, q Query) (*watchStream, error) {
  95. qp, err := q.toProto()
  96. if err != nil {
  97. return nil, err
  98. }
  99. target := &pb.Target{
  100. TargetType: &pb.Target_Query{
  101. Query: &pb.Target_QueryTarget{
  102. Parent: q.parentPath,
  103. QueryType: &pb.Target_QueryTarget_StructuredQuery{qp},
  104. },
  105. },
  106. TargetId: watchTargetID,
  107. }
  108. return newWatchStream(ctx, q.c, q.compareFunc(), target), nil
  109. }
  110. const btreeDegree = 4
  111. func newWatchStream(ctx context.Context, c *Client, compare func(_, _ *DocumentSnapshot) (int, error), target *pb.Target) *watchStream {
  112. w := &watchStream{
  113. ctx: ctx,
  114. c: c,
  115. compare: compare,
  116. target: target,
  117. backoff: defaultBackoff,
  118. docMap: map[string]*DocumentSnapshot{},
  119. changeMap: map[string]*DocumentSnapshot{},
  120. }
  121. w.docTree = btree.New(btreeDegree, func(a, b interface{}) bool {
  122. return w.less(a.(*DocumentSnapshot), b.(*DocumentSnapshot))
  123. })
  124. return w
  125. }
  126. func (s *watchStream) less(a, b *DocumentSnapshot) bool {
  127. c, err := s.compare(a, b)
  128. if err != nil {
  129. s.err = err
  130. return false
  131. }
  132. return c < 0
  133. }
  134. // Once nextSnapshot returns an error, it will always return the same error.
  135. func (s *watchStream) nextSnapshot() (*btree.BTree, []DocumentChange, time.Time, error) {
  136. if s.err != nil {
  137. return nil, nil, time.Time{}, s.err
  138. }
  139. var changes []DocumentChange
  140. for {
  141. // Process messages until we are in a consistent state.
  142. for !s.handleNextMessage() {
  143. }
  144. if s.err != nil {
  145. _ = s.close() // ignore error
  146. return nil, nil, time.Time{}, s.err
  147. }
  148. var newDocTree *btree.BTree
  149. newDocTree, changes = s.computeSnapshot(s.docTree, s.docMap, s.changeMap, s.readTime)
  150. if s.err != nil {
  151. return nil, nil, time.Time{}, s.err
  152. }
  153. // Only return a snapshot if something has changed, or this is the first snapshot.
  154. if !s.hasReturned || newDocTree != s.docTree {
  155. s.docTree = newDocTree
  156. break
  157. }
  158. }
  159. s.changeMap = map[string]*DocumentSnapshot{}
  160. s.hasReturned = true
  161. return s.docTree, changes, s.readTime, nil
  162. }
  163. // Read a message from the stream and handle it. Return true when
  164. // we're in a consistent state, or there is a permanent error.
  165. func (s *watchStream) handleNextMessage() bool {
  166. res, err := s.recv()
  167. if err != nil {
  168. s.err = err
  169. // Errors returned by recv are permanent.
  170. return true
  171. }
  172. switch r := res.ResponseType.(type) {
  173. case *pb.ListenResponse_TargetChange:
  174. return s.handleTargetChange(r.TargetChange)
  175. case *pb.ListenResponse_DocumentChange:
  176. name := r.DocumentChange.Document.Name
  177. s.logf("DocumentChange %q", name)
  178. if hasWatchTargetID(r.DocumentChange.TargetIds) { // document changed
  179. ref, err := pathToDoc(name, s.c)
  180. if err == nil {
  181. s.changeMap[name], err = newDocumentSnapshot(ref, r.DocumentChange.Document, s.c, nil)
  182. }
  183. if err != nil {
  184. s.err = err
  185. return true
  186. }
  187. } else if hasWatchTargetID(r.DocumentChange.RemovedTargetIds) { // document removed
  188. s.changeMap[name] = nil
  189. }
  190. case *pb.ListenResponse_DocumentDelete:
  191. s.logf("Delete %q", r.DocumentDelete.Document)
  192. s.changeMap[r.DocumentDelete.Document] = nil
  193. case *pb.ListenResponse_DocumentRemove:
  194. s.logf("Remove %q", r.DocumentRemove.Document)
  195. s.changeMap[r.DocumentRemove.Document] = nil
  196. case *pb.ListenResponse_Filter:
  197. s.logf("Filter %d", r.Filter.Count)
  198. if int(r.Filter.Count) != s.currentSize() {
  199. s.resetDocs() // Remove all the current results.
  200. // The filter didn't match; close the stream so it will be re-opened on the next
  201. // call to nextSnapshot.
  202. _ = s.close() // ignore error
  203. s.lc = nil
  204. }
  205. default:
  206. s.err = fmt.Errorf("unknown response type %T", r)
  207. return true
  208. }
  209. return false
  210. }
  211. // Return true iff in a consistent state, or there is a permanent error.
  212. func (s *watchStream) handleTargetChange(tc *pb.TargetChange) bool {
  213. switch tc.TargetChangeType {
  214. case pb.TargetChange_NO_CHANGE:
  215. s.logf("TargetNoChange %d %v", len(tc.TargetIds), tc.ReadTime)
  216. if len(tc.TargetIds) == 0 && tc.ReadTime != nil && s.current {
  217. // Everything is up-to-date, so we are ready to return a snapshot.
  218. rt, err := ptypes.Timestamp(tc.ReadTime)
  219. if err != nil {
  220. s.err = err
  221. return true
  222. }
  223. s.readTime = rt
  224. s.target.ResumeType = &pb.Target_ResumeToken{tc.ResumeToken}
  225. return true
  226. }
  227. case pb.TargetChange_ADD:
  228. s.logf("TargetAdd")
  229. if tc.TargetIds[0] != watchTargetID {
  230. s.err = errors.New("unexpected target ID sent by server")
  231. return true
  232. }
  233. case pb.TargetChange_REMOVE:
  234. s.logf("TargetRemove")
  235. // We should never see a remove.
  236. if tc.Cause != nil {
  237. s.err = status.Error(codes.Code(tc.Cause.Code), tc.Cause.Message)
  238. } else {
  239. s.err = status.Error(codes.Internal, "firestore: client saw REMOVE")
  240. }
  241. return true
  242. // The targets reflect all changes committed before the targets were added
  243. // to the stream.
  244. case pb.TargetChange_CURRENT:
  245. s.logf("TargetCurrent")
  246. s.current = true
  247. // The targets have been reset, and a new initial state for the targets will be
  248. // returned in subsequent changes. Whatever changes have happened so far no
  249. // longer matter.
  250. case pb.TargetChange_RESET:
  251. s.logf("TargetReset")
  252. s.resetDocs()
  253. default:
  254. s.err = fmt.Errorf("firestore: unknown TargetChange type %s", tc.TargetChangeType)
  255. return true
  256. }
  257. // If we see a resume token and our watch ID is affected, we assume the stream
  258. // is now healthy, so we reset our backoff time to the minimum.
  259. if tc.ResumeToken != nil && (len(tc.TargetIds) == 0 || hasWatchTargetID(tc.TargetIds)) {
  260. s.backoff = defaultBackoff
  261. }
  262. return false // not in a consistent state, keep receiving
  263. }
  264. func (s *watchStream) resetDocs() {
  265. s.target.ResumeType = nil // clear resume token
  266. s.current = false
  267. s.changeMap = map[string]*DocumentSnapshot{}
  268. // Mark each document as deleted. If documents are not deleted, they
  269. // will be send again by the server.
  270. it := s.docTree.BeforeIndex(0)
  271. for it.Next() {
  272. s.changeMap[it.Key.(*DocumentSnapshot).Ref.Path] = nil
  273. }
  274. }
  275. func (s *watchStream) currentSize() int {
  276. _, adds, deletes := extractChanges(s.docMap, s.changeMap)
  277. return len(s.docMap) + len(adds) - len(deletes)
  278. }
  279. // Return the changes that have occurred since the last snapshot.
  280. func extractChanges(docMap, changeMap map[string]*DocumentSnapshot) (updates, adds []*DocumentSnapshot, deletes []string) {
  281. for name, doc := range changeMap {
  282. switch {
  283. case doc == nil:
  284. if _, ok := docMap[name]; ok {
  285. deletes = append(deletes, name)
  286. }
  287. case docMap[name] != nil:
  288. updates = append(updates, doc)
  289. default:
  290. adds = append(adds, doc)
  291. }
  292. }
  293. return updates, adds, deletes
  294. }
  295. // For development only.
  296. // TODO(jba): remove.
  297. func assert(b bool) {
  298. if !b {
  299. panic("assertion failed")
  300. }
  301. }
  302. // Applies the mutations in changeMap to both the document tree and the
  303. // document lookup map. Modifies docMap in place and returns a new docTree.
  304. // If there were no changes, returns docTree unmodified.
  305. func (s *watchStream) computeSnapshot(docTree *btree.BTree, docMap, changeMap map[string]*DocumentSnapshot, readTime time.Time) (*btree.BTree, []DocumentChange) {
  306. var changes []DocumentChange
  307. updatedTree := docTree
  308. assert(docTree.Len() == len(docMap))
  309. updates, adds, deletes := extractChanges(docMap, changeMap)
  310. if len(adds) > 0 || len(deletes) > 0 {
  311. updatedTree = docTree.Clone()
  312. }
  313. // Process the sorted changes in the order that is expected by our clients
  314. // (removals, additions, and then modifications). We also need to sort the
  315. // individual changes to assure that oldIndex/newIndex keep incrementing.
  316. deldocs := make([]*DocumentSnapshot, len(deletes))
  317. for i, d := range deletes {
  318. deldocs[i] = docMap[d]
  319. }
  320. sort.Sort(byLess{deldocs, s.less})
  321. for _, oldDoc := range deldocs {
  322. assert(oldDoc != nil)
  323. delete(docMap, oldDoc.Ref.Path)
  324. _, oldi := updatedTree.GetWithIndex(oldDoc)
  325. // TODO(jba): have btree.Delete return old index
  326. _, found := updatedTree.Delete(oldDoc)
  327. assert(found)
  328. changes = append(changes, DocumentChange{
  329. Kind: DocumentRemoved,
  330. Doc: oldDoc,
  331. OldIndex: oldi,
  332. NewIndex: -1,
  333. })
  334. }
  335. sort.Sort(byLess{adds, s.less})
  336. for _, newDoc := range adds {
  337. name := newDoc.Ref.Path
  338. assert(docMap[name] == nil)
  339. newDoc.ReadTime = readTime
  340. docMap[name] = newDoc
  341. updatedTree.Set(newDoc, nil)
  342. // TODO(jba): change btree so Set returns index as second value.
  343. _, newi := updatedTree.GetWithIndex(newDoc)
  344. changes = append(changes, DocumentChange{
  345. Kind: DocumentAdded,
  346. Doc: newDoc,
  347. OldIndex: -1,
  348. NewIndex: newi,
  349. })
  350. }
  351. sort.Sort(byLess{updates, s.less})
  352. for _, newDoc := range updates {
  353. name := newDoc.Ref.Path
  354. oldDoc := docMap[name]
  355. assert(oldDoc != nil)
  356. if newDoc.UpdateTime.Equal(oldDoc.UpdateTime) {
  357. continue
  358. }
  359. if updatedTree == docTree {
  360. updatedTree = docTree.Clone()
  361. }
  362. newDoc.ReadTime = readTime
  363. docMap[name] = newDoc
  364. _, oldi := updatedTree.GetWithIndex(oldDoc)
  365. updatedTree.Delete(oldDoc)
  366. updatedTree.Set(newDoc, nil)
  367. _, newi := updatedTree.GetWithIndex(newDoc)
  368. changes = append(changes, DocumentChange{
  369. Kind: DocumentModified,
  370. Doc: newDoc,
  371. OldIndex: oldi,
  372. NewIndex: newi,
  373. })
  374. }
  375. assert(updatedTree.Len() == len(docMap))
  376. return updatedTree, changes
  377. }
  378. type byLess struct {
  379. s []*DocumentSnapshot
  380. less func(a, b *DocumentSnapshot) bool
  381. }
  382. func (b byLess) Len() int { return len(b.s) }
  383. func (b byLess) Swap(i, j int) { b.s[i], b.s[j] = b.s[j], b.s[i] }
  384. func (b byLess) Less(i, j int) bool { return b.less(b.s[i], b.s[j]) }
  385. func hasWatchTargetID(ids []int32) bool {
  386. for _, id := range ids {
  387. if id == watchTargetID {
  388. return true
  389. }
  390. }
  391. return false
  392. }
  393. func (s *watchStream) logf(format string, args ...interface{}) {
  394. if LogWatchStreams {
  395. log.Printf(format, args...)
  396. }
  397. }
  398. // Close the stream. From this point on, calls to nextSnapshot will return
  399. // io.EOF, or the error from CloseSend.
  400. func (s *watchStream) stop() {
  401. err := s.close()
  402. if s.err != nil { // don't change existing error
  403. return
  404. }
  405. if err != nil {
  406. s.err = err
  407. }
  408. s.err = io.EOF // normal shutdown
  409. }
  410. func (s *watchStream) close() error {
  411. if s.lc == nil {
  412. return nil
  413. }
  414. return s.lc.CloseSend()
  415. }
  416. // recv receives the next message from the stream. It also handles opening the stream
  417. // initially, and reopening it on non-permanent errors.
  418. // recv doesn't have to be goroutine-safe.
  419. func (s *watchStream) recv() (*pb.ListenResponse, error) {
  420. var err error
  421. for {
  422. if s.lc == nil {
  423. s.lc, err = s.open()
  424. if err != nil {
  425. // Do not retry if open fails.
  426. return nil, err
  427. }
  428. }
  429. res, err := s.lc.Recv()
  430. if err == nil || isPermanentWatchError(err) {
  431. return res, err
  432. }
  433. // Non-permanent error. Sleep and retry.
  434. s.changeMap = map[string]*DocumentSnapshot{} // clear changeMap
  435. dur := s.backoff.Pause()
  436. // If we're out of quota, wait a long time before retrying.
  437. if status.Code(err) == codes.ResourceExhausted {
  438. dur = s.backoff.Max
  439. }
  440. if err := sleep(s.ctx, dur); err != nil {
  441. return nil, err
  442. }
  443. s.lc = nil
  444. }
  445. }
  446. func (s *watchStream) open() (pb.Firestore_ListenClient, error) {
  447. dbPath := s.c.path()
  448. lc, err := s.c.c.Listen(withResourceHeader(s.ctx, dbPath))
  449. if err == nil {
  450. err = lc.Send(&pb.ListenRequest{
  451. Database: dbPath,
  452. TargetChange: &pb.ListenRequest_AddTarget{AddTarget: s.target},
  453. })
  454. }
  455. if err != nil {
  456. return nil, err
  457. }
  458. return lc, nil
  459. }
  460. func isPermanentWatchError(err error) bool {
  461. if err == io.EOF {
  462. // Retry on normal end-of-stream.
  463. return false
  464. }
  465. switch status.Code(err) {
  466. case codes.Unknown, codes.DeadlineExceeded, codes.ResourceExhausted,
  467. codes.Internal, codes.Unavailable, codes.Unauthenticated:
  468. return false
  469. default:
  470. return true
  471. }
  472. }