Merge pull request #30 from 30x/XAPID-867

Xapid 867
diff --git a/apigee_sync.go b/apigee_sync.go
index 150739c..b63255c 100644
--- a/apigee_sync.go
+++ b/apigee_sync.go
@@ -161,6 +161,16 @@
 			return err
 		}
 
+		/*
+		 * If the lastSequence is already newer or the same than what we got via
+		 * resp.LastSequence, Ignore it.
+		 */
+		if lastSequence != "" &&
+			getChangeStatus(lastSequence, resp.LastSequence) != 1 {
+			log.Errorf("Ignore change, already have newer changes")
+			continue
+		}
+
 		if changesRequireDDLSync(resp) {
 			log.Info("Detected DDL changes, going to fetch a new snapshot to sync...")
 			return changeServerError{
@@ -184,16 +194,35 @@
 			log.Debugf("No Changes detected for Scopes: %s", scopes)
 		}
 
-		if lastSequence != resp.LastSequence {
-			lastSequence = resp.LastSequence
-			err := updateLastSequence(resp.LastSequence)
-			if err != nil {
-				log.Panic("Unable to update Sequence in DB")
-			}
-		}
+		updateSequence(resp.LastSequence)
 	}
 }
 
+/*
+ * seqCurr.Compare() will return 1, if its newer than seqPrev,
+ * else will return 0, if same, or -1 if older.
+ */
+func getChangeStatus(lastSeq string, currSeq string) int {
+	seqPrev, err := common.ParseSequence(lastSeq)
+	if err != nil {
+		log.Panic("Unable to parse previous sequence string")
+	}
+	seqCurr, err := common.ParseSequence(currSeq)
+	if err != nil {
+		log.Panic("Unable to parse current sequence string")
+	}
+	return seqCurr.Compare(seqPrev)
+}
+
+func updateSequence(seq string) {
+	lastSequence = seq
+	err := updateLastSequence(seq)
+	if err != nil {
+		log.Panic("Unable to update Sequence in DB")
+	}
+
+}
+
 func changesRequireDDLSync(changes common.ChangeList) bool {
 
 	return !mapIsSubset(knownTables, extractTablesFromChangelist(changes))
diff --git a/apigee_sync_test.go b/apigee_sync_test.go
index 12198e9..f5142d2 100644
--- a/apigee_sync_test.go
+++ b/apigee_sync_test.go
@@ -11,7 +11,7 @@
 
 	It("should bootstrap from local DB if present", func(done Done) {
 
-		expectedTables := make(map[string] bool)
+		expectedTables := make(map[string]bool)
 		expectedTables["kms.company"] = true
 		expectedTables["edgex.apid_cluster"] = true
 		expectedTables["edgex.data_scope"] = true
@@ -71,4 +71,14 @@
 		})
 		testMock.forceNewSnapshot()
 	})
+
+	It("Verify the Sequence Number Logic works as expected", func() {
+		Expect(getChangeStatus("1.1.1", "1.1.2")).To(Equal(1))
+		Expect(getChangeStatus("1.1.1", "1.2.1")).To(Equal(1))
+		Expect(getChangeStatus("1.2.1", "1.2.1")).To(Equal(0))
+		Expect(getChangeStatus("1.2.1", "1.2.2")).To(Equal(1))
+		Expect(getChangeStatus("2.2.1", "1.2.2")).To(Equal(-1))
+		Expect(getChangeStatus("2.2.1", "2.2.0")).To(Equal(-1))
+	})
+
 })