|
| 1 | +const dgraph = require('dgraph-js'); |
| 2 | +const grpc = require('grpc'); |
| 3 | +const twitter = require('twitter'); |
| 4 | + |
| 5 | +const creds = require('./credentials.json'); |
| 6 | +const client = new twitter(creds); |
| 7 | + |
| 8 | +const ALPHA_ADDR = process.env.ALPHA_ADDR || "localhost:9080" |
| 9 | +const LOG_INTERVAL_TIME = process.env.LOG_INTERVAL_TIME || 2000; |
| 10 | +const startStatus = new Date().getTime(); |
| 11 | + |
| 12 | +let lastStatus = 0; |
| 13 | +let retry = true; |
| 14 | +let failureCount = 0; |
| 15 | +let totalTweets = 0; |
| 16 | +let oldTotalTweets = 0; |
| 17 | +let retryCount = 0; |
| 18 | +let errorCount = 0; |
| 19 | + |
| 20 | +const dgraphClientStub = new dgraph.DgraphClientStub(ALPHA_ADDR, grpc.credentials.createInsecure()); |
| 21 | +const dgraphClient = new dgraph.DgraphClient(dgraphClientStub); |
| 22 | + |
| 23 | +async function setSchema() { |
| 24 | + const schema = ` |
| 25 | + type Tweet { |
| 26 | + id_str: string |
| 27 | + created_at: dateTime |
| 28 | + message: string |
| 29 | + urls: [string] |
| 30 | + hashtags: [string] |
| 31 | + author: [User] |
| 32 | + mention: [User] |
| 33 | + retweet: bool |
| 34 | + } |
| 35 | +
|
| 36 | + type User { |
| 37 | + user_id: string |
| 38 | + user_name: string |
| 39 | + screen_name: string |
| 40 | + description: string |
| 41 | + friends_count: int |
| 42 | + verified: bool |
| 43 | + profile_banner_url: string |
| 44 | + profile_image_url: string |
| 45 | + } |
| 46 | +
|
| 47 | + user_id: string @index(exact) . |
| 48 | + user_name: string @index(hash) . |
| 49 | + screen_name: string @index(term) . |
| 50 | + id_str: string @index(exact) . |
| 51 | + created_at: dateTime @index(hour) . |
| 52 | + urls: [string] @index(term) . |
| 53 | + hashtags: [string] @index(exact) . |
| 54 | + mention: [uid] @count @reverse . |
| 55 | + author: [uid] @count @reverse . |
| 56 | + `; |
| 57 | + const op = new dgraph.Operation(); |
| 58 | + op.setSchema(schema) |
| 59 | + await dgraphClient.alter(op); |
| 60 | +} |
| 61 | + |
| 62 | +async function upsertData(jsonObj, query) { |
| 63 | + try { |
| 64 | + const mu = new dgraph.Mutation(); |
| 65 | + mu.setSetJson(jsonObj); |
| 66 | + |
| 67 | + const req = new dgraph.Request(); |
| 68 | + req.setMutationsList([mu]); |
| 69 | + req.setQuery(query); |
| 70 | + req.setCommitNow(true); |
| 71 | + |
| 72 | + await dgraphClient.newTxn().doRequest(req); |
| 73 | + } catch (err) { |
| 74 | + const errMsg = err.message; |
| 75 | + if (errMsg.includes('connection refused')) { |
| 76 | + // wait for alpha to restart |
| 77 | + console.log('ERROR Connection refused... waiting a bit'); |
| 78 | + await wait(5000); |
| 79 | + } else if (errMsg.includes('already been committed or discarded')) { |
| 80 | + failureCount += 1; |
| 81 | + } else if (retry && errMsg.includes('Please retry')) { |
| 82 | + retryCount += 1; |
| 83 | + await wait(100); |
| 84 | + retry = false; |
| 85 | + await upsertData(jsonObj, query); |
| 86 | + } else { |
| 87 | + errorCount += 1; |
| 88 | + console.log(`ERROR Unable to commit.\n${err}\n`); |
| 89 | + } |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +async function filterTweet(tweet) { |
| 94 | + const userMentions = []; |
| 95 | + const usersObject = []; |
| 96 | + usersObject[tweet.user.id_str] = 'uid(u)'; |
| 97 | + tweet.entities.user_mentions.forEach((element, index) => { |
| 98 | + let uid; |
| 99 | + if (usersObject[element.id_str] != undefined) { |
| 100 | + uid = usersObject[element.id_str]; |
| 101 | + } else { |
| 102 | + uid = `uid(m${index+1})`; |
| 103 | + usersObject[element.id_str] = uid; |
| 104 | + } |
| 105 | + userMentions.push({ |
| 106 | + 'uid': uid, |
| 107 | + 'user_id': element.id_str, |
| 108 | + 'dgraph.type': 'User', |
| 109 | + 'user_name': element.name, |
| 110 | + 'screen_name': element.screen_name, |
| 111 | + }); |
| 112 | + }); |
| 113 | + const hashtags = []; |
| 114 | + tweet.entities.hashtags.forEach((element) => { |
| 115 | + hashtags.push(element.text); |
| 116 | + }); |
| 117 | + const author = { |
| 118 | + 'uid': `uid(u)`, |
| 119 | + 'user_id': tweet.user.id_str, |
| 120 | + 'dgraph.type': 'User', |
| 121 | + 'user_name': tweet.user.name, |
| 122 | + 'screen_name': tweet.user.screen_name, |
| 123 | + 'description': tweet.user.description, |
| 124 | + 'friends_count': tweet.user.friends_count, |
| 125 | + 'followers_count': tweet.user.followers_count, |
| 126 | + 'verified': tweet.user.verified, |
| 127 | + 'profile_banner_url': tweet.user.profile_banner_url, |
| 128 | + 'profile_image_url': tweet.user.profile_image_url, |
| 129 | + }; |
| 130 | + const userObj = { |
| 131 | + 'uid': `uid(t)`, |
| 132 | + 'id_str': tweet.id_str, |
| 133 | + 'dgraph.type': 'Tweet', |
| 134 | + 'created_at': new Date(tweet.created_at), |
| 135 | + 'message': tweet.text, |
| 136 | + 'urls': tweet.urls, |
| 137 | + 'hashtags': hashtags, |
| 138 | + 'mention': userMentions, |
| 139 | + 'author': author, |
| 140 | + }; |
| 141 | + return userObj; |
| 142 | +} |
| 143 | + |
| 144 | +async function buildQuery(tweet) { |
| 145 | + const usersObject = []; |
| 146 | + const query = []; |
| 147 | + |
| 148 | + query.push(`t as var(func: eq(id_str, "${tweet.id_str}"))`); |
| 149 | + query.push(`u as var(func: eq(user_id, "${tweet.author.user_id}"))`); |
| 150 | + |
| 151 | + usersObject[tweet.author.user_id] = 'u'; |
| 152 | + |
| 153 | + tweet.mention.forEach((element, index) => { |
| 154 | + let name; |
| 155 | + if (usersObject[element.user_id] != undefined) { |
| 156 | + name = usersObject[element.user_id]; |
| 157 | + } else { |
| 158 | + name = `m${index+1}`; |
| 159 | + query.push(`${name} as var(func: eq(user_id, ${element.user_id}))`); |
| 160 | + usersObject[element.user_id] = name; |
| 161 | + } |
| 162 | + }); |
| 163 | + |
| 164 | + const finalQuery = `query {${query.join('\n')}}`; |
| 165 | + return finalQuery; |
| 166 | +} |
| 167 | + |
| 168 | +function reportStats() { |
| 169 | + const now = new Date().getTime(); |
| 170 | + // tslint:disable-next-line no-console |
| 171 | + console.log(`STATS Tweets: ${totalTweets}, Failues: ${failureCount}, Retries: ${retryCount}, \ |
| 172 | +Errors: ${errorCount}, Commit Rate: ${(totalTweets-oldTotalTweets)/(LOG_INTERVAL_TIME/1000)} Total Time: ${now - startStatus} ms`); |
| 173 | + oldTotalTweets = totalTweets; |
| 174 | +} |
| 175 | + |
| 176 | +async function wait(time) { |
| 177 | + return new Promise((resolve) => { |
| 178 | + const id = setTimeout( |
| 179 | + () => { |
| 180 | + clearTimeout(id); |
| 181 | + resolve(); |
| 182 | + }, |
| 183 | + time, |
| 184 | + ); |
| 185 | + }); |
| 186 | +} |
| 187 | + |
| 188 | +async function main() { |
| 189 | + await setSchema(); |
| 190 | + setInterval(reportStats, LOG_INTERVAL_TIME); |
| 191 | + client.stream('statuses/sample.json', function(stream) { |
| 192 | + stream.on('data', async function(tweet) { |
| 193 | + totalTweets += 1; |
| 194 | + const tweetObj = await filterTweet(tweet); |
| 195 | + const queries = await buildQuery(tweetObj); |
| 196 | + retry = true; |
| 197 | + await upsertData(tweetObj, queries); |
| 198 | + }); |
| 199 | + stream.on('error', function(error) { |
| 200 | + console.log(error); |
| 201 | + }); |
| 202 | + }); |
| 203 | +} |
| 204 | + |
| 205 | +main().then(() => { |
| 206 | + console.log(`\nReporting stats every ${LOG_INTERVAL_TIME/1000} seconds\n`) |
| 207 | +}).catch((e) => { |
| 208 | + console.log(e); |
| 209 | +}); |
0 commit comments