|
| 1 | +/* global Zinnia */ |
| 2 | + |
| 3 | +import { ActivityState } from './activity-state.js' |
| 4 | +import { encodeHex } from '../vendor/deno-deps.js' |
| 5 | +import { assertOkResponse, assertRedirectResponse } from './http-assertions.js' |
| 6 | +import { getRandomnessForSparkRound } from './drand-client.js' |
| 7 | +import { assertEquals, assertInstanceOf } from 'zinnia:assert' |
| 8 | + |
| 9 | +/** @typedef {{cid: string; minerId: string;}} RetrievalTask */ |
| 10 | +/** @typedef {RetrievalTask & { key: string}} KeyedRetrievalTask */ |
| 11 | + |
| 12 | +export class Tasker { |
| 13 | + #lastRoundUrl |
| 14 | + /** @type {Task[]} */ |
| 15 | + #remainingRoundTasks |
| 16 | + #fetch |
| 17 | + #activity |
| 18 | + |
| 19 | + /** |
| 20 | + * @param {object} args |
| 21 | + * @param {globalThis.fetch} args.fetch |
| 22 | + * @param {ActivityState} args.activityState |
| 23 | + */ |
| 24 | + constructor ({ |
| 25 | + fetch = globalThis.fetch, |
| 26 | + activityState = new ActivityState() |
| 27 | + } = {}) { |
| 28 | + this.#fetch = fetch |
| 29 | + this.#activity = activityState |
| 30 | + |
| 31 | + this.maxTasksPerRound = 360 |
| 32 | + |
| 33 | + // TODO: persist these two values across module restarts |
| 34 | + this.#lastRoundUrl = 'unknown' |
| 35 | + this.#remainingRoundTasks = [] |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @returns {Task | undefined} |
| 40 | + */ |
| 41 | + async next () { |
| 42 | + await this.#updateCurrentRound() |
| 43 | + return this.#remainingRoundTasks.pop() |
| 44 | + } |
| 45 | + |
| 46 | + async #updateCurrentRound () { |
| 47 | + console.log('Checking the current SPARK round...') |
| 48 | + let res = await this.#fetch('https://api.filspark.com/rounds/current', { |
| 49 | + method: 'GET', |
| 50 | + headers: { 'Content-Type': 'application/json' }, |
| 51 | + redirect: 'manual', |
| 52 | + signal: AbortSignal.timeout(10_000) |
| 53 | + }) |
| 54 | + |
| 55 | + const roundUrl = await assertRedirectResponse(res, 'Failed to find the URL of the current SPARK round') |
| 56 | + this.#activity.onHealthy() |
| 57 | + if (roundUrl === this.#lastRoundUrl) { |
| 58 | + console.log('Round did not change since the last iteration') |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + console.log('Fetching round details at location %s', roundUrl) |
| 63 | + this.#lastRoundUrl = roundUrl |
| 64 | + res = await this.#fetch(`https://api.filspark.com${roundUrl}`, { |
| 65 | + method: 'GET', |
| 66 | + headers: { 'Content-Type': 'application/json' }, |
| 67 | + signal: AbortSignal.timeout(10_000) |
| 68 | + }) |
| 69 | + await assertOkResponse(res, 'Failed to fetch the current SPARK round') |
| 70 | + const { retrievalTasks, maxTasksPerNode, ...round } = await res.json() |
| 71 | + console.log('Current SPARK round:', round) |
| 72 | + console.log(' %s max tasks per round', maxTasksPerNode ?? '<n/a>') |
| 73 | + console.log(' %s retrieval tasks', retrievalTasks.length) |
| 74 | + this.maxTasksPerRound = maxTasksPerNode |
| 75 | + |
| 76 | + const randomness = await getRandomnessForSparkRound(round.startEpoch) |
| 77 | + console.log(' randomness: %s', randomness) |
| 78 | + |
| 79 | + this.#remainingRoundTasks = await pickTasksForNode({ |
| 80 | + tasks: retrievalTasks, |
| 81 | + maxTasksPerRound: this.maxTasksPerRound, |
| 82 | + randomness, |
| 83 | + stationId: Zinnia.stationId |
| 84 | + }) |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +const textEncoder = new TextEncoder() |
| 89 | + |
| 90 | +/** |
| 91 | + * @param {Task} task |
| 92 | + * @param {string} randomness |
| 93 | + * @returns |
| 94 | + */ |
| 95 | +export async function getTaskKey (task, randomness) { |
| 96 | + assertEquals(typeof task, 'object', 'task must be an object') |
| 97 | + assertEquals(typeof task.cid, 'string', 'task.cid must be a string') |
| 98 | + assertEquals(typeof task.minerId, 'string', 'task.minerId must be a string') |
| 99 | + assertEquals(typeof randomness, 'string', 'randomness must be a string') |
| 100 | + |
| 101 | + const data = [task.cid, task.minerId, randomness].join('\n') |
| 102 | + const hash = await crypto.subtle.digest('sha-256', textEncoder.encode(data)) |
| 103 | + return BigInt('0x' + encodeHex(hash)) |
| 104 | +} |
| 105 | + |
| 106 | +/** |
| 107 | + * @param {string} stationId |
| 108 | + */ |
| 109 | +export async function getStationKey (stationId) { |
| 110 | + assertEquals(typeof stationId, 'string', 'stationId must be a string') |
| 111 | + |
| 112 | + const hash = await crypto.subtle.digest('sha-256', textEncoder.encode(stationId)) |
| 113 | + return BigInt('0x' + encodeHex(hash)) |
| 114 | +} |
| 115 | + |
| 116 | +/** |
| 117 | + * @param {object} args |
| 118 | + * @param {Task[]} args.tasks |
| 119 | + * @param {string} args.stationId |
| 120 | + * @param {string} args.randomness |
| 121 | + * @param {number} args.maxTasksPerRound |
| 122 | + * @returns {Promise<Task[]>} |
| 123 | + */ |
| 124 | +export async function pickTasksForNode ({ tasks, stationId, randomness, maxTasksPerRound }) { |
| 125 | + assertInstanceOf(tasks, Array, 'tasks must be an array') |
| 126 | + assertEquals(typeof stationId, 'string', 'stationId must be a string') |
| 127 | + assertEquals(typeof randomness, 'string', 'randomness must be a string') |
| 128 | + assertEquals(typeof maxTasksPerRound, 'number', 'maxTasksPerRound must be a number') |
| 129 | + |
| 130 | + const keyedTasks = await Promise.all(tasks.map( |
| 131 | + async (t) => ({ ...t, key: await getTaskKey(t, randomness) }) |
| 132 | + )) |
| 133 | + const stationKey = await getStationKey(stationId) |
| 134 | + |
| 135 | + /** |
| 136 | + * @param {{key: bigint}} a |
| 137 | + * @param {{key: bigint}} b |
| 138 | + * @returns {number} |
| 139 | + */ |
| 140 | + const comparator = (a, b) => { |
| 141 | + const ad = a.key ^ stationKey |
| 142 | + const bd = b.key ^ stationKey |
| 143 | + return ad > bd ? 1 : ad < bd ? -1 : 0 |
| 144 | + } |
| 145 | + |
| 146 | + keyedTasks.sort(comparator) |
| 147 | + keyedTasks.splice(maxTasksPerRound) |
| 148 | + |
| 149 | + return keyedTasks.map(({ key, ...t }) => (t)) |
| 150 | +} |
0 commit comments