loading
index.js
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
Fabric = require('jsc8')
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlHttp = new XMLHttpRequest();

// Define URLs
const fed_url = "https://gdn1.macrometa.io"
const fed_url_west = "https://gdn1-sfo2.prod.macrometa.io"
const fed_url_eastcoast = "https://gdn1-nyc1.prod.macrometa.io"
const fed_url_europe = "https://gdn1-fra1.prod.macrometa.io"
const fed_url_asia = "https://gdn1-blr1.prod.macrometa.io"

// Variables
const guest_password = "guest1"
const geo_fabric = "guest1"
const guest_email = "[email protected]"
const keys = ["dogs", "cats", "birds", "books", "business", "trees", "forests", "lakes"]

//---------------------------------------------------------------
// Cache class to utilize GDN for serving data from edge
//--------------------------------------------------------------
class Cache {
  // Create a collection in GDN (if not exists) to act as Cache
  constructor(fabric) {
    this.fabric = fabric;
    (async () => {
      this.cache =  fabric.collection('cache');
      const result = await this.cache.exists();
      if (!result) {
        await fabric.collection('cache');
      }
    })();

  }
  // Read from cache.
  async get(key) {
    try {
      const handle = await this.cache.document(key);
      return handle
    }
    catch{
      return null

    }
  }
  // Write to cache. The writes are automatically geo replicated.
  async set(key, doc, ttl = 0) {
    let res = await this.cache.documentExists(key)
    if (res) {
      //const docHandle = this.cache.document(key)
      await this.cache.replace(key, doc)
    }
    else {
      await this.cache.save(doc)
    }
    return true;
  }
  // Purge the cache. The purge is automatically geo replicated.
  async purge(keys) {
    try {
      for (let key of keys) {
            await this.cache.remove(key)
        }
    }catch{
      return false;
    }
    return true;
  }
}

//---------------------------------------------------------
// Code to Read & Write from Origin (i.e., from Cloud)
//----------------------------------------------------------
// Read from Origin
function get_from_origin_db(key) {
  let document = {}
  const url = "https://openlibrary.org/subjects/" + key + ".json?limit=0"

  xmlHttp.open("GET", url, false); // false for synchronous request
  xmlHttp.send()
  r = xmlHttp.responseText;
  document = JSON.parse(r)
  document["_key"] = key
  return document
}
// Write to Origin
function write_to_origin_db(document) {
  // Write to Origin DB
  console.log("writing to origin database..")
  return true;
}

