watch.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. // Copyright 2016 The etcd Authors
  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 clientv3
  15. import (
  16. "fmt"
  17. "sync"
  18. "time"
  19. v3rpc "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  20. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  21. mvccpb "github.com/coreos/etcd/mvcc/mvccpb"
  22. "golang.org/x/net/context"
  23. "google.golang.org/grpc"
  24. )
  25. const (
  26. EventTypeDelete = mvccpb.DELETE
  27. EventTypePut = mvccpb.PUT
  28. closeSendErrTimeout = 250 * time.Millisecond
  29. )
  30. type Event mvccpb.Event
  31. type WatchChan <-chan WatchResponse
  32. type Watcher interface {
  33. // Watch watches on a key or prefix. The watched events will be returned
  34. // through the returned channel.
  35. // If the watch is slow or the required rev is compacted, the watch request
  36. // might be canceled from the server-side and the chan will be closed.
  37. // 'opts' can be: 'WithRev' and/or 'WithPrefix'.
  38. Watch(ctx context.Context, key string, opts ...OpOption) WatchChan
  39. // Close closes the watcher and cancels all watch requests.
  40. Close() error
  41. }
  42. type WatchResponse struct {
  43. Header pb.ResponseHeader
  44. Events []*Event
  45. // CompactRevision is the minimum revision the watcher may receive.
  46. CompactRevision int64
  47. // Canceled is used to indicate watch failure.
  48. // If the watch failed and the stream was about to close, before the channel is closed,
  49. // the channel sends a final response that has Canceled set to true with a non-nil Err().
  50. Canceled bool
  51. // Created is used to indicate the creation of the watcher.
  52. Created bool
  53. closeErr error
  54. }
  55. // IsCreate returns true if the event tells that the key is newly created.
  56. func (e *Event) IsCreate() bool {
  57. return e.Type == EventTypePut && e.Kv.CreateRevision == e.Kv.ModRevision
  58. }
  59. // IsModify returns true if the event tells that a new value is put on existing key.
  60. func (e *Event) IsModify() bool {
  61. return e.Type == EventTypePut && e.Kv.CreateRevision != e.Kv.ModRevision
  62. }
  63. // Err is the error value if this WatchResponse holds an error.
  64. func (wr *WatchResponse) Err() error {
  65. switch {
  66. case wr.closeErr != nil:
  67. return v3rpc.Error(wr.closeErr)
  68. case wr.CompactRevision != 0:
  69. return v3rpc.ErrCompacted
  70. case wr.Canceled:
  71. return v3rpc.ErrFutureRev
  72. }
  73. return nil
  74. }
  75. // IsProgressNotify returns true if the WatchResponse is progress notification.
  76. func (wr *WatchResponse) IsProgressNotify() bool {
  77. return len(wr.Events) == 0 && !wr.Canceled && !wr.Created
  78. }
  79. // watcher implements the Watcher interface
  80. type watcher struct {
  81. remote pb.WatchClient
  82. // mu protects the grpc streams map
  83. mu sync.RWMutex
  84. // streams holds all the active grpc streams keyed by ctx value.
  85. streams map[string]*watchGrpcStream
  86. }
  87. type watchGrpcStream struct {
  88. owner *watcher
  89. remote pb.WatchClient
  90. // ctx controls internal remote.Watch requests
  91. ctx context.Context
  92. // ctxKey is the key used when looking up this stream's context
  93. ctxKey string
  94. cancel context.CancelFunc
  95. // mu protects the streams map
  96. mu sync.RWMutex
  97. // streams holds all active watchers
  98. streams map[int64]*watcherStream
  99. // reqc sends a watch request from Watch() to the main goroutine
  100. reqc chan *watchRequest
  101. // respc receives data from the watch client
  102. respc chan *pb.WatchResponse
  103. // stopc is sent to the main goroutine to stop all processing
  104. stopc chan struct{}
  105. // donec closes to broadcast shutdown
  106. donec chan struct{}
  107. // errc transmits errors from grpc Recv to the watch stream reconn logic
  108. errc chan error
  109. // the error that closed the watch stream
  110. closeErr error
  111. }
  112. // watchRequest is issued by the subscriber to start a new watcher
  113. type watchRequest struct {
  114. ctx context.Context
  115. key string
  116. end string
  117. rev int64
  118. // send created notification event if this field is true
  119. createdNotify bool
  120. // progressNotify is for progress updates
  121. progressNotify bool
  122. // filters is the list of events to filter out
  123. filters []pb.WatchCreateRequest_FilterType
  124. // get the previous key-value pair before the event happens
  125. prevKV bool
  126. // retc receives a chan WatchResponse once the watcher is established
  127. retc chan chan WatchResponse
  128. }
  129. // watcherStream represents a registered watcher
  130. type watcherStream struct {
  131. // initReq is the request that initiated this request
  132. initReq watchRequest
  133. // outc publishes watch responses to subscriber
  134. outc chan<- WatchResponse
  135. // recvc buffers watch responses before publishing
  136. recvc chan *WatchResponse
  137. id int64
  138. // lastRev is revision last successfully sent over outc
  139. lastRev int64
  140. // resumec indicates the stream must recover at a given revision
  141. resumec chan int64
  142. }
  143. func NewWatcher(c *Client) Watcher {
  144. return NewWatchFromWatchClient(pb.NewWatchClient(c.conn))
  145. }
  146. func NewWatchFromWatchClient(wc pb.WatchClient) Watcher {
  147. return &watcher{
  148. remote: wc,
  149. streams: make(map[string]*watchGrpcStream),
  150. }
  151. }
  152. // never closes
  153. var valCtxCh = make(chan struct{})
  154. var zeroTime = time.Unix(0, 0)
  155. // ctx with only the values; never Done
  156. type valCtx struct{ context.Context }
  157. func (vc *valCtx) Deadline() (time.Time, bool) { return zeroTime, false }
  158. func (vc *valCtx) Done() <-chan struct{} { return valCtxCh }
  159. func (vc *valCtx) Err() error { return nil }
  160. func (w *watcher) newWatcherGrpcStream(inctx context.Context) *watchGrpcStream {
  161. ctx, cancel := context.WithCancel(&valCtx{inctx})
  162. wgs := &watchGrpcStream{
  163. owner: w,
  164. remote: w.remote,
  165. ctx: ctx,
  166. ctxKey: fmt.Sprintf("%v", inctx),
  167. cancel: cancel,
  168. streams: make(map[int64]*watcherStream),
  169. respc: make(chan *pb.WatchResponse),
  170. reqc: make(chan *watchRequest),
  171. stopc: make(chan struct{}),
  172. donec: make(chan struct{}),
  173. errc: make(chan error, 1),
  174. }
  175. go wgs.run()
  176. return wgs
  177. }
  178. // Watch posts a watch request to run() and waits for a new watcher channel
  179. func (w *watcher) Watch(ctx context.Context, key string, opts ...OpOption) WatchChan {
  180. ow := opWatch(key, opts...)
  181. retc := make(chan chan WatchResponse, 1)
  182. var filters []pb.WatchCreateRequest_FilterType
  183. if ow.filterPut {
  184. filters = append(filters, pb.WatchCreateRequest_NOPUT)
  185. }
  186. if ow.filterDelete {
  187. filters = append(filters, pb.WatchCreateRequest_NODELETE)
  188. }
  189. wr := &watchRequest{
  190. ctx: ctx,
  191. createdNotify: ow.createdNotify,
  192. key: string(ow.key),
  193. end: string(ow.end),
  194. rev: ow.rev,
  195. progressNotify: ow.progressNotify,
  196. filters: filters,
  197. prevKV: ow.prevKV,
  198. retc: retc,
  199. }
  200. ok := false
  201. ctxKey := fmt.Sprintf("%v", ctx)
  202. // find or allocate appropriate grpc watch stream
  203. w.mu.Lock()
  204. if w.streams == nil {
  205. // closed
  206. w.mu.Unlock()
  207. ch := make(chan WatchResponse)
  208. close(ch)
  209. return ch
  210. }
  211. wgs := w.streams[ctxKey]
  212. if wgs == nil {
  213. wgs = w.newWatcherGrpcStream(ctx)
  214. w.streams[ctxKey] = wgs
  215. }
  216. donec := wgs.donec
  217. reqc := wgs.reqc
  218. w.mu.Unlock()
  219. // couldn't create channel; return closed channel
  220. closeCh := make(chan WatchResponse, 1)
  221. // submit request
  222. select {
  223. case reqc <- wr:
  224. ok = true
  225. case <-wr.ctx.Done():
  226. wgs.stopIfEmpty()
  227. case <-donec:
  228. if wgs.closeErr != nil {
  229. closeCh <- WatchResponse{closeErr: wgs.closeErr}
  230. break
  231. }
  232. // retry; may have dropped stream from no ctxs
  233. return w.Watch(ctx, key, opts...)
  234. }
  235. // receive channel
  236. if ok {
  237. select {
  238. case ret := <-retc:
  239. return ret
  240. case <-ctx.Done():
  241. case <-donec:
  242. if wgs.closeErr != nil {
  243. closeCh <- WatchResponse{closeErr: wgs.closeErr}
  244. break
  245. }
  246. // retry; may have dropped stream from no ctxs
  247. return w.Watch(ctx, key, opts...)
  248. }
  249. }
  250. close(closeCh)
  251. return closeCh
  252. }
  253. func (w *watcher) Close() (err error) {
  254. w.mu.Lock()
  255. streams := w.streams
  256. w.streams = nil
  257. w.mu.Unlock()
  258. for _, wgs := range streams {
  259. if werr := wgs.Close(); werr != nil {
  260. err = werr
  261. }
  262. }
  263. return err
  264. }
  265. func (w *watchGrpcStream) Close() (err error) {
  266. w.mu.Lock()
  267. if w.stopc != nil {
  268. close(w.stopc)
  269. w.stopc = nil
  270. }
  271. w.mu.Unlock()
  272. <-w.donec
  273. select {
  274. case err = <-w.errc:
  275. default:
  276. }
  277. return toErr(w.ctx, err)
  278. }
  279. func (w *watchGrpcStream) addStream(resp *pb.WatchResponse, pendingReq *watchRequest) {
  280. if pendingReq == nil {
  281. // no pending request; ignore
  282. return
  283. }
  284. if resp.Canceled || resp.CompactRevision != 0 {
  285. // a cancel at id creation time means the start revision has
  286. // been compacted out of the store
  287. ret := make(chan WatchResponse, 1)
  288. ret <- WatchResponse{
  289. Header: *resp.Header,
  290. CompactRevision: resp.CompactRevision,
  291. Canceled: true}
  292. close(ret)
  293. pendingReq.retc <- ret
  294. return
  295. }
  296. ret := make(chan WatchResponse)
  297. if resp.WatchId == -1 {
  298. // failed; no channel
  299. close(ret)
  300. pendingReq.retc <- ret
  301. return
  302. }
  303. ws := &watcherStream{
  304. initReq: *pendingReq,
  305. id: resp.WatchId,
  306. outc: ret,
  307. // buffered so unlikely to block on sending while holding mu
  308. recvc: make(chan *WatchResponse, 4),
  309. resumec: make(chan int64),
  310. }
  311. if pendingReq.rev == 0 {
  312. // note the header revision so that a put following a current watcher
  313. // disconnect will arrive on the watcher channel after reconnect
  314. ws.initReq.rev = resp.Header.Revision
  315. }
  316. w.mu.Lock()
  317. w.streams[ws.id] = ws
  318. w.mu.Unlock()
  319. // pass back the subscriber channel for the watcher
  320. pendingReq.retc <- ret
  321. // send messages to subscriber
  322. go w.serveStream(ws)
  323. }
  324. // closeStream closes the watcher resources and removes it
  325. func (w *watchGrpcStream) closeStream(ws *watcherStream) {
  326. w.mu.Lock()
  327. // cancels request stream; subscriber receives nil channel
  328. close(ws.initReq.retc)
  329. // close subscriber's channel
  330. close(ws.outc)
  331. delete(w.streams, ws.id)
  332. w.mu.Unlock()
  333. }
  334. // run is the root of the goroutines for managing a watcher client
  335. func (w *watchGrpcStream) run() {
  336. var wc pb.Watch_WatchClient
  337. var closeErr error
  338. defer func() {
  339. w.owner.mu.Lock()
  340. w.closeErr = closeErr
  341. if w.owner.streams != nil {
  342. delete(w.owner.streams, w.ctxKey)
  343. }
  344. close(w.donec)
  345. w.owner.mu.Unlock()
  346. w.cancel()
  347. }()
  348. // already stopped?
  349. w.mu.RLock()
  350. stopc := w.stopc
  351. w.mu.RUnlock()
  352. if stopc == nil {
  353. return
  354. }
  355. // start a stream with the etcd grpc server
  356. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  357. return
  358. }
  359. var pendingReq, failedReq *watchRequest
  360. curReqC := w.reqc
  361. cancelSet := make(map[int64]struct{})
  362. for {
  363. select {
  364. // Watch() requested
  365. case pendingReq = <-curReqC:
  366. // no more watch requests until there's a response
  367. curReqC = nil
  368. if err := wc.Send(pendingReq.toPB()); err == nil {
  369. // pendingReq now waits on w.respc
  370. break
  371. }
  372. failedReq = pendingReq
  373. // New events from the watch client
  374. case pbresp := <-w.respc:
  375. switch {
  376. case pbresp.Created:
  377. // response to pending req, try to add
  378. w.addStream(pbresp, pendingReq)
  379. pendingReq = nil
  380. curReqC = w.reqc
  381. w.dispatchEvent(pbresp)
  382. case pbresp.Canceled:
  383. delete(cancelSet, pbresp.WatchId)
  384. // shutdown serveStream, if any
  385. w.mu.Lock()
  386. if ws, ok := w.streams[pbresp.WatchId]; ok {
  387. close(ws.recvc)
  388. delete(w.streams, ws.id)
  389. }
  390. numStreams := len(w.streams)
  391. w.mu.Unlock()
  392. if numStreams == 0 {
  393. // don't leak watcher streams
  394. return
  395. }
  396. default:
  397. // dispatch to appropriate watch stream
  398. if ok := w.dispatchEvent(pbresp); ok {
  399. break
  400. }
  401. // watch response on unexpected watch id; cancel id
  402. if _, ok := cancelSet[pbresp.WatchId]; ok {
  403. break
  404. }
  405. cancelSet[pbresp.WatchId] = struct{}{}
  406. cr := &pb.WatchRequest_CancelRequest{
  407. CancelRequest: &pb.WatchCancelRequest{
  408. WatchId: pbresp.WatchId,
  409. },
  410. }
  411. req := &pb.WatchRequest{RequestUnion: cr}
  412. wc.Send(req)
  413. }
  414. // watch client failed to recv; spawn another if possible
  415. // TODO report watch client errors from errc?
  416. case err := <-w.errc:
  417. if isHaltErr(w.ctx, err) || toErr(w.ctx, err) == v3rpc.ErrNoLeader {
  418. closeErr = err
  419. return
  420. }
  421. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  422. return
  423. }
  424. curReqC = w.reqc
  425. if pendingReq != nil {
  426. failedReq = pendingReq
  427. }
  428. cancelSet = make(map[int64]struct{})
  429. case <-stopc:
  430. return
  431. }
  432. // send failed; queue for retry
  433. if failedReq != nil {
  434. go func(wr *watchRequest) {
  435. select {
  436. case w.reqc <- wr:
  437. case <-wr.ctx.Done():
  438. case <-w.donec:
  439. }
  440. }(pendingReq)
  441. failedReq = nil
  442. pendingReq = nil
  443. }
  444. }
  445. }
  446. // dispatchEvent sends a WatchResponse to the appropriate watcher stream
  447. func (w *watchGrpcStream) dispatchEvent(pbresp *pb.WatchResponse) bool {
  448. w.mu.RLock()
  449. defer w.mu.RUnlock()
  450. ws, ok := w.streams[pbresp.WatchId]
  451. if !ok {
  452. return false
  453. }
  454. events := make([]*Event, len(pbresp.Events))
  455. for i, ev := range pbresp.Events {
  456. events[i] = (*Event)(ev)
  457. }
  458. wr := &WatchResponse{
  459. Header: *pbresp.Header,
  460. Events: events,
  461. CompactRevision: pbresp.CompactRevision,
  462. Created: pbresp.Created,
  463. Canceled: pbresp.Canceled,
  464. }
  465. ws.recvc <- wr
  466. return true
  467. }
  468. // serveWatchClient forwards messages from the grpc stream to run()
  469. func (w *watchGrpcStream) serveWatchClient(wc pb.Watch_WatchClient) {
  470. for {
  471. resp, err := wc.Recv()
  472. if err != nil {
  473. select {
  474. case w.errc <- err:
  475. case <-w.donec:
  476. }
  477. return
  478. }
  479. select {
  480. case w.respc <- resp:
  481. case <-w.donec:
  482. return
  483. }
  484. }
  485. }
  486. // serveStream forwards watch responses from run() to the subscriber
  487. func (w *watchGrpcStream) serveStream(ws *watcherStream) {
  488. var closeErr error
  489. emptyWr := &WatchResponse{}
  490. wrs := []*WatchResponse{}
  491. resuming := false
  492. closing := false
  493. for !closing {
  494. curWr := emptyWr
  495. outc := ws.outc
  496. // ignore created event if create notify is not requested or
  497. // we already sent the initial created event (when we are on the resume path).
  498. if len(wrs) > 0 && wrs[0].Created &&
  499. (!ws.initReq.createdNotify || ws.lastRev != 0) {
  500. wrs = wrs[1:]
  501. }
  502. if len(wrs) > 0 {
  503. curWr = wrs[0]
  504. } else {
  505. outc = nil
  506. }
  507. select {
  508. case outc <- *curWr:
  509. if wrs[0].Err() != nil {
  510. closing = true
  511. break
  512. }
  513. var newRev int64
  514. if len(wrs[0].Events) > 0 {
  515. newRev = wrs[0].Events[len(wrs[0].Events)-1].Kv.ModRevision
  516. } else {
  517. newRev = wrs[0].Header.Revision
  518. }
  519. if newRev != ws.lastRev {
  520. ws.lastRev = newRev
  521. }
  522. wrs[0] = nil
  523. wrs = wrs[1:]
  524. case wr, ok := <-ws.recvc:
  525. if !ok {
  526. // shutdown from closeStream
  527. return
  528. }
  529. // resume up to last seen event if disconnected
  530. if resuming && wr.Err() == nil {
  531. resuming = false
  532. // trim events already seen
  533. for i := 0; i < len(wr.Events); i++ {
  534. if wr.Events[i].Kv.ModRevision > ws.lastRev {
  535. wr.Events = wr.Events[i:]
  536. break
  537. }
  538. }
  539. // only forward new events
  540. if wr.Events[0].Kv.ModRevision == ws.lastRev {
  541. break
  542. }
  543. }
  544. resuming = false
  545. // TODO don't keep buffering if subscriber stops reading
  546. wrs = append(wrs, wr)
  547. case resumeRev := <-ws.resumec:
  548. wrs = nil
  549. resuming = true
  550. if resumeRev == -1 {
  551. // pause serving stream while resume gets set up
  552. break
  553. }
  554. if resumeRev != ws.lastRev {
  555. panic("unexpected resume revision")
  556. }
  557. case <-w.donec:
  558. closing = true
  559. closeErr = w.closeErr
  560. case <-ws.initReq.ctx.Done():
  561. closing = true
  562. }
  563. }
  564. // try to send off close error
  565. if closeErr != nil {
  566. select {
  567. case ws.outc <- WatchResponse{closeErr: w.closeErr}:
  568. case <-w.donec:
  569. case <-time.After(closeSendErrTimeout):
  570. }
  571. }
  572. w.closeStream(ws)
  573. w.stopIfEmpty()
  574. // lazily send cancel message if events on missing id
  575. }
  576. func (wgs *watchGrpcStream) stopIfEmpty() {
  577. wgs.mu.Lock()
  578. if len(wgs.streams) == 0 && wgs.stopc != nil {
  579. close(wgs.stopc)
  580. wgs.stopc = nil
  581. }
  582. wgs.mu.Unlock()
  583. }
  584. func (w *watchGrpcStream) newWatchClient() (pb.Watch_WatchClient, error) {
  585. ws, rerr := w.resume()
  586. if rerr != nil {
  587. return nil, rerr
  588. }
  589. go w.serveWatchClient(ws)
  590. return ws, nil
  591. }
  592. // resume creates a new WatchClient with all current watchers reestablished
  593. func (w *watchGrpcStream) resume() (ws pb.Watch_WatchClient, err error) {
  594. for {
  595. if ws, err = w.openWatchClient(); err != nil {
  596. break
  597. } else if err = w.resumeWatchers(ws); err == nil {
  598. break
  599. }
  600. }
  601. return ws, v3rpc.Error(err)
  602. }
  603. // openWatchClient retries opening a watchclient until retryConnection fails
  604. func (w *watchGrpcStream) openWatchClient() (ws pb.Watch_WatchClient, err error) {
  605. for {
  606. w.mu.Lock()
  607. stopc := w.stopc
  608. w.mu.Unlock()
  609. if stopc == nil {
  610. if err == nil {
  611. err = context.Canceled
  612. }
  613. return nil, err
  614. }
  615. if ws, err = w.remote.Watch(w.ctx, grpc.FailFast(false)); ws != nil && err == nil {
  616. break
  617. }
  618. if isHaltErr(w.ctx, err) {
  619. return nil, v3rpc.Error(err)
  620. }
  621. }
  622. return ws, nil
  623. }
  624. // resumeWatchers rebuilds every registered watcher on a new client
  625. func (w *watchGrpcStream) resumeWatchers(wc pb.Watch_WatchClient) error {
  626. w.mu.RLock()
  627. streams := make([]*watcherStream, 0, len(w.streams))
  628. for _, ws := range w.streams {
  629. streams = append(streams, ws)
  630. }
  631. w.mu.RUnlock()
  632. for _, ws := range streams {
  633. // drain recvc so no old WatchResponses (e.g., Created messages)
  634. // are processed while resuming
  635. ws.drain()
  636. // pause serveStream
  637. ws.resumec <- -1
  638. // reconstruct watcher from initial request
  639. if ws.lastRev != 0 {
  640. ws.initReq.rev = ws.lastRev
  641. }
  642. if err := wc.Send(ws.initReq.toPB()); err != nil {
  643. return err
  644. }
  645. // wait for request ack
  646. resp, err := wc.Recv()
  647. if err != nil {
  648. return err
  649. } else if len(resp.Events) != 0 || !resp.Created {
  650. return fmt.Errorf("watcher: unexpected response (%+v)", resp)
  651. }
  652. // id may be different since new remote watcher; update map
  653. w.mu.Lock()
  654. delete(w.streams, ws.id)
  655. ws.id = resp.WatchId
  656. w.streams[ws.id] = ws
  657. w.mu.Unlock()
  658. // unpause serveStream
  659. ws.resumec <- ws.lastRev
  660. }
  661. return nil
  662. }
  663. // drain removes all buffered WatchResponses from the stream's receive channel.
  664. func (ws *watcherStream) drain() {
  665. for {
  666. select {
  667. case <-ws.recvc:
  668. default:
  669. return
  670. }
  671. }
  672. }
  673. // toPB converts an internal watch request structure to its protobuf messagefunc (wr *watchRequest)
  674. func (wr *watchRequest) toPB() *pb.WatchRequest {
  675. req := &pb.WatchCreateRequest{
  676. StartRevision: wr.rev,
  677. Key: []byte(wr.key),
  678. RangeEnd: []byte(wr.end),
  679. ProgressNotify: wr.progressNotify,
  680. Filters: wr.filters,
  681. PrevKv: wr.prevKV,
  682. }
  683. cr := &pb.WatchRequest_CreateRequest{CreateRequest: req}
  684. return &pb.WatchRequest{RequestUnion: cr}
  685. }