1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
//
// Copyright 2019 Joyent, Inc.
//
// THEORY STATEMENT -- READ THIS FIRST!
//
// This library has just one task: watch a zookeeper node for changes and notify
// users of the library when changes occur. This is accomplished in one big pair
// of nested loops. The code structure looks a little like this:
//
// ManateePrimaryResolver::run()
//   -> Spawns tokio task
//     -> Runs outer loop, which handles connecting/reconnecting to zookeeper.
//        The logic here is in the connect_loop() function.
//        -> Runs inner loop, which handles setting/resetting the zookeeper
//           watch. The logic here is in the watch_loop() function.
//           -> For every change in zookeeper data, calls the process_value()
//              function. This function parses the new zookeeper data and
//              notifies the user of the change in data if necessary.
//
// Note that this file also contains unit tests for process_value().
//

use std::convert::From;
use std::fmt::Debug;
use std::net::{AddrParseError, SocketAddr};
use std::str::{FromStr};
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use failure::Error as FailureError;
use futures::future::{ok, loop_fn, Either, Future, Loop};
use itertools::Itertools;
use serde::Deserialize;
use serde_json;
use serde_json::Value as SerdeJsonValue;
use slog::{error, info, debug, o, Drain, Key, Logger, Record, Serializer};
use slog::Result as SlogResult;
use slog::Value as SlogValue;
use tokio_zookeeper::*;
use tokio::prelude::*;
use tokio::runtime::Runtime;
use tokio::timer::Delay;
use url::Url;

use cueball::backend::*;
use cueball::resolver::{
    BackendAddedMsg,
    BackendRemovedMsg,
    BackendMsg,
    Resolver
};

pub mod util;

//
// The interval at which the resolver should send heartbeats via the
// connection pool channel.
//
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);

//
// Delays to be used when reconnecting to the zookeeper client
//
const RECONNECT_DELAY: Duration = Duration::from_secs(10);
const RECONNECT_NODELAY: Duration = Duration::from_secs(0);

//
// Delays to be used when re-setting the watch on the zookeeper node
//
const WATCH_LOOP_DELAY: Duration = Duration::from_secs(10);
const WATCH_LOOP_NODELAY: Duration = Duration::from_secs(0);

//
// An error type to be used internally.
//
#[derive(Clone, Debug, PartialEq)]
enum ResolverError {
    InvalidZkJson,
    InvalidZkData(ZkDataField),
    MissingZkData(ZkDataField),
    ConnectionPoolShutdown
}

