v3_watch_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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 integration
  15. import (
  16. "bytes"
  17. "context"
  18. "fmt"
  19. "reflect"
  20. "sort"
  21. "sync"
  22. "testing"
  23. "time"
  24. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. "github.com/coreos/etcd/mvcc/mvccpb"
  27. "github.com/coreos/etcd/pkg/testutil"
  28. )
  29. // TestV3WatchFromCurrentRevision tests Watch APIs from current revision.
  30. func TestV3WatchFromCurrentRevision(t *testing.T) {
  31. defer testutil.AfterTest(t)
  32. tests := []struct {
  33. putKeys []string
  34. watchRequest *pb.WatchRequest
  35. wresps []*pb.WatchResponse
  36. }{
  37. // watch the key, matching
  38. {
  39. []string{"foo"},
  40. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  41. CreateRequest: &pb.WatchCreateRequest{
  42. Key: []byte("foo")}}},
  43. []*pb.WatchResponse{
  44. {
  45. Header: &pb.ResponseHeader{Revision: 2},
  46. Created: false,
  47. Events: []*mvccpb.Event{
  48. {
  49. Type: mvccpb.PUT,
  50. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  51. },
  52. },
  53. },
  54. },
  55. },
  56. // watch the key, non-matching
  57. {
  58. []string{"foo"},
  59. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  60. CreateRequest: &pb.WatchCreateRequest{
  61. Key: []byte("helloworld")}}},
  62. []*pb.WatchResponse{},
  63. },
  64. // watch the prefix, matching
  65. {
  66. []string{"fooLong"},
  67. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  68. CreateRequest: &pb.WatchCreateRequest{
  69. Key: []byte("foo"),
  70. RangeEnd: []byte("fop")}}},
  71. []*pb.WatchResponse{
  72. {
  73. Header: &pb.ResponseHeader{Revision: 2},
  74. Created: false,
  75. Events: []*mvccpb.Event{
  76. {
  77. Type: mvccpb.PUT,
  78. Kv: &mvccpb.KeyValue{Key: []byte("fooLong"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  79. },
  80. },
  81. },
  82. },
  83. },
  84. // watch the prefix, non-matching
  85. {
  86. []string{"foo"},
  87. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  88. CreateRequest: &pb.WatchCreateRequest{
  89. Key: []byte("helloworld"),
  90. RangeEnd: []byte("helloworle")}}},
  91. []*pb.WatchResponse{},
  92. },
  93. // watch full range, matching
  94. {
  95. []string{"fooLong"},
  96. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  97. CreateRequest: &pb.WatchCreateRequest{
  98. Key: []byte(""),
  99. RangeEnd: []byte("\x00")}}},
  100. []*pb.WatchResponse{
  101. {
  102. Header: &pb.ResponseHeader{Revision: 2},
  103. Created: false,
  104. Events: []*mvccpb.Event{
  105. {
  106. Type: mvccpb.PUT,
  107. Kv: &mvccpb.KeyValue{Key: []byte("fooLong"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  108. },
  109. },
  110. },
  111. },
  112. },
  113. // multiple puts, one watcher with matching key
  114. {
  115. []string{"foo", "foo", "foo"},
  116. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  117. CreateRequest: &pb.WatchCreateRequest{
  118. Key: []byte("foo")}}},
  119. []*pb.WatchResponse{
  120. {
  121. Header: &pb.ResponseHeader{Revision: 2},
  122. Created: false,
  123. Events: []*mvccpb.Event{
  124. {
  125. Type: mvccpb.PUT,
  126. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  127. },
  128. },
  129. },
  130. {
  131. Header: &pb.ResponseHeader{Revision: 3},
  132. Created: false,
  133. Events: []*mvccpb.Event{
  134. {
  135. Type: mvccpb.PUT,
  136. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  137. },
  138. },
  139. },
  140. {
  141. Header: &pb.ResponseHeader{Revision: 4},
  142. Created: false,
  143. Events: []*mvccpb.Event{
  144. {
  145. Type: mvccpb.PUT,
  146. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  147. },
  148. },
  149. },
  150. },
  151. },
  152. // multiple puts, one watcher with matching prefix
  153. {
  154. []string{"foo", "foo", "foo"},
  155. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  156. CreateRequest: &pb.WatchCreateRequest{
  157. Key: []byte("foo"),
  158. RangeEnd: []byte("fop")}}},
  159. []*pb.WatchResponse{
  160. {
  161. Header: &pb.ResponseHeader{Revision: 2},
  162. Created: false,
  163. Events: []*mvccpb.Event{
  164. {
  165. Type: mvccpb.PUT,
  166. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  167. },
  168. },
  169. },
  170. {
  171. Header: &pb.ResponseHeader{Revision: 3},
  172. Created: false,
  173. Events: []*mvccpb.Event{
  174. {
  175. Type: mvccpb.PUT,
  176. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  177. },
  178. },
  179. },
  180. {
  181. Header: &pb.ResponseHeader{Revision: 4},
  182. Created: false,
  183. Events: []*mvccpb.Event{
  184. {
  185. Type: mvccpb.PUT,
  186. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  187. },
  188. },
  189. },
  190. },
  191. },
  192. }
  193. for i, tt := range tests {
  194. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  195. wAPI := toGRPC(clus.RandClient()).Watch
  196. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  197. defer cancel()
  198. wStream, err := wAPI.Watch(ctx)
  199. if err != nil {
  200. t.Fatalf("#%d: wAPI.Watch error: %v", i, err)
  201. }
  202. err = wStream.Send(tt.watchRequest)
  203. if err != nil {
  204. t.Fatalf("#%d: wStream.Send error: %v", i, err)
  205. }
  206. // ensure watcher request created a new watcher
  207. cresp, err := wStream.Recv()
  208. if err != nil {
  209. t.Errorf("#%d: wStream.Recv error: %v", i, err)
  210. clus.Terminate(t)
  211. continue
  212. }
  213. if !cresp.Created {
  214. t.Errorf("#%d: did not create watchid, got %+v", i, cresp)
  215. clus.Terminate(t)
  216. continue
  217. }
  218. if cresp.Canceled {
  219. t.Errorf("#%d: canceled watcher on create %+v", i, cresp)
  220. clus.Terminate(t)
  221. continue
  222. }
  223. createdWatchId := cresp.WatchId
  224. if cresp.Header == nil || cresp.Header.Revision != 1 {
  225. t.Errorf("#%d: header revision got +%v, wanted revison 1", i, cresp)
  226. clus.Terminate(t)
  227. continue
  228. }
  229. // asynchronously create keys
  230. go func() {
  231. for _, k := range tt.putKeys {
  232. kvc := toGRPC(clus.RandClient()).KV
  233. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  234. if _, err := kvc.Put(context.TODO(), req); err != nil {
  235. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  236. }
  237. }
  238. }()
  239. // check stream results
  240. for j, wresp := range tt.wresps {
  241. resp, err := wStream.Recv()
  242. if err != nil {
  243. t.Errorf("#%d.%d: wStream.Recv error: %v", i, j, err)
  244. }
  245. if resp.Header == nil {
  246. t.Fatalf("#%d.%d: unexpected nil resp.Header", i, j)
  247. }
  248. if resp.Header.Revision != wresp.Header.Revision {
  249. t.Errorf("#%d.%d: resp.Header.Revision got = %d, want = %d", i, j, resp.Header.Revision, wresp.Header.Revision)
  250. }
  251. if wresp.Created != resp.Created {
  252. t.Errorf("#%d.%d: resp.Created got = %v, want = %v", i, j, resp.Created, wresp.Created)
  253. }
  254. if resp.WatchId != createdWatchId {
  255. t.Errorf("#%d.%d: resp.WatchId got = %d, want = %d", i, j, resp.WatchId, createdWatchId)
  256. }
  257. if !reflect.DeepEqual(resp.Events, wresp.Events) {
  258. t.Errorf("#%d.%d: resp.Events got = %+v, want = %+v", i, j, resp.Events, wresp.Events)
  259. }
  260. }
  261. rok, nr := waitResponse(wStream, 1*time.Second)
  262. if !rok {
  263. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  264. }
  265. // can't defer because tcp ports will be in use
  266. clus.Terminate(t)
  267. }
  268. }
  269. // TestV3WatchFutureRevision tests Watch APIs from a future revision.
  270. func TestV3WatchFutureRevision(t *testing.T) {
  271. defer testutil.AfterTest(t)
  272. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  273. defer clus.Terminate(t)
  274. wAPI := toGRPC(clus.RandClient()).Watch
  275. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  276. defer cancel()
  277. wStream, err := wAPI.Watch(ctx)
  278. if err != nil {
  279. t.Fatalf("wAPI.Watch error: %v", err)
  280. }
  281. wkey := []byte("foo")
  282. wrev := int64(10)
  283. req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  284. CreateRequest: &pb.WatchCreateRequest{Key: wkey, StartRevision: wrev}}}
  285. err = wStream.Send(req)
  286. if err != nil {
  287. t.Fatalf("wStream.Send error: %v", err)
  288. }
  289. // ensure watcher request created a new watcher
  290. cresp, err := wStream.Recv()
  291. if err != nil {
  292. t.Fatalf("wStream.Recv error: %v", err)
  293. }
  294. if !cresp.Created {
  295. t.Fatalf("create %v, want %v", cresp.Created, true)
  296. }
  297. kvc := toGRPC(clus.RandClient()).KV
  298. for {
  299. req := &pb.PutRequest{Key: wkey, Value: []byte("bar")}
  300. resp, rerr := kvc.Put(context.TODO(), req)
  301. if rerr != nil {
  302. t.Fatalf("couldn't put key (%v)", rerr)
  303. }
  304. if resp.Header.Revision == wrev {
  305. break
  306. }
  307. }
  308. // ensure watcher request created a new watcher
  309. cresp, err = wStream.Recv()
  310. if err != nil {
  311. t.Fatalf("wStream.Recv error: %v", err)
  312. }
  313. if cresp.Header.Revision != wrev {
  314. t.Fatalf("revision = %d, want %d", cresp.Header.Revision, wrev)
  315. }
  316. if len(cresp.Events) != 1 {
  317. t.Fatalf("failed to receive events")
  318. }
  319. if cresp.Events[0].Kv.ModRevision != wrev {
  320. t.Errorf("mod revision = %d, want %d", cresp.Events[0].Kv.ModRevision, wrev)
  321. }
  322. }
  323. // TestV3WatchWrongRange tests wrong range does not create watchers.
  324. func TestV3WatchWrongRange(t *testing.T) {
  325. defer testutil.AfterTest(t)
  326. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  327. defer clus.Terminate(t)
  328. wAPI := toGRPC(clus.RandClient()).Watch
  329. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  330. defer cancel()
  331. wStream, err := wAPI.Watch(ctx)
  332. if err != nil {
  333. t.Fatalf("wAPI.Watch error: %v", err)
  334. }
  335. tests := []struct {
  336. key []byte
  337. end []byte
  338. canceled bool
  339. }{
  340. {[]byte("a"), []byte("a"), true}, // wrong range end
  341. {[]byte("b"), []byte("a"), true}, // wrong range end
  342. {[]byte("foo"), []byte{0}, false}, // watch request with 'WithFromKey'
  343. }
  344. for i, tt := range tests {
  345. if err := wStream.Send(&pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  346. CreateRequest: &pb.WatchCreateRequest{Key: tt.key, RangeEnd: tt.end, StartRevision: 1}}}); err != nil {
  347. t.Fatalf("#%d: wStream.Send error: %v", i, err)
  348. }
  349. cresp, err := wStream.Recv()
  350. if err != nil {
  351. t.Fatalf("#%d: wStream.Recv error: %v", i, err)
  352. }
  353. if !cresp.Created {
  354. t.Fatalf("#%d: create %v, want %v", i, cresp.Created, true)
  355. }
  356. if cresp.Canceled != tt.canceled {
  357. t.Fatalf("#%d: canceled %v, want %v", i, tt.canceled, cresp.Canceled)
  358. }
  359. if tt.canceled && cresp.WatchId != -1 {
  360. t.Fatalf("#%d: canceled watch ID %d, want -1", i, cresp.WatchId)
  361. }
  362. }
  363. }
  364. // TestV3WatchCancelSynced tests Watch APIs cancellation from synced map.
  365. func TestV3WatchCancelSynced(t *testing.T) {
  366. defer testutil.AfterTest(t)
  367. testV3WatchCancel(t, 0)
  368. }
  369. // TestV3WatchCancelUnsynced tests Watch APIs cancellation from unsynced map.
  370. func TestV3WatchCancelUnsynced(t *testing.T) {
  371. defer testutil.AfterTest(t)
  372. testV3WatchCancel(t, 1)
  373. }
  374. func testV3WatchCancel(t *testing.T, startRev int64) {
  375. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  376. defer clus.Terminate(t)
  377. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  378. defer cancel()
  379. wStream, errW := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  380. if errW != nil {
  381. t.Fatalf("wAPI.Watch error: %v", errW)
  382. }
  383. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  384. CreateRequest: &pb.WatchCreateRequest{
  385. Key: []byte("foo"), StartRevision: startRev}}}
  386. if err := wStream.Send(wreq); err != nil {
  387. t.Fatalf("wStream.Send error: %v", err)
  388. }
  389. wresp, errR := wStream.Recv()
  390. if errR != nil {
  391. t.Errorf("wStream.Recv error: %v", errR)
  392. }
  393. if !wresp.Created {
  394. t.Errorf("wresp.Created got = %v, want = true", wresp.Created)
  395. }
  396. creq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CancelRequest{
  397. CancelRequest: &pb.WatchCancelRequest{
  398. WatchId: wresp.WatchId}}}
  399. if err := wStream.Send(creq); err != nil {
  400. t.Fatalf("wStream.Send error: %v", err)
  401. }
  402. cresp, err := wStream.Recv()
  403. if err != nil {
  404. t.Errorf("wStream.Recv error: %v", err)
  405. }
  406. if !cresp.Canceled {
  407. t.Errorf("cresp.Canceled got = %v, want = true", cresp.Canceled)
  408. }
  409. kvc := toGRPC(clus.RandClient()).KV
  410. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  411. t.Errorf("couldn't put key (%v)", err)
  412. }
  413. // watch got canceled, so this should block
  414. rok, nr := waitResponse(wStream, 1*time.Second)
  415. if !rok {
  416. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  417. }
  418. }
  419. // TestV3WatchCurrentPutOverlap ensures current watchers receive all events with
  420. // overlapping puts.
  421. func TestV3WatchCurrentPutOverlap(t *testing.T) {
  422. defer testutil.AfterTest(t)
  423. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  424. defer clus.Terminate(t)
  425. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  426. defer cancel()
  427. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  428. if wErr != nil {
  429. t.Fatalf("wAPI.Watch error: %v", wErr)
  430. }
  431. // last mod_revision that will be observed
  432. nrRevisions := 32
  433. // first revision already allocated as empty revision
  434. for i := 1; i < nrRevisions; i++ {
  435. go func() {
  436. kvc := toGRPC(clus.RandClient()).KV
  437. req := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  438. if _, err := kvc.Put(context.TODO(), req); err != nil {
  439. t.Fatalf("couldn't put key (%v)", err)
  440. }
  441. }()
  442. }
  443. // maps watcher to current expected revision
  444. progress := make(map[int64]int64)
  445. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  446. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), RangeEnd: []byte("fop")}}}
  447. if err := wStream.Send(wreq); err != nil {
  448. t.Fatalf("first watch request failed (%v)", err)
  449. }
  450. more := true
  451. progress[-1] = 0 // watcher creation pending
  452. for more {
  453. resp, err := wStream.Recv()
  454. if err != nil {
  455. t.Fatalf("wStream.Recv error: %v", err)
  456. }
  457. if resp.Created {
  458. // accept events > header revision
  459. progress[resp.WatchId] = resp.Header.Revision + 1
  460. if resp.Header.Revision == int64(nrRevisions) {
  461. // covered all revisions; create no more watchers
  462. progress[-1] = int64(nrRevisions) + 1
  463. } else if err := wStream.Send(wreq); err != nil {
  464. t.Fatalf("watch request failed (%v)", err)
  465. }
  466. } else if len(resp.Events) == 0 {
  467. t.Fatalf("got events %v, want non-empty", resp.Events)
  468. } else {
  469. wRev, ok := progress[resp.WatchId]
  470. if !ok {
  471. t.Fatalf("got %+v, but watch id shouldn't exist ", resp)
  472. }
  473. if resp.Events[0].Kv.ModRevision != wRev {
  474. t.Fatalf("got %+v, wanted first revision %d", resp, wRev)
  475. }
  476. lastRev := resp.Events[len(resp.Events)-1].Kv.ModRevision
  477. progress[resp.WatchId] = lastRev + 1
  478. }
  479. more = false
  480. for _, v := range progress {
  481. if v <= int64(nrRevisions) {
  482. more = true
  483. break
  484. }
  485. }
  486. }
  487. if rok, nr := waitResponse(wStream, time.Second); !rok {
  488. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  489. }
  490. }
  491. // TestV3WatchEmptyKey ensures synced watchers see empty key PUTs as PUT events
  492. func TestV3WatchEmptyKey(t *testing.T) {
  493. defer testutil.AfterTest(t)
  494. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  495. defer clus.Terminate(t)
  496. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  497. defer cancel()
  498. ws, werr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  499. if werr != nil {
  500. t.Fatal(werr)
  501. }
  502. req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  503. CreateRequest: &pb.WatchCreateRequest{
  504. Key: []byte("foo")}}}
  505. if err := ws.Send(req); err != nil {
  506. t.Fatal(err)
  507. }
  508. if _, err := ws.Recv(); err != nil {
  509. t.Fatal(err)
  510. }
  511. // put a key with empty value
  512. kvc := toGRPC(clus.RandClient()).KV
  513. preq := &pb.PutRequest{Key: []byte("foo")}
  514. if _, err := kvc.Put(context.TODO(), preq); err != nil {
  515. t.Fatal(err)
  516. }
  517. // check received PUT
  518. resp, rerr := ws.Recv()
  519. if rerr != nil {
  520. t.Fatal(rerr)
  521. }
  522. wevs := []*mvccpb.Event{
  523. {
  524. Type: mvccpb.PUT,
  525. Kv: &mvccpb.KeyValue{Key: []byte("foo"), CreateRevision: 2, ModRevision: 2, Version: 1},
  526. },
  527. }
  528. if !reflect.DeepEqual(resp.Events, wevs) {
  529. t.Fatalf("got %v, expected %v", resp.Events, wevs)
  530. }
  531. }
  532. func TestV3WatchMultipleWatchersSynced(t *testing.T) {
  533. defer testutil.AfterTest(t)
  534. testV3WatchMultipleWatchers(t, 0)
  535. }
  536. func TestV3WatchMultipleWatchersUnsynced(t *testing.T) {
  537. defer testutil.AfterTest(t)
  538. testV3WatchMultipleWatchers(t, 1)
  539. }
  540. // testV3WatchMultipleWatchers tests multiple watchers on the same key
  541. // and one watcher with matching prefix. It first puts the key
  542. // that matches all watchers, and another key that matches only
  543. // one watcher to test if it receives expected events.
  544. func testV3WatchMultipleWatchers(t *testing.T, startRev int64) {
  545. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  546. defer clus.Terminate(t)
  547. kvc := toGRPC(clus.RandClient()).KV
  548. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  549. defer cancel()
  550. wStream, errW := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  551. if errW != nil {
  552. t.Fatalf("wAPI.Watch error: %v", errW)
  553. }
  554. watchKeyN := 4
  555. for i := 0; i < watchKeyN+1; i++ {
  556. var wreq *pb.WatchRequest
  557. if i < watchKeyN {
  558. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  559. CreateRequest: &pb.WatchCreateRequest{
  560. Key: []byte("foo"), StartRevision: startRev}}}
  561. } else {
  562. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  563. CreateRequest: &pb.WatchCreateRequest{
  564. Key: []byte("fo"), RangeEnd: []byte("fp"), StartRevision: startRev}}}
  565. }
  566. if err := wStream.Send(wreq); err != nil {
  567. t.Fatalf("wStream.Send error: %v", err)
  568. }
  569. }
  570. ids := make(map[int64]struct{})
  571. for i := 0; i < watchKeyN+1; i++ {
  572. wresp, err := wStream.Recv()
  573. if err != nil {
  574. t.Fatalf("wStream.Recv error: %v", err)
  575. }
  576. if !wresp.Created {
  577. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  578. }
  579. ids[wresp.WatchId] = struct{}{}
  580. }
  581. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  582. t.Fatalf("couldn't put key (%v)", err)
  583. }
  584. for i := 0; i < watchKeyN+1; i++ {
  585. wresp, err := wStream.Recv()
  586. if err != nil {
  587. t.Fatalf("wStream.Recv error: %v", err)
  588. }
  589. if _, ok := ids[wresp.WatchId]; !ok {
  590. t.Errorf("watchId %d is not created!", wresp.WatchId)
  591. } else {
  592. delete(ids, wresp.WatchId)
  593. }
  594. if len(wresp.Events) == 0 {
  595. t.Errorf("#%d: no events received", i)
  596. }
  597. for _, ev := range wresp.Events {
  598. if string(ev.Kv.Key) != "foo" {
  599. t.Errorf("ev.Kv.Key got = %s, want = foo", ev.Kv.Key)
  600. }
  601. if string(ev.Kv.Value) != "bar" {
  602. t.Errorf("ev.Kv.Value got = %s, want = bar", ev.Kv.Value)
  603. }
  604. }
  605. }
  606. // now put one key that has only one matching watcher
  607. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("fo"), Value: []byte("bar")}); err != nil {
  608. t.Fatalf("couldn't put key (%v)", err)
  609. }
  610. wresp, err := wStream.Recv()
  611. if err != nil {
  612. t.Errorf("wStream.Recv error: %v", err)
  613. }
  614. if len(wresp.Events) != 1 {
  615. t.Fatalf("len(wresp.Events) got = %d, want = 1", len(wresp.Events))
  616. }
  617. if string(wresp.Events[0].Kv.Key) != "fo" {
  618. t.Errorf("wresp.Events[0].Kv.Key got = %s, want = fo", wresp.Events[0].Kv.Key)
  619. }
  620. // now Recv should block because there is no more events coming
  621. rok, nr := waitResponse(wStream, 1*time.Second)
  622. if !rok {
  623. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  624. }
  625. }
  626. func TestV3WatchMultipleEventsTxnSynced(t *testing.T) {
  627. defer testutil.AfterTest(t)
  628. testV3WatchMultipleEventsTxn(t, 0)
  629. }
  630. func TestV3WatchMultipleEventsTxnUnsynced(t *testing.T) {
  631. defer testutil.AfterTest(t)
  632. testV3WatchMultipleEventsTxn(t, 1)
  633. }
  634. // testV3WatchMultipleEventsTxn tests Watch APIs when it receives multiple events.
  635. func testV3WatchMultipleEventsTxn(t *testing.T, startRev int64) {
  636. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  637. defer clus.Terminate(t)
  638. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  639. defer cancel()
  640. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  641. if wErr != nil {
  642. t.Fatalf("wAPI.Watch error: %v", wErr)
  643. }
  644. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  645. CreateRequest: &pb.WatchCreateRequest{
  646. Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: startRev}}}
  647. if err := wStream.Send(wreq); err != nil {
  648. t.Fatalf("wStream.Send error: %v", err)
  649. }
  650. if resp, err := wStream.Recv(); err != nil || !resp.Created {
  651. t.Fatalf("create response failed: resp=%v, err=%v", resp, err)
  652. }
  653. kvc := toGRPC(clus.RandClient()).KV
  654. txn := pb.TxnRequest{}
  655. for i := 0; i < 3; i++ {
  656. ru := &pb.RequestOp{}
  657. ru.Request = &pb.RequestOp_RequestPut{
  658. RequestPut: &pb.PutRequest{
  659. Key: []byte(fmt.Sprintf("foo%d", i)), Value: []byte("bar")}}
  660. txn.Success = append(txn.Success, ru)
  661. }
  662. tresp, err := kvc.Txn(context.Background(), &txn)
  663. if err != nil {
  664. t.Fatalf("kvc.Txn error: %v", err)
  665. }
  666. if !tresp.Succeeded {
  667. t.Fatalf("kvc.Txn failed: %+v", tresp)
  668. }
  669. events := []*mvccpb.Event{}
  670. for len(events) < 3 {
  671. resp, err := wStream.Recv()
  672. if err != nil {
  673. t.Errorf("wStream.Recv error: %v", err)
  674. }
  675. events = append(events, resp.Events...)
  676. }
  677. sort.Sort(eventsSortByKey(events))
  678. wevents := []*mvccpb.Event{
  679. {
  680. Type: mvccpb.PUT,
  681. Kv: &mvccpb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  682. },
  683. {
  684. Type: mvccpb.PUT,
  685. Kv: &mvccpb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  686. },
  687. {
  688. Type: mvccpb.PUT,
  689. Kv: &mvccpb.KeyValue{Key: []byte("foo2"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  690. },
  691. }
  692. if !reflect.DeepEqual(events, wevents) {
  693. t.Errorf("events got = %+v, want = %+v", events, wevents)
  694. }
  695. rok, nr := waitResponse(wStream, 1*time.Second)
  696. if !rok {
  697. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  698. }
  699. }
  700. type eventsSortByKey []*mvccpb.Event
  701. func (evs eventsSortByKey) Len() int { return len(evs) }
  702. func (evs eventsSortByKey) Swap(i, j int) { evs[i], evs[j] = evs[j], evs[i] }
  703. func (evs eventsSortByKey) Less(i, j int) bool { return bytes.Compare(evs[i].Kv.Key, evs[j].Kv.Key) < 0 }
  704. func TestV3WatchMultipleEventsPutUnsynced(t *testing.T) {
  705. defer testutil.AfterTest(t)
  706. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  707. defer clus.Terminate(t)
  708. kvc := toGRPC(clus.RandClient()).KV
  709. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  710. t.Fatalf("couldn't put key (%v)", err)
  711. }
  712. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  713. t.Fatalf("couldn't put key (%v)", err)
  714. }
  715. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  716. defer cancel()
  717. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  718. if wErr != nil {
  719. t.Fatalf("wAPI.Watch error: %v", wErr)
  720. }
  721. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  722. CreateRequest: &pb.WatchCreateRequest{
  723. Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: 1}}}
  724. if err := wStream.Send(wreq); err != nil {
  725. t.Fatalf("wStream.Send error: %v", err)
  726. }
  727. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  728. t.Fatalf("couldn't put key (%v)", err)
  729. }
  730. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  731. t.Fatalf("couldn't put key (%v)", err)
  732. }
  733. allWevents := []*mvccpb.Event{
  734. {
  735. Type: mvccpb.PUT,
  736. Kv: &mvccpb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  737. },
  738. {
  739. Type: mvccpb.PUT,
  740. Kv: &mvccpb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 3, Version: 1},
  741. },
  742. {
  743. Type: mvccpb.PUT,
  744. Kv: &mvccpb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 2},
  745. },
  746. {
  747. Type: mvccpb.PUT,
  748. Kv: &mvccpb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 5, Version: 2},
  749. },
  750. }
  751. events := []*mvccpb.Event{}
  752. for len(events) < 4 {
  753. resp, err := wStream.Recv()
  754. if err != nil {
  755. t.Errorf("wStream.Recv error: %v", err)
  756. }
  757. if resp.Created {
  758. continue
  759. }
  760. events = append(events, resp.Events...)
  761. // if PUT requests are committed by now, first receive would return
  762. // multiple events, but if not, it returns a single event. In SSD,
  763. // it should return 4 events at once.
  764. }
  765. if !reflect.DeepEqual(events, allWevents) {
  766. t.Errorf("events got = %+v, want = %+v", events, allWevents)
  767. }
  768. rok, nr := waitResponse(wStream, 1*time.Second)
  769. if !rok {
  770. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  771. }
  772. }
  773. func TestV3WatchMultipleStreamsSynced(t *testing.T) {
  774. defer testutil.AfterTest(t)
  775. testV3WatchMultipleStreams(t, 0)
  776. }
  777. func TestV3WatchMultipleStreamsUnsynced(t *testing.T) {
  778. defer testutil.AfterTest(t)
  779. testV3WatchMultipleStreams(t, 1)
  780. }
  781. // testV3WatchMultipleStreams tests multiple watchers on the same key on multiple streams.
  782. func testV3WatchMultipleStreams(t *testing.T, startRev int64) {
  783. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  784. defer clus.Terminate(t)
  785. wAPI := toGRPC(clus.RandClient()).Watch
  786. kvc := toGRPC(clus.RandClient()).KV
  787. streams := make([]pb.Watch_WatchClient, 5)
  788. for i := range streams {
  789. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  790. defer cancel()
  791. wStream, errW := wAPI.Watch(ctx)
  792. if errW != nil {
  793. t.Fatalf("wAPI.Watch error: %v", errW)
  794. }
  795. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  796. CreateRequest: &pb.WatchCreateRequest{
  797. Key: []byte("foo"), StartRevision: startRev}}}
  798. if err := wStream.Send(wreq); err != nil {
  799. t.Fatalf("wStream.Send error: %v", err)
  800. }
  801. streams[i] = wStream
  802. }
  803. for _, wStream := range streams {
  804. wresp, err := wStream.Recv()
  805. if err != nil {
  806. t.Fatalf("wStream.Recv error: %v", err)
  807. }
  808. if !wresp.Created {
  809. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  810. }
  811. }
  812. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  813. t.Fatalf("couldn't put key (%v)", err)
  814. }
  815. var wg sync.WaitGroup
  816. wg.Add(len(streams))
  817. wevents := []*mvccpb.Event{
  818. {
  819. Type: mvccpb.PUT,
  820. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  821. },
  822. }
  823. for i := range streams {
  824. go func(i int) {
  825. defer wg.Done()
  826. wStream := streams[i]
  827. wresp, err := wStream.Recv()
  828. if err != nil {
  829. t.Fatalf("wStream.Recv error: %v", err)
  830. }
  831. if wresp.WatchId != 0 {
  832. t.Errorf("watchId got = %d, want = 0", wresp.WatchId)
  833. }
  834. if !reflect.DeepEqual(wresp.Events, wevents) {
  835. t.Errorf("wresp.Events got = %+v, want = %+v", wresp.Events, wevents)
  836. }
  837. // now Recv should block because there is no more events coming
  838. rok, nr := waitResponse(wStream, 1*time.Second)
  839. if !rok {
  840. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  841. }
  842. }(i)
  843. }
  844. wg.Wait()
  845. }
  846. // waitResponse waits on the given stream for given duration.
  847. // If there is no more events, true and a nil response will be
  848. // returned closing the WatchClient stream. Or the response will
  849. // be returned.
  850. func waitResponse(wc pb.Watch_WatchClient, timeout time.Duration) (bool, *pb.WatchResponse) {
  851. rCh := make(chan *pb.WatchResponse, 1)
  852. donec := make(chan struct{})
  853. defer close(donec)
  854. go func() {
  855. resp, _ := wc.Recv()
  856. select {
  857. case rCh <- resp:
  858. case <-donec:
  859. }
  860. }()
  861. select {
  862. case nr := <-rCh:
  863. return false, nr
  864. case <-time.After(timeout):
  865. }
  866. // didn't get response
  867. wc.CloseSend()
  868. return true, nil
  869. }
  870. func TestWatchWithProgressNotify(t *testing.T) {
  871. // accelerate report interval so test terminates quickly
  872. oldpi := v3rpc.GetProgressReportInterval()
  873. // using atomics to avoid race warnings
  874. v3rpc.SetProgressReportInterval(3 * time.Second)
  875. testInterval := 3 * time.Second
  876. defer func() { v3rpc.SetProgressReportInterval(oldpi) }()
  877. defer testutil.AfterTest(t)
  878. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  879. defer clus.Terminate(t)
  880. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  881. defer cancel()
  882. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  883. if wErr != nil {
  884. t.Fatalf("wAPI.Watch error: %v", wErr)
  885. }
  886. // create two watchers, one with progressNotify set.
  887. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  888. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1, ProgressNotify: true}}}
  889. if err := wStream.Send(wreq); err != nil {
  890. t.Fatalf("watch request failed (%v)", err)
  891. }
  892. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  893. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1}}}
  894. if err := wStream.Send(wreq); err != nil {
  895. t.Fatalf("watch request failed (%v)", err)
  896. }
  897. // two creation + one notification
  898. for i := 0; i < 3; i++ {
  899. rok, resp := waitResponse(wStream, testInterval+time.Second)
  900. if resp.Created {
  901. continue
  902. }
  903. if rok {
  904. t.Errorf("failed to receive response from watch stream")
  905. }
  906. if resp.Header.Revision != 1 {
  907. t.Errorf("revision = %d, want 1", resp.Header.Revision)
  908. }
  909. if len(resp.Events) != 0 {
  910. t.Errorf("len(resp.Events) = %d, want 0", len(resp.Events))
  911. }
  912. }
  913. // no more notification
  914. rok, resp := waitResponse(wStream, time.Second)
  915. if !rok {
  916. t.Errorf("unexpected pb.WatchResponse is received %+v", resp)
  917. }
  918. }
  919. // TestV3WatcMultiOpenhClose opens many watchers concurrently on multiple streams.
  920. func TestV3WatchClose(t *testing.T) {
  921. defer testutil.AfterTest(t)
  922. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  923. defer clus.Terminate(t)
  924. c := clus.Client(0)
  925. wapi := toGRPC(c).Watch
  926. var wg sync.WaitGroup
  927. wg.Add(100)
  928. for i := 0; i < 100; i++ {
  929. go func() {
  930. ctx, cancel := context.WithCancel(context.TODO())
  931. defer func() {
  932. wg.Done()
  933. cancel()
  934. }()
  935. ws, err := wapi.Watch(ctx)
  936. if err != nil {
  937. return
  938. }
  939. cr := &pb.WatchCreateRequest{Key: []byte("a")}
  940. req := &pb.WatchRequest{
  941. RequestUnion: &pb.WatchRequest_CreateRequest{
  942. CreateRequest: cr}}
  943. ws.Send(req)
  944. ws.Recv()
  945. }()
  946. }
  947. clus.Members[0].DropConnections()
  948. wg.Wait()
  949. }
  950. // TestV3WatchWithFilter ensures watcher filters out the events correctly.
  951. func TestV3WatchWithFilter(t *testing.T) {
  952. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  953. defer clus.Terminate(t)
  954. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  955. defer cancel()
  956. ws, werr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  957. if werr != nil {
  958. t.Fatal(werr)
  959. }
  960. req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  961. CreateRequest: &pb.WatchCreateRequest{
  962. Key: []byte("foo"),
  963. Filters: []pb.WatchCreateRequest_FilterType{pb.WatchCreateRequest_NOPUT},
  964. }}}
  965. if err := ws.Send(req); err != nil {
  966. t.Fatal(err)
  967. }
  968. if _, err := ws.Recv(); err != nil {
  969. t.Fatal(err)
  970. }
  971. recv := make(chan *pb.WatchResponse)
  972. go func() {
  973. // check received PUT
  974. resp, rerr := ws.Recv()
  975. if rerr != nil {
  976. t.Fatal(rerr)
  977. }
  978. recv <- resp
  979. }()
  980. // put a key with empty value
  981. kvc := toGRPC(clus.RandClient()).KV
  982. preq := &pb.PutRequest{Key: []byte("foo")}
  983. if _, err := kvc.Put(context.TODO(), preq); err != nil {
  984. t.Fatal(err)
  985. }
  986. select {
  987. case <-recv:
  988. t.Fatal("failed to filter out put event")
  989. case <-time.After(100 * time.Millisecond):
  990. }
  991. dreq := &pb.DeleteRangeRequest{Key: []byte("foo")}
  992. if _, err := kvc.DeleteRange(context.TODO(), dreq); err != nil {
  993. t.Fatal(err)
  994. }
  995. select {
  996. case resp := <-recv:
  997. wevs := []*mvccpb.Event{
  998. {
  999. Type: mvccpb.DELETE,
  1000. Kv: &mvccpb.KeyValue{Key: []byte("foo"), ModRevision: 3},
  1001. },
  1002. }
  1003. if !reflect.DeepEqual(resp.Events, wevs) {
  1004. t.Fatalf("got %v, expected %v", resp.Events, wevs)
  1005. }
  1006. case <-time.After(100 * time.Millisecond):
  1007. t.Fatal("failed to receive delete event")
  1008. }
  1009. }
  1010. func TestV3WatchWithPrevKV(t *testing.T) {
  1011. defer testutil.AfterTest(t)
  1012. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  1013. defer clus.Terminate(t)
  1014. wctx, wcancel := context.WithCancel(context.Background())
  1015. defer wcancel()
  1016. tests := []struct {
  1017. key string
  1018. end string
  1019. vals []string
  1020. }{{
  1021. key: "foo",
  1022. end: "fop",
  1023. vals: []string{"bar1", "bar2"},
  1024. }, {
  1025. key: "/abc",
  1026. end: "/abd",
  1027. vals: []string{"first", "second"},
  1028. }}
  1029. for i, tt := range tests {
  1030. kvc := toGRPC(clus.RandClient()).KV
  1031. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte(tt.key), Value: []byte(tt.vals[0])}); err != nil {
  1032. t.Fatal(err)
  1033. }
  1034. ws, werr := toGRPC(clus.RandClient()).Watch.Watch(wctx)
  1035. if werr != nil {
  1036. t.Fatal(werr)
  1037. }
  1038. req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  1039. CreateRequest: &pb.WatchCreateRequest{
  1040. Key: []byte(tt.key),
  1041. RangeEnd: []byte(tt.end),
  1042. PrevKv: true,
  1043. }}}
  1044. if err := ws.Send(req); err != nil {
  1045. t.Fatal(err)
  1046. }
  1047. if _, err := ws.Recv(); err != nil {
  1048. t.Fatal(err)
  1049. }
  1050. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte(tt.key), Value: []byte(tt.vals[1])}); err != nil {
  1051. t.Fatal(err)
  1052. }
  1053. recv := make(chan *pb.WatchResponse)
  1054. go func() {
  1055. // check received PUT
  1056. resp, rerr := ws.Recv()
  1057. if rerr != nil {
  1058. t.Fatal(rerr)
  1059. }
  1060. recv <- resp
  1061. }()
  1062. select {
  1063. case resp := <-recv:
  1064. if tt.vals[1] != string(resp.Events[0].Kv.Value) {
  1065. t.Errorf("#%d: unequal value: want=%s, get=%s", i, tt.vals[1], resp.Events[0].Kv.Value)
  1066. }
  1067. if tt.vals[0] != string(resp.Events[0].PrevKv.Value) {
  1068. t.Errorf("#%d: unequal value: want=%s, get=%s", i, tt.vals[0], resp.Events[0].PrevKv.Value)
  1069. }
  1070. case <-time.After(30 * time.Second):
  1071. t.Error("timeout waiting for watch response")
  1072. }
  1073. }
  1074. }