Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 47x 47x 47x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 46x 93x 231x 231x 231x 231x 231x 231x 93x 93x 231x 7x 231x 66x 66x 66x 66x 66x 2x 66x 66x 66x 66x 66x 80x 2x 50x 50x 1x 49x 49x 49x 49x 14x 49x 49x 49x 4x 90x 90x 4x 90x 44x 44x 48x 48x 48x 48x 47x 47x 47x 47x 47x 48x 48x 1x 1x 67x 67x 67x 67x 67x 57x 57x 57x 57x 67x 2x 67x 67x 67x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 2x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 45x 45x 45x 45x 45x 55x 55x 2x 2x 2x 55x 46x 46x 46x 91x 45x 45x 45x 91x 45x 45x 46x 46x 46x 46x 91x 45x 45x | import EventSource from 'eventsource'
import Environment from './environment'
import {logger} from './logger'
import LRU from './lru'
import Router from './router'
import Stat from './stat'
import {version} from '../package.json'
import * as http from 'http'
import * as https from 'https'
import * as URL from 'url'
// Default API domain
const DEFAULT_API_DOMAIN = 'airshiphq.com'
// Primary API endpoints
const IDENTIFY_ENDPOINT = `/v2/identify`
const GATING_INFO_ENDPOINT = `/v2/gating-info`
// SSE API endpoints
const SSE_GATING_INFO_ENDPOINT = `/v2/sse-events`
// Backup API URL & endpoint
const BACKUP_URL = 'https://backup-api.airshiphq.com'
const BACKUP_GATING_INFO_ENDPOINT = `${BACKUP_URL}/v2/gating-info`
const REQUEST_TIMEOUT = 10 * 1000
// Default ingestion parameters
const DEFAULT_INGESTION_INTERVAL = 30
const DEFAULT_BROWSER_INGESTION_INTERVAL = 15
const DEFAULT_INGESTION_MAX_ITEMS = 500
const DEFAULT_BROWSER_INGESTION_MAX_ITEMS = 5
export default class Airship extends Environment {
constructor(gatingInfoListener) {
super()
this.gatingInfoListener = gatingInfoListener
this.init()
}
init() {
this.ingestionMaxItems = DEFAULT_INGESTION_MAX_ITEMS
this.ingestionInterval = DEFAULT_INGESTION_INTERVAL * 1000
// eslint-disable-next-line no-undef
Eif (__BROWSER__) {
this.ingestionMaxItems = DEFAULT_BROWSER_INGESTION_MAX_ITEMS
this.ingestionInterval = DEFAULT_BROWSER_INGESTION_INTERVAL * 1000
}
this.objects = []
this.stats = []
this.exposures = []
this.flags = new Set()
this.oldFlags = new Set()
this.objectLRUCache = new LRU(500)
this.firstIngestion = true
this.shouldIngestObjects = true
this.shouldIngestStats = true
this.shouldIngestExposures = true
this.shouldIngestFlags = true
this.restartIngestionWorker()
}
restartIngestionWorker() {
if (this.ingestionWorker) {
clearInterval(this.ingestionWorker)
}
this.ingestionWorker = setInterval(() => {
this.maybeIngest(true)
}, this.ingestionInterval)
}
async maybeIngest(force = false) {
Iif (!this.shouldIngestObjects) {
this.objects = []
}
Iif (!this.shouldIngestStats) {
this.stats = []
}
Iif (!this.shouldIngestExposures) {
this.exposures = []
}
Iif (!this.shouldIngestFlags) {
this.flags = new Set()
}
let shouldIngest =
force ||
(this.objects.length >= this.ingestionMaxItems ||
this.stats.length >= this.ingestionMaxItems ||
this.exposures.length >= this.ingestionMaxItems ||
this.flags.size > 0)
if (this.firstIngestion) {
shouldIngest = shouldIngest || this.objects.length > 0
this.firstIngestion = !shouldIngest
}
if (
this.objects.length === 0 &&
this.stats.length === 0 &&
this.exposures.length === 0 &&
this.flags.size === 0
) {
shouldIngest = false
}
if (shouldIngest) {
const objects = this.objects
const stats = this.stats
const exposures = this.exposures
const flags = Array.from(this.flags)
flags.forEach(flagName => {
this.oldFlags.add(flagName)
})
this.objects = []
this.stats = []
this.exposures = []
this.flags = new Set()
await this.postContent(
this.primaryServerUrl + IDENTIFY_ENDPOINT + '/' + this.envKey,
JSON.stringify({
objects: objects,
stats: stats.map(s => s.getStatsObj()).filter(so => so !== null),
exposures: exposures,
flags: flags,
sdkInfo: {
name: '__SDK_NAME__',
version: version
}
})
).catch(err => {
logger(err)
})
}
}
_identifyObject(obj) {
const airshipObj = Environment.prototype._identifyObject.call(this, obj)
if (!airshipObj.isValid()) {
return airshipObj
}
const id = airshipObj.getId()
const hash = airshipObj.getHash()
const storedHash = this.objectLRUCache.get(id)
if (storedHash === null || hash !== storedHash) {
this.objects.push(airshipObj.getRawObject())
}
this.objectLRUCache.set(id, hash)
this.maybeIngest()
return airshipObj
}
_compactStats() {
this.stats = Stat.compactStats(this.stats)
}
_saveStat(stat) {
this.stats.push(stat)
if (this.stats.length >= this.ingestionMaxItems) {
this._compactStats()
}
this.maybeIngest()
}
_saveExposure(expo) {
this.exposures.push(expo)
this.maybeIngest()
}
async publish(objs) {
if (!Array.isArray(objs)) {
logger('The "publish" method takes an array of objects (aka entities).')
return
}
objs.forEach(obj => {
this._identifyObject(obj)
})
await this.maybeIngest(true)
}
getContent(url, timeout = REQUEST_TIMEOUT) {
return new Promise((resolve, reject) => {
const urlObj = URL.parse(url)
const lib = urlObj.protocol === 'https:' ? https : http
const request = lib.get(url, response => {
Iif (response.statusCode < 200 || response.statusCode > 299) {
reject('Failed to load page, status code: ' + response.statusCode)
}
const body = []
response.on('data', chunk => body.push(chunk))
response.on('end', () => {
resolve(body.join(''))
})
})
request.on('error', err => reject(err))
request.setTimeout(timeout, () => {
request.abort()
reject('Request timed out')
})
})
}
postContent(
url,
data,
contentType = 'application/json',
timeout = REQUEST_TIMEOUT
) {
return new Promise((resolve, reject) => {
const urlObj = URL.parse(url)
const lib = urlObj.protocol === 'https:' ? https : http
const options = {
protocol: urlObj.protocol,
hostname: urlObj.hostname,
port: urlObj.port,
path: urlObj.path,
method: 'POST',
headers: {
'Content-Type': contentType,
'Content-Length': Buffer.byteLength(data)
}
}
const request = lib.request(options, response => {
Iif (response.statusCode < 200 || response.statusCode > 299) {
reject('Failed to post to url, status code: ' + response.statusCode)
}
const body = []
response.on('data', chunk => body.push(chunk))
response.on('end', () => resolve(body.join('')))
})
request.on('error', err => {
reject(err)
})
request.setTimeout(timeout, () => {
request.abort()
reject('Request timed out')
})
request.write(data)
request.end()
})
}
async _getGatingInfo() {
const body = await this.getContent(
`${this.primaryServerUrl}${GATING_INFO_ENDPOINT}/${
this.envKey
}?casing=camel`
)
return JSON.parse(body)
}
async _getBackupGatingInfo() {
const body = await this.getContent(
`${BACKUP_GATING_INFO_ENDPOINT}/${this.envKey}-camel`
)
return JSON.parse(body)
}
updateSDK() {
const ingestionMaxItems = this.router.getIngestionMaxItem()
const browserIngestionMaxItems = this.router.getBrowserIngestionMaxItems()
const ingestionInterval = this.router.getIngestionInterval()
const browserIngestionInterval = this.router.getBrowserIngestionInterval()
const shouldIngestObjects = this.router.getShouldIngestObjects()
const shouldIngestStats = this.router.getShouldIngestStats()
const shouldIngestExposures = this.router.getShouldIngestExposures()
const shouldIngestFlags = this.router.getShouldIngestFlags()
// eslint-disable-next-line no-undef
Eif (__BROWSER__) {
// Use SDK info's browserIngestionMaxItems threshold instead (if it exists)
Iif (
typeof browserIngestionMaxItems === 'number' &&
browserIngestionMaxItems > 0
) {
this.ingestionMaxItems = browserIngestionMaxItems
this.restartIngestionWorker()
}
// Use SDK info's ingestionInterval instead (if it exists)
Iif (
typeof browserIngestionInterval === 'number' &&
browserIngestionInterval > 0 &&
browserIngestionInterval != this.ingestionInterval
) {
this.ingestionInterval = browserIngestionInterval
this.restartIngestionWorker()
}
} else {
// Use SDK info's ingestionMaxItem threshold instead (if it exists)
if (typeof ingestionMaxItems === 'number' && ingestionMaxItems > 0) {
this.ingestionMaxItems = ingestionMaxItems
this.restartIngestionWorker()
}
// Use SDK info's ingestionInterval instead (if it exists)
if (
typeof ingestionInterval === 'number' &&
ingestionInterval > 0 &&
ingestionInterval != this.ingestionInterval
) {
this.ingestionInterval = ingestionInterval
this.restartIngestionWorker()
}
}
// Check if SDK info directs SDK to ingest entities
Iif (typeof shouldIngestObjects === 'boolean') {
this.shouldIngestObjects = shouldIngestObjects
}
// Check if SDK info directs SDK to ingest stats
Iif (typeof shouldIngestStats === 'boolean') {
this.shouldIngestStats = shouldIngestStats
}
// Check if SDK info directs SDK to ingest exposures
Iif (typeof shouldIngestExposures === 'boolean') {
this.shouldIngestExposures = shouldIngestExposures
}
// Check if SDK info directs SDK to ingest flags
Iif (typeof shouldIngestFlags === 'boolean') {
this.shouldIngestFlags = shouldIngestFlags
}
}
async updateGatingInfo(statName, fetchFn) {
try {
const stat = new Stat(statName, Stat.TYPE_DURATION)
stat.start()
const result = await fetchFn()
const gatingInfo = result
this.router = new Router(gatingInfo)
this.updateSDK()
if (this.gatingInfoListener) {
this.gatingInfoListener(gatingInfo)
}
stat.stop()
this._saveStat(stat)
} catch (err) {
logger(err)
return false
}
return true
}
async configure(
envKey,
subscribeToUpdates = true,
apiDomain = DEFAULT_API_DOMAIN
) {
const envKeyRegex = /^[a-z0-9]{16}$/
Iif (!envKey.match(envKeyRegex)) {
throw 'options["envKey"] should be a string of lowercase characters and digits. Double check on the Airship web app.'
}
this.envKey = envKey
this.subscribeToUpdates = subscribeToUpdates
this.primaryServerUrl = `https://api.${apiDomain}`
this.sseServerUrl = `https://sse.${apiDomain}`
this.init()
this.failed = false
// First try the Airship server
Iif (
!(await this.updateGatingInfo(
'duration__gating_info',
this._getGatingInfo.bind(this)
))
) {
// Then try the Airship CloudFront distribution
this.failed = !(await this.updateGatingInfo(
'duration__cloudfront_gating_info',
this._getBackupGatingInfo.bind(this)
))
}
Iif (this.failed) {
throw 'Failed to retrieve initial gating information'
}
Eif (subscribeToUpdates) {
this._subscribeToUpdates()
this._policeSSE()
}
}
async shutdown() {
Eif (this.ingestionWorker) {
clearInterval(this.ingestionWorker)
}
this._unpoliceSSE()
this._unsubscribeFromUpdates()
await this.maybeIngest(true)
}
flag(flagName) {
const flag = Environment.prototype.flag.call(this, flagName)
if (flag.isWild()) {
// Register the new uncategorized flag
Eif (!this.oldFlags.has(flagName)) {
this.flags.add(flagName)
this.maybeIngest()
}
}
return flag
}
_policeSSE() {
this._unpoliceSSE()
this.policeSSEInterval = setInterval(() => {
const now = Date.now()
const then = this.lastSSEConnectTimestamp || 0
if ((now - then) / 1000 > 30) {
logger(
'Did not receive a keepalive for more than 30 seconds. Reconnecting.'
)
this._subscribeToUpdates()
}
}, 5 * 1000)
this.pollGatingInfoInterval = setInterval(() => {
const now = Date.now()
const then = this.lastSSEConnectTimestamp || 0
if ((now - then) / 1000 > 60) {
logger(
'Did not receive a keepalive for more than 30 seconds. Polling gating info.'
)
this.updateGatingInfo(
'duration__cloudfront_gating_info',
this._getBackupGatingInfo.bind(this)
).then(
() => logger('Polled gating info from CloudFront'),
() => logger('Failed polling gating info from CloudFront')
)
}
}, 60 * 1000)
}
_unpoliceSSE() {
if (this.policeSSEInterval) {
clearInterval(this.policeSSEInterval)
delete this.policeSSEInterval
Iif (this.lastSSEConnectTimestamp) {
delete this.lastSSEConnectTimestamp
}
}
if (this.pollGatingInfoInterval) {
clearInterval(this.pollGatingInfoInterval)
delete this.pollGatingInfoInterval
}
}
_subscribeToUpdates() {
this._unsubscribeFromUpdates()
this.eventSource = new EventSource(
`${this.sseServerUrl}${SSE_GATING_INFO_ENDPOINT}?envkey=${
this.envKey
}&casing=camel`
)
this.eventSource.addEventListener('gatingInfoUpdate', evt => {
const gatingInfo = JSON.parse(evt.data)
this.router = new Router(gatingInfo)
this.updateSDK()
if (this.gatingInfoListener) {
this.gatingInfoListener(gatingInfo)
}
this.lastSSEConnectTimestamp = Date.now()
})
this.eventSource.addEventListener('keepalive', () => {
this.lastSSEConnectTimestamp = Date.now()
})
}
_unsubscribeFromUpdates() {
if (this.eventSource) {
this.eventSource.close()
delete this.eventSource
}
}
}
|