impl ResolverError {
    ///
    /// This function provides a means of determining whether or not a given
    /// error should cause the resolver to stop.
    ///
    fn should_stop(&self) -> bool {
        match self {
            ResolverError::ConnectionPoolShutdown => true,
            _ => false
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
enum ZkDataField {
    Ip,
    Port,
    PostgresUrl
}

#[derive(Debug)]
pub enum ZkConnectStringError {
    EmptyString,
    MalformedAddr
}

impl From<AddrParseError> for ZkConnectStringError {
    fn from(_: AddrParseError) -> Self {
        ZkConnectStringError::MalformedAddr
    }
}

///
/// `ZkConnectString` represents a list of zookeeper addresses to connect to.
///
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct ZkConnectString(Vec<SocketAddr>);

impl ZkConnectString {
    ///
    /// Gets a reference to the SocketAddr at the provided index. Returns None
    /// if the index is out of bounds.
    ///
    fn get_addr_at(&self, index: usize) -> Option<&SocketAddr> {
        self.0.get(index)
    }
}

impl ToString for ZkConnectString {
    fn to_string(&self) -> String {
        self
            .0
            .iter()
            .map(|x| x.to_string())
            .intersperse(String::from(","))
            .collect()
    }
}

impl FromStr for ZkConnectString {
    type Err = ZkConnectStringError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Err(ZkConnectStringError::EmptyString);
        }
        let acc: Result<Vec<SocketAddr>, Self::Err> = Ok(vec![]);
        s.split(',')
            .map(|x| SocketAddr::from_str(x))
            .fold(acc, |acc, x| {
                match (acc, x) {
                    (Ok(mut addrs), Ok(addr)) => {
                        addrs.push(addr);
                        Ok(addrs)
                    },
                    (Err(e), _) => Err(e),
                    (_, Err(e)) => Err(ZkConnectStringError::from(e))
                }
            })
            .and_then(|x| Ok(ZkConnectString(x)))
    }
}

///
/// A serializable type to be used in log entries. Wraps around any type that
/// implements Debug and uses the Debug representation of the type as the
/// serialized output.
///
struct LogItem<T>(T) where T: Debug;

impl<T: Debug> SlogValue for LogItem<T> {
    fn serialize(&self, _rec: &Record, key: Key,
        serializer: &mut dyn Serializer) -> SlogResult {
            serializer.emit_str(key, &format!("{:?}", self.0))
    }
}

// Represents an action to be taken in the event of a connection error.
enum NextAction {
    //
    // The Duration field is the amount of time to wait before
    // reconnecting.
    //
    Reconnect(Duration),
    Stop,
}

//
// Encapsulates the state that one iteration of the watch loop passes
// to the next iteration.
//
struct WatchLoopState {
    watcher: Box<dyn futures::stream::Stream
        <Item = WatchedEvent, Error = ()> + Send>,
    curr_event: WatchedEvent,
    delay: Duration
}

#[derive(Debug)]
pub struct ManateePrimaryResolver {
    ///
    /// The addresses of the Zookeeper cluster the Resolver is connecting to
    ///
    connect_string: ZkConnectString,
    ///
    /// The Zookeeper path for manatee cluster state for the shard. *e.g.*
    /// "/manatee/1.moray.coal.joyent.us/state"
    ///
    cluster_state_path: String,
    ///
    /// The key representation of the last backend sent to the cueball
    /// connection pool. Persists across multiple calls to run().
    ///
    last_backend: Arc<Mutex<Option<BackendKey>>>,
    ///
    /// Indicates whether or not the resolver is running. This is slightly
    /// superfluous (this field is `true` for exactly the duration of each
    /// call to run(), and false otherwise), but could be useful if the caller
    /// wants to check if the resolver is running for some reason.
    ///
    is_running: bool,
    ///
    /// The ManateePrimaryResolver's root log
    ///
    log: Logger
}

impl ManateePrimaryResolver {
    ///
    /// Creates a new ManateePrimaryResolver instance.
    ///
    /// # Arguments
    ///
    /// * `connect_string` - a comma-separated list of the zookeeper instances
    ///   in the cluster
    /// * `path` - The path to the root node in zookeeper for the shard we're
    ///    watching
    ///
    pub fn new(
        connect_string: ZkConnectString,
        path: String,
        log: Option<Logger>
    ) -> Self
    {
        let cluster_state_path = [&path, "/state"].concat();

        //
        // Add the log_values to the passed-in logger, or create a new logger if
        // the caller did not pass one in
        //
        let log = log.unwrap_or_else(||
            Logger::root(slog_stdlog::StdLog.fuse(), o!()));

        ManateePrimaryResolver {
            connect_string: connect_string.clone(),
            cluster_state_path,
            last_backend: Arc::new(Mutex::new(None)),
            is_running: false,
            log
        }
    }
}

///
/// Parses the given zookeeper node data into a Backend object, compares it to
/// the last Backend sent to the cueball connection pool, and sends it to the
/// connection pool if the values differ.
///
/// We need to extract two pieces of data from the "primary" json object in the
/// json returned by zookeeper:
/// * The backend's IP address
/// * The backend's port
/// The json object has an "ip" field, but not a port field. However, the port
/// is contained in the "pgUrl" field, so this function extracts it from that.
/// The port could also be extracted from the "id" field, but the pgUrl field is
/// a convenient choice as it can be parsed structurally as a url and the port
/// extracted from there.
///
/// What this all means is: the resolver relies on the "primary.ip" and
/// "primary.pgUrl" fields as an _interface_ to the zookeeper data. This feels a
/// little ad-hoc and should be formalized and documented.
///
/// # Arguments
///
/// * `pool_tx` - The Sender upon which to send the update message
/// * `new_value` - The raw zookeeper data we've newly retrieved
/// * `last_backend` - The last Backend we sent to the connection pool
/// * `log` - The Logger to be used for logging
///
fn process_value(
    pool_tx: &Sender<BackendMsg>,
    new_value: &[u8],
    last_backend: Arc<Mutex<Option<BackendKey>>>,
    log: Logger
) -> Result<(), ResolverError> {
    debug!(log, "process_value() entered");

    // Parse the bytes into a json object
    let v: SerdeJsonValue = match serde_json::from_slice(&new_value) {
        Ok(v) => v,
        Err(_) => {
            return Err(ResolverError::InvalidZkJson);
        }
    };

    //
    // Parse out the ip. We expect the json fields to exist, and return an error
    // if they don't, or if they are of the wrong type.
    //
    let ip = match &v["primary"]["ip"] {
        SerdeJsonValue::String(s) => {
            match BackendAddress::from_str(s) {
                Ok(s) => s,
                Err(_) => {
                    return Err(ResolverError::InvalidZkData(ZkDataField::Ip));
                }
            }
        },
        SerdeJsonValue::Null => {
            return Err(ResolverError::MissingZkData(ZkDataField::Ip));
        },
        _ => {
            return Err(ResolverError::InvalidZkData(ZkDataField::Ip));
        }
    };

    //
    // Parse out the port. We expect the json fields to exist, and return an
    // error if they don't, or if they are of the wrong type.
    //
    let port = match &v["primary"]["pgUrl"] {
        SerdeJsonValue::String(s) => {
            match Url::parse(s) {
                Ok(url) => {
                    match url.port() {
                        Some(port) => port,
                        None => {
                            return Err(ResolverError::MissingZkData(
                                ZkDataField::Port));
                        }
                    }
                },
                Err(_) => {
                    return Err(ResolverError::InvalidZkData(
                        ZkDataField::PostgresUrl))
                }
            }
        },
        SerdeJsonValue::Null => {
            return Err(ResolverError::MissingZkData(ZkDataField::PostgresUrl));
        },
        _ => {
            return Err(ResolverError::InvalidZkData(ZkDataField::PostgresUrl));
        }
    };

    // Construct a backend and key
    let backend = Backend::new(&ip, port);
    let backend_key = srv_key(&backend);

    // Determine whether we need to send the new backend over
    let mut last_backend = last_backend.lock().unwrap();
    let should_send = match (*last_backend).clone() {
        Some(lb) => lb != backend_key,
        None => true,
    };

    // Send the new backend if necessary
    if should_send {
        info!(log, "New backend found; sending to connection pool";
            "backend" => LogItem(backend.clone()));
        if pool_tx.send(BackendMsg::AddedMsg(BackendAddedMsg {
            key: backend_key.clone(),
            backend
        })).is_err() {
            return Err(ResolverError::ConnectionPoolShutdown);
        }

        let lb_clone = (*last_backend).clone();
        *last_backend = Some(backend_key);

        //
        // Notify the connection pool that the old backend should be
        // removed, if the old backend is not None
        //
        if let Some(lbc) = lb_clone {
            info!(log, "Notifying connection pool of removal of old backend");
            if pool_tx.send(BackendMsg::RemovedMsg(
                BackendRemovedMsg(lbc))).is_err() {
                return Err(ResolverError::ConnectionPoolShutdown);
            }
        }
    } else {
        info!(log, "New backend value does not differ; not sending");
    }
    debug!(log, "process_value() returned successfully");
    Ok(())
}

///
/// This function represents the body of the watch loop. It both sets and
/// handles the watch, and calls process_value() to send new data to the
/// connection pool as the data arrives.
///
/// This function can return from two states: before we've waited for the
///  watch to fire (if we hit an error before waiting), or after we've waited
/// for the watch to fire (this could be a success or an error). These two
/// states require returning different Future types, so we wrap the returned
/// values in a future::Either to satisfy the type checker.
///
/// # Arguments
///
/// * `pool_tx` - The Sender upon which to send the update message
/// * `last_backend` - The last Backend we sent to the connection pool
/// * `cluster_state_path` - The path to the cluster state node in zookeeper for
///   the shard we're watching
/// * `zk` - The ZooKeeper client object
/// * `loop_state`: The state to be passed to the next iteration of loop_fn()
/// * `log` - The Logger to be used for logging
///
fn watch_loop(
    pool_tx: Sender<BackendMsg>,
    last_backend: Arc<Mutex<Option<BackendKey>>>,
    cluster_state_path: String,
    zk: ZooKeeper,
    loop_state: WatchLoopState,
    log: Logger
) -> impl Future<Item = Loop<NextAction, WatchLoopState>,
    Error = FailureError> + Send {

    let watcher = loop_state.watcher;
    let curr_event = loop_state.curr_event;
    let delay = loop_state.delay;
    //
    // TODO avoid mutex boilerplate from showing up in the log
    //
    let log = log.new(o!(
        "curr_event" => LogItem(curr_event.clone()),
        "delay" => LogItem(delay),
        "last_backend" => LogItem(Arc::clone(&last_backend))
    ));

    info!(log, "Getting data");
    let oe_log = log.clone();

    //
    // We set the watch here. If the previous iteration of the loop ended
    // because the keeper state changed rather than because the watch fired, the
    // watch will already have been set, so we don't _need_ to set it here. With
    // that said, it does no harm (zookeeper deduplicates watches on the server
    // side), and it may not be worth the effort to optimize for this case,
    // since keeper state changes (and, indeed, changes of any sort) should
    // happen infrequently.
    //
    Delay::new(Instant::now() + delay)
    .and_then(move |_| {
        zk
        .watch()
        .get_data(&cluster_state_path)
        .and_then(move |(_, data)| {
            match curr_event.event_type {
                // Keeper state has changed
                WatchedEventType::None => {
                    match curr_event.keeper_state {
                        //
                        // TODO will these cases ever happen? Because if the
                        // keeper state is "bad", then get_data() will have
                        // failed and we won't be here.
                        //
                        KeeperState::Disconnected |
                        KeeperState::AuthFailed |
                        KeeperState::Expired => {
                            error!(log, "Keeper state changed; reconnecting";
                                "keeper_state" =>
                                LogItem(curr_event.keeper_state));
                            return Either::A(ok(Loop::Break(
                                NextAction::Reconnect(RECONNECT_NODELAY))));
                        },
                        KeeperState::SyncConnected |
                        KeeperState::ConnectedReadOnly |
                        KeeperState::SaslAuthenticated => {
                            info!(log, "Keeper state changed"; "keeper_state" =>
                                LogItem(curr_event.keeper_state));
                        }
                    }
                },
                // The data watch fired
                WatchedEventType::NodeDataChanged => {
                    //
                    // We didn't get the data, which means the node doesn't
                    // exist yet. We should wait a bit and try again. We'll just
                    // use the same event as before.
                    //
                    if data.is_none() {
                        info!(log, "ZK data does not exist yet");
                        return Either::A(ok(Loop::Continue(WatchLoopState {
                            watcher,
                            curr_event,
                            delay: WATCH_LOOP_DELAY
                        })));
                    }
                    //
                    // Discard the Stat from the data, as we don't use it.
                    //
                    let data = data.unwrap().0;
                    info!(log, "got data"; "data" => LogItem(data.clone()));
                    match process_value(
                        &pool_tx.clone(),
                        &data,
                        Arc::clone(&last_backend),
                        log.clone()
                    ) {
                        Ok(_) => {},
                        Err(e) => {
                            error!(log, ""; "error" => LogItem(e.clone()));
                            //
                            // The error is between the client and the
                            // outward-facing channel, not between the client
                            // and the zookeeper connection, so we don't have to
                            // attempt to reconnect here and can continue,
                            // unless the error tells us to stop.
                            //
                            if e.should_stop() {
                                return Either::A(ok(Loop::Break(
                                    NextAction::Stop)));
                            }
                        }
                    }
                },
                WatchedEventType::NodeDeleted => {
                    //
                    // Same behavior as the above case where we didn't get the
                    // data because the node doesn't exist. See comment above.
                    //
                    info!(log, "ZK node deleted");
                    return Either::A(ok(Loop::Continue(WatchLoopState {
                        watcher,
                        curr_event,
                        delay: WATCH_LOOP_DELAY
                    })));
                },
                e => panic!("Unexpected event received: {:?}", e)
            };

            //
            // If we got here, we're waiting for the watch to fire. Before this
            // point, we wrap the return value in Either::A. After this point,
            // we wrap the return value in Either::B. See the comment about
            // "Either" some lines above.
            //
            info!(log, "Watching for change");
            let oe_log = log.clone();
            Either::B(watcher.into_future()
                .and_then(move |(event, watcher)| {
                    let loop_next = match event {
                        Some(event) => {
                            info!(log, "change event received; looping to \
                                process event"; "event" =>
                                LogItem(event.clone()));
                            Loop::Continue(WatchLoopState {
                                watcher,
                                curr_event: event,
                                delay:WATCH_LOOP_NODELAY
                            })
                        },
                        //
                        // If we didn't get a valid event, this means the Stream
                        // got closed, which indicates a connection issue, so we
                        // reconnect.
                        //
                        None => {
                            error!(log, "Event stream closed; reconnecting");
                            Loop::Break(NextAction::Reconnect(
                                RECONNECT_NODELAY))
                        }
                    };
                    ok(loop_next)
                })
                .or_else(move |_| {
                    //
                    // If we get an error from the event Stream, we assume that
                    // something went wrong with the zookeeper connection and
                    // attempt to reconnect.
                    //
                    // The stream's error type is (), so there's no information
                    // to extract from it.
                    //
                    error!(oe_log, "Error received from event stream");
                    ok(Loop::Break(NextAction::Reconnect(RECONNECT_NODELAY)))
                }))
        })
        //
        // If some error occurred getting the data, we assume we should
        // reconnect to the zookeeper server.
        //
        .or_else(move |error| {
            error!(oe_log, "Error getting data"; "error" => LogItem(error));
            ok(Loop::Break(NextAction::Reconnect(RECONNECT_NODELAY)))
        })
    })
    .map_err(|e| panic!("delay errored; err: {:?}", e))
}

fn connect_loop(
    pool_tx: Sender<BackendMsg>,
    last_backend: Arc<Mutex<Option<BackendKey>>>,
    connect_string: ZkConnectString,
    cluster_state_path: String,
    delay: Duration,
    log: Logger
) -> impl Future<Item = Loop<(), Duration>,
    Error = ()> + Send {

    let oe_log = log.clone();
    Delay::new(Instant::now() + delay)
    .and_then(move |_| {
        info!(log, "Connecting to ZooKeeper cluster");
        //
        // We expect() the result of get_addr_at() because we anticipate the
        // connect string having at least one element, and we can't do anything
        // useful if it doesn't.
        //
        ZooKeeper::connect(connect_string.get_addr_at(0)
        .expect("connect_string should have at least one IP address"))
        .and_then(move |(zk, default_watcher)| {
            info!(log, "Connected to ZooKeeper cluster");

            //
            // Main change-watching loop. A new loop iteration means we're
            // setting a new watch (if necessary) and waiting for a result.
            // Breaking from the loop means that we've hit some error and are
            // returning control to the outer loop.
            //
            // Arg: WatchLoopState -- we set curr_event to an artificially
            //     constructed WatchedEvent for the first loop iteration, so the
            //     connection pool will be initialized with the initial primary
            //     as its backend.
            // Loop::Break type: NextAction -- this value is used to instruct
            //     the outer loop (this function) whether to try to reconnect or
            //     terminate.
            //
            loop_fn(WatchLoopState {
                watcher: Box::new(default_watcher),
                curr_event: WatchedEvent {
                    event_type: WatchedEventType::NodeDataChanged,
                    //
                    // This initial artificial keeper_state doesn't necessarily
                    // reflect reality, but that's ok because it's paired with
                    // an artificial NodeDataChanged event, and our handling for
                    // this type of event doesn't involve the keeper_state
                    // field.
                    //
                    keeper_state: KeeperState::SyncConnected,
                    //
                    // We never use `path`, so we might as well set it to an
                    // empty string in our artificially constructed WatchedEvent
                    // object.
                    //
                    path: "".to_string(),
                },
                delay: WATCH_LOOP_NODELAY
            } , move |loop_state| {
                //
                // These fields require a new clone for every loop iteration,
                // but they don't actually change from iteration to iteration,
                // so they're not included as part of loop_state.
                //
                let pool_tx = pool_tx.clone();
                let last_backend = Arc::clone(&last_backend);
                let cluster_state_path = cluster_state_path.clone();
                let zk = zk.clone();
                let log = log.clone();

                watch_loop(
                    pool_tx,
                    last_backend,
                    cluster_state_path,
                    zk,
                    loop_state,
                    log
                )
            })
            .and_then(|next_action| {
                ok(match next_action {
                    NextAction::Stop => Loop::Break(()),
                    //
                    // We reconnect immediately here instead of waiting, because
                    // if we're here it means that we came from the inner loop
                    // and thus we just had a valid connection terminate (as
                    // opposed to the `or_else` block below, were we've just
                    // tried to connect and failed), and thus there's no reason
                    // for us to delay trying to connect again.
                    //
                    NextAction::Reconnect(delay) => Loop::Continue(delay)
                })
            })
        })
        .or_else(move |error| {
            error!(oe_log, "Error connecting to ZooKeeper cluster";
                "error" => LogItem(error));
            ok(Loop::Continue(RECONNECT_DELAY))
        })
    })
    .map_err(|e| panic!("delay errored; err: {:?}", e))
}

impl Resolver for ManateePrimaryResolver {

