discover.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. const axios = require('axios')
  2. const debug = require('debug')('discovery::discover')
  3. const stripEndingSlash = require('@joystream/util/stripEndingSlash')
  4. const ipfs = require('ipfs-http-client')('localhost', '5001', { protocol: 'http' })
  5. function inBrowser() {
  6. return typeof window !== 'undefined'
  7. }
  8. var activeDiscoveries = {};
  9. var accountInfoCache = {};
  10. const CACHE_TTL = 60 * 60 * 1000;
  11. async function getIpnsIdentity (actorAccountId, runtimeApi) {
  12. // lookup ipns identity from chain corresponding to actorAccountId
  13. const info = await runtimeApi.discovery.getAccountInfo(actorAccountId)
  14. if (info == null) {
  15. // no identity found on chain for account
  16. return null
  17. } else {
  18. return info.identity.toString()
  19. }
  20. }
  21. async function discover_over_ipfs_http_gateway(actorAccountId, runtimeApi, gateway) {
  22. let isActor = await runtimeApi.identities.isActor(actorAccountId)
  23. if (!isActor) {
  24. throw new Error('Cannot discover non actor account service info')
  25. }
  26. const identity = await getIpnsIdentity(actorAccountId, runtimeApi)
  27. gateway = gateway || 'http://localhost:8080'
  28. const url = `${gateway}/ipns/${identity}`
  29. const response = await axios.get(url)
  30. return response.data
  31. }
  32. async function discover_over_joystream_discovery_service(actorAccountId, runtimeApi, discoverApiEndpoint) {
  33. let isActor = await runtimeApi.identities.isActor(actorAccountId)
  34. if (!isActor) {
  35. throw new Error('Cannot discover non actor account service info')
  36. }
  37. const identity = await getIpnsIdentity(actorAccountId, runtimeApi)
  38. if (identity == null) {
  39. // dont waste time trying to resolve if no identity was found
  40. throw new Error('no identity to resolve');
  41. }
  42. if (!discoverApiEndpoint) {
  43. // Use bootstrap nodes
  44. let discoveryBootstrapNodes = await runtimeApi.discovery.getBootstrapEndpoints()
  45. if (discoveryBootstrapNodes.length) {
  46. discoverApiEndpoint = stripEndingSlash(discoveryBootstrapNodes[0].toString())
  47. } else {
  48. throw new Error('No known discovery bootstrap nodes found on network');
  49. }
  50. }
  51. const url = `${discoverApiEndpoint}/discover/v0/${actorAccountId}`
  52. // should have parsed if data was json?
  53. const response = await axios.get(url)
  54. return response.data
  55. }
  56. async function discover_over_local_ipfs_node(actorAccountId, runtimeApi) {
  57. let isActor = await runtimeApi.identities.isActor(actorAccountId)
  58. if (!isActor) {
  59. throw new Error('Cannot discover non actor account service info')
  60. }
  61. const identity = await getIpnsIdentity(actorAccountId, runtimeApi)
  62. const ipns_address = `/ipns/${identity}/`
  63. debug('resolved ipns to ipfs object')
  64. let ipfs_name = await ipfs.name.resolve(ipns_address, {
  65. recursive: false, // there should only be one indirection to service info file
  66. nocache: false,
  67. }) // this can hang forever!? can we set a timeout?
  68. debug('getting ipfs object', ipfs_name)
  69. let data = await ipfs.get(ipfs_name) // this can sometimes hang forever!?! can we set a timeout?
  70. // there should only be one file published under the resolved path
  71. let content = data[0].content
  72. // verify information and if 'discovery' service found
  73. // add it to our list of bootstrap nodes
  74. // TODO cache result or flag
  75. return JSON.parse(content)
  76. }
  77. async function discover (actorAccountId, runtimeApi, useCachedValue = false, maxCacheAge = 0) {
  78. const id = actorAccountId.toString();
  79. const cached = accountInfoCache[id];
  80. if (cached && useCachedValue) {
  81. if (maxCacheAge > 0) {
  82. // get latest value
  83. if (Date.now() > (cached.updated + maxCacheAge)) {
  84. return _discover(actorAccountId, runtimeApi);
  85. }
  86. }
  87. // refresh if cache is stale, new value returned on next cached query
  88. if (Date.now() > (cached.updated + CACHE_TTL)) {
  89. _discover(actorAccountId, runtimeApi);
  90. }
  91. // return best known value
  92. return cached.value;
  93. } else {
  94. return _discover(actorAccountId, runtimeApi);
  95. }
  96. }
  97. function createExternallyControlledPromise() {
  98. let resolve, reject;
  99. const promise = new Promise((_resolve, _reject) => {
  100. resolve = _resolve;
  101. reject = _reject;
  102. });
  103. return ({ resolve, reject, promise });
  104. }
  105. async function _discover(actorAccountId, runtimeApi) {
  106. const id = actorAccountId.toString();
  107. const discoveryResult = activeDiscoveries[id];
  108. if (discoveryResult) {
  109. debug('discovery in progress waiting for result for',id);
  110. return discoveryResult
  111. }
  112. debug('starting new discovery for', id);
  113. const deferredDiscovery = createExternallyControlledPromise();
  114. activeDiscoveries[id] = deferredDiscovery.promise;
  115. let result;
  116. try {
  117. if (inBrowser()) {
  118. result = await discover_over_joystream_discovery_service(actorAccountId, runtimeApi)
  119. } else {
  120. result = await discover_over_local_ipfs_node(actorAccountId, runtimeApi)
  121. }
  122. debug(result)
  123. result = JSON.stringify(result)
  124. accountInfoCache[id] = {
  125. value: result,
  126. updated: Date.now()
  127. };
  128. deferredDiscovery.resolve(result);
  129. delete activeDiscoveries[id];
  130. return result;
  131. } catch (err) {
  132. debug(err.message);
  133. deferredDiscovery.reject(err);
  134. delete activeDiscoveries[id];
  135. throw err;
  136. }
  137. }
  138. module.exports = {
  139. discover,
  140. discover_over_joystream_discovery_service,
  141. discover_over_ipfs_http_gateway,
  142. discover_over_local_ipfs_node,
  143. }