//------------------------------------------
// Utilize GDN as edge cache for serving reads & writes. Following is the behavior of the main() method:
// 1. For First time reads, 
//       Gets data from OriginDB. Populates GDN transparently.
// 2. For subsequent reads from same region,
//       Serves data from the GDN directly.
// 3. For subsequent reads from other regions,
//       Serves data from the GDN directly. 
// 4. For writes, 
//       Invalidates the Cache globally in realtime
//       Writes to Origin
//       Updates the Cache globally in realtime.
// 5. For subsequent reads from other regions,
//       Serves data from the GDN directly. 
//------------------------------------------
async function main() {

  // Login to GDN and Create cache (if not exists)
  fabric = new Fabric(fed_url)
  await fabric.login(guest_email, guest_password)
  await fabric.useFabric(geo_fabric)
  const cache = new Cache(fabric)

  //Clean Cache from previous runs
  await cache.purge(keys);

  // Use Macrometa GDN as Cache for Remote Origin Database
  console.log("----------------------\n1. First time access:\n----------------------")

  var before = Date.now();
  for (let key of keys) {
    doc = await cache.get(key)
    if (doc == null) {
      console.log("CACHE_MISS: get from remote origin database...")
      doc = await get_from_origin_db(key)
      cache.set(key, doc)
    }
    else {
      console.log("CACHE_HIT: get from closest region cache...")
    }

  }
  console.log("\n------- Execution Time: " + (Date.now()-before) + "ms  (from Origin) -------\n")

  // 2nd time access served from GDN edge cache.
  console.log("----------------------\n2. Second time access:\n----------------------")
  before = Date.now();
  for (key of keys) {
    doc = await cache.get(key)
    if (doc == null) {
      console.log("CACHE_MISS: get from remote origin database...")
      doc = get_from_origin_db(key)
      cache.set(key, doc)
    }
    else {
      console.log("CACHE_HIT: get from closest region cache...")
    }
  }
   console.log("\n------- Execution Time: " + (Date.now()-before) + "ms  (from Closest Cache)-------\n")

  // GDN Cache Geo replication in action... US West Coast
  console.log("------------------------------\n3a. Access from US_WEST_COAST:\n------------------------------")
  fabric = new Fabric(fed_url_west)
  await fabric.login(guest_email, guest_password)
  await fabric.useFabric(geo_fabric)
  cache3a = new Cache(fabric)

  var before = Date.now();
  for (key of keys) {
    doc = await cache3a.get(key)
    if (doc == null) {
      console.log("CACHE_MISS: get from remote origin database...")
      doc = get_from_origin_db(key)
      cache3a.set(key, doc)
    }
    else {
      console.log("CACHE_HIT: doc_id:" + doc._id)
    }
  }
  console.log("\n------- Execution Time: " + (Date.now()-before) + "ms  (from US_WEST_COAST Cache) -------\n")


  // GDN Cache Geo replication in action... US East Coast
  console.log("------------------------------\n3b. Access from US_EAST_COAST:\n------------------------------")
  fabric = new Fabric(fed_url_eastcoast)
  await fabric.login(guest_email, guest_password)
  await fabric.useFabric(geo_fabric)
  cache3b = new Cache(fabric)

  var before = Date.now();
  for (key of keys) {
    doc = await cache3b.get(key)
    if (doc == null) {
      console.log("CACHE_MISS: get from remote origin database...")
      doc = get_from_origin_db(key)
      cache3b.set(key, doc)
    }
    else {
      console.log("CACHE_HIT: doc_id:" + doc._id)
    }
  }
  console.log("\n------- Execution Time: " + (Date.now()-before) + "ms (from US_EAST_COAST Cache) -------\n")

  // GDN Cache Geo replication in action... Europe
  console.log("------------------------------\n3c. Access from EUROPE:\n------------------------------")
  fabric = new Fabric(fed_url_europe)
  await fabric.login(guest_email, guest_password)
  await fabric.useFabric(geo_fabric)
  cache3c = new Cache(fabric)

  var before = Date.now();
  for (key of keys) {
    doc = await cache3c.get(key)
    if (doc == null) {
      console.log("CACHE_MISS: get from remote origin database...")
      doc = get_from_origin_db(key)
      cache3c.set(key, doc)
    }
    else {
      console.log("CACHE_HIT: doc_id:" + doc._id)
    }
  }
  console.log("\n------- Execution Time: " + (Date.now()-before) + "ms  (from EUROPE Cache)-------\n")

  // GDN Cache Geo replication in action... Asia
  console.log("------------------------------\n3c. Access from ASIA:\n------------------------------")
  fabric = new Fabric(fed_url_asia)
  await fabric.login(guest_email, guest_password)
  await fabric.useFabric(geo_fabric)
  cache3d = new Cache(fabric)

  var before = Date.now();
  for (key of keys) {
    doc = await cache3d.get(key)
    if (doc == null) {
      console.log("CACHE_MISS: get from remote origin database...")
      doc = get_from_origin_db(key)
      cache3d.set(key, doc)
    }
    else {
      console.log("CACHE_HIT: doc_id:" + doc._id)
    }
  }
  console.log("\n------- Execution Time: " + (Date.now()-before) + "ms  (from ASIA Cache)-------\n")

  // Invalidate & update cache globally on writes. 
  console.log("------------------------------\n4. Writes from Edge to origin and global cache update: \n------------------------------")
  for (key of keys) {
    doc = await cache.get(key)
    doc["company"] = "macrometa"
    write_to_origin_db(doc)
    cache.set(key, doc)
  }

  console.log("------------------------------\n5. After writes... Access from EUROPE:\n------------------------------")
  for (key of keys) {
    doc = await cache3b.get(key)
    if (doc == null) {
      console.log("CACHE_MISS: get from remote origin database...")
      doc = get_from_origin_db(key)
      cache3b.set(key, doc)
    }
    else {
      console.log("CACHE_HIT: \ndoc:" + JSON.stringify(doc))
    }

  }
}

// Call main method. Starting point for the program.
main()