    //
    // The resolver object is not Sync, so we can assume that only one instance
    // of this function is running at once, because callers will have to control
    // concurrent access.
    //
    // If the connection pool closes the receiving end of the channel, this
    // function may not return right away -- this function will not notice that
    // the pool has disconnected until this function tries to send another
    // heartbeat, at which point this function will return. This means that the
    // time between disconnection and function return is at most the length of
    // HEARTBEAT_INTERVAL. Any change in the meantime will be picked up by the
    // next call to run().
    //
    // Indeed, the heartbeat messages exist solely as a time-boxed method to
    // test whether the connection pool has closed the channel, so we don't leak
    // resolver threads.
    //
    fn run(&mut self, s: Sender<BackendMsg>) {
        debug!(self.log, "run() method entered");

        let mut rt = Runtime::new().unwrap();
        //
        // There's no need to check if the pool is already running and return
        // early, because multiple instances of this function _cannot_ be
        // running concurrently -- see this function's header comment.
        //
        self.is_running = true;

        //
        // Variables moved to tokio runtime thread:
        //
        // * `connect_string` - A comma-separated list of the zookeeper
        //   instances in the cluster
        // * `cluster_state_path` - The path to the cluster state node in
        //   zookeeper for the shard we're watching
        // * `pool_tx` - The Sender that this function should use to communicate
        //   with the cueball connection pool
        // * `last_backend` - The key representation of the last backend sent to
        //   the cueball connection pool. It will be updated by process_value()
        //   if we send a new backend over.
        // * log - A clone of the resolver's master log
        // * at_log - Another clone, used in the `and_then` portion of the loop
        //
        let connect_string = self.connect_string.clone();
        let cluster_state_path = self.cluster_state_path.clone();
        let pool_tx = s.clone();
        let last_backend = Arc::clone(&self.last_backend);
        let log = self.log.clone();
        let at_log = self.log.clone();

        //
        // Start the event-processing task. This is structured as two nested
        // loops: one to handle the zookeeper connection and one to handle
        // setting the watch. These are handled by the connect_loop() and
        // watch_loop() functions, respectively
        //
        info!(self.log, "run(): starting runtime");
        rt.spawn(
            //
            // Outer loop. Handles connecting to zookeeper. A new loop iteration
            // means a new zookeeper connection. We break from the loop if we
            // discover that the user has closed the receiving channel, which
            // is their sole means of stopping the client.
            //
            // Arg: Time to wait before attempting to connect. Initially 0s.
            //     Repeated iterations of the loop set a delay before
            //     connecting.
            // Loop::Break type: ()
            //
            loop_fn(Duration::from_secs(0), move |delay| {
                let pool_tx = pool_tx.clone();
                let last_backend = Arc::clone(&last_backend);
                let connect_string = connect_string.clone();
                let cluster_state_path = cluster_state_path.clone();
                let log = log.clone();

                connect_loop(
                    pool_tx,
                    last_backend,
                    connect_string,
                    cluster_state_path,
                    delay,
                    log
                )
            }).and_then(move |_| {
                info!(at_log, "Event-processing task stopping");
                Ok(())
            })
            .map(|_| ())
        );
        loop {
            if s.send(BackendMsg::HeartbeatMsg).is_err() {
                info!(self.log, "Connection pool channel closed");
                break;
            }
            thread::sleep(HEARTBEAT_INTERVAL);
        }
        info!(self.log, "Stopping runtime");
        //
        // We shut down the background watch-looping thread. It may have already
        // exited by itself if it noticed that the connection pool closed its
        // channel, but there's no harm still calling shutdown_now() in that
        // case.
        //
        rt.shutdown_now().wait().unwrap();
        info!(self.log, "Runtime stopped successfully");
        self.is_running = false;
        debug!(self.log, "run() returned successfully");
    }
}

//
// Unit tests
//
#[cfg(test)]
mod test {
    use super::*;

