PeerTube/server/lib/jobs/activitypub-http-job-scheduler/activitypub-http-job-schedu...

62 lines
2.0 KiB
TypeScript
Raw Normal View History

import { JobCategory } from '../../../../shared'
2017-12-12 10:53:50 -06:00
import { buildSignedActivity, logger } from '../../../helpers'
import { ACTIVITY_PUB } from '../../../initializers'
import { AccountModel } from '../../../models/account/account'
import { JobHandler, JobScheduler } from '../job-scheduler'
2017-11-17 04:35:10 -06:00
import * as activitypubHttpBroadcastHandler from './activitypub-http-broadcast-handler'
2017-11-22 03:29:55 -06:00
import * as activitypubHttpFetcherHandler from './activitypub-http-fetcher-handler'
import * as activitypubHttpUnicastHandler from './activitypub-http-unicast-handler'
2017-11-17 04:35:10 -06:00
type ActivityPubHttpPayload = {
uris: string[]
2017-11-22 03:29:55 -06:00
signatureAccountId?: number
body?: any
2017-11-23 07:19:55 -06:00
attemptNumber?: number
2017-11-17 04:35:10 -06:00
}
2017-11-23 07:19:55 -06:00
2017-11-17 04:35:10 -06:00
const jobHandlers: { [ handlerName: string ]: JobHandler<ActivityPubHttpPayload, void> } = {
activitypubHttpBroadcastHandler,
2017-11-22 03:29:55 -06:00
activitypubHttpUnicastHandler,
activitypubHttpFetcherHandler
2017-11-17 04:35:10 -06:00
}
const jobCategory: JobCategory = 'activitypub-http'
const activitypubHttpJobScheduler = new JobScheduler(jobCategory, jobHandlers)
2017-11-23 07:19:55 -06:00
function maybeRetryRequestLater (err: Error, payload: ActivityPubHttpPayload, uri: string) {
logger.warn('Cannot make request to %s.', uri, err)
let attemptNumber = payload.attemptNumber || 1
attemptNumber += 1
if (attemptNumber < ACTIVITY_PUB.MAX_HTTP_ATTEMPT) {
logger.debug('Retrying request to %s (attempt %d/%d).', uri, attemptNumber, ACTIVITY_PUB.MAX_HTTP_ATTEMPT, err)
const newPayload = Object.assign(payload, {
uris: [ uri ],
attemptNumber
})
return activitypubHttpJobScheduler.createJob(undefined, 'activitypubHttpUnicastHandler', newPayload)
}
}
async function computeBody (payload: ActivityPubHttpPayload) {
let body = payload.body
if (payload.signatureAccountId) {
2017-12-12 10:53:50 -06:00
const accountSignature = await AccountModel.load(payload.signatureAccountId)
if (!accountSignature) throw new Error('Unknown signature account id.')
body = await buildSignedActivity(accountSignature, payload.body)
}
2017-11-24 08:00:10 -06:00
return body
}
2017-11-17 04:35:10 -06:00
export {
ActivityPubHttpPayload,
2017-11-23 07:19:55 -06:00
activitypubHttpJobScheduler,
maybeRetryRequestLater,
computeBody
2017-11-17 04:35:10 -06:00
}