-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
start working in the advertisement walker
Signed-off-by: Miroslav Bajtoš <[email protected]>
- Loading branch information
Showing
12 changed files
with
582 additions
and
50 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
import createDebug from 'debug' | ||
import { assertOkResponse } from './http-assertions.js' | ||
import { CID } from 'multiformats/cid' | ||
import * as multihash from 'multiformats/hashes/digest' | ||
import { varint } from 'multiformats' | ||
import * as cbor from '@ipld/dag-cbor' | ||
|
||
/** @import { ProviderInfo, WalkerState } from './typings.js' */ | ||
/** @import { RedisRepository as Repository } from './redis-repository.js' */ | ||
|
||
const debug = createDebug('spark-piece-indexer:observer') | ||
|
||
/** | ||
* @param {string} providerId | ||
* @param {ProviderInfo} providerInfo | ||
* @param {WalkerState | undefined} currentWalkerState | ||
*/ | ||
export async function processNextAdvertisement (providerId, providerInfo, currentWalkerState) { | ||
const nextHead = providerInfo.lastAdvertisementCID | ||
|
||
/** @type {WalkerState} */ | ||
let state | ||
|
||
if (!currentWalkerState?.lastHead) { | ||
console.log('Initial walk for provider %s (%s): %s', providerId, providerInfo.providerAddress, providerInfo.lastAdvertisementCID) | ||
|
||
/** @type {WalkerState} */ | ||
state = { | ||
lastHead: nextHead, | ||
head: nextHead, | ||
tail: nextHead, | ||
status: 'placeholder' | ||
} | ||
} else { | ||
console.log('WALK NOT IMPLEMENTED YET %s %o', providerId, currentWalkerState) | ||
return {} | ||
} | ||
|
||
// if (state.tail === state.lastHead || state.tail === undefined) { | ||
// console.log('WALK FINISHED: %s %o', state) | ||
// return { } | ||
// } | ||
if (!state || !state.tail) { | ||
console.log('NOTHING TO DO for %s %o', providerId, currentWalkerState) | ||
return {} | ||
} | ||
|
||
// TODO: handle networking errors, Error: connect ENETUNREACH 154.42.3.42:3104 | ||
|
||
const { previousAdvertisementCid, ...entry } = await fetchAdvertisedPayload(providerInfo.providerAddress, state.tail) | ||
state.tail = previousAdvertisementCid | ||
state.status = `Walking the advertisements from ${state.head}, next step: ${state.tail}` | ||
|
||
const indexEntry = entry.pieceCid ? entry : undefined | ||
return { | ||
newState: state, | ||
indexEntry | ||
} | ||
} | ||
|
||
/** | ||
* @param {string} providerAddress | ||
* @param {string} advertisementCid | ||
*/ | ||
export async function fetchAdvertisedPayload (providerAddress, advertisementCid) { | ||
const advertisement = | ||
/** @type {{ | ||
Addresses: string[], | ||
ContextID: { '/': { bytes: string } }, | ||
Entries: { '/': string }, | ||
IsRm: false, | ||
Metadata: { '/': { bytes: string } }, | ||
PreviousID?: { '/': string , | ||
Provider: string | ||
Signature: { | ||
'/': { | ||
bytes: string | ||
} | ||
} | ||
}} */( | ||
await fetchCid(providerAddress, advertisementCid) | ||
) | ||
const previousAdvertisementCid = advertisement.PreviousID?.['/'] | ||
debug('advertisement %s %j', advertisementCid, advertisement) | ||
|
||
const entriesCid = advertisement.Entries['/'] | ||
const entriesChunk = | ||
/** @type {{ | ||
Entries: { '/' : { bytes: string } }[] | ||
}} */( | ||
await fetchCid(providerAddress, entriesCid) | ||
) | ||
debug('entriesChunk %s %j', entriesCid, entriesChunk.Entries.slice(0, 5)) | ||
const entryHash = entriesChunk.Entries[0]['/'].bytes | ||
const payloadCid = CID.create(1, 0x55 /* raw */, multihash.decode(Buffer.from(entryHash, 'base64'))).toString() | ||
|
||
const meta = parseMetadata(advertisement.Metadata['/'].bytes) | ||
const pieceCid = meta.deal?.PieceCID.toString() | ||
|
||
return { | ||
previousAdvertisementCid, | ||
pieceCid, | ||
payloadCid | ||
} | ||
} | ||
|
||
/** | ||
* @param {string} providerBaseUrl | ||
* @param {string} cid | ||
* @returns {Promise<unknown>} | ||
*/ | ||
async function fetchCid (providerBaseUrl, cid) { | ||
const url = new URL(cid, new URL('/ipni/v1/ad/_cid_placeholder_', providerBaseUrl)) | ||
debug('Fetching %s', url) | ||
// const res = await fetch(url) | ||
const res = await fetch(url, { signal: AbortSignal.timeout(30_000) }) | ||
await assertOkResponse(res) | ||
return await res.json() | ||
} | ||
|
||
/** | ||
* @param {string} meta | ||
*/ | ||
export function parseMetadata (meta) { | ||
const bytes = Buffer.from(meta, 'base64') | ||
const [protocolCode, nextOffset] = varint.decode(bytes) | ||
|
||
const protocol = { | ||
0x900: 'bitswap', | ||
0x910: 'graphsync', | ||
0x0920: 'http' | ||
}[protocolCode] ?? '0x' + protocolCode.toString(16) | ||
|
||
if (protocol === 'graphsync') { | ||
// console.log(bytes.subarray(nextOffset).toString('hex')) | ||
/** @type {{ | ||
PieceCID: import('multiformats/cid').CID, | ||
VerifiedDeal: boolean, | ||
FastRetrieval: boolean | ||
}} */ | ||
const deal = cbor.decode(bytes.subarray(nextOffset)) | ||
return { protocol, deal } | ||
} else { | ||
return { protocol } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import createDebug from 'debug' | ||
import { assertOkResponse } from './http-assertions.js' | ||
import { multiaddrToHttpUrl } from './vendored/multiaddr.js' | ||
|
||
const debug = createDebug('spark-piece-indexer:observer') | ||
|
||
/** @import { ProviderToInfoMap, ProviderInfo } from './typings.js' */ | ||
/** @import { RedisRepository as Repository } from './redis-repository.js' */ | ||
|
||
/** | ||
* @returns {Promise<ProviderToInfoMap>} | ||
*/ | ||
export async function getProvidersWithMetadata () { | ||
const res = await fetch('https://cid.contact/providers') | ||
assertOkResponse(res) | ||
|
||
const providers = /** @type {{ | ||
AddrInfo: { | ||
ID: string; | ||
Addrs: string[]; | ||
}, | ||
LastAdvertisement: { | ||
"/": string; | ||
}, | ||
LastAdvertisementTime: string; | ||
Publisher: { | ||
ID: string; | ||
Addrs: string[]; | ||
}, | ||
// Ignored: ExtendedProviders, FrozenAt | ||
* }[]} | ||
*/(await res.json()) | ||
|
||
/** @type {[string, ProviderInfo][]} */ | ||
const entries = providers.map(p => { | ||
const providerId = p.Publisher.ID | ||
const lastAdvertisementCID = p.LastAdvertisement['/'] | ||
|
||
// FIXME: handle empty Addrs[] | ||
let providerAddress = p.Publisher.Addrs[0] | ||
try { | ||
providerAddress = multiaddrToHttpUrl(providerAddress) | ||
} catch (err) { | ||
debug('Cannot convert address to HTTP(s) URL (provider: %s): %s', providerId, err) | ||
} | ||
|
||
return [providerId, { providerAddress, lastAdvertisementCID }] | ||
}) | ||
return new Map(entries) | ||
} | ||
|
||
/** | ||
* @param {Repository} repository | ||
*/ | ||
export async function syncProvidersFromIPNI (repository) { | ||
const providerInfos = await getProvidersWithMetadata() | ||
await repository.setIpniInfoForAllProviders(providerInfos) | ||
return providerInfos | ||
} |
Oops, something went wrong.