    use std::iter;
    use std::sync::{Arc, Mutex};
    use std::sync::mpsc::{channel, TryRecvError};
    use std::vec::Vec;

    use clap::crate_version;
    use quickcheck::{quickcheck, Arbitrary, Gen};

    use super::util;

    impl Arbitrary for ZkConnectString {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            let size = usize::arbitrary(g);
            ZkConnectString(
                iter::repeat(())
                    .map(|()| SocketAddr::arbitrary(g))
                    .take(size)
                    .collect()
            )
        }
    }

    //
    // Test parsing ZkConnectString from string
    //
    quickcheck! {
        fn prop_zk_connect_string_parse(
            connect_string: ZkConnectString
        ) -> bool
        {
            //
            // We expect an error only if the input string was zero-length
            //
            match ZkConnectString::from_str(&connect_string.to_string()) {
                Ok(cs) => cs == connect_string,
                _ => connect_string.to_string() == ""
            }
        }
    }

    // Below: test process_value()

    fn test_log() -> Logger {
        let plain = slog_term::PlainSyncDecorator::new(std::io::stdout());
        Logger::root(
            Mutex::new(slog_term::FullFormat::new(plain).build()).fuse(),
            o!("build-id" => crate_version!()))
    }

    #[derive(Clone)]
    struct BackendData {
        raw: Vec<u8>,
        object: Backend
    }

