Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

6.7 KB
Raw Blame
import { CopyObjectCommand, PutObjectCommand, S3Client, S3ServiceException } from '@aws-sdk/client-s3'
import { Counter } from 'prom-client'

import { ConcurrencyController } from '~/common/utils/concurrencyController'
import type { TeamMonthKeys } from '~/ingestion/pipelines/sessionreplay/ai-research/v4-keys/team-month-keys'

import type { FetchCandidate } from './collected-urls-record'
import type { ImageFetchResult } from './image-fetcher'
import type { RefreshingImageSink } from './image-sink'
import { InvalidImageTransportError } from './image-transport'
import { ImageFetchProcessingMetrics } from './processing-metrics'
import { URL_ASSET_RULES } from './url-asset-rules'
import { V4UrlAsset, V4UrlRef, parseV4UrlRef, publicFontRefOf, sealFetchedImage } from './v4-native'

const S3_WRITE_TIMEOUT_MS = 30_000
const CONTENT_TYPE = 'application/octet-stream'

const storedImages = new Counter({
    name: 'ai_research_v4_image_fetch_stored_images_total',
    help: 'Fetched images and fonts the v4 lane handled, by asset and outcome.',
    labelNames: ['asset', 'outcome'],
})

/**
 * Stores each fetched image sealed and unscrubbed in `images-v4`, under the team month key of its reference. The v4
 * dataset is anonymized downstream, so unlike the v3 lane this sink never sends an image to the scrub lane.
 * A public font is the same public file for every team, so it is stored once and unsealed.
 *
 * S3 expires an object by its creation time, and blocks that reference an image are written all month. So a new fetch
 * overwrites the object of its reference, and `refreshImage` copies it onto itself to reset its age.
 */
export class RawImageStore implements RefreshingImageSink {
    private readonly writes: ConcurrencyController

    constructor(
        private readonly keys: Pick<TeamMonthKeys, 'get'>,
        private readonly s3: Pick<S3Client, 'send'>,
        private readonly bucket: string,
        maxConcurrentWrites: number
    ) {
        if (!Number.isInteger(maxConcurrentWrites) || maxConcurrentWrites < 1) {
            throw new Error('the v4 image store needs a positive write limit')
        }
        this.writes = new ConcurrencyController(maxConcurrentWrites)
    }

    /** Bounds images held in memory while S3 is slow. */
    public async publishImage(candidate: FetchCandidate, result: ImageFetchResult): Promise<void> {
        await ImageFetchProcessingMetrics.runLimited(this.writes, 'image_publish_admission', 'image_publish_delivery', {
            debugTag: candidate.registrableDomain,
            fn: () => this.store(candidate, result),
        })
    }

    public async refreshImage(candidate: FetchCandidate): Promise<boolean> {
        const ref = parseV4UrlRef(candidate.originalRef)
        if (!ref) {
            storedImages.labels('unknown', 'foreign_ref').inc()
            return false
        }
        return await ImageFetchProcessingMetrics.runLimited(
            this.writes,
            'image_publish_admission',
            'image_publish_delivery',
            {
                debugTag: candidate.registrableDomain,
                fn: () => this.copyOntoItself(ref.asset, objectKey(ref)),
            }
        )
    }

    private async copyOntoItself(asset: V4UrlAsset, objectKey: string): Promise<boolean> {
        try {
            await this.s3.send(
                new CopyObjectCommand({
                    Bucket: this.bucket,
                    Key: objectKey,
                    // S3 URL-decodes CopySource (unlike Key), so path segments must be percent-encoded.
                    CopySource: `${this.bucket}/${objectKey.split('/').map(encodeURIComponent).join('/')}`,
                    MetadataDirective: 'REPLACE',
                    ContentType: CONTENT_TYPE,
                }),
                { abortSignal: AbortSignal.timeout(S3_WRITE_TIMEOUT_MS) }
            )
        } catch (error) {
            // The fetch stored nothing for this reference, for example because the body was not an image.
            if (error instanceof S3ServiceException && error.$metadata.httpStatusCode === 404) {
                storedImages.labels(asset, 'refresh_not_stored').inc()
                return false
            }
            throw error
        }
        storedImages.labels(asset, 'refreshed').inc()
        return true
    }

    private async store(candidate: FetchCandidate, result: ImageFetchResult): Promise<void> {
        const ref = parseV4UrlRef(candidate.originalRef)
        // A throw keeps the URL unfinished, and these inputs come back the same on every fetch.
        if (!ref) {
            storedImages.labels('unknown', 'foreign_ref').inc()
            return
        }
        const { asset } = ref
        if (!result.bytes) {
            storedImages.labels(asset, 'invalid').inc()
            return
        }
        // Every team reads this one object, so it must hold the file its reference names and not a redirect target.
        if (ref.scope === 'public' && publicFontRefOf(candidate.currentUrl) !== candidate.originalRef) {
            storedImages.labels(asset, 'not_public').inc()
            return
        }
        const rules = URL_ASSET_RULES[asset]
        let body: Buffer
        try {
            body = await rules.prepare(result.bytes, result.contentType, result.contentEncoding)
        } catch (error) {
            // A body that is not the image it claims to be is handled: fetching it again returns the same body.
            if (error instanceof InvalidImageTransportError) {
                storedImages.labels(asset, 'invalid').inc()
                return
            }
            throw error
        }
        let stored = body
        if (ref.scope === 'team') {
            const { teamId, keyMonth } = ref
            const key = await this.keys.get(teamId, keyMonth)
            if (key.status !== 'ok') {
                storedImages.labels(asset, key.status === 'deleted' ? 'deleted' : 'missing_key').inc()
                return
            }
            stored = await sealFetchedImage(key.key, candidate.originalRef, body)
        }
        await this.s3.send(
            new PutObjectCommand({
                Bucket: this.bucket,
                Key: objectKey(ref),
                Body: stored,
                ContentType: CONTENT_TYPE,
            }),
            { abortSignal: AbortSignal.timeout(S3_WRITE_TIMEOUT_MS) }
        )
        storedImages.labels(asset, 'stored').inc()
    }
}

/** One object per reference. The month is the reference's key month, not the day it was fetched. */
function objectKey(ref: V4UrlRef): string {
    const prefix = URL_ASSET_RULES[ref.asset].objectKeyPrefix
    return ref.scope === 'public'
        ? `${prefix}/public/${ref.hash}`
        : `${prefix}/month=${ref.keyMonth}/${ref.teamId}/${ref.hash}`
}