    impl BackendData {
        //
        // Most of the data here isn't relevant, but real json from zookeeper
        // will include it, so we include it here.
        //
        fn new(ip: &str, port: u16) -> Self {
            let raw = format!(r#" {{
                "generation": 1,
                "primary": {{
                    "id": "{ip}:{port}:12345",
                    "ip": "{ip}",
                    "pgUrl": "tcp://postgres@{ip}:{port}/postgres",
                    "zoneId": "f47c4766-1857-4bdc-97f0-c1fd009c955b",
                    "backupUrl": "http://{ip}:12345"
                }},
                "sync": {{
                    "id": "10.77.77.21:5432:12345",
                    "zoneId": "f8727df9-c639-4152-a861-c77a878ca387",
                    "ip": "10.77.77.21",
                    "pgUrl": "tcp://postgres@10.77.77.21:5432/postgres",
                    "backupUrl": "http://10.77.77.21:12345"
                }},
                "async": [],
                "deposed": [
                    {{
                        "id":"10.77.77.22:5432:12345",
                        "ip": "10.77.77.22",
                        "pgUrl": "tcp://postgres@10.77.77.22:5432/postgres",
                        "zoneId": "c7a64f9f-4d49-4e6b-831a-68fd6ebf1d3c",
                        "backupUrl": "http://10.77.77.22:12345"
                    }}
                ],
                "initWal": "0/16522D8"
            }}"#, ip = ip, port = port).as_bytes().to_vec();

            BackendData {
                raw,
                object: Backend::new(&BackendAddress::from_str(ip).unwrap(),
                    port)
            }
        }

        fn raw(&self) -> Vec<u8> {
            self.raw.clone()
        }

        fn key(&self) -> BackendKey {
            srv_key(&self.object)
        }

        fn added_msg(&self) -> BackendAddedMsg {
            BackendAddedMsg {
                key: self.key(),
                backend: self.object.clone()
            }
        }

        fn removed_msg(&self) -> BackendRemovedMsg {
            BackendRemovedMsg(self.key())
        }
    }

    fn backend_ip1_port1() -> BackendData {
        BackendData::new("10.77.77.28", 5432)
    }

    fn backend_ip1_port2() -> BackendData {
        BackendData::new("10.77.77.28", 5431)
    }

    fn backend_ip2_port1() -> BackendData {
        BackendData::new("10.77.77.21", 5432)
    }

    fn backend_ip2_port2() -> BackendData {
        BackendData::new("10.77.77.21", 5431)
    }

    fn raw_invalid_json() -> Vec<u8> {
        "foo".as_bytes().to_vec()
    }

    fn raw_no_ip() -> Vec<u8> {
        r#" {
                "generation": 1,
                "primary": {
                    "id": "10.77.77.21:5432:12345",
                    "zoneId": "f8727df9-c639-4152-a861-c77a878ca387",
                    "pgUrl": "tcp://postgres@10.77.77.21:5432/postgres",
                    "backupUrl": "http://10.77.77.21:12345"
                },
                "sync": {
                    "id": "10.77.77.28:5432:12345",
                    "ip": "10.77.77.28",
                    "pgUrl": "tcp://postgres@10.77.77.28:5432/postgres",
                    "zoneId": "f47c4766-1857-4bdc-97f0-c1fd009c955b",
                    "backupUrl": "http://10.77.77.28:12345"
                },
                "async": [],
                "deposed": [
                    {
                        "id":"10.77.77.22:5432:12345",
                        "ip": "10.77.77.22",
                        "pgUrl": "tcp://postgres@10.77.77.22:5432/postgres",
                        "zoneId": "c7a64f9f-4d49-4e6b-831a-68fd6ebf1d3c",
                        "backupUrl": "http://10.77.77.22:12345"
                    }
                ],
                "initWal": "0/16522D8"
            }
        "#.as_bytes().to_vec()
    }

    fn raw_invalid_ip() -> Vec<u8> {
        r#" {
                "generation": 1,
                "primary": {
                    "id": "10.77.77.21:5432:12345",
                    "zoneId": "f8727df9-c639-4152-a861-c77a878ca387",
                    "ip": "foo",
                    "pgUrl": "tcp://postgres@10.77.77.21:5432/postgres",
                    "backupUrl": "http://10.77.77.21:12345"
                },
                "sync": {
                    "id": "10.77.77.28:5432:12345",
                    "ip": "10.77.77.28",
                    "pgUrl": "tcp://postgres@10.77.77.28:5432/postgres",
                    "zoneId": "f47c4766-1857-4bdc-97f0-c1fd009c955b",
                    "backupUrl": "http://10.77.77.28:12345"
                },
                "async": [],
                "deposed": [
                    {
                        "id":"10.77.77.22:5432:12345",
                        "ip": "10.77.77.22",
                        "pgUrl": "tcp://postgres@10.77.77.22:5432/postgres",
                        "zoneId": "c7a64f9f-4d49-4e6b-831a-68fd6ebf1d3c",
                        "backupUrl": "http://10.77.77.22:12345"
                    }
                ],
                "initWal": "0/16522D8"
            }
        "#.as_bytes().to_vec()
    }

    fn raw_wrong_type_ip() -> Vec<u8> {
        r#" {
                "generation": 1,
                "primary": {
                    "id": "10.77.77.21:5432:12345",
                    "zoneId": "f8727df9-c639-4152-a861-c77a878ca387",
                    "ip": true,
                    "pgUrl": "tcp://postgres@10.77.77.21:5432/postgres",
                    "backupUrl": "http://10.77.77.21:12345"
                },
                "sync": {
                    "id": "10.77.77.28:5432:12345",
                    "ip": "10.77.77.28",
                    "pgUrl": "tcp://postgres@10.77.77.28:5432/postgres",
                    "zoneId": "f47c4766-1857-4bdc-97f0-c1fd009c955b",
                    "backupUrl": "http://10.77.77.28:12345"
                },
                "async": [],
                "deposed": [
                    {
                        "id":"10.77.77.22:5432:12345",
                        "ip": "10.77.77.22",
                        "pgUrl": "tcp://postgres@10.77.77.22:5432/postgres",
                        "zoneId": "c7a64f9f-4d49-4e6b-831a-68fd6ebf1d3c",
                        "backupUrl": "http://10.77.77.22:12345"
                    }
                ],
                "initWal": "0/16522D8"
            }
        "#.as_bytes().to_vec()
    }

    fn raw_no_pg_url() -> Vec<u8> {
        r#" {
                "generation": 1,
                "primary": {
                    "id": "10.77.77.28:5432:12345",
                    "ip": "10.77.77.28",
                    "zoneId": "f47c4766-1857-4bdc-97f0-c1fd009c955b",
                    "backupUrl": "http://10.77.77.28:12345"
                },
                "sync": {
                    "id": "10.77.77.21:5432:12345",
                    "zoneId": "f8727df9-c639-4152-a861-c77a878ca387",
                    "ip": "10.77.77.21",
                    "pgUrl": "tcp://postgres@10.77.77.21:5432/postgres",
                    "backupUrl": "http://10.77.77.21:12345"
                },
                "async": [],
                "deposed": [
                    {
                        "id":"10.77.77.22:5432:12345",
                        "ip": "10.77.77.22",
                        "pgUrl": "tcp://postgres@10.77.77.22:5432/postgres",
                        "zoneId": "c7a64f9f-4d49-4e6b-831a-68fd6ebf1d3c",
                        "backupUrl": "http://10.77.77.22:12345"
                    }
                ],
                "initWal": "0/16522D8"
            }
        "#.as_bytes().to_vec()
    }

    fn raw_invalid_pg_url() -> Vec<u8> {
        r#" {
                "generation": 1,
                "primary": {
                    "id": "10.77.77.28:5432:12345",
                    "ip": "10.77.77.28",
                    "pgUrl": "foo",
                    "zoneId": "f47c4766-1857-4bdc-97f0-c1fd009c955b",
                    "backupUrl": "http://10.77.77.28:12345"
                },
                "sync": {
                    "id": "10.77.77.21:5432:12345",
                    "zoneId": "f8727df9-c639-4152-a861-c77a878ca387",
                    "ip": "10.77.77.21",
                    "pgUrl": "tcp://postgres@10.77.77.21:5432/postgres",
                    "backupUrl": "http://10.77.77.21:12345"
                },
                "async": [],
                "deposed": [
                    {
                        "id":"10.77.77.22:5432:12345",
                        "ip": "10.77.77.22",
                        "pgUrl": "tcp://postgres@10.77.77.22:5432/postgres",
                        "zoneId": "c7a64f9f-4d49-4e6b-831a-68fd6ebf1d3c",
                        "backupUrl": "http://10.77.77.22:12345"
                    }
                ],
                "initWal": "0/16522D8"
            }
        "#.as_bytes().to_vec()
    }

    fn raw_wrong_type_pg_url() -> Vec<u8> {
        r#" {
                "generation": 1,
                "primary": {
                    "id": "10.77.77.28:5432:12345",
                    "ip": "10.77.77.28",
                    "pgUrl": true,
                    "zoneId": "f47c4766-1857-4bdc-97f0-c1fd009c955b",
                    "backupUrl": "http://10.77.77.28:12345"
                },
                "sync": {
                    "id": "10.77.77.21:5432:12345",
                    "zoneId": "f8727df9-c639-4152-a861-c77a878ca387",
                    "ip": "10.77.77.21",
                    "pgUrl": "tcp://postgres@10.77.77.21:5432/postgres",
                    "backupUrl": "http://10.77.77.21:12345"
                },
                "async": [],
                "deposed": [
                    {
                        "id":"10.77.77.22:5432:12345",
                        "ip": "10.77.77.22",
                        "pgUrl": "tcp://postgres@10.77.77.22:5432/postgres",
                        "zoneId": "c7a64f9f-4d49-4e6b-831a-68fd6ebf1d3c",
                        "backupUrl": "http://10.77.77.22:12345"
                    }
                ],
                "initWal": "0/16522D8"
            }
        "#.as_bytes().to_vec()
    }

    fn raw_no_port_pg_url() -> Vec<u8> {
        r#" {
                "generation": 1,
                "primary": {
                    "id": "10.77.77.28:5432:12345",
                    "ip": "10.77.77.28",
                    "pgUrl": "tcp://postgres@10.77.77.22/postgres",
                    "zoneId": "f47c4766-1857-4bdc-97f0-c1fd009c955b",
                    "backupUrl": "http://10.77.77.28:12345"
                },
                "sync": {
                    "id": "10.77.77.21:5432:12345",
                    "zoneId": "f8727df9-c639-4152-a861-c77a878ca387",
                    "ip": "10.77.77.21",
                    "pgUrl": "tcp://postgres@10.77.77.21:5432/postgres",
                    "backupUrl": "http://10.77.77.21:12345"
                },
                "async": [],
                "deposed": [
                    {
                        "id":"10.77.77.22:5432:12345",
                        "ip": "10.77.77.22",
                        "pgUrl": "tcp://postgres@10.77.77.22:5432/postgres",
                        "zoneId": "c7a64f9f-4d49-4e6b-831a-68fd6ebf1d3c",
                        "backupUrl": "http://10.77.77.22:12345"
                    }
                ],
                "initWal": "0/16522D8"
            }
        "#.as_bytes().to_vec()
    }

    //
    // Represents a process_value test case, including inputs and expected
    // outputs.
    //
    struct ProcessValueFields {
        value: Vec<u8>,
        last_backend: BackendKey,
        expected_error: Option<ResolverError>,
        message_count: u32,
        added_backend: Option<BackendAddedMsg>,
        removed_backend: Option<BackendRemovedMsg>
    }

    //
    // Run a process_value test case
    //
    fn run_process_value_fields(input: ProcessValueFields) {
        let (tx, rx) = channel();
        let last_backend = Arc::new(Mutex::new(Some(input.last_backend)));

        let result = process_value(
            &tx.clone(),
            &input.value,
            last_backend,
            test_log());
        match input.expected_error {
            None => assert_eq!(result, Ok(())),
            Some(expected_error) => {
                assert_eq!(result, Err(expected_error))
            }
        }

        let mut received_messages = Vec::new();

        // Receive as many messages as we expect
        for i in 0..input.message_count {
            let channel_result = rx.try_recv();
            match channel_result {
                Err(e) => panic!("Unexpected error receiving on channel: {:?} \
                    -- Loop iteration: {:?}", e, i),
                Ok(result) => {
                    received_messages.push(result);
                }
            }
        }

        //
        // Make sure there are not more messages than we expect on the channel.
        // Can't use assert_eq! here because BackendMsg doesn't implement Debug.
        //
        match rx.try_recv() {
            Err(TryRecvError::Empty) => (),
            _ => panic!("Unexpected message on resolver channel")
        }

        // Check that the "added" message was received if applicable
        if let Some(msg) = input.added_backend {
            let msg = BackendMsg::AddedMsg(msg);
            match util::find_msg_match(&received_messages, &msg) {
                None => panic!("added_backend not found in received messages"),
                Some(index) => {
                    received_messages.remove(index);
                    ()
                }
            }
        }

        // Check that the "removed" message was received if applicable
        if let Some(msg) = input.removed_backend {
            let msg = BackendMsg::RemovedMsg(msg);
            match util::find_msg_match(&received_messages, &msg) {
                None =>
                    panic!("removed_backend not found in received messages"),
                Some(index) => {
                    received_messages.remove(index);
                    ()
                }
            }
        }
    }

    #[test]
    fn port_ip_change_test() {
        let data_1 = backend_ip1_port1();
        let data_2 = backend_ip2_port2();

        run_process_value_fields(ProcessValueFields{
            value: data_2.raw(),
            last_backend: data_1.key(),
            expected_error: None,
            message_count: 2,
            added_backend: Some(data_2.added_msg()),
            removed_backend: Some(data_1.removed_msg())
        });
    }

    #[test]
    fn port_change_test() {
        let data_1 = backend_ip1_port1();
        let data_2 = backend_ip2_port1();

        run_process_value_fields(ProcessValueFields{
            value: data_2.raw(),
            last_backend: data_1.key(),
            expected_error: None,
            message_count: 2,
            added_backend: Some(data_2.added_msg()),
            removed_backend: Some(data_1.removed_msg())
        });
    }

    #[test]
    fn ip_change_test() {
        let data_1 = backend_ip1_port1();
        let data_2 = backend_ip1_port2();

        run_process_value_fields(ProcessValueFields{
            value: data_2.raw(),
            last_backend: data_1.key(),
            expected_error: None,
            message_count: 2,
            added_backend: Some(data_2.added_msg()),
            removed_backend: Some(data_1.removed_msg())
        });
    }

    #[test]
    fn no_change_test() {
        let data = backend_ip1_port1();

        run_process_value_fields(ProcessValueFields{
            value: data.raw(),
            last_backend: data.key(),
            expected_error: None,
            message_count: 0,
            added_backend: None,
            removed_backend: None
        });
    }

    #[test]
    fn no_ip_test() {
        let filler = backend_ip1_port1();

        run_process_value_fields(ProcessValueFields{
            value: raw_no_ip(),
            last_backend: filler.key(),
            expected_error: Some(ResolverError::MissingZkData(ZkDataField::Ip)),
            message_count: 0,
            added_backend: None,
            removed_backend: None
        });
    }

    #[test]
    fn wrong_type_ip_test() {
        let filler = backend_ip1_port1();

        run_process_value_fields(ProcessValueFields{
            value: raw_wrong_type_ip(),
            last_backend: filler.key(),
            expected_error: Some(ResolverError::InvalidZkData(ZkDataField::Ip)),
            message_count: 0,
            added_backend: None,
            removed_backend: None
        });
    }

    #[test]
    fn invalid_ip_test() {
        let filler = backend_ip1_port1();

        run_process_value_fields(ProcessValueFields{
            value: raw_invalid_ip(),
            last_backend: filler.key(),
            expected_error: Some(ResolverError::InvalidZkData(ZkDataField::Ip)),
            message_count: 0,
            added_backend: None,
            removed_backend: None
        });
    }

    #[test]
    fn no_pg_url_test() {
        let filler = backend_ip1_port1();

        run_process_value_fields(ProcessValueFields{
            value: raw_no_pg_url(),
            last_backend: filler.key(),
            expected_error: Some(ResolverError::MissingZkData(
                ZkDataField::PostgresUrl)),
            message_count: 0,
            added_backend: None,
            removed_backend: None
        });
    }

    #[test]
    fn wrong_type_pg_url_test() {
        let filler = backend_ip1_port1();

        run_process_value_fields(ProcessValueFields{
            value: raw_wrong_type_pg_url(),
            last_backend: filler.key(),
            expected_error: Some(ResolverError::InvalidZkData(
                ZkDataField::PostgresUrl)),
            message_count: 0,
            added_backend: None,
            removed_backend: None
        });
    }

    #[test]
    fn invalid_pg_url_test() {
        let filler = backend_ip1_port1();

        run_process_value_fields(ProcessValueFields{
            value: raw_invalid_pg_url(),
            last_backend: filler.key(),
            expected_error: Some(ResolverError::InvalidZkData(
                ZkDataField::PostgresUrl)),
            message_count: 0,
            added_backend: None,
            removed_backend: None
        });
    }

    #[test]
    fn no_port_pg_url_test() {
        let filler = backend_ip1_port1();

        run_process_value_fields(ProcessValueFields{
            value: raw_no_port_pg_url(),
            last_backend: filler.key(),
            expected_error: Some(ResolverError::MissingZkData(
                ZkDataField::Port)),
            message_count: 0,
            added_backend: None,
            removed_backend: None
        });
    }

    #[test]
    fn invalid_json_test() {
        let filler = backend_ip1_port1();

        run_process_value_fields(ProcessValueFields{
            value: raw_invalid_json(),
            last_backend: filler.key(),
            expected_error: Some(ResolverError::InvalidZkJson),
            message_count: 0,
            added_backend: None,
            removed_backend: None
        });
    }
 }