: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ai-research): fetch the images, under a per-site budget (#82030)
Robbie768f5f940602
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex 22a6b76312d6..7ec6d4fa7a06 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -197,6 +197,7 @@ export function getPluginServerCapabilities(case PluginServerMode.recordings_blob_ingestion_v2_ml_image_scrub:case PluginServerMode.recordings_blob_ingestion_v2_ml_image_scrub_dlq_replay:case PluginServerMode.recordings_blob_ingestion_v2_ml_image_fetch:+ case PluginServerMode.recordings_blob_ingestion_v2_ml_image_fetch_retry:case PluginServerMode.recording_api:throw new Error(`Mode ${mode} is handled by IngestionSessionReplayServer, not PluginServer`)}diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 018e45a1932b..1c5a0f49c35f 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -41,6 +41,7 @@ export enum PluginServerMode {recordings_blob_ingestion_v2_ml_image_scrub = 'recordings-blob-ingestion-v2-ml-image-scrub',recordings_blob_ingestion_v2_ml_image_scrub_dlq_replay = 'recordings-blob-ingestion-v2-ml-image-scrub-dlq-replay',recordings_blob_ingestion_v2_ml_image_fetch = 'recordings-blob-ingestion-v2-ml-image-fetch',+ recordings_blob_ingestion_v2_ml_image_fetch_retry = 'recordings-blob-ingestion-v2-ml-image-fetch-retry',cdp_processed_events = 'cdp-processed-events',cdp_person_updates = 'cdp-person-updates',cdp_data_warehouse_events = 'cdp-data-warehouse-events',diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.tsindex c27be037384d..8c11afd64d81 100644--- a/nodejs/src/common/config/kafka-topics.ts+++ b/nodejs/src/common/config/kafka-topics.ts@@ -49,6 +49,12 @@ export const KAFKA_SESSION_REPLAY_IMAGE_SCRUB = `${prefix}session_replay_image_s// example.com, so it gets one budget rather than eight. A record holds an original, unscrubbed// URL, so this topic is as sensitive as the raw replay topic.export const KAFKA_SESSION_REPLAY_IMAGE_FETCH = `${prefix}session_replay_image_fetch${suffix}`+// Kafka has no delayed delivery, so a retry waits in a topic whose period is fixed. The period+// belongs to the topic rather than to the record, so the records leave in the order they become+// ready and an hour-long wait never sits in front of a one minute wait.+export const KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M = `${prefix}session_replay_image_fetch_retry_1m${suffix}`+export const KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M = `${prefix}session_replay_image_fetch_retry_10m${suffix}`+export const KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H = `${prefix}session_replay_image_fetch_retry_1h${suffix}`// images the scrub sidecar cannot process, parked so they stop holding the head of their partition.// The original bytes are kept: unscrubbed content must never reach the ML bucket, but it must not bediff --git a/nodejs/src/common/kafka/consumer/consumer-v1.ts b/nodejs/src/common/kafka/consumer/consumer-v1.tsindex 7a1ed95660e9..3e9df68736cb 100644--- a/nodejs/src/common/kafka/consumer/consumer-v1.ts+++ b/nodejs/src/common/kafka/consumer/consumer-v1.ts@@ -234,6 +234,21 @@ export class KafkaConsumer {this.lastHeartbeatTime = Date.now()}+ /**+ * Say that this consumer waits on purpose, and does not stall.+ *+ * Separate from `heartbeat()` because it relaxes the loop stall detector, and most callers must+ * not do that. Two lanes drive `heartbeat()` from a `setInterval`, which keeps firing while a+ * batch is wedged on a promise that never settles, so moving the loop clock there would leave+ * such a pod reporting healthy forever.+ *+ * Call this only from a handler that sleeps by design, and only from its own await chain.+ */+ public reportDeliberateWait(): void {+ this.lastHeartbeatTime = Date.now()+ this.lastConsumerLoopTime = Date.now()+ }+public isHealthy(): HealthCheckResult {// Use legacy heartbeat-based health check if feature flag is disabledif (!defaultConfig.CONSUMER_LOOP_BASED_HEALTH_CHECK) {diff --git a/nodejs/src/common/utils/concurrencyController.ts b/nodejs/src/common/utils/concurrencyController.tsindex cb2a51615ffa..6af5d2d06a05 100644--- a/nodejs/src/common/utils/concurrencyController.ts+++ b/nodejs/src/common/utils/concurrencyController.ts@@ -75,6 +75,11 @@ export class ConcurrencyController {this._concurrencyLimit = concurrencyLimit}+ /** Functions running now. A queued one is not counted, because it holds nothing yet. */+ public get running(): number {+ return this._current.length+ }+/*** Run a function with a mutex. If the mutex is already running, the function will be queued and run when the mutex* is available.diff --git a/nodejs/src/common/utils/request-streamed.test.ts b/nodejs/src/common/utils/request-streamed.test.tsnew file mode 100644index 000000000000..806aa88860ac--- /dev/null+++ b/nodejs/src/common/utils/request-streamed.test.ts@@ -0,0 +1,97 @@+import { Readable } from 'node:stream'+// eslint-disable-next-line no-restricted-imports+import { request } from 'undici'++import { InvalidRequestError, fetchStreamed } from './request'++jest.mock('undici', () => ({+ ...jest.requireActual('undici'),+ request: jest.fn(),+}))++const requestMock = request as jest.MockedFunction<typeof request>++function respond(chunks: Buffer[], headers: Record<string, string> = {}): void {+ requestMock.mockResolvedValue({+ statusCode: 200,+ headers,+ body: Readable.from(chunks),+ } as unknown as Awaited<ReturnType<typeof request>>)+}++describe('fetchStreamed', () => {+ beforeEach(() => {+ requestMock.mockReset()+ })++ it('returns a body that fits the limit', async () => {+ respond([Buffer.from('abc'), Buffer.from('de')])++ const response = await fetchStreamed('https://example.com/a.png', { timeoutMs: 1000 })+ const { bytes, overLimit } = await response.read(10)++ expect(overLimit).toBe(false)+ expect(bytes.toString()).toBe('abcde')+ })++ it.each([+ ['one chunk already past it', [Buffer.alloc(20)]],+ ['several chunks that cross it together', [Buffer.alloc(4), Buffer.alloc(4), Buffer.alloc(4)]],+ ])('abandons a body that passes the limit as %s', async (_name, chunks) => {+ // The limit has to bind on what has arrived rather than on a declared size, because an+ // origin can declare nothing and send gigabytes.+ respond(chunks)++ const response = await fetchStreamed('https://example.com/a.png', { timeoutMs: 1000 })+ const { bytes, overLimit } = await response.read(10)++ expect(overLimit).toBe(true)+ // Empty, because a truncated image is not an image and must not look like one to a caller.+ expect(bytes).toHaveLength(0)+ })++ it.each([+ ['exactly its declared length', 5],+ ['less than it declared', 10],+ ['more than it declared', 3],+ ])('ignores a Content-Length that is %s', async (_name, declared) => {+ // Content-Length is a claim, not a fact. Only the caller's limit binds, and it binds on the+ // bytes that arrive.+ respond([Buffer.from('abcde')], { 'content-length': String(declared) })++ const response = await fetchStreamed('https://example.com/a.png', { timeoutMs: 1000 })+ const { bytes, overLimit } = await response.read(100)++ expect(overLimit).toBe(false)+ expect(bytes.toString()).toBe('abcde')+ })++ it('reads no body after the response was discarded', async () => {+ respond([Buffer.from('abc')])++ const response = await fetchStreamed('https://example.com/a.png', { timeoutMs: 1000 })+ response.discard()+ const { bytes } = await response.read(10)++ expect(bytes).toHaveLength(0)+ })++ it('does not let a header named __proto__ reach the prototype', async () => {+ // The remote server chooses every key here. The key is computed, because a plain `__proto__:`+ // in a literal is the setter this test is about rather than an own property.+ respond([], { ['__proto__']: 'polluted', 'content-type': 'image/png' })++ const response = await fetchStreamed('https://example.com/a.png', { timeoutMs: 1000 })+ response.discard()++ expect(response.headers['__proto__']).toBe('polluted')+ expect(({} as Record<string, unknown>)['polluted']).toBeUndefined()+ expect(Object.getPrototypeOf(response.headers)).toBeNull()+ })++ it.each([['ftp://example.com/a.png'], ['not a url']])('refuses %s before opening a socket', async (url) => {+ await expect(fetchStreamed(url, { timeoutMs: 1000 })).rejects.toThrow(InvalidRequestError)++ expect(requestMock).not.toHaveBeenCalled()+ })+})diff --git a/nodejs/src/common/utils/request.ts b/nodejs/src/common/utils/request.tsindex 4dacfd6c8a55..45bc8b822f24 100644--- a/nodejs/src/common/utils/request.ts+++ b/nodejs/src/common/utils/request.ts@@ -313,6 +313,30 @@ const sharedSecureH2Agent = new Agent({})const sharedInsecureAgent = new InsecureAgent()+function destroyBody(body: Dispatcher.ResponseData['body']): void {+ try {+ body.on('error', () => {})+ body.destroy()+ } catch {+ // The body already ended, or another caller destroyed it.+ }+}++/**+ * The prototype is null because every key comes from the remote server, and `__proto__` on a plain+ * object literal is a setter rather than a key.+ */+function flattenHeaders(raw: Dispatcher.ResponseData['headers']): Record<string, string> {+ const headers: Record<string, string> = Object.create(null)+ for (const [key, value] of Object.entries(raw)) {+ const singleValue = Array.isArray(value) ? value[0] : value+ if (singleValue) {+ headers[key] = singleValue+ }+ }+ return headers+}+/*** Reads a response body stream and destroys it immediately after to release* the underlying socket and its off-heap buffers. Without explicit destruction,@@ -324,11 +348,7 @@ async function readAndDestroyBody(body: Dispatcher.ResponseData['body']): Promis// After text() fully consumes the stream, destroy to release socket buffers.// At this point the stream is already ended so destroy is a cleanup no-op,// but it signals undici to release the underlying socket immediately.- try {- body.destroy()- } catch {- // Ignore destroy errors — the body is already fully consumed- }+ destroyBody(body)return text}@@ -360,13 +380,7 @@ export async function _fetch(signal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : undefined,})- const headers: Record<string, string> = {}- for (const [key, value] of Object.entries(result.headers)) {- const singleValue = Array.isArray(value) ? value[0] : value- if (singleValue) {- headers[key] = singleValue- }- }+ const headers = flattenHeaders(result.headers)// On first .text()/.json() call, read the full body and destroy the// stream immediately after. This releases undici's socket buffers@@ -388,12 +402,7 @@ export async function _fetch(dump: () => {if (!bodyPromise) {bodyPromise = Promise.resolve('')- try {- result.body.on('error', () => {})- result.body.destroy()- } catch {- // Ignore destroy errors- }+ destroyBody(result.body)}return Promise.resolve()},@@ -422,6 +431,117 @@ export async function fetch(url: string, options: FetchOptions = {}): Promise<Fe}}+export type StreamedFetchOptions = {+ headers?: HeadersInit+ timeoutMs: number+}++export type StreamedResponse = {+ status: number+ headers: Record<string, string>+ /**+ * Reads at most `maxBytes`, then abandons the rest. `overLimit` says the response had more, and+ * `bytes` is then empty, because a truncated payload is not usable.+ */+ read: (maxBytes: number) => Promise<{ bytes: Buffer; overLimit: boolean }>+ discard: () => void+}++/**+ * Memory here follows the bytes that arrive, never the bytes a response claims.+ *+ * One buffer sized from `Content-Length` would halve the peak for an honest response, because the+ * chunks and the concatenated copy exist together for a moment. It would also let an origin hold+ * `maxBytes` for the whole request timeout, once for every request in flight, by declaring a large+ * body and then sending almost nothing.+ */+async function readCappedBody(+ body: Dispatcher.ResponseData['body'],+ maxBytes: number+): Promise<{ bytes: Buffer; overLimit: boolean }> {+ const chunks: Buffer[] = []+ let total = 0+ let overLimit = false+ try {+ for await (const chunk of body) {+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)+ total += buffer.length+ if (total > maxBytes) {+ overLimit = true+ break+ }+ chunks.push(buffer)+ }+ } finally {+ destroyBody(body)+ }+ return { bytes: overLimit ? Buffer.alloc(0) : Buffer.concat(chunks), overLimit }+}++/**+ * A third-party request whose caller reads the body under a byte limit.+ *+ * `fetch` above gives the caller `text()`, which buffers a whole body of any size. An origin can+ * answer a request for a small image with gigabytes. Here the caller reads the status and the+ * headers first, then sets a byte limit or abandons the body.+ *+ * This does not follow redirects, as `fetch` does not, so a response cannot bounce to a host that no+ * check has seen. A caller that follows one must call this again for the new URL.+ *+ * The caller must call `read` or `discard`, and only one of them. The socket stays held until then.+ */+export async function fetchStreamed(url: string, options: StreamedFetchOptions): Promise<StreamedResponse> {+ const parsed = validateUrl(url)+ validateHostnameIPLiteral(parsed.hostname, !isProdEnv())++ inflightExternalRequests.inc()+ let result: Dispatcher.ResponseData+ try {+ result = await request(parsed.toString(), {+ method: 'GET',+ headers: options.headers,+ dispatcher: sharedSecureAgent,+ signal: AbortSignal.timeout(options.timeoutMs),+ })+ } catch (error) {+ inflightExternalRequests.dec()+ throw error+ }++ // The gauge holds until the body is done, not until the headers arrive, because the body takes+ // nearly all the time of an image request.+ let settled = false+ const settle = (): boolean => {+ if (settled) {+ return false+ }+ settled = true+ inflightExternalRequests.dec()+ return true+ }++ const headers = flattenHeaders(result.headers)+ return {+ status: result.statusCode,+ headers,+ read: async (maxBytes: number) => {+ if (settled) {+ return { bytes: Buffer.alloc(0), overLimit: false }+ }+ try {+ return await readCappedBody(result.body, maxBytes)+ } finally {+ settle()+ }+ },+ discard: () => {+ if (settle()) {+ destroyBody(result.body)+ }+ },+ }+}+// Legacy fetch implementation that exposes the entire fetch implementationexport function legacyFetch(input: RequestInfo, options?: RequestInit): Promise<Response> {let parsed: URLdiff --git a/nodejs/src/index.ts b/nodejs/src/index.tsindex 3d6b14ae19a8..b94778413d82 100644--- a/nodejs/src/index.ts+++ b/nodejs/src/index.ts@@ -12,6 +12,7 @@ import { IngestionApiServer } from '~/servers/ingestion-api-server'import { IngestionGeneralServer } from '~/servers/ingestion-general-server'import { IngestionLogsServer } from '~/servers/ingestion-logs-server'import { IngestionMetricsServer } from '~/servers/ingestion-metrics-server'+import { IngestionSessionReplayMlImageFetchRetryServer } from '~/servers/ingestion-session-replay-ml-image-fetch-retry-server'import { IngestionSessionReplayMlImageFetchServer } from '~/servers/ingestion-session-replay-ml-image-fetch-server'import { IngestionSessionReplayMlImageScrubDlqReplayServer } from '~/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server'import { IngestionSessionReplayMlImageScrubServer } from '~/servers/ingestion-session-replay-ml-image-scrub-server'@@ -52,6 +53,9 @@ function createServer(): NodeServer {case PluginServerMode.recordings_blob_ingestion_v2_ml_image_fetch:return new IngestionSessionReplayMlImageFetchServer()+ case PluginServerMode.recordings_blob_ingestion_v2_ml_image_fetch_retry:+ return new IngestionSessionReplayMlImageFetchRetryServer()+case PluginServerMode.recording_api:return new RecordingApiServer()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.mdnew file mode 100644index 000000000000..6be571e7a95b--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md@@ -0,0 +1,260 @@+# The image fetch lane++This lane downloads the remote images that a session replay refers to, so the scrub lane can+remove private data from them and the result can train a model.++It is a web crawler. The names here are the crawler's names, and this file is the specification the+code is written against. Where the code and this file disagree, one of them is a bug.++## The model++| Part | What it is |+| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Mirror | The upstream lane. It replaces each image in a recording with a ref, and publishes the URLs it collected to the frontier. |+| Ref | What the mirror writes into the recording in place of an image, built from a hash of the image URL. It is how a fetched image is later matched back to the recording that wanted it. |+| Frontier | The topic `session_replay_image_fetch`. It holds the URLs waiting to be fetched. |+| Back queue | The URLs of one registrable domain. The topic key is the domain, so a partition holds whole back queues. |+| Pass | The fetching for one Kafka poll batch. Every back queue in the batch runs at the same time, and wall time bounds the pass rather than work. |+| Crawl history | The Redis record of the URLs this lane has finished with, whatever the outcome. It answers the URL-seen test. |+| Host budget | The token bucket, connection limit, and circuit breaker for one registrable domain. The rate moves by AIMD: a failure halves it, and success raises it slowly. |+| Hop | One trip a URL makes back through Kafka. The lane spends a hop when it puts a URL back: a retry, a redirect that left the domain, or a URL that arrived before its wait ended. A redirect the lane follows in place costs no hop. |+| Hop budget | The number of hops one URL may make before the lane gives up. |+| Registrable domain | The operator boundary, from the Public Suffix List. Also called eTLD+1. `example.com` for `img1.cdn.example.com`, but `myapp.vercel.app` for itself. |++A redirect to another domain is a new candidate URL. It goes back through the frontier rather than+being fetched in place, because the budget that governs it belongs to whichever consumer owns that+domain's partition.++## Limits++| Constant | Scope | Value |+| --------------------------------------- | ------------------------------------------------- | ---------- |+| Requests in flight | pod | 300 |+| Requests in flight per domain | domain | 6 |+| Requests per second per domain | domain | 1, burst 5 |+| Hop budget | one original URL, across every message it becomes | 10 |+| Redirects followed without republishing | one fetch | 3 |+| Response bytes | one response | 2 MB |+| Request timeout | one URL, redirects included | 10 seconds |+| Pass deadline | one pass | 20 seconds |+| Pass wall time, worst case | one pass | 30 seconds |+| Domains tracked | pod | 20000 |++Every back queue runs at the same time. This is how the pod reaches its limit rather than a+fairness rule: one domain holds at most 6 requests, so about 50 domains must be active together to+use 300.++Only a request holding a socket counts as in flight. A URL waiting for its domain's rate limit+holds nothing, so it is not counted. A wait between the hops of one redirect chain is counted,+because the request is already open.++The pass deadline decides whether a request starts. It never decides how long that request may+take. A request cut short by the pass clock would time out through no fault of the site, and the+budget would read that as the site failing. So a request that starts just inside the deadline still+gets its whole timeout, and one pass can run to the deadline plus one request timeout. That is the+worst case in the table, and it stays well inside Kafka's `max.poll.interval.ms` of 300 seconds.++## Requirements++Each of these is numbered so a test can name the one it covers.++### Limits++1. Requests in flight never exceed the pod limit.+2. Requests in flight to one domain never exceed the domain limit, redirects included.+3. Requests to one domain never exceed the rate its token bucket allows.+4. A redirect is not a way around either limit.+5. After any wait, a request checks again before it goes out. The domain must not be blocked, and+ the pass deadline must not have passed. A grant that went stale during the wait is returned,+ not sent.++### Redirects++6. The lane follows a redirect that stays on the same domain, up to the limit.+7. The lane publishes a redirect that leaves the domain back to the frontier, keyed by the new+ domain.+8. Every redirect target passes the same checks the first candidate passed. See "Security: what we+ never connect to".+9. The lane never follows a redirect from HTTPS to plain HTTP.+10. A republished message carries the original ref. The ref is a hash of the original URL, so a ref+ built from a redirect target matches nothing in the recording that wanted the image.++### Hops and retries share one budget++11. Every message carries a hop budget. A republish and a retry each spend one. A redirect that+ stays on the same domain is bounded separately, by the redirect limit of one fetch, so a chain+ is bounded by the two limits together rather than by the budget alone.+12. When the budget reaches zero, the lane writes the crawl history and stops.+13. Only a transient failure spends a hop on a retry: a timeout, a connection error, HTTP 429, HTTP+ 503, or a refusal by the host budget. HTTP 404 and HTTP 403 are answers.+14. A retry is a publish to a delay topic. The lane does not sleep and try again in place.+15. Every message carries the earliest time to try again.++### Host budget: what the lane learns about a site++16. One network failure for a domain applies to every URL queued for that domain in the same pass.+17. A `Retry-After` header holds the whole domain for the period it names.+18. Repeated failures open the circuit breaker for the domain, and its cooldown grows each time.+19. This knowledge lives in the pod that owns the partition. It does not cross pods, and a+ rebalance loses it.++### Order, offsets, and termination++20. The lane does not need per-key order. Images have no order between them.+21. An offset commits only after the work behind it is durable: fetched and recorded, republished,+ or given up.+22. A duplicate is acceptable. The crawl history absorbs it.+23. A message that does not parse is counted and dropped. There is no dead letter topic: the lane+ cannot record what it cannot read, and replaying it helps nobody until the format disagreement+ is fixed.+24. A URL the lane gives up on goes into the crawl history, so it stops coming back.++**Keeping one record uncommitted means restarting the pod.** Kafka commits one offset for each+partition, and that offset is a high water mark. Committing it commits every record below it, so a+consumer cannot hold one record back and commit the ones around it. A consumer that must not commit+a record has one move, which is to throw. The throw leaves the poll loop and the pod shuts down.+Kubernetes starts it again, and the new pod reads the batch from the last committed offset.++The lane spends that on one condition: a Kafka produce that failed. It is the only case where the+lane took a URL out of the frontier and put nothing back, so no copy of that URL is left anywhere.+It is also usually brief, so the pod that comes back is likely to get the record through.++A crawl history read the store could not answer loses URLs the same way, and the lane commits it+regardless. A store that cannot answer this batch cannot answer the next one either, so throwing+would restart the pod on every batch and fetch nothing at all. The lane leaves those URLs+unrecorded, so the mirror offers them again the next time a session refers to the same image. A+counter records each one, which keeps the loss visible.++**Rule 21 is about URLs the lane got an answer for.** The fetch pass returns an outcome for every+URL it is given, so an exception out of the pass is a fault in our own code rather than something a+site did. The consumer counts it, drops the batch, and lets the offset commit. A replay would run+the same code over the same records and meet the same fault, which stops the partition instead of+clearing it.++### Metrics++25. Requests by outcome, and refusals by reason. No team label on these.+26. The hops a URL took, and the time it spent in the system.+27. The rate of republishing, so amplification is visible.+28. Requests in flight, and the domains that are blocked.+29. The busiest teams, as a bounded top N with an `other` bucket, using the Space-Saving algorithm+ for heavy hitters. Nothing on this path holds the team ID, so a team here is the pseudonym the+ mirror sends.+30. The number of distinct teams, as one gauge, estimated with HyperLogLog.+31. No metric carries a URL, and no metric carries an unbounded team label. The team ID space is in+ the low millions, so a `team_id` label on a per-request metric is unbounded both in the time+ series database and in the memory of the pod exporting it.++### Security: what we never connect to++These rules exist to stop server-side request forgery. The URLs come from a page the lane did not+write, so an attacker chooses them, and the request leaves from inside our network.++32. The lane must never connect to an IP address that is not globally routable. That covers+ loopback, the RFC 1918 private ranges, link-local, carrier-grade NAT, multicast, and the+ reserved ranges, in IPv4 and IPv6. Smokescreen, the egress proxy, enforces this in production.+ `httpStaticLookup`, our DNS hook for undici, enforces it when no proxy is set.+33. The check must use the same DNS answer as the connection, so that DNS rebinding cannot slip an+ IP address past it. An attacker who owns a name can return a different IP address on every+ lookup. Code that resolves a name, checks the IP address, then hands the name to something that+ resolves it again has checked one address and connected to another.+34. The collector, which is the URL policy the mirror runs before it publishes, drops a URL that a+ later check would refuse, so it never reaches the topic. It drops four kinds: a host that is not+ public, a scheme that is not HTTPS, a port that the scheme does not own, and a URL that is too+ long.+35. Every check in rule 34 runs again in the lane, on the first URL and on every redirect target.+ The network layer performs none of them. Smokescreen limits which IP addresses we reach, not+ which service we reach at those addresses.++Neither implementation passes a name onward, which is what satisfies rule 33. Smokescreen resolves+the name, checks the IP addresses it got, and connects to one of those. `httpStaticLookup` resolves+the name, checks the IP addresses it got, and hands that list to undici, which connects to them.++The lane repeats the collector's checks because nothing below the lane performs them. Smokescreen+sees an IP address, not a scheme, a port, or a hostname, so the collector and the lane are the only+two places these run, and the two must agree. Both allow HTTPS on port 443 and nothing else.++The host check is the one that needs both layers. An IP address check at connect time refuses a+private address, so it covers `169.254.169.254`, the cloud instance metadata endpoint. It cannot+refuse `wiki.corp`, because that hostname looks ordinary and its DNS answer can be a globally+routable address. Only a check on the hostname itself refuses that.++A hostname the attacker owns can still reach any globally routable IP address on port 443, and the+outcome metric shows whether something answered. Any port scanner learns the same thing for less+effort, so the cost to us is our reputation rather than leaked data: the request leaves our egress+IP addresses, not a customer's. The per-domain token bucket holds it to one request each second.++### Smokescreen++`PostHog/smokescreen` is a small wrapper around `stripe/smokescreen`. Two settings matter here.++Its ACL is `action: open`, so it allows every domain. That is what this lane needs, because a+customer's images can sit on any host.++Its private IP address blocking is on. The deployment passes no `--unsafe-allow-private-ranges`,+and that flag is the only way to turn the blocking off.++The ACL says nothing about ports, which is why rule 35 exists.++## How a message waits++Kafka has no delayed delivery. The delay belongs to the topic, not to the message, because a+message that waits an hour would otherwise sit in front of one that waits a minute.++```text+session_replay_image_fetch_retry_1m+session_replay_image_fetch_retry_10m+session_replay_image_fetch_retry_1h+```++Every message in one topic waits the same period, so they arrive in the order they become ready.+The consumer reads the first message, waits out the remainder, and publishes it back to the+frontier. A message needing longer than an hour goes around the 1h topic again and spends a hop.++Three things follow. Each one stops the design from working if it is missed.++**The consumer of a long topic must outlive `max.poll.interval.ms`.** The shared default is 300+seconds. A consumer that sleeps for 10 minutes is evicted, and its partition is replayed by a+consumer that will sleep just as long. The retry server therefore sets the value itself, as the+period of its topic plus one minute, rather than leaving it to the deployment.++That figure holds only because a batch carries one record. A batch of several is held one record at+a time, and a delay topic can hold records written hours apart, so each would wait its own period+inside one batch. The server refuses to start with any other batch size, and refuses to start+against any topic other than the three the publisher writes to.++**A sleeping consumer must keep reporting itself healthy.** It calls+`KafkaConsumer.reportDeliberateWait()`, which moves the loop clock as well as the heartbeat clock.+That is separate from `heartbeat()` on purpose: two lanes drive `heartbeat()` from a timer, and a+timer keeps firing while a batch is wedged, so relaxing the stall detector there would leave a stuck+pod reporting healthy forever.++**Lag on a delay topic is the design working.** A 1h topic reports an hour of lag whenever it holds+anything. Alert on the age of the oldest message passing the topic's period by a wide margin, which+means the consumer stopped. Do not alert on lag.++Each delay consumer runs `minPods: 0` and `maxPods: 1`. The maximum of one matters: a lag trigger+assumes more consumers drain a topic faster, and that is false here. These messages are waiting on+purpose. A delay topic holding thousands of them would otherwise scale to dozens of pods, none of+which can make a message become ready sooner.++## Why a retry is necessary at all++The mirror keeps a cache of the refs it has published, 500,000 per pod, and does not produce a ref+twice while it is cached. So a URL that fails, and that this lane does not write to the crawl+history, does not come back until that entry leaves the cache.++An earlier version of this lane treated an absent crawl history entry as a retry. It is a loss.++## Dry run++The lane runs every decision that needs no request, and sends none. It parses the records, applies+the age limit and all three layers of dedup (within the batch, within the pod, and against the+crawl history), and writes the crawl history. What it would have+fetched is counted as `fetchable`, which is the offered request rate.++The host budget belongs to the fetch pass, which dry run does not build. So the gauges of rule 28+report zero, which is what a lane holding no request and blocking no domain should report.++This is the mode phase 0 measures in. The server refuses to clear the flag, and names the two things+that must land before it can: reading robots.txt, and producing the image to the scrub topic.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.tsindex 34465017b2b0..d819535b1fde 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts@@ -15,7 +15,7 @@ describe('parseCollectedUrlsRecord', () => {['a magnitude no double can hold', '"capturedAtMs":-1e400'],['a positive one', '"capturedAtMs":1e400'],])('refuses %s rather than passing a non-finite timestamp on', (_name, fields) => {- // JSON.stringify cannot produce these, so the record is written by hand. They parse to+ // JSON.stringify cannot produce these, so this writes the record by hand. They parse to// Infinity, which reaches a histogram as an infinite observation, and prom-client throws// there. A throw inside a batch stops the consumer and replays the same record forever.const parsed = parseCollectedUrlsRecord(body(fields), 'example.com')@@ -23,6 +23,89 @@ describe('parseCollectedUrlsRecord', () => {expect(parsed).toEqual({ ok: false, reason: 'malformed' })})+ it.each([+ ['a fully qualified host against a bare key', 'cdn.example.com.', 'example.com'],+ ['a bare host against a fully qualified key', 'cdn.example.com', 'example.com.'],+ ['both fully qualified', 'cdn.example.com.', 'example.com.'],+ ])('keeps %s', (_name, host, key) => {+ // politenessKey strips the trailing dot, so a record written before the canonicalizer did+ // the same carries a dotted host against a bare key. A plain string comparison drops every+ // such URL as foreign, and those records are already in the topic.+ const value = Buffer.from(+ `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` ++ `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://${host}/a.png","host":"${host}"}]}`+ )++ const parsed = parseCollectedUrlsRecord(value, key)++ expect(parsed.ok && parsed.candidates).toHaveLength(1)+ })++ it.each([+ ['a key that is a subdomain rather than the operator', 'cdn.example.com', 'cdn.example.com'],+ ['a key belonging to another operator', 'cdn.example.com', 'other.net'],+ ])('drops %s (requirement 3)', (_name, host, key) => {+ // The key scopes the rate budget. One key for each subdomain would give one operator a+ // multiple of the rate we promise it, and the record would be on the wrong partition too.+ const value = Buffer.from(+ `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` ++ `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://${host}/a.png","host":"${host}"}]}`+ )++ const parsed = parseCollectedUrlsRecord(value, key)++ expect(parsed.ok && parsed.candidates).toHaveLength(0)+ expect(parsed.ok && parsed.rejected).toEqual([{ reason: 'foreign_domain' }])+ })++ it.each([+ ['plain HTTP', 'http://cdn.example.com/a.png'],+ ['a scheme this lane never fetches', 'ftp://cdn.example.com/a.png'],+ ])('drops %s (requirements 34 and 35)', (_name, url) => {+ // The collector produces HTTPS only. Anything else means a wrong or stale producer, and a+ // fetch would put an image on the wire in clear text.+ const value = Buffer.from(+ `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` ++ `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"${url}","host":"cdn.example.com"}]}`+ )++ const parsed = parseCollectedUrlsRecord(value, 'example.com')++ expect(parsed.ok && parsed.rejected).toEqual([{ reason: 'bad_url' }])+ })++ it.each([+ ['a name that only resolves inside a network', 'wiki.corp'],+ ['a link-local address', '169.254.169.254'],+ ['a loopback address', '127.0.0.1'],+ ])('drops %s (requirement 35)', (_name, host) => {+ // The connect-time address check cannot refuse a name like wiki.corp whose DNS answer is+ // public, so this is the only place that does.+ const value = Buffer.from(+ `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` ++ `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://${host}/a.png","host":"${host}"}]}`+ )++ const parsed = parseCollectedUrlsRecord(value, host)++ expect(parsed.ok && parsed.rejected).toEqual([{ reason: 'private_host' }])+ })++ it('keys one domain by one spelling, whatever the record key used', () => {+ // The budget, the metrics, and the republish key all read this. Two spellings of one+ // domain would take two budgets on the same pod, so each would get the full rate.+ const value = Buffer.from(+ `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` ++ `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://cdn.example.com/a.png","host":"cdn.example.com"}]}`+ )++ const dotted = parseCollectedUrlsRecord(value, 'example.com.')+ const bare = parseCollectedUrlsRecord(value, 'example.com')++ expect(dotted.ok && dotted.candidates[0].domain).toBe('example.com')+ expect(bare.ok && bare.candidates[0].domain).toBe('example.com')+ })+it('accepts an ordinary timestamp', () => {const parsed = parseCollectedUrlsRecord(body('"capturedAtMs":1700000000000'), 'example.com')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.tsindex 63819897f11b..1500bbfc0841 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts@@ -2,16 +2,15 @@ import { parseJSON } from '~/common/utils/json-parse'import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'import { UrlDropReason } from './metrics'+import { isPublicHost, politenessKey } from './politeness-key'/** Beyond this the URL is not something the mirror produced, so it is a format disagreement. */const MAX_URL_LENGTH = 2048-const FETCHABLE_SCHEMES = new Set(['http:', 'https:'])-/*** A record holds one domain from one message, and the collector caps a message at 512, so a- * well-formed record stays under this. Headroom is deliberately small: the Redis round trips of a- * batch scale with this value and run one after another inside one batch budget.+ * well-formed record stays under this. The headroom is small on purpose, because the Redis round+ * trips of a batch scale with this value and run one after another inside one batch budget.*/const MAX_URLS_PER_RECORD = 640@@ -23,8 +22,18 @@ export interface FetchCandidate {domain: stringpseudoTeam: stringcapturedAtMs: number+ /** Moves this URL may still make. A republish and a retry each spend one. Requirement 11. */+ hopsRemaining: number+ /** The lane must not fetch this URL before this epoch ms. Zero means now. Requirement 15. */+ notBeforeMs: number}+/**+ * One budget rather than one counter for redirects and another for retries, because a chain that+ * alternates between the two would otherwise never end. Requirement 11.+ */+export const MAX_HOPS = 10+export type RecordParse =| { ok: true; candidates: FetchCandidate[]; urlCount: number; rejected: { reason: UrlDropReason }[] }| { ok: false; reason: Extract<UrlDropReason, 'malformed' | 'unsupported_version' | 'oversized_record'> }@@ -34,20 +43,22 @@ function isStringRecord(value: unknown): value is Record<string, unknown> {}/**- * Read one record off the fetch topic.- ** The producer and this consumer ship from separate deployments, so a record can arrive from a- * mirror older or newer than this code. Every field is therefore checked rather than trusted, and a- * record that does not parse is counted and dropped instead of throwing: one bad record must not- * stall the partition it shares with every other site.+ * mirror older or newer than this code. This checks every field rather than trusts it, and it counts+ * and drops a record that does not parse instead of throwing, because one bad record must not stall+ * the partition it shares with every other site.*- * `domain` comes from the Kafka key rather than the record body, because the key is what routed the- * record to this partition and so is what the politeness budget must be scoped to.+ * `domain` comes from the Kafka key, because the key routed the record to this partition, so the key+ * is what the politeness budget must be scoped to.*/export function parseCollectedUrlsRecord(value: Buffer | null, key: string | null): RecordParse {if (!value || !key) {return { ok: false, reason: 'malformed' }}+ // Normalized once here, because the budget, the metrics, and the republish key all read it. A+ // record written before the producer stripped the trailing dot carries the dotted spelling, and+ // two spellings of one domain would take two budgets on the same pod.+ const domain = withoutTrailingDot(key)let parsed: unknowntry {parsed = parseJSON(value.toString())@@ -60,7 +71,7 @@ export function parseCollectedUrlsRecord(value: Buffer | null, key: string | nulif (parsed.v !== 1) {return { ok: false, reason: 'unsupported_version' }}- const { pseudoTeam, capturedAtMs, urls } = parsed+ const { pseudoTeam, capturedAtMs, urls, hopsRemaining, notBeforeMs } = parsedif (typeof pseudoTeam !== 'string' || !pseudoTeam || typeof capturedAtMs !== 'number' || !Array.isArray(urls)) {return { ok: false, reason: 'malformed' }}@@ -74,6 +85,12 @@ export function parseCollectedUrlsRecord(value: Buffer | null, key: string | nulreturn { ok: false, reason: 'oversized_record' }}+ // Absent means a record straight from the mirror, which has made no moves and may go now. Both+ // fields are optional additions rather than a new version, so a consumer that predates them+ // reads such a record as it always did: full budget, fetch immediately.+ const hops = clampHops(hopsRemaining)+ const notBefore = typeof notBeforeMs === 'number' && Number.isFinite(notBeforeMs) ? notBeforeMs : 0+const candidates: FetchCandidate[] = []const rejected: { reason: UrlDropReason }[] = []for (const entry of urls) {@@ -91,9 +108,14 @@ export function parseCollectedUrlsRecord(value: Buffer | null, key: string | nulrejected.push({ reason: 'bad_url' })continue}- // The key is what the per-site budget is scoped to, so a host outside it would be rate- // limited against another site's allowance.- if (!hostBelongsToDomain(host, key)) {+ // The connection layer refuses a private address, so this is not the only guard against+ // one. It is the only guard against a name that looks internal and resolves to a public+ // address, because no address check can refuse that. Requirement 35.+ if (!isPublicHost(withoutTrailingDot(host))) {+ rejected.push({ reason: 'private_host' })+ continue+ }+ if (!hostIsKeyedByItsOperator(host, key)) {rejected.push({ reason: 'foreign_domain' })continue}@@ -102,16 +124,40 @@ export function parseCollectedUrlsRecord(value: Buffer | null, key: string | nulurlHash: ref.hash,url: entry.url,host,- domain: key,+ domain,pseudoTeam,capturedAtMs,+ hopsRemaining: hops,+ notBeforeMs: notBefore,})}return { ok: true, candidates, urlCount: urls.length, rejected }}-function hostBelongsToDomain(host: string, domain: string): boolean {- return host === domain || host.endsWith(`.${domain}`)+/** A record naming more hops than the budget allows is treated as a full budget, so a bad producer cannot buy itself extra trips. */+function clampHops(value: unknown): number {+ if (typeof value !== 'number' || !Number.isFinite(value)) {+ return MAX_HOPS+ }+ return Math.max(0, Math.min(MAX_HOPS, Math.floor(value)))+}++/**+ * The key must be the registrable domain of the host, not merely a domain the host sits under. A key+ * of `cdn.example.com` would give that subdomain a rate budget of its own, and a producer that+ * writes one key for each subdomain would hand one operator a multiple of the rate we promise it.+ * The key also decides the partition, so a record that fails this test is on the wrong partition as+ * well. Requirement 3.+ *+ * This drops the trailing dot first. `example.com.` and `example.com` name the same host, and a+ * record written before the producer stripped the dot carries the dotted form.+ */+function hostIsKeyedByItsOperator(host: string, key: string): boolean {+ return politenessKey(withoutTrailingDot(host)) === withoutTrailingDot(key)+}++function withoutTrailingDot(value: string): string {+ return value.endsWith('.') ? value.slice(0, -1) : value}/**@@ -125,7 +171,17 @@ function isFetchableUrl(url: string, host: string): boolean {}try {const parsed = new URL(url)- return FETCHABLE_SCHEMES.has(parsed.protocol) && parsed.hostname === host+ // HTTPS only, which is what the collector produces. A plain HTTP URL would put an image on+ // the wire in clear text, and requirement 9 keeps a redirect off HTTP only if the first URL+ // is HTTPS.+ if (parsed.protocol !== 'https:' || parsed.hostname !== host) {+ return false+ }+ // The lane refuses both on a redirect target, so it holds the first hop to the same rule. A+ // port other than the scheme's own would make this lane a port prober, and userinfo is a+ // credential this lane never sends. The canonicalizer strips both, so this checks against a+ // wrong or stale producer rather than an expected case.+ return parsed.port === '' && !parsed.username && !parsed.password} catch {return false}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.test.tssimilarity index 74%rename from nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.test.tsrename to nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.test.tsindex 3994c5ef456f..5832caf22d34 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.test.ts@@ -1,11 +1,11 @@-import { SightingRedis, SightingRedisPool, UrlSightings } from './url-sightings'+import { CrawlHistory, CrawlHistoryRedis, CrawlHistoryRedisPool } from './crawl-history'/** Above one round trip's key limit, so every test crosses a chunk boundary. */const KEYS = Array.from({ length: 600 }, (_value, index) => `k${index}`)type ExecResult = [Error | null, unknown][] | null-class FakeClient implements SightingRedis {+class FakeClient implements CrawlHistoryRedis {public readonly pipelined: string[] = []constructor(private readonly behavior: {@@ -33,7 +33,7 @@ class FakeClient implements SightingRedis {}}-function poolOf(client: FakeClient): SightingRedisPool {+function poolOf(client: FakeClient): CrawlHistoryRedisPool {return {acquire: () => Promise.resolve(client),release: () => Promise.resolve(),@@ -41,23 +41,23 @@ function poolOf(client: FakeClient): SightingRedisPool {}}-describe('UrlSightings', () => {- const build = (client: FakeClient, budgetMs = 60_000): UrlSightings =>- new UrlSightings(poolOf(client), 1_000, budgetMs)+describe('CrawlHistory', () => {+ const build = (client: FakeClient, budgetMs = 60_000): CrawlHistory =>+ new CrawlHistory(poolOf(client), 1_000, budgetMs)it('reports the index of every key that exists, across chunk boundaries', async () => {- // The one place a silent mistake is possible: the caller maps these indexes back onto its- // own candidate list, so an off-by-one skips the wrong URL and nothing surfaces it.+ // The caller maps these indexes back onto its own candidate list, so an off-by-one skips the+ // wrong URL and nothing reports it.const present = new Set(['k0', 'k255', 'k256', 'k599'])const client = new FakeClient({ mget: (keys) => keys.map((key) => (present.has(key) ? '{}' : null)) })const result = await build(client).read(KEYS)expect([...result.known].sort((a, b) => a - b)).toEqual([0, 255, 256, 599])- expect(result.failed).toBe(0)+ expect(result.failed.size).toBe(0)})- it('counts a chunk that throws as failed rather than as absent', async () => {+ it('reports the index of every key in a chunk that threw, rather than calling them absent', async () => {const client = new FakeClient({mget: (keys) => {if (keys.includes('k256')) {@@ -69,7 +69,10 @@ describe('UrlSightings', () => {const result = await build(client).read(KEYS)- expect(result.failed).toBe(256)+ // The caller drops these rather than fetches them, so it needs which keys, not how many.+ expect(result.failed.size).toBe(256)+ expect(result.failed.has(256)).toBe(true)+ expect(result.failed.has(255)).toBe(false)expect(result.known.size).toBe(0)})@@ -92,8 +95,8 @@ describe('UrlSightings', () => {})it('stops issuing round trips once the batch budget is spent', async () => {- // A batch that outruns the heartbeat gets the pod restarted onto the same offsets, so the- // lane sheds the rest of the work instead.+ // A batch that runs past the heartbeat restarts the pod onto the same offsets, so the lane+ // sheds the rest of the work instead.const client = new FakeClient({mget: async (keys) => {await new Promise((resolve) => setTimeout(resolve, 20))@@ -103,7 +106,7 @@ describe('UrlSightings', () => {const result = await build(client, 30).read(KEYS)- expect(result.failed).toBeGreaterThan(0)+ expect(result.failed.size).toBeGreaterThan(0)})it('writes every key exactly once', async () => {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.tssimilarity index 54%rename from nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.tsrename to nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.tsindex 7ced023d7069..0520f49a36b2 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.ts@@ -1,28 +1,27 @@import { Pool } from 'generic-pool'/**- * The dry run records sightings under their own prefix, separate from the fetch results a later- * lane will write.+ * The keyspace of the URL-seen test, asked before every fetch. An entry means this lane finished+ * with the URL, whatever the outcome, so a URL the site refused sits beside one it served.*- * Two stores rather than one outcome value, because they answer different questions and only one of- * them may suppress a request. A sighting says this lane has handled a URL, which is what the phase- * 0 dedup measurement counts. It says nothing about bytes, because none were downloaded. Sharing a- * keyspace would leave whoever enables fetching with 30 days of entries that look like completed- * work, and every URL behind them would be skipped with no error and no metric to show it.+ * The entry says nothing about the bytes, which live under their own keys once a later lane writes+ * them. One keyspace for both would leave whoever enables fetching with a month of entries that look+ * like completed downloads, and the lane would skip every URL behind them with no error.*/-const SIGHTING_PREFIX = 'imgfetch:seen'+const CRAWL_HISTORY_PREFIX = 'imgfetch:seen'/**- * Long enough that the key count converges on the distinct-URL count of the window, which is the- * number that sizes the Redis. Short enough that sightings cannot outlive the phase that wrote them.+ * The recrawl interval. Long enough that the key count converges on the distinct-URL count of the+ * window, which is the number that sizes the Redis. Short enough that an entry cannot outlive the+ * phase that wrote it.*/-export const SIGHTING_TTL_SECONDS = 30 * 24 * 60 * 60+export const CRAWL_HISTORY_TTL_SECONDS = 30 * 24 * 60 * 60/** Bounds one round trip. A poll batch can carry thousands of URLs, and one pipeline holding all of them times out as a unit. */const MAX_KEYS_PER_ROUND_TRIP = 256-export function sightingKey(pseudoTeam: string, urlHash: string): string {- return `${SIGHTING_PREFIX}:${pseudoTeam}:${urlHash}`+export function crawlHistoryKey(pseudoTeam: string, urlHash: string): string {+ return `${CRAWL_HISTORY_PREFIX}:${pseudoTeam}:${urlHash}`}function chunk<T>(items: T[], size: number): T[][] {@@ -33,18 +32,18 @@ function chunk<T>(items: T[], size: number): T[][] {return out}-export interface SightingReadResult {- /** Indexes of the keys that were already recorded. */+export interface CrawlHistoryReadResult {+ /** Indexes of the keys the store already holds. */known: Set<number>- /** Keys whose read did not complete, which the caller must treat as unknown rather than as absent. */- failed: number+ /** Indexes whose read did not complete. The caller knows nothing about these, which is not the same as knowing they are absent. */+ failed: Set<number>}/**- * The two commands this store issues. Narrower than `Redis` so a test supplies exactly these, and a- * command added here has to be added to the fake before it compiles.+ * Narrower than `Redis`, so a test supplies exactly these commands, and a command added here must+ * reach the fake before this compiles.*/-export interface SightingRedis {+export interface CrawlHistoryRedis {mget(...keys: string[]): Promise<(string | null)[]>pipeline(): {set(key: string, value: string, expiryMode: 'EX', seconds: number): unknown@@ -52,36 +51,35 @@ export interface SightingRedis {}}-/** The three pool operations this store uses. Narrow so a test needs no cast to supply them. */-export type SightingRedisPool = Pick<Pool<SightingRedis>, 'acquire' | 'release' | 'destroy'>+/** Narrow, so a test supplies these operations without a cast. */+export type CrawlHistoryRedisPool = Pick<Pool<CrawlHistoryRedis>, 'acquire' | 'release' | 'destroy'>/** What the consumer needs of the store, so its tests exercise the real contract rather than a cast. */-export interface SightingStore {- read(keys: string[]): Promise<SightingReadResult>+export interface CrawlHistoryStore {+ read(keys: string[]): Promise<CrawlHistoryReadResult>record(keys: string[], nowMs: number, ttlSeconds: number): Promise<{ failed: Set<number> }>}/**- * The record of which image URLs this lane has already reached, shared by every pod.+ * Every pod shares this store. The in-memory cache in front of it holds only what one pod saw since+ * it started, so a rebalance or a restart would otherwise count every URL again. A lost store costs+ * an overstated measurement now, and outbound requests once fetching is on. It never costs+ * correctness.*- * The in-memory cache in front of it holds only what one pod saw since it started, so a rebalance- * or a restart would otherwise count every URL again. Losing this store costs an overstated- * measurement now, and outbound requests once fetching is on. It never costs correctness.- *- * Both methods stop early once the batch budget is spent and report the rest as failed. A batch that- * runs past Kafka's max.poll.interval.ms gets the pod evicted mid-batch, and the partition is then- * replayed by a pod that will take just as long, so offered load rises while throughput falls.+ * Both methods stop early once the batch budget is spent and report the rest as failed. Kafka evicts+ * a pod whose batch runs past max.poll.interval.ms, and the next pod replays that partition and+ * takes just as long, so offered load rises while throughput falls.*/-export class UrlSightings implements SightingStore {+export class CrawlHistory implements CrawlHistoryStore {constructor(- private readonly pool: SightingRedisPool,+ private readonly pool: CrawlHistoryRedisPool,private readonly commandTimeoutMs: number,private readonly batchBudgetMs: number) {}- public async read(keys: string[]): Promise<SightingReadResult> {+ public async read(keys: string[]): Promise<CrawlHistoryReadResult> {const known = new Set<number>()- let failed = 0+ const failed = new Set<number>()await this.forEachChunk(keys, {onChunk: async (client, batch, base) => {const values = await client.mget(...batch)@@ -91,8 +89,8 @@ export class UrlSightings implements SightingStore {}})},- onChunkFailed: (batch) => {- failed += batch.length+ onChunkFailed: (batch, base) => {+ batch.forEach((_key, index) => failed.add(base + index))},})return { known, failed }@@ -105,8 +103,8 @@ export class UrlSightings implements SightingStore {onChunk: async (client, batch, base) => {const pipeline = client.pipeline()for (const key of batch) {- // One command, so a key can never be left without its expiry. A separate EXPIRE- // can be the command that fails, and the key it leaves behind is never reclaimed.+ // One command, so a key can never sit without its expiry. A separate EXPIRE can+ // be the command that fails, and Redis never reclaims the key it leaves behind.pipeline.set(key, value, 'EX', ttlSeconds)}const results = (await pipeline.exec()) as [Error | null, unknown][] | null@@ -127,7 +125,7 @@ export class UrlSightings implements SightingStore {private async forEachChunk(keys: string[],handlers: {- onChunk: (client: SightingRedis, batch: string[], base: number) => Promise<void>+ onChunk: (client: CrawlHistoryRedis, batch: string[], base: number) => Promise<void>onChunkFailed: (batch: string[], base: number) => void}): Promise<void> {@@ -151,13 +149,13 @@ export class UrlSightings implements SightingStore {/*** The pool rejects rather than queues once its own acquire timeout passes, so this never races- * `acquire()`. generic-pool cannot cancel one, and a caller that walked away from a pending- * acquire is still handed the next free connection and still counted as borrowing it.+ * `acquire()`. generic-pool cannot cancel an acquire, and it still hands the next free connection+ * to a caller that walked away, and still counts that caller as a borrower.*- * A connection whose command was abandoned is destroyed rather than returned, because its reply- * is still in flight and would be read as the answer to whichever command borrowed it next.+ * This destroys a connection whose command it abandoned rather than returns it, because the+ * reply is still in flight and would read as the answer to whichever command borrows it next.*/- private async withClient(run: (client: SightingRedis) => Promise<void>): Promise<void> {+ private async withClient(run: (client: CrawlHistoryRedis) => Promise<void>): Promise<void> {const client = await this.pool.acquire()let timer: NodeJS.Timeout | undefinedtry {@@ -165,7 +163,7 @@ export class UrlSightings implements SightingStore {run(client),new Promise<never>((_resolve, reject) => {timer = setTimeout(- () => reject(new Error('sighting store command timed out')),+ () => reject(new Error('crawl history command timed out')),this.commandTimeoutMs)timer.unref()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.tsnew file mode 100644index 000000000000..68a0c32580c3--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts@@ -0,0 +1,490 @@+import { delay } from '~/common/utils/utils'++import { FetchCandidate, MAX_HOPS } from './collected-urls-record'+import { FetchRunner, FetchRunnerOptions, isTerminal } from './fetch-runner'+import { FrontierPublisher } from './frontier-publisher'+import { HostBudget } from './host-budget'+import { FetchOutcome, ImageFetchResult, ImageFetcher, RedirectDecision } from './image-fetcher'++const OPTIONS: FetchRunnerOptions = {+ maxConcurrentPerDomain: 2,+ maxInFlightRequests: 50,+ batchBudgetMs: 5000,+ maxBytes: 1000,+ requestTimeoutMs: 1000,+ maxRedirects: 3,+ defaultRetryAfterMs: 60_000,+}++function candidate(domain: string, index: number): FetchCandidate {+ return {+ ref: `imageurl:team:${domain}-${index}`,+ urlHash: `${domain}-${index}`,+ url: `https://cdn.${domain}/${index}.png`,+ host: `cdn.${domain}`,+ domain,+ pseudoTeam: 'team',+ capturedAtMs: 1000,+ hopsRemaining: MAX_HOPS,+ notBeforeMs: 0,+ }+}++class FakeFetcher implements ImageFetcher {+ public calls: string[] = []+ public peakConcurrent = 0+ private inFlight = 0++ constructor(private readonly answer: (url: string) => Partial<ImageFetchResult>) {}++ public async fetch(url: string): Promise<ImageFetchResult> {+ this.calls.push(url)+ this.inFlight+++ this.peakConcurrent = Math.max(this.peakConcurrent, this.inFlight)+ await Promise.resolve()+ this.inFlight--+ return { outcome: 'ok', redirects: 0, ...this.answer(url) }+ }+}++const FAR_FUTURE = 10 ** 12++const defaultBudget = (): HostBudget =>+ new HostBudget({+ requestsPerSecond: 1000,+ burst: 1000,+ maxConcurrent: 4,+ breakerFailures: 3,+ breakerCooldownMs: 60_000,+ breakerMaxCooldownMs: 600_000,+ maxTrackedDomains: 100,+ })++function runner(+ fetcher: ImageFetcher,+ options: Partial<FetchRunnerOptions> = {},+ budget = new HostBudget({+ requestsPerSecond: 1000,+ burst: 1000,+ maxConcurrent: 4,+ breakerFailures: 3,+ breakerCooldownMs: 60_000,+ breakerMaxCooldownMs: 600_000,+ maxTrackedDomains: 100,+ }),+ publisher: FrontierPublisher = noopPublisher()+): FetchRunner {+ return new FetchRunner(fetcher, budget, { ...OPTIONS, ...options }, publisher)+}++function noopPublisher(): FrontierPublisher {+ return { republish: () => Promise.resolve(true) } as unknown as FrontierPublisher+}++describe('FetchRunner', () => {+ it('sheds every remaining URL of a domain that answered 429, and leaves the other domain alone', async () => {+ const fetcher = new FakeFetcher((url) =>+ url.includes('busy.com') ? { outcome: 'rate_limited', status: 429 } : { outcome: 'ok' }+ )+ const candidates = [+ ...[0, 1, 2].map((index) => candidate('busy.com', index)),+ ...[0, 1].map((index) => candidate('calm.com', index)),+ ]++ const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1 }).run(candidates)++ expect(fetcher.calls.filter((url) => url.includes('busy.com'))).toHaveLength(1)+ expect(attempts.filter((a) => a.outcome === 'rate_limited')).toHaveLength(3)+ expect(attempts.filter((a) => a.candidate.domain === 'calm.com' && a.outcome === 'ok')).toHaveLength(2)+ })++ it('stops sending to a domain once its breaker opens', async () => {+ const fetcher = new FakeFetcher(() => ({ outcome: 'timeout' }))+ const candidates = [0, 1, 2, 3, 4, 5].map((index) => candidate('broken.com', index))++ const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1 }).run(candidates)++ expect(fetcher.calls).toHaveLength(3)+ expect(attempts.filter((a) => a.outcome === 'breaker_open')).toHaveLength(3)+ })++ it('holds one domain to the configured number of connections', async () => {+ const fetcher = new FakeFetcher(() => ({ outcome: 'ok' }))++ await runner(fetcher, { maxConcurrentPerDomain: 2 }).run(+ [0, 1, 2, 3, 4, 5].map((index) => candidate('example.com', index))+ )++ expect(fetcher.peakConcurrent).toBe(2)+ })++ it('sheds what the rate would not carry before the batch budget runs out', async () => {+ const budget = new HostBudget({+ requestsPerSecond: 1,+ burst: 1,+ maxConcurrent: 4,+ breakerFailures: 100,+ breakerCooldownMs: 60_000,+ breakerMaxCooldownMs: 600_000,+ maxTrackedDomains: 100,+ })+ const fetcher = new FakeFetcher(() => ({ outcome: 'ok' }))++ // Long enough to grant the first URL whatever the machine is doing, and far shorter than+ // the wait of the second. A budget of zero makes the first grant depend on less than a+ // millisecond passing between two clock reads, which is a race a loaded runner loses.+ const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1, batchBudgetMs: 50 }, budget).run(+ [0, 1, 2].map((index) => candidate('slow.com', index))+ )++ // The burst token carries the first URL. Each of the rest needs a second of waiting, which+ // the batch does not have.+ expect(fetcher.calls).toHaveLength(1)+ expect(attempts.filter((a) => a.outcome === 'deadline')).toHaveLength(2)+ })++ it('does not write off a URL whose redirect target had no budget left', async () => {+ const fetcher = new FakeFetcher(() => ({ outcome: 'redirect_deferred', status: 302 }))++ const attempts = await runner(fetcher).run([candidate('example.com', 0)])++ expect(isTerminal(attempts[0].outcome)).toBe(false)+ })++ it('handles a domain with more queued URLs than a spread can carry', async () => {+ // One batch offers up to BATCH_SIZE x MAX_URLS_PER_RECORD URLs, and the topic keys by+ // domain, so a popular CDN can fill one queue past the argument limit of Function.apply. A+ // RangeError escapes the pass, and the consumer then records nothing for the batch.+ const budget = new HostBudget({+ requestsPerSecond: 1,+ burst: 1,+ maxConcurrent: 4,+ breakerFailures: 100,+ breakerCooldownMs: 60_000,+ breakerMaxCooldownMs: 600_000,+ maxTrackedDomains: 100,+ })+ const fetcher = new FakeFetcher(() => ({ outcome: 'ok' }))+ const many = Array.from({ length: 130_000 }, (_value, index) => candidate('big.com', index))++ // A zero budget is safe here because the count below is the same whether or not the first+ // URL wins its grant. Do not copy it into a test that asserts how many requests went out,+ // because that turns on less than a millisecond passing between two clock reads.+ const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1, batchBudgetMs: 0 }, budget).run(many)++ expect(attempts).toHaveLength(many.length)+ })++ it('hands a redirect off rather than following it to another domain (requirement 7)', async () => {+ const published: { domain: string; url: string; reason: string }[] = []+ const publisher = {+ republish: (candidate: FetchCandidate, target: { url: string; domain: string }, reason: string) => {+ published.push({ domain: target.domain, url: target.url, reason })+ return Promise.resolve(true)+ },+ } as unknown as FrontierPublisher+ let offsite: boolean | undefined+ const fetcher: ImageFetcher = {+ fetch: (_url, options) => {+ offsite = options.isOffsite(new URL('https://img.other-site.net/a.png'))+ return Promise.resolve({+ outcome: 'redirect_offsite',+ redirects: 1,+ redirectTarget: { url: 'https://img.other-site.net/a.png', host: 'img.other-site.net' },+ })+ },+ }++ const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([candidate('example.com', 0)])++ expect(offsite).toBe(true)+ expect(published).toEqual([+ { domain: 'other-site.net', url: 'https://img.other-site.net/a.png', reason: 'redirect' },+ ])+ // The URL comes back on another partition, so a crawl history entry would stop that.+ expect(attempts[0].finished).toBe(false)+ })++ it('stops a redirect whose domain was blocked while it waited (requirement 5)', async () => {+ const budget = new HostBudget({+ requestsPerSecond: 1,+ burst: 1,+ maxConcurrent: 6,+ breakerFailures: 100,+ breakerCooldownMs: 60_000,+ breakerMaxCooldownMs: 600_000,+ maxTrackedDomains: 100,+ })+ // Spend the burst token, so the redirect below has to wait a second for the next one.+ budget.take('example.com', Date.now(), Date.now() + 60_000)+ let decision: RedirectDecision | undefined+ const fetcher: ImageFetcher = {+ fetch: async (_url, options) => {+ setTimeout(() => budget.recordRetryAfter('example.com', Date.now(), 60_000), 5)+ decision = await options.authorizeRedirect(new URL('https://img2.example.com/a.png'), 30_000)+ return { outcome: 'ok', redirects: 1 }+ },+ }++ await runner(fetcher, {}, budget).run([candidate('example.com', 0)])++ expect(decision).toBe('defer')+ })++ it('follows a redirect that stays on the same domain (requirement 6)', async () => {+ let decision: RedirectDecision | undefined+ const fetcher: ImageFetcher = {+ fetch: async (_url, options) => {+ decision = await options.authorizeRedirect(new URL('https://img2.example.com/a.png'), 5000)+ return { outcome: 'ok', redirects: 1 }+ },+ }++ await runner(fetcher).run([candidate('example.com', 0)])++ expect(decision).toBe('allow')+ })++ it('publishes a transient failure to a delay topic rather than dropping it (requirement 14)', async () => {+ const published: { reason: string; waitMs: number }[] = []+ const publisher = {+ republish: (_c: FetchCandidate, _t: unknown, reason: string, waitMs: number) => {+ published.push({ reason, waitMs })+ return Promise.resolve(true)+ },+ } as unknown as FrontierPublisher+ const fetcher = new FakeFetcher(() => ({ outcome: 'rate_limited', status: 429, retryAfterMs: 30_000 }))++ const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([candidate('busy.com', 0)])++ expect(published).toEqual([{ reason: 'retry', waitMs: 30_000 }])+ expect(attempts[0].finished).toBe(false)+ })++ it.each([+ ['a retry', { outcome: 'timeout' as const }],+ [+ 'a redirect',+ {+ outcome: 'redirect_offsite' as const,+ redirectTarget: { url: 'https://cdn.other.com/i.png', host: 'cdn.other.com' },+ },+ ],+ ])(+ 'reports %s the publisher could not send, so the batch does not commit past it (requirement 21)',+ async (_name, result) => {+ const publisher = { republish: () => Promise.resolve(false) } as unknown as FrontierPublisher+ const fetcher = new FakeFetcher(() => result)++ const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([candidate('example.com', 0)])++ expect(attempts[0]).toMatchObject({ finished: false, lost: true })+ }+ )++ it('reports nothing lost when the publisher sent the URL', async () => {+ const publisher = { republish: () => Promise.resolve(true) } as unknown as FrontierPublisher+ const fetcher = new FakeFetcher(() => ({ outcome: 'timeout' as const }))++ const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([candidate('example.com', 0)])++ expect(attempts[0]).toMatchObject({ finished: false, lost: false })+ })++ it('checks again when a request reaches the front of the pod queue (requirement 5)', async () => {+ // A sibling request can meet a `Retry-After` while this one waits for a pod slot, and a+ // request sent after that reaches a site which just asked to be left alone.+ const budget = defaultBudget()+ const published: string[] = []+ const publisher = {+ republish: (_c: FetchCandidate, _t: unknown, reason: string) => {+ published.push(reason)+ return Promise.resolve(true)+ },+ } as unknown as FrontierPublisher+ const fetcher: ImageFetcher = {+ fetch: async (url: string) => {+ if (url.endsWith('/0.png')) {+ // This yields first, so the second request passes the token bucket and reaches+ // the pod queue before the hold exists. Without the yield the token bucket+ // refuses it, and this test passes whatever the queue does.+ await delay(1)+ budget.recordRetryAfter('example.com', Date.now(), 60_000)+ }+ return { outcome: 'ok' as const, redirects: 0 }+ },+ }++ const attempts = await runner(fetcher, { maxInFlightRequests: 1 }, budget, publisher).run([+ candidate('example.com', 0),+ candidate('example.com', 1),+ ])++ expect(attempts.map((attempt) => attempt.outcome).sort()).toEqual(['ok', 'rate_limited'])+ expect(published).toEqual(['retry'])+ })++ it('puts back a bounded number of shed URLs, and does it in one go', async () => {+ // A shed runs after the pass deadline has passed. One awaited produce for each URL of a+ // large back queue would run past max.poll.interval.ms and lose the partition mid-batch,+ // and putting every one of them back answers overload with more Kafka traffic.+ let open = 0+ let peak = 0+ let published = 0+ const publisher = {+ republish: async () => {+ open+++ peak = Math.max(peak, open)+ await Promise.resolve()+ published+++ open--+ return true+ },+ } as unknown as FrontierPublisher+ const fetcher = new FakeFetcher(() => ({ outcome: 'rate_limited', status: 429, retryAfterMs: 30_000 }))+ const queue = Array.from({ length: 2500 }, () => candidate('busy.com', 0))++ const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run(queue)++ expect(attempts).toHaveLength(2500)+ // The cap, plus the few that held a burst token and were fetched before the 429 blocked the+ // domain. Well under 2500, which is what one awaited produce for each would have cost.+ expect(published).toBeGreaterThanOrEqual(1000)+ expect(published).toBeLessThanOrEqual(1000 + OPTIONS.maxConcurrentPerDomain)+ // More than one produce was open at a time, so the shed did not await them one by one.+ expect(peak).toBeGreaterThan(1)+ })++ it('bounds the shed republish across the whole pass, not once for each domain', async () => {+ // Domains run at the same time, so an allowance for each of them multiplies by however many+ // a batch touches. One busy domain per record of a full batch would open that many times+ // the cap as Kafka produces at once, past what the producer queue holds.+ let open = 0+ let peak = 0+ let published = 0+ const publisher = {+ republish: async () => {+ open+++ peak = Math.max(peak, open)+ await Promise.resolve()+ published+++ open--+ return true+ },+ } as unknown as FrontierPublisher+ const fetcher = new FakeFetcher(() => ({ outcome: 'rate_limited', status: 429, retryAfterMs: 30_000 }))+ // 40 domains, 100 URLs each. A per-domain cap of 1000 would put back all 4000.+ const queue = Array.from({ length: 40 }).flatMap((_unused, domain) =>+ Array.from({ length: 100 }, () => candidate(`site${domain}.com`, 0))+ )++ const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run(queue)++ expect(attempts).toHaveLength(4000)+ // The pass allowance, plus the few per domain that held a burst token and were fetched.+ expect(published).toBeLessThanOrEqual(1000 + 40 * OPTIONS.maxConcurrentPerDomain)+ expect(peak).toBeLessThanOrEqual(1000 + 40 * OPTIONS.maxConcurrentPerDomain)+ })++ it('gives up and records a URL with no hops left (requirement 12)', async () => {+ const publisher = { republish: () => Promise.resolve(true) } as unknown as FrontierPublisher+ const fetcher = new FakeFetcher(() => ({ outcome: 'timeout' }))+ const spent = { ...candidate('example.com', 0), hopsRemaining: 1 }++ const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([spent])++ expect(attempts[0]).toMatchObject({ outcome: 'hops_exhausted', finished: true })+ })++ it('runs every domain at once but holds the requests under them to the in-flight limit', async () => {+ let inFlight = 0+ let peak = 0+ const fetcher: ImageFetcher = {+ fetch: async () => {+ peak = Math.max(peak, ++inFlight)+ await new Promise((resolve) => setTimeout(resolve, 5))+ inFlight--+ return { outcome: 'ok', redirects: 0 }+ },+ }+ const domains = Array.from({ length: 60 }, (_value, index) => candidate(`site${index}.com`, 0))++ const attempts = await runner(fetcher, { maxInFlightRequests: 5 }).run(domains)++ expect(peak).toBe(5)+ expect(attempts.filter((a) => a.outcome === 'ok')).toHaveLength(60)+ })++ it.each([+ ['a 429', 'rate_limited' as const, undefined, true],+ ['a 503 that named a period', 'server_error' as const, 30_000, true],+ ['a one-off 500', 'server_error' as const, undefined, false],+ ])('holds the whole domain after %s: %s', async (_name, outcome, retryAfterMs, expectHeld) => {+ // A hold silences every URL of the domain. A site that failed one request did not ask for+ // that, so it gets the rate cut and the breaker count instead.+ const fetcher = new FakeFetcher(() => ({ outcome, status: 500, retryAfterMs }))++ const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1 }).run(+ [0, 1].map((index) => candidate('site.com', index))+ )++ expect(attempts.some((a) => a.outcome === 'rate_limited')).toBe(expectHeld)+ })++ it('does not send a request whose domain was blocked while it waited (requirement 5)', async () => {+ const budget = new HostBudget({+ requestsPerSecond: 1,+ burst: 1,+ maxConcurrent: 6,+ breakerFailures: 100,+ breakerCooldownMs: 60_000,+ breakerMaxCooldownMs: 600_000,+ maxTrackedDomains: 100,+ })+ const fetcher = new FakeFetcher(() => ({ outcome: 'ok' }))+ // The burst token carries the first URL. The second waits a second for its token, and the+ // site says stop during that wait.+ setTimeout(() => budget.recordRetryAfter('slow.com', Date.now(), 60_000), 5)++ const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1 }, budget).run(+ [0, 1].map((index) => candidate('slow.com', index))+ )++ expect(fetcher.calls).toHaveLength(1)+ expect(attempts.filter((a) => a.outcome === 'rate_limited')).toHaveLength(1)+ })++ it('returns the token of a request it did not send (requirement 5)', () => {+ const budget = new HostBudget({+ requestsPerSecond: 1,+ burst: 2,+ maxConcurrent: 6,+ breakerFailures: 100,+ breakerCooldownMs: 60_000,+ breakerMaxCooldownMs: 600_000,+ maxTrackedDomains: 100,+ })+ budget.take('example.com', 1000, FAR_FUTURE)+ budget.take('example.com', 1000, FAR_FUTURE)++ budget.returnGrant('example.com', 1000)++ expect(budget.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 0 })+ })++ it.each([+ ['ok', true],+ ['not_found', true],+ ['too_large', true],+ ['blocked', true],+ ['timeout', false],+ ['rate_limited', false],+ ['server_error', false],+ ['breaker_open', false],+ ['deadline', false],+ ])('treats %s as terminal: %s', (outcome, terminal) => {+ // A terminal outcome writes a crawl history entry, which is the one thing that stops this+ // lane from looking at the URL again. A transient outcome must not write one.+ expect(isTerminal(outcome as FetchOutcome)).toBe(terminal)+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.tsnew file mode 100644index 000000000000..d39e310ce969--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts@@ -0,0 +1,516 @@+import { ConcurrencyController } from '~/common/utils/concurrencyController'+import { logger } from '~/common/utils/logger'+import { delay } from '~/common/utils/utils'++import { FetchCandidate, MAX_HOPS } from './collected-urls-record'+import { FrontierPublisher } from './frontier-publisher'+import { HostBudget } from './host-budget'+import { FetchOutcome, ImageFetchResult, ImageFetcher, RedirectDecision } from './image-fetcher'+import { ImageFetchRequestMetrics } from './metrics'+import { politenessKey } from './politeness-key'++/** Why a URL never reached a request. It shares `rate_limited` with the response of the same name, because both mean the site asked us to wait. */+export type ShedReason = 'breaker_open' | 'rate_limited' | 'deadline' | 'connection_limit'++/** A URL that ran out of hops. The lane records it so it stops coming back. Requirement 12. */+export const HOPS_EXHAUSTED = 'hops_exhausted'++export type AttemptOutcome = FetchOutcome | ShedReason | typeof HOPS_EXHAUSTED++export interface FetchAttempt {+ candidate: FetchCandidate+ outcome: AttemptOutcome+ /**+ * True when the lane is done with this URL and must write it to the crawl history.+ *+ * False means the URL comes back, from a republish to the frontier or to a delay topic, or from+ * a failed republish. A crawl history entry for one of those stops it ever being fetched.+ * Requirements 12 and 24.+ */+ finished: boolean+ /**+ * True when the URL was meant to go back to Kafka and did not.+ *+ * Nothing else holds it, so its offset must not commit. The URL is otherwise gone until a+ * session refers to the same image again. Requirement 21.+ */+ lost: boolean+}++export interface FetchRunnerOptions {+ /** Workers per domain. The limit itself lives in the budget, because a redirect reaches a domain without passing through this pool. */+ maxConcurrentPerDomain: number+ /**+ * Requests open across every domain at once. This bounds the pod rather than politeness.+ *+ * The lane reads a body into a buffer, so the peak memory is about this number times the byte+ * limit. The sockets and the DNS lookups come with it.+ */+ maxInFlightRequests: number+ /** Wall time the whole pass may take. The lane sheds a URL it does not reach, and fetches it again when a session next refers to it. */+ batchBudgetMs: number+ maxBytes: number+ requestTimeoutMs: number+ maxRedirects: number+ /** Used for a 429 or a 503 that named no period, so a site that only says "slow down" still gets a pause. */+ defaultRetryAfterMs: number+}++/**+ * Outcomes that will not change if the lane tries the same URL again.+ *+ * Only these write a crawl history entry. The lane leaves a URL shed by the budget, or lost to a+ * timeout, unrecorded, because it goes back to a delay topic and comes round again. An entry for one+ * of those would suppress the URL for the whole crawl history TTL because a site was busy for a+ * moment.+ */+const TERMINAL_OUTCOMES: ReadonlySet<AttemptOutcome> = new Set<AttemptOutcome>([+ 'ok',+ 'not_found',+ 'forbidden',+ 'too_large',+ 'not_image',+ 'blocked',+ 'bad_redirect',+ 'too_many_redirects',+ 'unexpected_status',+ // A property of the origin rather than of the moment, so a retry meets the same response and+ // spends a hop for nothing.+ 'unsupported_encoding',+])++/**+ * URLs one pass puts back after a shed, across every domain in it.+ *+ * A shed happens under overload, and one back queue can hold every URL of a batch. Republishing all+ * of them answers overload with more Kafka traffic, and the same URLs arrive again a minute later+ * having each spent a hop. Past this the rest are left unrecorded, so the mirror offers them again.+ *+ * One allowance for the pass rather than one for each domain, because domains run at the same time.+ * A per-domain cap multiplies by however many domains a batch touches, and a batch that offers+ * URLs across hundreds of them would open that many times this number of produces at once.+ */+const MAX_SHED_REPUBLISHED_PER_PASS = 1000++/** What is left of the pass allowance. Read and written between awaits, so a domain never sees a torn value. */+interface ShedAllowance {+ remaining: number+}++/** Hosts named in one batch-level log line, bounded so one bad batch cannot log a host list of its own size. */+const MAX_LOGGED_HOSTS = 5++/** These values come from the environment, where a typo parses to NaN and switches a politeness control off. */+function requirePositive(name: string, value: number): number {+ if (!Number.isFinite(value) || value <= 0) {+ throw new Error(`${name} must be a positive number, got ${value}`)+ }+ return value+}++export function isTerminal(outcome: AttemptOutcome): boolean {+ return TERMINAL_OUTCOMES.has(outcome)+}++/** What the consumer needs of the fetch pass, so its tests use the real contract rather than a cast. */+export interface FetchPass {+ run(candidates: FetchCandidate[]): Promise<FetchAttempt[]>+}++/**+ * Runs the fetches of one poll batch inside the per-domain budget.+ *+ * Domains run in parallel, so one slow site delays only its own URLs. Inside a domain the worker+ * count is the connection limit and the token bucket is the rate, so a domain receives from this+ * pod exactly what an operator configured for it.+ *+ * Wall time bounds the pass rather than work. A batch can hold more URLs for one domain than a+ * polite rate carries in the time a Kafka batch may take, and the lane then fetches fewer of them.+ */+export class FetchRunner implements FetchPass {+ private readonly inFlight: ConcurrencyController++ constructor(+ private readonly fetcher: ImageFetcher,+ private readonly budget: HostBudget,+ private readonly options: FetchRunnerOptions,+ /** Required, because without it every transient outcome becomes a loss rather than a retry. */+ private readonly publisher: FrontierPublisher+ ) {+ requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN', options.maxConcurrentPerDomain)+ requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS', options.maxInFlightRequests)+ this.inFlight = new ConcurrencyController(options.maxInFlightRequests)+ ImageFetchRequestMetrics.trackBudget(budget, this.inFlight)+ requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES', options.maxBytes)+ requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS', options.requestTimeoutMs)+ requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_DEFAULT_RETRY_AFTER_MS', options.defaultRetryAfterMs)+ // Zero is meaningful for both, and means no fetch at all and no redirect at all.+ if (!Number.isFinite(options.batchBudgetMs) || !Number.isFinite(options.maxRedirects)) {+ throw new Error('SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS and MAX_REDIRECTS must be numbers')+ }+ }++ public async run(candidates: FetchCandidate[]): Promise<FetchAttempt[]> {+ if (candidates.length === 0) {+ return []+ }+ const deadlineMs = Date.now() + this.options.batchBudgetMs+ const byDomain = new Map<string, FetchCandidate[]>()+ for (const candidate of candidates) {+ const backQueue = byDomain.get(candidate.domain)+ if (backQueue) {+ backQueue.push(candidate)+ } else {+ byDomain.set(candidate.domain, [candidate])+ }+ }++ const attempts = await this.runDomains([...byDomain], deadlineMs, { remaining: MAX_SHED_REPUBLISHED_PER_PASS })+ this.logFailures(attempts)+ return attempts+ }++ /**+ * One line for each outcome of the whole pass, because a site that is down turns every URL of a+ * batch into a log line. The counts answer the same question, and the hosts say where to look.+ *+ * A URL is page content, so it appears in no log.+ */+ private logFailures(attempts: FetchAttempt[]): void {+ const byOutcome = new Map<AttemptOutcome, { count: number; hosts: Set<string> }>()+ for (const attempt of attempts) {+ if (attempt.outcome === 'ok') {+ continue+ }+ const seen = byOutcome.get(attempt.outcome) ?? { count: 0, hosts: new Set<string>() }+ seen.count+++ if (seen.hosts.size < MAX_LOGGED_HOSTS) {+ seen.hosts.add(attempt.candidate.host)+ }+ byOutcome.set(attempt.outcome, seen)+ }+ for (const [outcome, seen] of byOutcome) {+ logger.warn('🌐', 'ml_image_fetch_batch_failures', {+ outcome,+ count: seen.count,+ hosts: [...seen.hosts],+ })+ }+ }++ /**+ * Every domain runs at once. A domain spends nearly all of its time waiting on its own rate+ * limit, so thousands of them cost a queue and a closure each, and a cap on domains would make+ * unrelated sites wait for each other for no reason of politeness.+ *+ * `maxInFlightRequests` bounds the requests underneath them.+ */+ private async runDomains(+ entries: [string, FetchCandidate[]][],+ deadlineMs: number,+ allowance: ShedAllowance+ ): Promise<FetchAttempt[]> {+ // Every domain writes into this array rather than concatenating afterwards. One batch can+ // offer hundreds of thousands of URLs to a single domain, and both `push(...array)` and+ // `concat` of that size exceed the argument limit of `Function.apply`.+ const attempts: FetchAttempt[] = []+ await Promise.all(+ entries.map(([domain, backQueue]) => this.runBackQueue(domain, backQueue, deadlineMs, attempts, allowance))+ )+ return attempts+ }++ /** A back queue is the crawler term for the queue of one registrable domain, which a politeness limit applies to. */+ private async runBackQueue(+ domain: string,+ backQueue: FetchCandidate[],+ deadlineMs: number,+ attempts: FetchAttempt[],+ allowance: ShedAllowance+ ): Promise<void> {+ let next = 0+ // A refusal is a property of the domain, so it applies to every URL still queued for it.+ const shedRemaining = async (reason: ShedReason, first?: FetchCandidate): Promise<void> => {+ const shed = first ? [first, ...backQueue.slice(next)] : backQueue.slice(next)+ next = backQueue.length+ if (shed.length === 0) {+ return+ }+ ImageFetchRequestMetrics.incOutcome(reason, shed.length)+ const waitMs = this.budget.blockedForMs(domain, Date.now())+ // Taken before the first await, so two domains shedding at once cannot both read the+ // same remainder and spend it twice.+ const takes = Math.min(shed.length, allowance.remaining)+ allowance.remaining -= takes+ // Together rather than one after another. A shed runs once the pass deadline has passed,+ // and one awaited produce for each of tens of thousands of URLs would run past+ // `max.poll.interval.ms` and lose the partition in the middle of the batch.+ const republished = await Promise.all(+ shed.slice(0, takes).map((candidate) => this.reschedule(candidate, reason, waitMs))+ )+ for (const attempt of republished) {+ attempts.push(attempt)+ }+ for (const candidate of shed.slice(takes)) {+ attempts.push({ candidate, outcome: reason, finished: false, lost: false })+ }+ if (shed.length > takes) {+ ImageFetchRequestMetrics.incShedDropped(shed.length - takes)+ }+ }++ const worker = async (): Promise<void> => {+ while (next < backQueue.length) {+ const grant = this.budget.take(domain, Date.now(), deadlineMs)+ if (!grant.granted) {+ await shedRemaining(grant.reason)+ return+ }+ const candidate = backQueue[next++]+ ImageFetchRequestMetrics.observeBudgetWait(grant.waitMs / 1000)+ if (grant.waitMs > 0) {+ await delay(grant.waitMs)+ // The budget granted this before the wait. A `Retry-After` or an open breaker+ // can arrive during the wait, and the deadline can pass. Requirement 5.+ const stale = this.staleAfterWait(domain, deadlineMs)+ if (stale) {+ this.budget.returnGrant(domain, Date.now())+ // The whole back queue, not this URL alone. Whatever went stale during the+ // wait is a property of the domain, so it holds for every URL still queued+ // for it. Requirement 16.+ await shedRemaining(stale, candidate)+ return+ }+ }+ attempts.push(await this.fetchOne(candidate, deadlineMs))+ }+ }++ const workers = Math.min(this.options.maxConcurrentPerDomain, backQueue.length)+ await Promise.all(Array.from({ length: workers }, () => worker()))+ }++ /** Why a granted request must not go out after its wait, or null when it may still go out. Requirement 5. */+ private staleAfterWait(domain: string, deadlineMs: number): ShedReason | null {+ const nowMs = Date.now()+ const blocked = this.budget.blockedReason(domain, nowMs)+ if (blocked) {+ return blocked+ }+ return nowMs > deadlineMs ? 'deadline' : null+ }++ /**+ * The request keeps its whole configured timeout even when the pass deadline is closer.+ *+ * A request that the batch clock cut short would time out through no fault of the site, and the+ * budget would read that as the site failing. So the deadline decides whether a request starts,+ * and never how long it may take. One pass can therefore run to `batchBudgetMs` plus one+ * request timeout, which is still far inside Kafka's max.poll.interval.ms.+ */+ private async fetchOne(candidate: FetchCandidate, deadlineMs: number): Promise<FetchAttempt> {+ // One slot, held until the chain ends. A chain reaches only its own domain, because+ // `isOffsite` refuses every other target, and the set makes a second take of the same+ // domain free so a redirect back to it cannot deadlock against itself.+ const held = new Set<string>()+ const acquire = (domain: string): boolean => {+ if (held.has(domain)) {+ return true+ }+ if (!this.budget.acquireConnection(domain, Date.now())) {+ return false+ }+ held.add(domain)+ return true+ }+ const releaseAll = (): void => {+ for (const domain of held) {+ this.budget.releaseConnection(domain)+ }+ }++ if (!acquire(candidate.domain)) {+ // One setting feeds both the worker count and this limit, so the pool already holds a+ // domain to the same number and nothing gets here today. The budget is where the limit+ // belongs, so the check stays. A refusal means the domain is busy now, which is not a+ // fact about the URL, so the lane writes no crawl history entry for it.+ this.budget.returnGrant(candidate.domain, Date.now())+ ImageFetchRequestMetrics.incOutcome('connection_limit')+ return await this.reschedule(candidate, 'connection_limit', 0)+ }++ const startedAt = process.hrtime.bigint()+ let outcome: ImageFetchResult | { shed: ShedReason }+ try {+ outcome = await this.inFlight.run<ImageFetchResult | { shed: ShedReason }>({+ debugTag: candidate.domain,+ fn: () => {+ // The pod queue is the third place a request waits, after the token bucket and+ // the connection limit, and it can hold a request longest because its slots+ // serve every domain this pod owns. A sibling request can meet a `Retry-After`+ // while this one queues. Requirement 5.+ const stale = this.staleAfterWait(candidate.domain, deadlineMs)+ if (stale) {+ return Promise.resolve({ shed: stale })+ }+ return this.fetcher.fetch(candidate.url, {+ maxBytes: this.options.maxBytes,+ timeoutMs: this.options.requestTimeoutMs,+ maxRedirects: this.options.maxRedirects,+ isOffsite: (url) => politenessKey(url.hostname) !== candidate.domain,+ // The earlier of the two clocks, because a wait that outlives the request+ // reports the site as timing out.+ authorizeRedirect: (url, remainingMs) =>+ this.authorizeRedirect(+ Math.min(deadlineMs, Date.now() + remainingMs),+ acquire,+ candidate.domain+ ),+ })+ },+ })+ } catch (error) {+ // The fetcher answers with an outcome rather than a throw, so a throw here means a+ // defect. The catch stays because a throw would leave the other domains of this batch+ // running while the partition replays them.+ logger.error('🌐', 'ml_image_fetch_unhandled_error', {+ host: candidate.host,+ // The name only. An error message from the request layer can carry the URL, and a+ // URL is page content.+ error: error instanceof Error ? error.name : 'unknown',+ })+ ImageFetchRequestMetrics.incOutcome('error')+ return await this.reschedule(candidate, 'error', 0)+ } finally {+ releaseAll()+ }+ if ('shed' in outcome) {+ this.budget.returnGrant(candidate.domain, Date.now())+ ImageFetchRequestMetrics.incOutcome(outcome.shed)+ return await this.reschedule(+ candidate,+ outcome.shed,+ this.budget.blockedForMs(candidate.domain, Date.now())+ )+ }+ const result = outcome+ const durationSeconds = Number(process.hrtime.bigint() - startedAt) / 1e9++ this.applyToBudget(candidate.domain, result.outcome, result.retryAfterMs)+ ImageFetchRequestMetrics.observeRequest(result.outcome, durationSeconds, result.redirects)+ if (result.bytes) {+ ImageFetchRequestMetrics.observeBytes(result.bytes.length)+ }+ if (result.outcome === 'redirect_offsite' && result.redirectTarget) {+ return await this.handOff(candidate, result.redirectTarget)+ }+ if (isTerminal(result.outcome)) {+ ImageFetchRequestMetrics.observeHops(MAX_HOPS - candidate.hopsRemaining)+ return { candidate, outcome: result.outcome, finished: true, lost: false }+ }+ return await this.reschedule(+ candidate,+ result.outcome,+ result.retryAfterMs ?? this.budget.blockedForMs(candidate.domain, Date.now())+ )+ }++ private applyToBudget(domain: string, outcome: FetchOutcome, retryAfterMs: number | undefined): void {+ const nowMs = Date.now()+ if (outcome === 'ok') {+ this.budget.recordSuccess(domain, nowMs)+ return+ }+ if (outcome === 'rate_limited' || outcome === 'server_error') {+ // The lane holds the whole domain when the site asked to be left alone, which means a+ // 429 or any response that named a period. A one-off 500 gets the rate cut and the+ // breaker count instead, because it says this request failed and nothing more.+ if (outcome === 'rate_limited' || retryAfterMs !== undefined) {+ this.budget.recordRetryAfter(domain, nowMs, retryAfterMs ?? this.options.defaultRetryAfterMs)+ }+ this.budget.recordBackoff(domain, nowMs)+ return+ }+ if (outcome === 'timeout' || outcome === 'error') {+ this.budget.recordBackoff(domain, nowMs)+ return+ }+ if (outcome === 'redirect_deferred' || outcome === 'unsupported_encoding') {+ // Neither says anything about the load this domain is under.+ return+ }+ if (outcome === 'forbidden') {+ // One 403 is a missing image, which is no reason to slow down. A run of them is an+ // anti-bot rule, which the breaker must catch.+ this.budget.recordRefusal(domain, nowMs)+ }+ }++ /**+ * Put a URL back for another try, or give up on it.+ *+ * The lane records a URL with no hops left, so it stops coming back and stops costing requests.+ * Requirement 12. Everything else goes to the delay topic whose period covers the wait, and the+ * lane records nothing, because the URL has no answer yet. Requirements 13 to 15.+ */+ private async reschedule(+ candidate: FetchCandidate,+ outcome: AttemptOutcome,+ waitMs: number+ ): Promise<FetchAttempt> {+ if (candidate.hopsRemaining <= 1) {+ ImageFetchRequestMetrics.incOutcome(HOPS_EXHAUSTED)+ ImageFetchRequestMetrics.observeHops(MAX_HOPS)+ return { candidate, outcome: HOPS_EXHAUSTED, finished: true, lost: false }+ }+ const target = { url: candidate.url, host: candidate.host, domain: candidate.domain }+ const republished = await this.publisher.republish(candidate, target, 'retry', waitMs)+ return { candidate, outcome, finished: false, lost: !republished }+ }++ /**+ * Send a redirect target to the consumer that owns its domain.+ *+ * This pod does not follow the hop. That domain's rate, breaker, and connection count live in+ * the pod holding its partition, and a hop followed from this pod spends none of them.+ * Requirement 7.+ */+ private async handOff(candidate: FetchCandidate, target: { url: string; host: string }): Promise<FetchAttempt> {+ if (candidate.hopsRemaining <= 1) {+ ImageFetchRequestMetrics.incOutcome(HOPS_EXHAUSTED)+ ImageFetchRequestMetrics.observeHops(MAX_HOPS)+ return { candidate, outcome: HOPS_EXHAUSTED, finished: true, lost: false }+ }+ const domain = politenessKey(target.host)+ const republished = await this.publisher.republish(candidate, { ...target, domain }, 'redirect')+ return { candidate, outcome: 'redirect_offsite', finished: false, lost: !republished }+ }++ /** The target belongs to `domain`, because `isOffsite` already refused every other one. A hop spends a token like a first request. */+ private async authorizeRedirect(+ deadlineMs: number,+ acquire: (domain: string) => boolean,+ domain: string+ ): Promise<RedirectDecision> {+ if (!acquire(domain)) {+ return 'defer'+ }+ const grant = this.budget.take(domain, Date.now(), deadlineMs)+ if (!grant.granted) {+ // Deferred rather than refused, so the lane writes no crawl history entry. Every+ // refusal reason here is about this moment rather than about the URL.+ return 'defer'+ }+ ImageFetchRequestMetrics.observeBudgetWait(grant.waitMs / 1000)+ if (grant.waitMs > 0) {+ await delay(grant.waitMs)+ // A `Retry-After` or an open breaker can arrive while a redirect waits, exactly as it+ // can while a first request waits. Requirement 5.+ if (this.staleAfterWait(domain, deadlineMs)) {+ this.budget.returnGrant(domain, Date.now())+ return 'defer'+ }+ }+ return 'allow'+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.tsnew file mode 100644index 000000000000..54efafca0b92--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts@@ -0,0 +1,143 @@+import { KafkaProducerWrapper } from '~/common/kafka/producer'+import { parseJSON } from '~/common/utils/json-parse'++import { FetchCandidate, MAX_HOPS } from './collected-urls-record'+import { FrontierPublisher } from './frontier-publisher'++const FRONTIER = 'session_replay_image_fetch'+const TIERS = [+ { topic: 'retry_1m', delayMs: 60_000 },+ { topic: 'retry_10m', delayMs: 600_000 },+ { topic: 'retry_1h', delayMs: 3_600_000 },+]++function candidate(overrides: Partial<FetchCandidate> = {}): FetchCandidate {+ return {+ ref: 'imageurl:team:originalhash0000000000',+ urlHash: 'originalhash0000000000',+ url: 'https://cdn.example.com/a.png',+ host: 'cdn.example.com',+ domain: 'example.com',+ pseudoTeam: 'team',+ capturedAtMs: 1_700_000_000_000,+ hopsRemaining: MAX_HOPS,+ notBeforeMs: 0,+ ...overrides,+ }+}++function build(): { publisher: FrontierPublisher; sent: { topic: string; key: string; body: any }[] } {+ const sent: { topic: string; key: string; body: any }[] = []+ const producer = {+ produce: ({ topic, key, value }: { topic: string; key: Buffer; value: Buffer }) => {+ sent.push({ topic, key: key.toString(), body: parseJSON(value.toString()) })+ return Promise.resolve()+ },+ } as unknown as KafkaProducerWrapper+ return { publisher: new FrontierPublisher(producer, { frontierTopic: FRONTIER, delayTiers: TIERS }), sent }+}++describe('FrontierPublisher', () => {+ it('keeps the original ref when handing a redirect target on (requirement 10)', async () => {+ // The recording points at the original ref. A hash of the redirect target names an image+ // nothing refers to, so the fetch would succeed and the image would still be unreachable.+ const { publisher, sent } = build()++ await publisher.republish(+ candidate(),+ { url: 'https://img.other.net/a.png', host: 'img.other.net', domain: 'other.net' },+ 'redirect'+ )++ expect(sent).toHaveLength(1)+ expect(sent[0].key).toBe('other.net')+ expect(sent[0].body.urls[0]).toEqual({+ ref: 'imageurl:team:originalhash0000000000',+ url: 'https://img.other.net/a.png',+ host: 'img.other.net',+ })+ })++ it('spends a hop on every republish (requirement 11)', async () => {+ const { publisher, sent } = build()++ await publisher.republish(candidate({ hopsRemaining: 4 }), targetOf(), 'retry', 0)++ expect(sent[0].body.hopsRemaining).toBe(3)+ })++ it('refuses to republish a URL with one hop left, so nothing circulates forever', async () => {+ const { publisher, sent } = build()++ const published = await publisher.republish(candidate({ hopsRemaining: 1 }), targetOf(), 'retry', 0)++ expect(published).toBe(false)+ expect(sent).toEqual([])+ })++ it.each([+ ['a retry with no period named', 0, 'retry_1m'],+ ['a wait inside the first tier', 30_000, 'retry_1m'],+ ['a wait between tiers', 120_000, 'retry_10m'],+ ['a wait past every tier', 24 * 3_600_000, 'retry_1h'],+ ])('parks %s in the right topic', async (_name, waitMs, topic) => {+ const { publisher, sent } = build()++ await publisher.republish(candidate(), targetOf(), 'retry', waitMs)++ expect(sent[0].topic).toBe(topic)+ })++ it('never sends a retry straight back to the frontier (requirement 14)', async () => {+ // A retry sent to the frontier is a loop: the consumer reads the record, meets the same+ // condition, and publishes it again, spending a hop each lap until the URL is written off+ // without ever being fetched.+ const { publisher, sent } = build()++ await publisher.republish(candidate(), targetOf(), 'retry', 0)++ expect(sent[0].topic).not.toBe(FRONTIER)+ expect(sent[0].body.notBeforeMs).toBeGreaterThan(Date.now())+ })++ it('sends a redirect to the frontier at once, because its target is ready', async () => {+ const { publisher, sent } = build()++ await publisher.republish(candidate(), targetOf(), 'redirect')++ expect(sent[0].topic).toBe(FRONTIER)+ expect(sent[0].body.notBeforeMs).toBe(0)+ })++ it('keeps the requested wait when it is longer than every tier (requirement 15)', async () => {+ // A site that names a day comes back after an hour. The record says it is not due, so the+ // consumer leaves it alone rather than fetching it 23 hours early.+ const { publisher, sent } = build()+ const before = Date.now()++ await publisher.republish(candidate(), targetOf(), 'retry', 24 * 3_600_000)++ expect(sent[0].body.notBeforeMs).toBeGreaterThanOrEqual(before + 24 * 3_600_000)+ })++ it('holds a short wait for the whole period of the tier it parks in', async () => {+ const { publisher, sent } = build()+ const before = Date.now()++ await publisher.republish(candidate(), targetOf(), 'retry', 30_000)++ expect(sent[0].body.notBeforeMs).toBeGreaterThanOrEqual(before + 60_000)+ })++ it('reports a failed publish rather than throwing', async () => {+ const producer = { produce: () => Promise.reject(new Error('broker down')) } as unknown as KafkaProducerWrapper+ const publisher = new FrontierPublisher(producer, { frontierTopic: FRONTIER, delayTiers: TIERS })++ // One failed produce must not abandon the rest of the batch.+ await expect(publisher.republish(candidate(), targetOf(), 'retry', 0)).resolves.toBe(false)+ })+})++function targetOf(): { url: string; host: string; domain: string } {+ return { url: 'https://cdn.example.com/a.png', host: 'cdn.example.com', domain: 'example.com' }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.tsnew file mode 100644index 000000000000..25dca2d3803f--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts@@ -0,0 +1,102 @@+import { KafkaProducerWrapper } from '~/common/kafka/producer'+import { logger } from '~/common/utils/logger'++import { FetchCandidate } from './collected-urls-record'+import { ImageFetchRequestMetrics } from './metrics'++/** One delay topic. Every record in it waits the same period, so the records leave in the order they become ready. */+export interface DelayTier {+ topic: string+ delayMs: number+}++export interface FrontierPublisherOptions {+ frontierTopic: string+ /** Ordered by delay, shortest first, because the publisher takes the first tier that covers the wait. */+ delayTiers: DelayTier[]+}++export type RepublishReason = 'redirect' | 'retry' | 'not_ready'++/**+ * Sends a URL back to the frontier, at once or after a wait.+ *+ * Two things use this. A redirect that leaves the registrable domain cannot be followed here,+ * because the budget for the new domain belongs to whichever consumer owns its partition, so the+ * target goes back as a new candidate. A transient failure cannot be retried here either, because+ * waiting in place holds the partition against every other site on it.+ *+ * Both spend a hop, so neither can go around forever. See the README, requirements 7 and 11 to 15.+ */+export class FrontierPublisher {+ constructor(+ private readonly producer: KafkaProducerWrapper,+ private readonly options: FrontierPublisherOptions+ ) {+ if (options.delayTiers.length === 0) {+ throw new Error('the image fetch lane needs at least one delay tier to retry with')+ }+ }++ /**+ * The ref stays the original one. The recording points at that ref, and a hash of a redirect+ * target matches nothing, so a new ref would leave the image unreachable. Requirement 10.+ */+ public async republish(+ candidate: FetchCandidate,+ target: { url: string; host: string; domain: string },+ reason: RepublishReason,+ waitMs = 0+ ): Promise<boolean> {+ const hopsRemaining = candidate.hopsRemaining - 1+ if (hopsRemaining <= 0) {+ return false+ }+ // A retry always waits, even when nothing named a period. A timeout, a connection error,+ // and a batch that ran out of time name none, and publishing those straight back to the+ // frontier is a loop: the consumer reads the record, meets the same condition, and+ // publishes it again, spending a hop each lap until the URL is written off unfetched. A URL+ // that arrived early waits for the same reason, for a period it already knows. A redirect+ // goes back at once, because its target is a different domain with its own budget.+ const tier = reason === 'redirect' ? undefined : this.tierFor(Math.max(waitMs, 1))+ const topic = tier?.topic ?? this.options.frontierTopic+ const value = Buffer.from(+ JSON.stringify({+ v: 1,+ pseudoTeam: candidate.pseudoTeam,+ capturedAtMs: candidate.capturedAtMs,+ hopsRemaining,+ // The longer of the wait asked for and the period of the tier holding it. A wait+ // past the longest tier arrives before it is due, and the consumer sends it back+ // for the rest. Requirement 15.+ notBeforeMs: tier ? Date.now() + Math.max(waitMs, tier.delayMs) : 0,+ urls: [{ ref: candidate.ref, url: target.url, host: target.host }],+ })+ )++ try {+ await this.producer.produce({ topic, key: Buffer.from(target.domain), value })+ } catch (error) {+ // Nothing throws here, because one failed produce must not abandon the rest of the+ // batch. The caller counts the false return and holds the batch instead. Requirement 21.+ logger.warn('🌐', 'ml_image_fetch_republish_failed', {+ reason,+ topic,+ error: error instanceof Error ? error.name : 'unknown',+ })+ ImageFetchRequestMetrics.incRepublishFailed(reason)+ return false+ }+ ImageFetchRequestMetrics.incRepublished(reason, topic)+ return true+ }++ /**+ * A wait longer than every tier comes back early, spends another hop, and waits again. That is+ * cheaper than a tier long enough for the worst `Retry-After` a site can name, and the host+ * budget refuses an early arrival without sending anything.+ */+ private tierFor(waitMs: number): DelayTier {+ return this.options.delayTiers.find((tier) => tier.delayMs >= waitMs) ?? this.options.delayTiers.at(-1)!+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.tsnew file mode 100644index 000000000000..c3fe2178bbcb--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts@@ -0,0 +1,222 @@+import { HostBudget, HostBudgetOptions } from './host-budget'++const OPTIONS: HostBudgetOptions = {+ requestsPerSecond: 1,+ burst: 2,+ maxConcurrent: 4,+ breakerFailures: 3,+ breakerCooldownMs: 60_000,+ breakerMaxCooldownMs: 600_000,+ maxTrackedDomains: 3,+}++function budget(overrides: Partial<HostBudgetOptions> = {}): HostBudget {+ return new HostBudget({ ...OPTIONS, ...overrides })+}++const FAR_FUTURE = 10 ** 12++describe('HostBudget', () => {+ it('spends the burst at once and then paces at the configured rate', () => {+ const host = budget()++ const grants = [0, 0, 0, 0].map(() => host.take('example.com', 1000, FAR_FUTURE))++ expect(grants).toEqual([+ { granted: true, waitMs: 0 },+ { granted: true, waitMs: 0 },+ { granted: true, waitMs: 1000 },+ { granted: true, waitMs: 2000 },+ ])+ })++ it('refuses rather than granting a slot that lands after the deadline', () => {+ const host = budget()+ host.take('example.com', 1000, FAR_FUTURE)+ host.take('example.com', 1000, FAR_FUTURE)++ // A grant here spends a token for a request the caller cannot send, and the next batch then+ // waits that token out for nothing.+ expect(host.take('example.com', 1000, 1500)).toEqual({ granted: false, reason: 'deadline' })+ expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 1000 })+ })++ it('opens the breaker on consecutive failures and closes it when the cooldown passes', () => {+ const host = budget()++ for (let i = 0; i < OPTIONS.breakerFailures; i++) {+ host.recordBackoff('example.com', 1000)+ }++ expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: false, reason: 'breaker_open' })+ expect(host.blockedDomains(1000)).toBe(1)+ expect(host.take('example.com', 1000 + OPTIONS.breakerCooldownMs + 1, FAR_FUTURE)).toMatchObject({+ granted: true,+ })+ })++ it('doubles the cooldown for a domain that fails again after the breaker closed', () => {+ const host = budget()+ const openBreaker = (atMs: number): void => {+ for (let i = 0; i < OPTIONS.breakerFailures; i++) {+ host.recordBackoff('example.com', atMs)+ }+ }++ openBreaker(1000)+ const reopenedAt = 1000 + OPTIONS.breakerCooldownMs + 1+ openBreaker(reopenedAt)++ // Still blocked one cooldown later, because the second cooldown is twice the first.+ expect(host.take('example.com', reopenedAt + OPTIONS.breakerCooldownMs + 1, FAR_FUTURE)).toEqual({+ granted: false,+ reason: 'breaker_open',+ })+ })++ it.each([+ ['a period the site named', 30_000, 30_000],+ ['a period longer than the cap', 24 * 60 * 60 * 1000, OPTIONS.breakerMaxCooldownMs],+ ])('holds the domain for %s', (_name, retryAfterMs, expectedHoldMs) => {+ const host = budget()++ host.recordRetryAfter('example.com', 1000, retryAfterMs)++ expect(host.take('example.com', 1000 + expectedHoldMs - 1, FAR_FUTURE)).toEqual({+ granted: false,+ reason: 'rate_limited',+ })+ expect(host.take('example.com', 1000 + expectedHoldMs + 1, FAR_FUTURE)).toMatchObject({ granted: true })+ })++ it('halves the rate on a backoff and never raises it above the configured one', () => {+ const host = budget({ requestsPerSecond: 4, burst: 1 })++ host.recordBackoff('example.com', 1000)+ // The burst went with the halving, so even the first request waits. At 2 per second rather+ // than 4, that wait is 500ms. Requirement 16.+ expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 500 })+ expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 1000 })++ for (let i = 0; i < 20; i++) {+ host.recordSuccess('example.com', 1000)+ }+ host.take('example.com', 20_000, FAR_FUTURE)+ expect(host.take('example.com', 20_000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 250 })+ })++ it('makes one failure reach the URLs already queued for the domain (requirement 16)', () => {+ // Without this a site that just failed still receives the whole burst, and the cut reaches+ // only the URLs behind them.+ const host = budget({ requestsPerSecond: 1, burst: 5 })++ expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 0 })+ host.recordBackoff('example.com', 1000)++ expect(host.take('example.com', 1000, FAR_FUTURE)).toMatchObject({ granted: true, waitMs: 2000 })+ })++ it('does not shorten a Retry-After hold when the breaker opens inside it', () => {+ const host = budget()+ const anHourMs = 60 * 60 * 1000+ host.recordRetryAfter('example.com', 1000, anHourMs)++ for (let i = 0; i < OPTIONS.breakerFailures; i++) {+ host.recordBackoff('example.com', 1000)+ }++ // The breaker cooldown is one minute. A cooldown that replaces the hold sends us back to a+ // site that asked for an hour, 59 minutes early.+ expect(host.take('example.com', 1000 + OPTIONS.breakerCooldownMs + 1, FAR_FUTURE)).toEqual({+ granted: false,+ reason: 'rate_limited',+ })+ })++ it('holds one domain to its connection limit however many callers ask', () => {+ const host = budget({ maxConcurrent: 2 })++ expect(host.acquireConnection('example.com', 1000)).toBe(true)+ expect(host.acquireConnection('example.com', 1000)).toBe(true)+ expect(host.acquireConnection('example.com', 1000)).toBe(false)++ host.releaseConnection('example.com')++ expect(host.acquireConnection('example.com', 1000)).toBe(true)+ })++ it('keeps a domain holding a connection out of the eviction scan', () => {+ // An eviction drops the in-flight count, and the next caller then opens one more connection+ // than the limit allows.+ const host = budget({ maxTrackedDomains: 2, maxConcurrent: 1 })+ host.acquireConnection('busy.com', 1000)+ host.take('idle.com', 1000, FAR_FUTURE)++ host.take('new.com', 1000, FAR_FUTURE)++ expect(host.acquireConnection('busy.com', 1000)).toBe(false)+ })++ it('opens the breaker on a domain that fails more often than it succeeds', () => {+ // Two failures for every success never make a run of failures, so a counter that cleared on+ // success leaves a mostly broken domain in retry forever.+ const host = budget()++ for (let round = 0; round < 5; round++) {+ host.recordBackoff('flapping.com', 1000)+ host.recordBackoff('flapping.com', 1000)+ host.recordSuccess('flapping.com', 1000)+ }++ expect(host.take('flapping.com', 1000, FAR_FUTURE)).toEqual({ granted: false, reason: 'breaker_open' })+ })++ it('keeps reporting an open breaker when a shorter rate-limit hold arrives inside it', () => {+ const host = budget()+ for (let i = 0; i < OPTIONS.breakerFailures; i++) {+ host.recordBackoff('example.com', 1000)+ }++ host.recordRetryAfter('example.com', 1000, 1_000)++ // The shed outcome and the metric carry this reason. A rename by the shorter hold hides the+ // breaker from the one number that exists to show it.+ expect(host.take('example.com', 2000, FAR_FUTURE)).toEqual({ granted: false, reason: 'breaker_open' })+ })++ it('does not report a busy but unblocked domain as one whose hold it forgot', () => {+ // The eviction scan skips a domain that is blocked or that has connections open. Only the+ // first kind loses a hold, and the metric carries the name of that kind.+ const host = budget({ maxTrackedDomains: 1, maxConcurrent: 1 })+ host.acquireConnection('busy.com', 1000)++ host.take('new.com', 1000, FAR_FUTURE)++ expect(host.evictedWhileBlocked).toBe(0)+ })++ it('never evicts a domain holding connections, so its slots are not leaked', () => {+ // A slot is released by domain name. A lost entry leaks every slot it held, and the domain+ // can then hold more than its limit for the rest of the pod's life.+ const host = budget({ maxTrackedDomains: 2, maxConcurrent: 1 })+ expect(host.acquireConnection('busy.com', 1000)).toBe(true)++ host.take('a.com', 1000, FAR_FUTURE)+ host.take('b.com', 1000, FAR_FUTURE)++ // Its entry survived the eviction, so it is still at its limit. A dropped entry would come+ // back with no connections counted and let this domain hold a second one.+ expect(host.acquireConnection('busy.com', 1000)).toBe(false)+ })++ it('evicts an idle domain in preference to one it is still holding back', () => {+ const host = budget({ maxTrackedDomains: 2 })+ host.recordRetryAfter('blocked.com', 1000, 60_000)+ host.take('idle.com', 1000, FAR_FUTURE)++ host.take('new.com', 1000, FAR_FUTURE)++ expect(host.trackedDomains).toBe(2)+ expect(host.take('blocked.com', 1000, FAR_FUTURE)).toEqual({ granted: false, reason: 'rate_limited' })+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.tsnew file mode 100644index 000000000000..beebbe247d89--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts@@ -0,0 +1,305 @@+export interface HostBudgetOptions {+ /** The ceiling for one registrable domain. Only a backoff moves a domain off it, and always downward. */+ requestsPerSecond: number+ /** Tokens a domain holds while idle, so a domain seen once an hour can send a few requests together. */+ burst: number+ /** Connections open to one domain at once. This counts them rather than the caller's worker pool, because a redirect reaches a domain without going through that pool. */+ maxConcurrent: number+ breakerFailures: number+ breakerCooldownMs: number+ /** The longest a domain stays blocked. It bounds the doubling cooldown and a `Retry-After` header alike. */+ breakerMaxCooldownMs: number+ maxTrackedDomains: number+}++export type BudgetGrant =+ | { granted: true; waitMs: number }+ | { granted: false; reason: 'breaker_open' | 'rate_limited' | 'deadline' }++interface DomainState {+ inFlight: number+ tokens: number+ lastRefillMs: number+ requestsPerSecond: number+ failureScore: number+ cooldownMs: number+ blockedUntilMs: number+ blockedReason: 'breaker_open' | 'rate_limited'+}++/** A domain's rate never falls below the configured rate divided by this. */+const MIN_RATE_DIVISOR = 16++/** Domains checked for an idle one before an eviction falls back to the oldest entry. */+const EVICTION_SCAN = 16++/**+ * How fast this pod may send to one registrable domain.+ *+ * The domain rather than the host, because one operator can serve images from many hostnames, and a+ * rate limit protects the operator. The topic uses the same key, so a domain lands on one partition+ * and one pod, and this budget is then the whole rate that domain receives from this lane. A+ * rebalance can put two pods on one domain for a few seconds, which doubles the rate for that long.+ * No counter across pods closes that window.+ *+ * A restart loses this state, including an open breaker, so a restart sends one more round of+ * requests to a failing site before the breaker opens again.+ */+export class HostBudget {+ private readonly domains = new Map<string, DomainState>()++ constructor(private readonly options: HostBudgetOptions) {+ // These values arrive from the environment, where a typo parses to NaN. A NaN rate makes+ // every wait NaN and every comparison against it false, so the rate limit stops existing.+ for (const [name, value] of Object.entries(options)) {+ if (!Number.isFinite(value) || value <= 0) {+ throw new Error(`the image fetch host budget needs a positive ${name}, got ${value}`)+ }+ }+ }++ /**+ * Take the right to send one request to `domain`, or learn why this pod must not send to it.+ *+ * A grant carries the time the caller must wait before it sends. The grant already spent the+ * token, so a caller that waits keeps the rate exact, and a caller that drops the grant only+ * slows the domain down. A grant that lands after `deadlineMs` is refused instead, because+ * nobody sends it and the next batch still waits the token out.+ */+ public take(domain: string, nowMs: number, deadlineMs: number): BudgetGrant {+ const state = this.stateFor(domain, nowMs)+ if (state.blockedUntilMs > nowMs) {+ return { granted: false, reason: state.blockedReason }+ }+ this.refill(state, nowMs)+ const waitMs = state.tokens >= 1 ? 0 : Math.ceil(((1 - state.tokens) / state.requestsPerSecond) * 1000)+ if (nowMs + waitMs > deadlineMs) {+ return { granted: false, reason: 'deadline' }+ }+ state.tokens -= 1+ return { granted: true, waitMs }+ }++ /**+ * Why this pod must not send to the domain, or null when it may.+ *+ * A caller that waited for a token asks again before it sends. A `Retry-After` or an open+ * breaker can arrive during a wait, and a request sent after that reaches a site which just+ * asked to be left alone. Requirement 5.+ */+ public blockedReason(domain: string, nowMs: number): 'breaker_open' | 'rate_limited' | null {+ const state = this.domains.get(domain)+ return state && state.blockedUntilMs > nowMs ? state.blockedReason : null+ }++ /**+ * How long the domain stays blocked, so a retry can wait that long rather than guess.+ *+ * An unknown domain reads as not blocked, and this creates no entry for it. An entry would let+ * a question about one domain evict the hold on another.+ */+ public blockedForMs(domain: string, nowMs: number): number {+ const state = this.domains.get(domain)+ return state ? Math.max(0, state.blockedUntilMs - nowMs) : 0+ }++ /**+ * Give back a token for a request that never went out.+ *+ * The rate limits what leaves this pod, so a grant that went stale during its wait must not+ * count against the domain. The burst caps the return, so a return cannot create capacity.+ */+ public returnGrant(domain: string, nowMs: number): void {+ const state = this.stateFor(domain, nowMs)+ state.tokens = Math.min(this.options.burst, state.tokens + 1)+ }++ /**+ * Take one of the domain's connection slots, or report that they are all taken.+ *+ * The rate limit and the connection limit answer different questions: how often we may start,+ * and how many we may hold open. A slow site makes the second one bind, and a redirect target+ * reaches this without passing through the per-domain worker pool that would otherwise bound it.+ */+ public acquireConnection(domain: string, nowMs: number): boolean {+ const state = this.stateFor(domain, nowMs)+ if (state.inFlight >= this.options.maxConcurrent) {+ return false+ }+ state.inFlight += 1+ return true+ }++ public releaseConnection(domain: string): void {+ const state = this.domains.get(domain)+ if (state) {+ state.inFlight = Math.max(0, state.inFlight - 1)+ }+ }++ public recordSuccess(domain: string, nowMs: number): void {+ const state = this.stateFor(domain, nowMs)+ // Decremented rather than cleared. A domain that fails two requests for every one it answers+ // never reaches a run of failures, and a counter that resets never opens its breaker.+ state.failureScore = Math.max(0, state.failureScore - 1)+ const step = this.options.requestsPerSecond / 8+ state.requestsPerSecond = Math.min(this.options.requestsPerSecond, state.requestsPerSecond + step)+ // The doubling ladder clears only once the rate is fully back, so a site that fails,+ // recovers for one request, and fails again keeps escalating. It does not restart at the+ // base cooldown every time.+ if (state.requestsPerSecond >= this.options.requestsPerSecond) {+ state.cooldownMs = 0+ }+ }++ /**+ * A site said it is unhappy. Halve the rate, and count toward the breaker.+ *+ * The rate halves on the first signal rather than after a threshold. A cut that comes too early+ * costs one slower domain. A cut that comes too late adds load to a site that asked us to stop.+ *+ * The tokens go with it. A domain holds a burst while it is idle, so without this the URLs+ * already queued behind the failed one would leave at the old rate and the cut would reach only+ * the URLs after them. Requirement 16.+ */+ public recordBackoff(domain: string, nowMs: number): void {+ const state = this.stateFor(domain, nowMs)+ const floor = this.options.requestsPerSecond / MIN_RATE_DIVISOR+ state.requestsPerSecond = Math.max(floor, state.requestsPerSecond / 2)+ state.tokens = 0+ this.countTowardBreaker(state, nowMs)+ }++ /**+ * A refusal that says nothing about load, such as a 403 from an anti-bot rule.+ *+ * It counts toward the breaker, because a run of refusals means the site refuses this bot and+ * more requests only add to that. It leaves the rate alone, because one refused image is an+ * ordinary answer that must not slow down the images beside it.+ */+ public recordRefusal(domain: string, nowMs: number): void {+ this.countTowardBreaker(this.stateFor(domain, nowMs), nowMs)+ }++ private countTowardBreaker(state: DomainState, nowMs: number): void {+ state.failureScore += 1+ if (state.failureScore < this.options.breakerFailures) {+ return+ }+ // Doubled from the last cooldown rather than reset, so a site that keeps failing after the+ // breaker closes gets a longer pause each time rather than a probe on a fixed beat.+ state.cooldownMs = Math.min(+ state.cooldownMs > 0 ? state.cooldownMs * 2 : this.options.breakerCooldownMs,+ this.options.breakerMaxCooldownMs+ )+ // Extended rather than replaced. A breaker that opens inside an hour-long hold must not+ // shorten that hold to its own cooldown.+ const openUntilMs = nowMs + state.cooldownMs+ if (openUntilMs > state.blockedUntilMs) {+ state.blockedUntilMs = openUntilMs+ state.blockedReason = 'breaker_open'+ }+ state.failureScore = 0+ }++ /**+ * Hold the domain for the period a `Retry-After` header asked for.+ *+ * The clamp is necessary because a site can name any period, and an unclamped one holds a+ * domain in this pod's memory for as long as the pod lives.+ */+ public recordRetryAfter(domain: string, nowMs: number, retryAfterMs: number): void {+ const state = this.stateFor(domain, nowMs)+ const held = Math.min(Math.max(retryAfterMs, 0), this.options.breakerMaxCooldownMs)+ // The reason moves only when this hold wins. A domain already held by an open breaker would+ // otherwise report every later shed as a rate limit, which hides the breaker from the+ // metric that exists to show it.+ if (nowMs + held > state.blockedUntilMs) {+ state.blockedUntilMs = nowMs + held+ state.blockedReason = 'rate_limited'+ }+ }++ public get trackedDomains(): number {+ return this.domains.size+ }++ /** Domains this dropped while they were still blocked, which resumes traffic to a site that asked us to wait. */+ public evictedWhileBlocked = 0++ public blockedDomains(nowMs: number): number {+ let blocked = 0+ for (const state of this.domains.values()) {+ if (state.blockedUntilMs > nowMs) {+ blocked+++ }+ }+ return blocked+ }++ private refill(state: DomainState, nowMs: number): void {+ const elapsedMs = Math.max(0, nowMs - state.lastRefillMs)+ state.lastRefillMs = nowMs+ state.tokens = Math.min(this.options.burst, state.tokens + (elapsedMs / 1000) * state.requestsPerSecond)+ }++ private stateFor(domain: string, nowMs: number): DomainState {+ const existing = this.domains.get(domain)+ if (existing) {+ // Re-inserted so that the map orders by last use, which the eviction below reads.+ this.domains.delete(domain)+ this.domains.set(domain, existing)+ return existing+ }+ this.evictIfFull(nowMs)+ const state: DomainState = {+ inFlight: 0,+ tokens: this.options.burst,+ lastRefillMs: nowMs,+ requestsPerSecond: this.options.requestsPerSecond,+ failureScore: 0,+ cooldownMs: 0,+ blockedUntilMs: 0,+ blockedReason: 'breaker_open',+ }+ this.domains.set(domain, state)+ return state+ }++ /**+ * An evicted domain loses its block, so the scan prefers an idle domain. When the map holds+ * only blocked domains the oldest one goes anyway, because a refusal to evict grows the map+ * without a bound and the memory limit is the harder failure.+ */+ private evictIfFull(nowMs: number): void {+ if (this.domains.size < this.options.maxTrackedDomains) {+ return+ }+ let oldest: string | undefined+ let scanned = 0+ for (const [domain, state] of this.domains) {+ if (state.inFlight > 0) {+ // Never evicted. A slot is released by domain name, so a lost entry leaks every+ // slot it held and the domain can then hold more than its limit. The map cannot+ // grow without a bound this way, because the pod caps its requests in flight.+ continue+ }+ oldest = oldest ?? domain+ if (state.blockedUntilMs <= nowMs) {+ this.domains.delete(domain)+ return+ }+ if (++scanned >= EVICTION_SCAN) {+ break+ }+ }+ if (oldest) {+ // Counted only when the entry really was blocked.+ const evicted = this.domains.get(oldest)+ this.domains.delete(oldest)+ if (evicted && evicted.blockedUntilMs > nowMs) {+ this.evictedWhileBlocked+++ }+ }+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.tsnew file mode 100644index 000000000000..1ba9635f0632--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts@@ -0,0 +1,294 @@+import { ResolutionError, SecureRequestError, StreamedResponse, fetchStreamed } from '~/common/utils/request'++import { HttpImageFetcher, ImageFetchOptions, RedirectPolicy } from './image-fetcher'++jest.mock('~/common/utils/request', () => ({+ ...jest.requireActual('~/common/utils/request'),+ fetchStreamed: jest.fn(),+}))++const fetchStreamedMock = fetchStreamed as jest.MockedFunction<typeof fetchStreamed>++const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00])+const GIF = Buffer.from('GIF89a-and-then-some')++const OPTIONS: ImageFetchOptions = {+ maxBytes: 1000,+ timeoutMs: 5000,+ maxRedirects: 3,+ isOffsite: () => false,+ authorizeRedirect: () => Promise.resolve('allow' as const),+}++function respond(+ status: number,+ headers: Record<string, string>,+ body: { bytes: Buffer; overLimit: boolean } = { bytes: Buffer.alloc(0), overLimit: false }+): StreamedResponse {+ return {+ status,+ headers,+ read: jest.fn().mockResolvedValue(body),+ discard: jest.fn(),+ }+}++function image(bytes: Buffer, contentType: string, extraHeaders: Record<string, string> = {}): StreamedResponse {+ return respond(200, { 'content-type': contentType, ...extraHeaders }, { bytes, overLimit: false })+}++/** Everything public by default, so a test that cares about the policy says so. */+const fetcher = (policy: Partial<RedirectPolicy> = {}): HttpImageFetcher =>+ new HttpImageFetcher({ maxUrlLength: 2048, isPublicHost: () => true, ...policy })++describe('HttpImageFetcher', () => {+ beforeEach(() => {+ fetchStreamedMock.mockReset()+ })++ it('returns the bytes of an image whose payload matches its declared type', async () => {+ fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png; charset=binary'))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toEqual({ outcome: 'ok', status: 200, bytes: PNG, contentType: 'image/png', redirects: 0 })+ })++ it.each([+ ['a type that is not an image', 'text/html', PNG],+ ['a type outside the raster set', 'image/svg+xml', PNG],+ ['a payload that is not the declared format', 'image/gif', PNG],+ ['a payload of the wrong raster format', 'image/png', GIF],+ ])('refuses %s', async (_name, contentType, bytes) => {+ fetchStreamedMock.mockResolvedValue(image(bytes, contentType))++ const result = await fetcher().fetch('https://cdn.example.com/a', OPTIONS)++ expect(result).toMatchObject({ outcome: 'not_image' })+ })++ it('refuses a declared size over the limit without reading the body', async () => {+ const response = image(PNG, 'image/png', { 'content-length': '99999' })+ fetchStreamedMock.mockResolvedValue(response)++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'too_large' })+ expect(response.read).not.toHaveBeenCalled()+ expect(response.discard).toHaveBeenCalled()+ })++ it('refuses a body that passes the limit while it is being read', async () => {+ // The case an origin reaches when it declares no length. No check before the body catches it.+ fetchStreamedMock.mockResolvedValue(+ respond(200, { 'content-type': 'image/png' }, { bytes: Buffer.alloc(0), overLimit: true })+ )++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'too_large' })+ })++ it.each([+ [404, 'not_found'],+ [410, 'not_found'],+ [403, 'forbidden'],+ [429, 'rate_limited'],+ [503, 'server_error'],+ [500, 'server_error'],+ [418, 'unexpected_status'],+ ])('maps status %s to %s', async (status, outcome) => {+ fetchStreamedMock.mockResolvedValue(respond(status, {}))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome, status })+ })++ it.each([+ ['a count of seconds', '120', 120_000],+ ['an HTTP date', new Date(Date.now() + 90_000).toUTCString(), 90_000],+ ])('reads a Retry-After header given as %s', async (_name, header, expectedMs) => {+ fetchStreamedMock.mockResolvedValue(respond(429, { 'retry-after': header }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ // The parser resolves a date against the clock, so the range allows for the test's own runtime.+ expect(result.retryAfterMs).toBeGreaterThan(expectedMs - 2000)+ expect(result.retryAfterMs).toBeLessThanOrEqual(expectedMs)+ })++ it('follows a redirect and reports how many hops it took', async () => {+ fetchStreamedMock+ .mockResolvedValueOnce(respond(302, { location: '/moved.png' }))+ .mockResolvedValueOnce(image(PNG, 'image/png'))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'ok', redirects: 1 })+ expect(fetchStreamedMock.mock.calls[1][0]).toBe('https://cdn.example.com/moved.png')+ })++ it.each([+ ['the target is one this lane never follows', 'https://other.example/a.png', 'refuse' as const],+ ['it leaves HTTP for another scheme', 'javascript:alert(1)', 'allow' as const],+ ['it carries credentials for the next hop', 'https://user:[email protected]/a.png', 'allow' as const],+ ['it downgrades from HTTPS to plain HTTP', 'http://other.example/a.png', 'allow' as const],+ ])('refuses a redirect when %s', async (_name, location, decision) => {+ fetchStreamedMock.mockResolvedValue(respond(302, { location }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ authorizeRedirect: () => Promise.resolve(decision),+ })++ expect(result).toMatchObject({ outcome: 'bad_redirect' })+ expect(fetchStreamedMock).toHaveBeenCalledTimes(1)+ })++ it('refuses a downgrade when the first hop named its scheme in capitals (requirement 9)', async () => {+ // A record can carry `HTTPS://`, because the parser validates a parsed copy and stores the+ // string it was given. A guard that reads the raw string misses the capitals and follows+ // the hop in clear text. `URL.protocol` is lower case whatever the URL used.+ fetchStreamedMock.mockResolvedValue(respond(302, { location: 'http://cdn.example.com/b.png' }))++ const result = await fetcher().fetch('HTTPS://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'bad_redirect' })+ expect(fetchStreamedMock).toHaveBeenCalledTimes(1)+ })++ it.each([+ ['a host the collector would have refused', 'https://internal.corp/a.png', { isPublicHost: () => false }],+ ['a target past the length limit', `https://cdn.example.com/${'a'.repeat(300)}.png`, { maxUrlLength: 100 }],+ ['a port the scheme does not own', 'https://cdn.example.com:11211/a.png', {}],+ ])('refuses a redirect to %s (requirement 8)', async (_name, location, policy) => {+ // The collector applied these checks to the first candidate. A redirect target has passed+ // none of them, so a hop could otherwise reach a name that resolves only inside a network.+ fetchStreamedMock.mockResolvedValue(respond(302, { location }))++ const result = await fetcher(policy).fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'bad_redirect' })+ expect(fetchStreamedMock).toHaveBeenCalledTimes(1)+ })++ it('hands off an offsite target that arrives at the redirect limit (requirement 7)', async () => {+ // The limit bounds the hops this request follows itself. Nobody here follows a target for+ // another operator, so it goes back to Kafka and costs one hop rather than being written off+ // with hops left.+ fetchStreamedMock.mockResolvedValue(respond(302, { location: 'https://img.other.net/a.png' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ maxRedirects: 0,+ isOffsite: () => true,+ })++ expect(result).toMatchObject({+ outcome: 'redirect_offsite',+ redirectTarget: { url: 'https://img.other.net/a.png', host: 'img.other.net' },+ })+ })++ it('stops at the redirect limit for a target on the same domain', async () => {+ fetchStreamedMock.mockResolvedValue(respond(302, { location: 'https://cdn.example.com/b.png' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', { ...OPTIONS, maxRedirects: 0 })++ expect(result).toMatchObject({ outcome: 'too_many_redirects' })+ })++ it('defers a redirect whose target has no budget left, so nothing is written to the crawl history for it', async () => {+ // `bad_redirect` is terminal. A CDN in cooldown would otherwise suppress every image behind+ // it for the crawl history TTL, because the lane read a momentary budget as a property of+ // the URL.+ fetchStreamedMock.mockResolvedValue(respond(302, { location: 'https://cdn.example.net/a.png' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ authorizeRedirect: () => Promise.resolve('defer' as const),+ })++ expect(result).toMatchObject({ outcome: 'redirect_deferred' })+ })++ it('refuses a response that arrives compressed, under its own outcome', async () => {+ // The byte limit counts bytes on the wire, and a compressed body expands past it. The image+ // may be perfectly good, so the lane must not report it, or record it, as "not an image".+ fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png', { 'content-encoding': 'gzip' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'unsupported_encoding' })+ })++ it('defers a redirect whose politeness wait would outlive the request', async () => {+ // The wait comes out of this request's clock. A wait that cannot land would report the site+ // as slow when our own budget ran out.+ fetchStreamedMock.mockResolvedValue(respond(302, { location: '/moved.png' }))+ const authorizeRedirect = jest.fn().mockResolvedValue('allow')++ await fetcher().fetch('https://cdn.example.com/a.png', { ...OPTIONS, authorizeRedirect })++ const remainingMs = authorizeRedirect.mock.calls[0][1]+ expect(remainingMs).toBeGreaterThan(0)+ expect(remainingMs).toBeLessThanOrEqual(OPTIONS.timeoutMs)+ })++ it('gives up on a redirect chain longer than the limit', async () => {+ fetchStreamedMock.mockResolvedValue(respond(302, { location: '/again.png' }))+ const authorizeRedirect = jest.fn().mockResolvedValue('allow')++ const result = await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ maxRedirects: 2,+ authorizeRedirect,+ })++ expect(result).toEqual({ outcome: 'too_many_redirects', redirects: 2, status: 302 })+ // Three requests carry two redirects. The third response is read and refused, and the+ // budget of whatever it points at is never asked for a token.+ expect(fetchStreamedMock).toHaveBeenCalledTimes(3)+ expect(authorizeRedirect).toHaveBeenCalledTimes(2)+ })++ it('reports a redirect authorizer that threw rather than letting it escape', async () => {+ // The authorizer reaches into the host budget, which the fetcher does not own. A throw there+ // would leave the sibling domains of the batch running while the partition replayed them.+ fetchStreamedMock.mockResolvedValue(respond(302, { location: '/moved.png' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ authorizeRedirect: () => Promise.reject(new Error('budget exploded')),+ })++ expect(result).toEqual({ outcome: 'error', redirects: 0 })+ })++ it.each([+ ['a period of zero', '0'],+ ['a negative period', '-5'],+ ['whitespace', ' '],+ ['a date already past', new Date(Date.now() - 60_000).toUTCString()],+ ])('reports no Retry-After period for %s, so the caller applies its own default', async (_name, header) => {+ fetchStreamedMock.mockResolvedValue(respond(429, { 'retry-after': header }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result.retryAfterMs).toBeUndefined()+ })++ it.each([+ ['an address the SSRF check refuses', new SecureRequestError('Hostname is not allowed'), 'blocked'],+ ['a name that did not resolve', new ResolutionError('Invalid hostname'), 'error'],+ ['a request that timed out', Object.assign(new Error('timeout'), { name: 'TimeoutError' }), 'timeout'],+ ['a connection that failed', new Error('socket hang up'), 'error'],+ ])('reports %s as an outcome rather than throwing', async (_name, error, outcome) => {+ fetchStreamedMock.mockRejectedValue(error)++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toEqual({ outcome, redirects: 0 })+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.tsnew file mode 100644index 000000000000..13a57b12335b--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts@@ -0,0 +1,356 @@+import { InvalidRequestError, ResolutionError, SecureRequestError, fetchStreamed } from '~/common/utils/request'++/**+ * The raster set the anonymizer keeps on a collected ref, so a fetched image and an inline one reach+ * the scrub lane as the same kind of thing.+ *+ * SVG is absent on purpose. It is a text format that can carry the page's own data, so its redaction+ * belongs on the inline path rather than on an image model.+ */+const ALLOWED_CONTENT_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/avif'] as const++export type ImageContentType = (typeof ALLOWED_CONTENT_TYPES)[number]++export type FetchOutcome =+ | 'ok'+ | 'not_found'+ | 'forbidden'+ | 'rate_limited'+ | 'server_error'+ | 'unexpected_status'+ | 'too_many_redirects'+ | 'bad_redirect'+ | 'redirect_deferred'+ | 'redirect_offsite'+ | 'too_large'+ | 'not_image'+ | 'unsupported_encoding'+ | 'blocked'+ | 'timeout'+ | 'error'++export interface ImageFetchResult {+ outcome: FetchOutcome+ redirects: number+ status?: number+ bytes?: Buffer+ contentType?: ImageContentType+ /** Set by a 429 or a 503 that named a period. The caller holds the whole domain for that period. */+ retryAfterMs?: number+ /** Where a redirect this lane did not follow points. The caller republishes it rather than fetching it. */+ redirectTarget?: { url: string; host: string }+}++export interface ImageFetchOptions {+ maxBytes: number+ /** Covers the redirect chain as a whole, so a chain of slow hops cannot outlive one hop's budget. */+ timeoutMs: number+ maxRedirects: number+ /**+ * The fetch asks this for every redirect target it will follow, so each hop spends a token.+ *+ * `remainingMs` is what is left of this request, so a wait longer than that must `defer`.+ *+ * A `defer` must not read as a `refuse`, because the caller writes a refusal to the crawl+ * history and writes nothing for a deferral.+ */+ authorizeRedirect: (url: URL, remainingMs: number) => Promise<RedirectDecision>+ /**+ * True when the target belongs to another operator, so this fetch must not follow it.+ *+ * The fetch asks this before it applies the redirect limit, and the question spends nothing. The+ * limit bounds the hops this request follows itself. Nobody here follows a target for another+ * operator, so it goes back to Kafka and costs one hop instead. Requirement 7.+ */+ isOffsite: (url: URL) => boolean+}++/**+ * `allow` follows the target here. `defer` means the budget is spent or the breaker is open.+ * `refuse` means this lane will never follow the target.+ */+export type RedirectDecision = 'allow' | 'refuse' | 'defer'++export interface ImageFetcher {+ fetch(url: string, options: ImageFetchOptions): Promise<ImageFetchResult>+}++const USER_AGENT = 'PostHogSessionReplayBot/1.0 (+https://posthog.com/docs/session-replay/image-bot)'++const REQUEST_HEADERS: Record<string, string> = {+ 'user-agent': USER_AGENT,+ accept: 'image/*',+ // Every type this lane accepts is compressed already, so gzip saves the origin almost nothing,+ // and the byte limit can count what arrives rather than what a decoder would produce from it.+ 'accept-encoding': 'identity',+}++const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])++/**+ * This sends no credential of any kind: no cookie, no `Authorization`, and no `Referer`. This lane+ * must not reach an image behind a login, and a `Referer` would tell the origin which page of the+ * customer's site the image sat on.+ *+ * Every refusal is an outcome rather than a throw. This runs inside a Kafka batch, one URL at a+ * time, and a throw would abandon the URLs after it in the same batch.+ */+export class HttpImageFetcher implements ImageFetcher {+ constructor(private readonly policy: RedirectPolicy) {}++ public async fetch(url: string, options: ImageFetchOptions): Promise<ImageFetchResult> {+ const deadlineMs = Date.now() + options.timeoutMs+ let target = url+ for (let redirects = 0; ; redirects++) {+ const remainingMs = deadlineMs - Date.now()+ if (remainingMs <= 0) {+ return { outcome: 'timeout', redirects }+ }+ let hop: HopResult+ try {+ hop = await this.hop(target, remainingMs, options.maxBytes)+ } catch (error) {+ return { outcome: classifyError(error), redirects }+ }+ if (hop.kind !== 'redirect') {+ return { ...hop.result, redirects }+ }+ const next = resolveRedirect(target, hop.location, this.policy)+ if (!next) {+ return { outcome: 'bad_redirect', redirects, status: hop.status }+ }+ if (options.isOffsite(next)) {+ // The budget, the breaker, and the connection count for that domain belong to the+ // consumer that owns its partition.+ return {+ outcome: 'redirect_offsite',+ redirects,+ status: hop.status,+ redirectTarget: { url: next.toString(), host: next.hostname },+ }+ }+ // After the offsite test and before authorization, so a hop this lane refuses spends no+ // token from the budget of the site it would have landed on.+ if (redirects >= options.maxRedirects) {+ return { outcome: 'too_many_redirects', redirects, status: hop.status }+ }+ let decision: RedirectDecision+ try {+ decision = await options.authorizeRedirect(next, deadlineMs - Date.now())+ } catch (error) {+ return { outcome: classifyError(error), redirects }+ }+ if (decision !== 'allow') {+ const outcome = decision === 'defer' ? 'redirect_deferred' : 'bad_redirect'+ return { outcome, redirects, status: hop.status }+ }+ target = next.toString()+ }+ }++ private async hop(url: string, timeoutMs: number, maxBytes: number): Promise<HopResult> {+ const response = await fetchStreamed(url, { headers: REQUEST_HEADERS, timeoutMs })+ const status = response.status++ if (REDIRECT_STATUSES.has(status)) {+ response.discard()+ const location = response.headers['location']+ return location+ ? { kind: 'redirect', status, location }+ : { kind: 'done', result: { outcome: 'bad_redirect', status } }+ }+ if (status !== 200) {+ response.discard()+ return { kind: 'done', result: statusResult(status, response.headers['retry-after']) }+ }++ const contentType = normalizeContentType(response.headers['content-type'])+ if (!contentType) {+ response.discard()+ return { kind: 'done', result: { outcome: 'not_image', status } }+ }+ // An origin that compresses anyway makes the byte limit count compressed bytes, and the+ // payload behind them can be far larger. This is a refusal by this lane rather than a fact+ // about the image, so it gets its own outcome and does not write the URL off.+ const encoding = response.headers['content-encoding']?.trim().toLowerCase()+ if (encoding && encoding !== 'identity') {+ response.discard()+ return { kind: 'done', result: { outcome: 'unsupported_encoding', status } }+ }+ // Before the body, so a declared size over the limit costs one header exchange.+ const declaredBytes = Number(response.headers['content-length'])+ if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {+ response.discard()+ return { kind: 'done', result: { outcome: 'too_large', status } }+ }++ const { bytes, overLimit } = await response.read(maxBytes)+ if (overLimit) {+ return { kind: 'done', result: { outcome: 'too_large', status } }+ }+ // A payload that disagrees with its declared type would reach the scrub lane as an image no+ // model can read, and by then the URL that produced it is gone.+ if (!magicBytesMatch(bytes, contentType)) {+ return { kind: 'done', result: { outcome: 'not_image', status } }+ }+ return { kind: 'done', result: { outcome: 'ok', status, bytes, contentType } }+ }+}++type HopResult =+ | { kind: 'redirect'; status: number; location: string }+ | { kind: 'done'; result: Omit<ImageFetchResult, 'redirects'> }++function statusResult(status: number, retryAfter: string | undefined): Omit<ImageFetchResult, 'redirects'> {+ if (status === 404 || status === 410) {+ return { outcome: 'not_found', status }+ }+ if (status === 401 || status === 403) {+ return { outcome: 'forbidden', status }+ }+ if (status === 429) {+ return { outcome: 'rate_limited', status, retryAfterMs: parseRetryAfterMs(retryAfter) }+ }+ if (status === 503) {+ return { outcome: 'server_error', status, retryAfterMs: parseRetryAfterMs(retryAfter) }+ }+ if (status >= 500) {+ return { outcome: 'server_error', status }+ }+ return { outcome: 'unexpected_status', status }+}++/** RFC 9110 allows a count of seconds or an HTTP date. Real responses use both. */+export function parseRetryAfterMs(value: string | undefined): number | undefined {+ if (!value) {+ return undefined+ }+ // An absent, zero, or past period returns undefined, so the caller applies its own default+ // rather than reading zero as a site that wants no pause.+ const trimmed = value.trim()+ const seconds = trimmed === '' ? NaN : Number(trimmed)+ if (Number.isFinite(seconds)) {+ return seconds > 0 ? seconds * 1000 : undefined+ }+ const dateMs = Date.parse(trimmed)+ if (Number.isNaN(dateMs)) {+ return undefined+ }+ const heldMs = dateMs - Date.now()+ return heldMs > 0 ? heldMs : undefined+}++/**+ * The rules a redirect target must pass, beyond the SSRF checks every hop re-enters.+ *+ * The collector applied all of these to the first candidate before it reached the topic. A redirect+ * target has passed none of them, so a hop could otherwise reach a host the collector would have+ * refused, such as a single-label name, or a name under a suffix that resolves only inside a+ * network. Requirement 8.+ */+export interface RedirectPolicy {+ maxUrlLength: number+ isPublicHost: (host: string) => boolean+}++function resolveRedirect(from: string, location: string, policy: RedirectPolicy): URL | null {+ let next: URL+ try {+ next = new URL(location, from)+ } catch {+ return null+ }+ // Requirement 9: no downgrade to plain HTTP. `URL.protocol` is lower case already, which a+ // comparison against the raw location string is not.+ if (next.protocol !== 'https:') {+ return null+ }+ // This lane sends no credentials, and a userinfo part would put some back on the next hop.+ if (next.username || next.password) {+ return null+ }+ // A port other than the scheme's own would turn this lane into a port prober. A page names any+ // host and port, the connection leaves from our egress addresses, and the outcome metric reports+ // what answered. Few images are served on another port, so this refuses the whole case.+ if (next.port !== '') {+ return null+ }+ const target = next.toString()+ if (target.length > policy.maxUrlLength) {+ return null+ }+ if (!policy.isPublicHost(next.hostname)) {+ return null+ }+ return next+}++function normalizeContentType(header: string | undefined): ImageContentType | undefined {+ if (!header) {+ return undefined+ }+ const type = header.split(';')[0].trim().toLowerCase()+ return ALLOWED_CONTENT_TYPES.find((allowed) => allowed === type)+}++function startsWith(bytes: Buffer, signature: number[], offset = 0): boolean {+ if (bytes.length < offset + signature.length) {+ return false+ }+ return signature.every((byte, index) => bytes[offset + index] === byte)+}++function asciiAt(bytes: Buffer, offset: number, text: string): boolean {+ return startsWith(+ bytes,+ [...text].map((char) => char.charCodeAt(0)),+ offset+ )+}++/**+ * This checks agreement rather than format. Anything that passes still reaches an image decoder+ * later, so this only has to catch a payload that is not the format it claims.+ */+export function magicBytesMatch(bytes: Buffer, contentType: ImageContentType): boolean {+ switch (contentType) {+ case 'image/png':+ return startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ case 'image/jpeg':+ return startsWith(bytes, [0xff, 0xd8, 0xff])+ case 'image/gif':+ return asciiAt(bytes, 0, 'GIF87a') || asciiAt(bytes, 0, 'GIF89a')+ case 'image/webp':+ return asciiAt(bytes, 0, 'RIFF') && asciiAt(bytes, 8, 'WEBP')+ case 'image/bmp':+ return asciiAt(bytes, 0, 'BM')+ case 'image/avif':+ // An ISO base media file names its brand after the `ftyp` box header, and AVIF still+ // ships under the `mif1` and `msf1` brands that came before the AVIF ones.+ return (+ asciiAt(bytes, 4, 'ftyp') &&+ (asciiAt(bytes, 8, 'avif') ||+ asciiAt(bytes, 8, 'avis') ||+ asciiAt(bytes, 8, 'mif1') ||+ asciiAt(bytes, 8, 'msf1'))+ )+ }+}++export function classifyError(error: unknown): FetchOutcome {+ // `blocked` is terminal, so it must only cover a permanent property of the URL. A refused+ // address and an unparsable URL are permanent. A name that did not resolve is not, because the+ // shared lookup raises the same error for a resolver timeout as for a name that does not exist.+ if (error instanceof SecureRequestError || error instanceof InvalidRequestError) {+ return 'blocked'+ }+ if (error instanceof ResolutionError) {+ return 'error'+ }+ const name = error instanceof Error ? error.name : ''+ const code = typeof error === 'object' && error !== null ? String((error as { code?: unknown }).code ?? '') : ''+ if (name === 'TimeoutError' || name === 'AbortError' || code.includes('TIMEOUT')) {+ return 'timeout'+ }+ return 'error'+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.tsindex 0b9f706b85b6..600cc2eea173 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts@@ -1,5 +1,19 @@import { Counter, Gauge, Histogram } from 'prom-client'+import type { TeamVolume } from './team-volume'++/** What the in-flight gauge reads. Narrower than `ConcurrencyController`, so the metrics do not depend on the whole of it. */+export interface InFlightCount {+ readonly running: number+}++/** What the budget gauges read. Narrower than `HostBudget`, so the metrics do not depend on the whole of it. */+export interface BudgetCounts {+ readonly trackedDomains: number+ readonly evictedWhileBlocked: number+ blockedDomains(nowMs: number): number+}+export type UrlDropReason =| 'malformed'| 'unsupported_version'@@ -7,29 +21,20 @@ export type UrlDropReason =| 'bad_ref'| 'bad_url'| 'foreign_domain'+ | 'private_host'| 'oversized_record'export type DedupScope = 'batch' | 'pod' | 'store'export class ImageFetchConsumerMetrics {- /**- * URLs that reached the end of the dry run, meaning the lane would have sent a request for them.- *- * This is the phase 0 headline. Divided by the window it gives the request rate the fetcher would- * offer, which is the number that decides whether the politeness budget of section 4.5 can carry- * real traffic.- */private static readonly fetchable = new Counter({name: 'ml_image_fetch_consumer_fetchable_total',help: 'URLs that passed every check and would have been fetched. In dry run no request is sent, so this is the offered rate rather than the sent rate',})/**- * Duplicates split by which layer caught them.- *- * The split is the measurement, not the total. `batch` and `pod` are free and bounded by memory,- * `store` costs a Redis read, and anything the store catches that the pod cache did not is what- * the shared store is buying. A high `store` share against a full pod cache says the cache is- * undersized; a low one says it is already holding the working set.+ * `batch` and `pod` cost only memory, and `store` costs a Redis read, so the split is the+ * measurement rather than the total. A high `store` share against a full pod cache says the pod+ * cache is too small. A low one says the pod cache already holds the working set.*/private static readonly deduped = new Counter({name: 'ml_image_fetch_consumer_deduped_total',@@ -37,24 +42,18 @@ export class ImageFetchConsumerMetrics {labelNames: ['scope'],})/**- * URLs the lane refused before any dedup decision.- *- * `stale` is the expected one under a backlog and is working as designed. The others mean the- * producer and this consumer disagree about the wire format, so a sustained rate on any of them- * zeroes the lane while looking healthy from the Kafka side.+ * `stale` is the expected reason under a backlog. The others mean the producer and this consumer+ * disagree about the wire format, so a sustained rate on any of them takes the lane to zero while+ * the Kafka side still looks healthy.*/private static readonly dropped = new Counter({name: 'ml_image_fetch_consumer_dropped_total',- help: 'URLs refused before dedup, by reason: "stale" (older than the age limit), "malformed" / "unsupported_version" / "oversized_record" (the record did not parse), "bad_ref" / "bad_url" (an entry inside a record did not parse), "foreign_domain" (the host sits outside the domain the record is keyed by)',+ help: 'URLs refused before dedup, by reason: "stale" (older than the age limit), "malformed" / "unsupported_version" / "oversized_record" (the record did not parse), "bad_ref" / "bad_url" (an entry inside a record did not parse), "foreign_domain" (the key is not the registrable domain of the host), "private_host" (the host is a private address or a name that only resolves inside a network)',labelNames: ['reason'],})/**- * Distinct registrable domains seen per poll batch.- *- * The topic is keyed by domain, so one partition carries a small number of domains and one pod- * holds their whole request rate. A batch spanning many domains means the key is spreading work- * more finely than the partition count can express, which is what would let one pod exceed a- * single site's budget.+ * A batch that spans many domains means the key spreads work more finely than the partition count+ * can express, which is what would let one pod pass the budget of a single site.*/private static readonly domainsPerBatch = new Histogram({name: 'ml_image_fetch_consumer_domains_per_batch',@@ -68,7 +67,7 @@ export class ImageFetchConsumerMetrics {})private static readonly storeErrors = new Counter({name: 'ml_image_fetch_consumer_store_errors_total',- help: 'Sighting-store keys that failed, by operation. A failed read makes the lane treat a known URL as new, so the measured hit rate understates the real one. A failed write leaves the URL unrecorded, so the next pod to see it counts it again',+ help: 'Crawl-history keys that failed, by operation. A failed read makes the lane treat a known URL as new, so the measured hit rate understates the real one. A failed write leaves the URL unrecorded, so the next pod to see it counts it again',labelNames: ['operation'],})private static readonly batchDuration = new Histogram({@@ -112,3 +111,233 @@ export class ImageFetchConsumerMetrics {this.ageSeconds.observe(ageSeconds)}}++/**+ * The request path.+ *+ * No metric here carries a host or a URL. The host set is unbounded, so it lives in the structured+ * logs of the runner. A URL is page content and belongs in no metric, log, or trace.+ */+export class ImageFetchRequestMetrics {+ /**+ * `ok` against the sum is the yield of the lane. The site answers `not_found`, `forbidden`,+ * `rate_limited`, and `server_error`. This lane refuses `too_large`, `not_image`, `blocked`,+ * `bad_redirect`, and `too_many_redirects`. Only `breaker_open` and `deadline` come back in a+ * later batch.+ */+ private static readonly outcomes = new Counter({+ name: 'ml_image_fetch_requests_total',+ help: 'URLs that reached the request stage, by outcome. "deadline", "breaker_open", "connection_limit" and "rate_limited" cover URLs the lane never sent, so they say the lane wants more pods or the site wants less traffic, rather than that a fetch failed',+ labelNames: ['outcome'],+ })+ private static readonly duration = new Histogram({+ name: 'ml_image_fetch_request_duration_seconds',+ help: 'Time from the first request of a URL to its outcome, redirects included. It excludes the wait for a rate-limit token, which ml_image_fetch_budget_wait_seconds holds',+ labelNames: ['outcome'],+ buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],+ })+ /**+ * A rising tail means one domain offers more URLs than its rate carries. Past the pass deadline+ * the wait becomes a `deadline` shed, so read this against that outcome: a growing wait with no+ * sheds is headroom, and a growing wait with sheds is a domain the lane cannot keep up with.+ */+ private static readonly budgetWait = new Histogram({+ name: 'ml_image_fetch_budget_wait_seconds',+ help: 'Time a URL waited for its domain rate limit before its request went out',+ buckets: [0, 0.1, 0.5, 1, 2, 5, 10, 20],+ })+ private static readonly responseBytes = new Histogram({+ name: 'ml_image_fetch_response_bytes',+ help: 'Size of a downloaded image. The tail against the configured byte limit says how much of the catalog the limit refuses',+ buckets: [1024, 8 * 1024, 32 * 1024, 128 * 1024, 512 * 1024, 1024 * 1024, 2 * 1024 * 1024],+ })+ private static readonly redirects = new Histogram({+ name: 'ml_image_fetch_redirects',+ help: 'Redirects followed for one URL. Each hop is a separate request against the budget of whichever domain it lands on',+ buckets: [0, 1, 2, 3],+ })+ /**+ * The tracked count against the configured maximum says whether the map evicts, and an eviction+ * forgets that a domain is blocked.+ *+ * Both gauges read the budget at scrape time. A hold expires by the clock, so a count taken at+ * the end of a batch would report blocked domains until the next batch arrives.+ */+ private static readonly trackedDomains = new Gauge({+ name: 'ml_image_fetch_tracked_domains',+ help: 'Registrable domains this pod holds rate-limit state for',+ collect() {+ this.set(ImageFetchRequestMetrics.budget?.trackedDomains ?? 0)+ },+ })+ private static readonly blockedDomains = new Gauge({+ name: 'ml_image_fetch_blocked_domains',+ help: 'Domains this pod is currently sending nothing to, because a breaker opened or a Retry-After header is still in force',+ collect() {+ this.set(ImageFetchRequestMetrics.budget?.blockedDomains(Date.now()) ?? 0)+ },+ })++ public static incOutcome(outcome: string, count = 1): void {+ this.outcomes.labels(outcome).inc(count)+ }+ public static observeRequest(outcome: string, durationSeconds: number, redirects: number): void {+ this.outcomes.labels(outcome).inc()+ this.duration.labels(outcome).observe(durationSeconds)+ this.redirects.observe(redirects)+ }+ public static observeBudgetWait(waitSeconds: number): void {+ this.budgetWait.observe(waitSeconds)+ }+ public static observeBytes(bytes: number): void {+ this.responseBytes.observe(bytes)+ }+ private static readonly evictedWhileBlocked = new Gauge({+ name: 'ml_image_fetch_domains_evicted_while_blocked',+ help: 'Domains dropped from the rate-limit map while they were still blocked. Each one resumes traffic to a site that asked us to wait, so a rising value means the tracked-domain limit is too low',+ collect() {+ this.set(ImageFetchRequestMetrics.budget?.evictedWhileBlocked ?? 0)+ },+ })++ /**+ * Requests holding a socket right now, against the pod limit.+ *+ * A request waiting for a politeness token has not reached this yet, so a value at the limit+ * means the pod is the bottleneck rather than the sites.+ */+ private static readonly inFlight = new Gauge({+ name: 'ml_image_fetch_requests_in_flight',+ help: "Image requests this pod holds open right now. A URL waiting for its domain's rate limit is not counted, because it holds no socket",+ collect() {+ this.set(ImageFetchRequestMetrics.requests?.running ?? 0)+ },+ })++ private static budget: BudgetCounts | undefined+ private static requests: InFlightCount | undefined++ /**+ * URLs a shed left in the back queue, which the lane will not put back.+ *+ * A pass sheds whatever it did not reach, and one back queue can hold far more than a delay+ * tier can carry. Republishing all of them answers overload with more Kafka traffic, and the+ * same URLs come round again a minute later, each having spent a hop.+ */+ private static readonly shedDropped = new Counter({+ name: 'ml_image_fetch_shed_dropped_total',+ help: 'URLs a shed did not put back, because one pass republishes at most a fixed number for one domain. They return when a session refers to the same image',+ })++ public static incShedDropped(count: number): void {+ this.shedDropped.inc(count)+ }++ /** The runner owns both. Requirement 28. */+ public static trackBudget(budget: BudgetCounts, requests: InFlightCount): void {+ this.budget = budget+ this.requests = requests+ }++ /**+ * Read against `ml_image_fetch_requests_total` this is the amplification factor, because the lane+ * reads every republished message again. A rate that approaches the request rate means most work+ * goes around rather than completes. Requirement 27.+ */+ private static readonly republished = new Counter({+ name: 'ml_image_fetch_republished_total',+ help: 'URLs published back to Kafka, by why and to which topic. "redirect" left the registrable domain, so another consumer owns its budget. "retry" hit a transient failure and waits in a delay topic. "not_ready" arrived before the period it was waiting out had passed',+ labelNames: ['reason', 'topic'],+ })+ private static readonly republishFailed = new Counter({+ name: 'ml_image_fetch_republish_failed_total',+ help: 'URLs that could not be put back. Each one is dropped without a crawl history entry, so it returns only when a session refers to it again',+ labelNames: ['reason'],+ })+ /**+ * Zero is the common case, which is a URL fetched on first sight. The tail shows redirect chains+ * and retries, and a value at the budget is a URL the lane gave up on. Requirement 26.+ */+ private static readonly hopsUsed = new Histogram({+ name: 'ml_image_fetch_hops_used',+ help: 'Moves one URL made before the lane finished with it. A republish and a retry each count one. A redirect that stays on the same domain is bounded separately and counts none',+ buckets: [0, 1, 2, 3, 5, 10],+ })++ public static incRepublished(reason: string, topic: string): void {+ this.republished.labels(reason, topic).inc()+ }+ public static incRepublishFailed(reason: string): void {+ this.republishFailed.labels(reason).inc()+ }+ public static observeHops(hops: number): void {+ this.hopsUsed.observe(hops)+ }+}++/**+ * The consumer of one delay topic.+ *+ * Lag on these topics is the design at work rather than a fault, because a record that waits out its+ * period counts as lag. Read `ml_image_fetch_retry_wait_seconds` against the period of the topic+ * instead. A wait far short of the period means records arrive with their wait already spent, which+ * means the tier below is too small.+ */+export class RetryDelayMetrics {+ private static readonly released = new Counter({+ name: 'ml_image_fetch_retry_released_total',+ help: 'Records this delay consumer finished with, by what happened: "released" back to the frontier, "failed" to publish, or "malformed" and dropped',+ labelNames: ['outcome'],+ })+ private static readonly waitSeconds = new Histogram({+ name: 'ml_image_fetch_retry_wait_seconds',+ help: 'Time a record still had to wait when this consumer read it. Compare with the period of the topic: a much shorter wait means the records arrived late, and the consumer is behind',+ buckets: [1, 10, 60, 300, 600, 1800, 3600],+ })++ public static incReleased(outcome: 'released' | 'failed' | 'malformed' | 'abandoned'): void {+ this.released.labels(outcome).inc()+ }+ public static observeWait(waitSeconds: number): void {+ this.waitSeconds.observe(waitSeconds)+ }+}++/**+ * How the lane's work divides between teams, without an unbounded label.+ *+ * The team ID space is in the low millions, so this bounds `pseudo_team` here rather than at the+ * database. The busiest teams keep their name, everything else is one `other` row, and the count of+ * distinct teams is an estimate in a single series. Requirements 29, 30, and 31.+ *+ * Nothing on this path holds the team ID, so a team ID label here would need the mirror to send it.+ */+export class ImageFetchTeamMetrics {+ private static source: TeamVolume | undefined++ private static readonly urlsByTeam = new Gauge({+ name: 'ml_image_fetch_team_urls',+ help: 'URLs handled for each of the busiest teams, with the rest summed as "other". The label is the team pseudonym the topic carries, not the team ID',+ labelNames: ['pseudo_team'],+ collect() {+ // Rebuilt at scrape rather than kept in step with the counts, so a team that drops out+ // of the top list loses its series instead of holding its last value.+ this.reset()+ for (const { team, count } of ImageFetchTeamMetrics.source?.top() ?? []) {+ this.labels(team).set(count)+ }+ },+ })+ private static readonly distinctTeams = new Gauge({+ name: 'ml_image_fetch_distinct_teams',+ help: 'About how many distinct teams this pod has handled URLs for, estimated rather than counted, because an exact set of a million team pseudonyms costs hundreds of megabytes',+ collect() {+ this.set(ImageFetchTeamMetrics.source?.distinctTeams() ?? 0)+ },+ })++ /** The consumer owns the counts. These gauges read them at scrape time. */+ public static track(volume: TeamVolume): void {+ this.source = volume+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.test.tsnew file mode 100644index 000000000000..20f87d743081--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.test.ts@@ -0,0 +1,27 @@+import { politenessKey } from '@posthog/replay-anonymizer'++/**+ * The crate owns the rule and tests it. This file tests only that the fetch lane reaches that+ * function across the FFI boundary, so every case here asserts behaviour the crate already had.+ */+describe('politenessKey', () => {+ it.each([['d111.cloudfront.net'], ['bucket.s3.amazonaws.com'], ['user.github.io'], ['myapp.vercel.app']])(+ 'keeps %s as its own operator',+ (host) => {+ // Each provider sits in the private section of the public suffix list. A list read+ // without that section folds every tenant of one provider into a single rate budget.+ expect(politenessKey(host)).toBe(host)+ }+ )++ it.each([+ ['img1.cdn.example.com', 'example.com'],+ ['a.b.example.co.uk', 'example.co.uk'],+ ])('folds %s onto %s', (host, expected) => {+ expect(politenessKey(host)).toBe(expected)+ })++ it.each([['203.0.113.4'], ['::1']])('returns the address %s unchanged', (host) => {+ expect(politenessKey(host)).toBe(host)+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.tsnew file mode 100644index 000000000000..69e252f813fb--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.ts@@ -0,0 +1,48 @@+/**+ * The URL policy of the collector, reached through the node addon rather than reimplemented here. One+ * public suffix list answers for the producer and for this lane, so the key a record arrives under+ * and the key its budget is scoped to cannot drift.+ *+ * The addon holds a 15 MB native library, and `index.ts` imports every server whatever mode the pod+ * runs. This loads the addon on first use rather than at import, so only a pod in this lane pays for+ * it. The mirror server defers it the same way.+ */+let cached: typeof import('@posthog/replay-anonymizer') | undefined++function addon(): typeof import('@posthog/replay-anonymizer') {+ if (!cached) {+ const loaded = require('@posthog/replay-anonymizer') as typeof import('@posthog/replay-anonymizer')+ if (typeof loaded.politenessKey !== 'function' || typeof loaded.isPublicHost !== 'function') {+ throw new Error('the replay-anonymizer addon is missing the url policy: rebuild index.node')+ }+ cached = loaded+ }+ return cached+}++/**+ * Load the addon now, so a stale `index.node` stops the pod at startup.+ *+ * The parser calls into it for every URL, and requirement 23 says a record is counted and dropped+ * rather than thrown. A throw from there would crash loop on the first batch and stall the+ * partition for every site on it.+ */+export function assertUrlPolicyLoaded(): void {+ addon()+}++export function politenessKey(host: string): string {+ return addon().politenessKey(host)+}++/**+ * False for a host the collector would have declined: a private or reserved address, and a name+ * that only resolves inside a network.+ *+ * The connection layer refuses a private address, so this is not the only guard against one. It is+ * the only guard against a name that looks internal and whose DNS answer is public, because no+ * address check can refuse that. Requirement 35.+ */+export function isPublicHost(host: string): boolean {+ return addon().isPublicHost(host)+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.test.tsnew file mode 100644index 000000000000..cf465377f1b0--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.test.ts@@ -0,0 +1,166 @@+import { Message } from 'node-rdkafka'++import { KafkaProducerWrapper } from '~/common/kafka/producer'++import { RetryDelayConsumer } from './retry-delay-consumer'++const DELAY_MS = 60_000+const FRONTIER = 'session_replay_image_fetch'++function message(writtenAtMs: number, overrides: Partial<Message> = {}): Message {+ return {+ value: Buffer.from('{"v":1}'),+ key: Buffer.from('example.com'),+ size: 7,+ topic: 'session_replay_image_fetch_retry_1m',+ partition: 0,+ offset: 0,+ timestamp: writtenAtMs,+ ...overrides,+ }+}++function build(overrides: { isStopping?: () => boolean; produce?: () => Promise<void>; delayMs?: number } = {}): {+ consumer: RetryDelayConsumer+ published: string[]+ stored: number[]+ beats: () => number+} {+ const published: string[] = []+ const stored: number[] = []+ let beats = 0+ const producer = {+ produce: async ({ topic }: { topic: string }) => {+ await (overrides.produce?.() ?? Promise.resolve())+ published.push(topic)+ },+ } as unknown as KafkaProducerWrapper+ const consumer = new RetryDelayConsumer(producer, {+ frontierTopic: FRONTIER,+ delayMs: overrides.delayMs ?? DELAY_MS,+ heartbeat: () => beats++,+ heartbeatIntervalMs: 1,+ storeOffset: (m) => stored.push(m.offset),+ isStopping: overrides.isStopping,+ })+ return { consumer, published, stored, beats: () => beats }+}++describe('RetryDelayConsumer', () => {+ it('publishes a record whose period has already passed, without waiting', async () => {+ const { consumer, published, stored } = build()++ await consumer.handleBatch([message(Date.now() - DELAY_MS - 1000)])++ expect(published).toEqual([FRONTIER])+ expect(stored).toEqual([0])+ })++ it('waits out what is left of the period, measured from when the record was written', async () => {+ // A consumer that restarts must not begin the wait again, or a record could be held for+ // several periods by a rolling deploy.+ const { consumer, published, beats } = build()++ await consumer.handleBatch([message(Date.now() - DELAY_MS + 20)])++ expect(published).toEqual([FRONTIER])+ expect(beats()).toBeGreaterThan(0)+ })++ it('waits no longer than the period of its topic, whatever the record timestamp says', async () => {+ // The timestamp comes from whichever pod wrote the record. A clock ahead of this one would+ // otherwise hold the record for longer than the tier it is in.+ const { consumer, published } = build({ delayMs: 50 })++ const startedAt = Date.now()+ await consumer.handleBatch([message(Date.now() + 60 * 60 * 1000, { offset: 1 })])++ expect(published).toEqual([FRONTIER])+ expect(Date.now() - startedAt).toBeLessThan(DELAY_MS)+ })++ it('abandons a record when the pod is shutting down before the wait starts', async () => {+ const { consumer, published, stored } = build({ isStopping: () => true })++ await consumer.handleBatch([message(Date.now())])++ expect(published).toEqual([])+ expect(stored).toEqual([])+ })++ it('gives up a wait in progress rather than finishing it', async () => {+ // A record with a full period left would otherwise hold a rolling deploy for that period,+ // until Kubernetes killed the pod. The offset stays uncommitted, so the next pod reads the+ // record and waits out what remains.+ let stopping = false+ const { consumer, published, stored } = build({ isStopping: () => stopping })+ setTimeout(() => (stopping = true), 20)++ const startedAt = Date.now()+ await consumer.handleBatch([message(Date.now())])+ const elapsed = Date.now() - startedAt++ expect(published).toEqual([])+ expect(stored).toEqual([])+ // The record had the whole period left. Returning anywhere near it means the wait ran on.+ expect(elapsed).toBeLessThan(DELAY_MS / 10)+ })++ it('fails the batch for a record it could not publish, so no later offset commits past it', async () => {+ // Storing nothing is not enough on its own. The next poll would read the records after this+ // one and store one of their offsets, and an offset is a high water mark.+ const { consumer, published, stored } = build({+ produce: () => Promise.reject(new Error('broker down')),+ })++ await expect(consumer.handleBatch([message(Date.now() - DELAY_MS - 1000)])).rejects.toThrow(+ 'could not publish a record back to the frontier'+ )++ expect(published).toEqual([])+ expect(stored).toEqual([])+ })++ it('stores the offset of a record it can never publish, so the partition still moves', async () => {+ const { consumer, published, stored } = build()++ await consumer.handleBatch([message(Date.now() - DELAY_MS - 1000, { offset: 7, value: null })])++ expect(published).toEqual([])+ expect(stored).toEqual([7])+ })++ it('stores each offset as it goes, so a shutdown keeps only the records it did not reach', async () => {+ // Requirement 21. The consumer that owns this one stores offsets for a whole batch once the+ // handler returns, so anything left unstored here must stay unstored there.+ let releasedSoFar = 0+ const { consumer, published, stored } = build({+ produce: () => Promise.resolve(releasedSoFar++).then(() => {}),+ isStopping: () => releasedSoFar >= 2,+ })+ const ripe = Date.now() - DELAY_MS - 1000++ await consumer.handleBatch([+ message(ripe, { offset: 4 }),+ message(ripe, { offset: 5 }),+ message(ripe, { offset: 6 }),+ ])++ expect(published).toEqual([FRONTIER, FRONTIER])+ expect(stored).toEqual([4, 5])+ })++ it.each([[0], [-1], [NaN]])('refuses to start with a delay of %p', (delayMs) => {+ const producer = {} as KafkaProducerWrapper++ expect(+ () =>+ new RetryDelayConsumer(producer, {+ frontierTopic: FRONTIER,+ delayMs,+ heartbeat: () => {},+ storeOffset: () => {},+ })+ ).toThrow('positive delay')+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.tsnew file mode 100644index 000000000000..416e312dc46e--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.ts@@ -0,0 +1,141 @@+import { Message } from 'node-rdkafka'++import { KafkaProducerWrapper } from '~/common/kafka/producer'+import { logger } from '~/common/utils/logger'+import { delay } from '~/common/utils/utils'++import { RetryDelayMetrics } from './metrics'++export interface RetryDelayConsumerOptions {+ frontierTopic: string+ /** The period every record in this topic waits. The period belongs to the topic, not to the record. */+ delayMs: number+ /** Called while the consumer sleeps, so the health check does not restart a pod that is working as designed. */+ heartbeat: () => void+ /** The default sits well inside CONSUMER_MAX_HEARTBEAT_INTERVAL_MS (30s), which binds before the loop stall threshold. */+ heartbeatIntervalMs?: number+ /** True once the pod is shutting down. A wait of an hour would otherwise hold the rolling deploy until Kubernetes killed it. */+ isStopping?: () => boolean+ /**+ * Called only for a record this consumer finished with. The consumer that owns this one stores+ * offsets for a whole batch once the handler returns, whatever the handler did with the+ * records, so a record abandoned mid-wait would commit and never be seen again. Requirement 21.+ */+ storeOffset: (message: Message) => void+}++const DEFAULT_HEARTBEAT_INTERVAL_MS = 10_000++/**+ * The consumer of one delay topic.+ *+ * Kafka has no delayed delivery, so a retry waits in a topic whose period is fixed and a consumer+ * holds it there. Every record in one topic waits the same period, so the records leave in the+ * order they become ready.+ *+ * The record already carries its hop budget and its earliest fetch time, so nothing here parses it.+ *+ * Two properties of this lane live outside this file, and both are in the README. Its+ * `max.poll.interval.ms` must exceed the period of its topic, or the broker evicts it mid-sleep. It+ * runs one pod and no more, because adding consumers cannot make a record become ready sooner.+ */+export class RetryDelayConsumer {+ constructor(+ private readonly producer: KafkaProducerWrapper,+ private readonly options: RetryDelayConsumerOptions+ ) {+ if (!Number.isFinite(options.delayMs) || options.delayMs <= 0) {+ throw new Error(`the retry delay consumer needs a positive delay, got ${options.delayMs}`)+ }+ }++ public async handleBatch(messages: Message[]): Promise<void> {+ for (const message of messages) {+ if (this.stopping()) {+ // The record stays where it is, with no offset stored. The next pod to own this+ // partition reads it again and waits out what is left of its period, measured from+ // when it was written. Requirement 21.+ RetryDelayMetrics.incReleased('abandoned')+ return+ }+ const waitMs = this.remainingWaitMs(message)+ if (waitMs > 0) {+ RetryDelayMetrics.observeWait(waitMs / 1000)+ if (!(await this.sleepWithHeartbeat(waitMs))) {+ RetryDelayMetrics.incReleased('abandoned')+ return+ }+ }+ if (!(await this.release(message))) {+ // Thrown, not returned. Returning holds this batch and no more: the next poll reads+ // the records after it and stores one of their offsets, and an offset is a high+ // water mark, so that commits this record too. A throw leaves the poll loop, so+ // nothing is stored and the record is read again. Requirement 21.+ throw new Error('the image fetch retry lane could not publish a record back to the frontier')+ }+ this.options.storeOffset(message)+ }+ }++ private stopping(): boolean {+ return this.options.isStopping?.() ?? false+ }++ /**+ * Measured from when the record was written rather than from when it was read, so a consumer+ * that restarts does not begin the wait again. librdkafka reports an absent timestamp as -1,+ * which is not nullish, so a plain `??` would make the whole period look already spent.+ */+ private remainingWaitMs(message: Message): number {+ const writtenAtMs = message.timestamp !== undefined && message.timestamp > 0 ? message.timestamp : Date.now()+ // Clamped to the period, because the timestamp comes from whichever pod wrote the record.+ // A clock ahead of this one would otherwise hold the record for longer than its tier, and+ // the tier period is the whole reason a record can be held here at all.+ return Math.min(this.options.delayMs, writtenAtMs + this.options.delayMs - Date.now())+ }++ /** False when the pod started shutting down during the wait, so the caller abandons the record. */+ private async sleepWithHeartbeat(waitMs: number): Promise<boolean> {+ const interval = this.options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS+ const deadline = Date.now() + waitMs+ while (Date.now() < deadline) {+ if (this.stopping()) {+ return false+ }+ this.options.heartbeat()+ await delay(Math.min(interval, deadline - Date.now()))+ }+ this.options.heartbeat()+ return !this.stopping()+ }++ /**+ * True when this consumer is finished with the record, whether it went out or can never go out.+ *+ * A failed produce returns false, because reading the record again is the only way it comes+ * back. Nothing else holds it.+ */+ private async release(message: Message): Promise<boolean> {+ if (!message.value || !message.key) {+ // The offset stores anyway. This record can never be released, and holding its offset+ // would stop the partition rather than fix it.+ RetryDelayMetrics.incReleased('malformed')+ return true+ }+ try {+ await this.producer.produce({+ topic: this.options.frontierTopic,+ key: message.key,+ value: message.value,+ })+ } catch (error) {+ logger.warn('🌐', 'ml_image_fetch_retry_release_failed', {+ error: error instanceof Error ? error.name : 'unknown',+ })+ RetryDelayMetrics.incReleased('failed')+ return false+ }+ RetryDelayMetrics.incReleased('released')+ return true+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.test.tsnew file mode 100644index 000000000000..dccee6597632--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.test.ts@@ -0,0 +1,96 @@+import { TeamVolume } from './team-volume'++/**+ * These tests pin the bound, the accounting, and the estimate. They do not pin the count inheritance+ * on eviction, which is the step that guarantees the map always holds a team above total over+ * capacity. A change that drops it makes this a random-eviction cache, which still finds a heavy team+ * often enough that no small test fails.+ */+describe('TeamVolume', () => {+ it('names the busiest teams and sums the rest into one bucket (requirement 29)', () => {+ const volume = new TeamVolume(2)+ volume.record('busiest', 100)+ volume.record('second', 50)+ volume.record('third', 7)+ volume.record('fourth', 3)++ expect(volume.top()).toEqual([+ { team: 'busiest', count: 100 },+ { team: 'second', count: 50 },+ { team: 'other', count: 10 },+ ])+ })++ it('names every team when there are fewer than the limit', () => {+ const volume = new TeamVolume(20)+ volume.record('only', 5)++ // No `other` row: an empty bucket would be a series carrying nothing.+ expect(volume.top()).toEqual([{ team: 'only', count: 5 }])+ })++ it.each([+ [1, 1],+ [10, 10],+ [500, 500],+ [50_000, 50_000],+ ])('estimates %i distinct teams (requirement 30)', (teams, expected) => {+ // A reader takes the order of magnitude, so a few percent of error costs nothing. A set would+ // be exact and would cost hundreds of megabytes at the top of this range.+ const volume = new TeamVolume()+ for (let i = 0; i < teams; i++) {+ volume.record(`team-${i}`)+ }++ const estimate = volume.distinctTeams()++ expect(estimate).toBeGreaterThan(expected * 0.9)+ expect(estimate).toBeLessThan(expected * 1.1)+ })++ it('holds a bounded number of counters however many teams arrive', () => {+ // Someone who spreads traffic over many project tokens must not grow this map for the life+ // of the pod. The map keeps the metric label bounded, so the map must stay bounded itself.+ const volume = new TeamVolume(20)++ for (let i = 0; i < 100_000; i++) {+ volume.record(`team-${i}`)+ }++ expect(volume.trackedTeams).toBeLessThanOrEqual(200)+ })++ it('keeps a busy team named through a flood of teams seen once (requirement 29)', () => {+ // Space-Saving holds any team whose share is above total divided by the counters kept. Here+ // that is 15000 over 20, so 750, and a team at a third of all volume sits far above it.+ // Someone who spreads traffic over many tokens therefore cannot hide a heavy team.+ const volume = new TeamVolume(2)+ volume.record('busy', 5_000)++ for (let i = 0; i < 10_000; i++) {+ volume.record(`noise-${i}`)+ }++ expect(volume.top()[0].team).toBe('busy')+ })++ it('accounts for every URL it was given, named or not', () => {+ const volume = new TeamVolume(2)+ volume.record('a', 10)+ volume.record('b', 5)+ volume.record('c', 3)+ volume.record('d', 2)++ expect(volume.top().reduce((sum, { count }) => sum + count, 0)).toBe(20)+ })++ it('counts a repeated team once', () => {+ const volume = new TeamVolume()+ for (let i = 0; i < 1000; i++) {+ volume.record('same')+ }++ expect(volume.distinctTeams()).toBe(1)+ expect(volume.top()).toEqual([{ team: 'same', count: 1000 }])+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.tsnew file mode 100644index 000000000000..e03dfa2dbdcc--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.ts@@ -0,0 +1,138 @@+import { createHash } from 'node:crypto'++/** This many teams keep their name. The class sums everything else into `other`. */+const DEFAULT_TOP_N = 20++/**+ * Counters held to find those teams, wider than the reported list so that the reported list is+ * right. Space-Saving holds any team whose share is above one over this number of counters. At 200+ * counters that is half a percent of the lane's volume.+ *+ * The count is bounded because the team ID space is in the low millions. A map of every team ever+ * seen is the unbounded growth this class exists to avoid.+ */+const TRACKED_MULTIPLE = 10++/**+ * Registers of the estimator. 2^12 gives about 1.6% error for a few kilobytes, which is far finer+ * than any decision this number feeds.+ */+const HLL_REGISTER_BITS = 12+const HLL_REGISTERS = 1 << HLL_REGISTER_BITS++/**+ * How much of the lane one team uses, without a `team_id` label on anything.+ *+ * The team ID space is in the low millions. A label of that cardinality is unbounded twice over: in+ * the time series database, and in the memory of this process, because prom-client holds every label+ * combination for the life of the pod. So this class holds the identities of the busiest teams,+ * bounded, and counts everything else without a name.+ *+ * Requirements 29, 30, and 31.+ */+export class TeamVolume {+ private readonly counts = new Map<string, number>()+ private readonly registers = new Uint8Array(HLL_REGISTERS)+ private readonly capacity: number+ private total = 0++ constructor(private readonly topN: number = DEFAULT_TOP_N) {+ this.capacity = topN * TRACKED_MULTIPLE+ }++ /**+ * Space-Saving: a full map replaces its smallest counter rather than grows.+ *+ * The replacement inherits the count it displaced, so a team that keeps arriving climbs past the+ * churn of teams seen once. A flood of quiet teams therefore cannot push a busy team out, and+ * that flood is what someone who spreads traffic over many project tokens produces.+ */+ public record(team: string, count = 1): void {+ this.total += count+ this.observeDistinct(team)++ const seen = this.counts.get(team)+ if (seen !== undefined) {+ this.counts.set(team, seen + count)+ return+ }+ if (this.counts.size < this.capacity) {+ this.counts.set(team, count)+ return+ }+ const smallest = this.smallest()+ this.counts.delete(smallest.team)+ this.counts.set(team, smallest.count + count)+ }++ private smallest(): { team: string; count: number } {+ let team = ''+ let count = Infinity+ for (const [candidate, candidateCount] of this.counts) {+ if (candidateCount < count) {+ team = candidate+ count = candidateCount+ }+ }+ return { team, count }+ }++ /**+ * The busiest teams by name, and everything else summed as `other`.+ *+ * This sorts on each read rather than keeps an order on each record, because a read happens once+ * for each scrape and a record happens once for each URL.+ */+ public top(): { team: string; count: number }[] {+ const sorted = [...this.counts].sort((left, right) => right[1] - left[1])+ const named = sorted.slice(0, this.topN).map(([team, count]) => ({ team, count }))+ // Everything this pod handled, less what the named rows account for. This reads the running+ // total, because the counters of the untracked teams no longer exist.+ const rest = this.total - named.reduce((sum, { count }) => sum + count, 0)+ return rest > 0 ? [...named, { team: 'other', count: rest }] : named+ }++ /**+ * About how many distinct teams this pod saw. HyperLogLog rather than a set, because a set of a+ * million team IDs is hundreds of megabytes, and a reader only ever takes the order of magnitude.+ */+ public distinctTeams(): number {+ let sum = 0+ let empty = 0+ for (const rank of this.registers) {+ sum += 2 ** -rank+ if (rank === 0) {+ empty+++ }+ }+ const estimate = (ALPHA * HLL_REGISTERS * HLL_REGISTERS) / sum+ // The estimator is biased below this point, and a count of the untouched registers is exact there.+ if (estimate <= 2.5 * HLL_REGISTERS && empty > 0) {+ return Math.round(HLL_REGISTERS * Math.log(HLL_REGISTERS / empty))+ }+ return Math.round(estimate)+ }++ /** Counters held right now, which never pass the capacity. */+ public get trackedTeams(): number {+ return this.counts.size+ }++ private observeDistinct(team: string): void {+ // The team ID is already an HMAC on this topic, but it is not uniform across the register+ // index and the leading zero count, and the estimator needs both of them to be uniform.+ const digest = createHash('sha1').update(team).digest()+ const index = digest.readUInt16BE(0) % HLL_REGISTERS+ const rank = leadingZeros(digest.readUInt32BE(2)) + 1+ if (rank > this.registers[index]) {+ this.registers[index] = rank+ }+ }+}++/** The bias constant for this register count, from the HyperLogLog paper. */+const ALPHA = 0.7213 / (1 + 1.079 / HLL_REGISTERS)++function leadingZeros(value: number): number {+ return value === 0 ? 32 : Math.clz32(value)+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.tsindex bbe34ff6ae54..fbbc2a530226 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts@@ -1,39 +1,47 @@import { Message } from 'node-rdkafka'+import { FetchCandidate } from './collected-urls-record'+import { CrawlHistoryReadResult, CrawlHistoryStore, crawlHistoryKey } from './crawl-history'+import { AttemptOutcome, FetchPass, isTerminal } from './fetch-runner'+import { FrontierPublisher } from './frontier-publisher'import { UrlFetchConsumer } from './url-fetch-consumer'-import { SightingStore, sightingKey } from './url-sightings'const TEAM = '0123456789abcdef0123456789abcdef'const OTHER_TEAM = 'fedcba9876543210fedcba9876543210'const NOW = 1_700_000_000_000-/** The ref format fixes the hash at 22 base64url characters, so a short test name has to be padded. */+/** The ref format fixes the hash at 22 base64url characters, so a short test name needs padding. */const hash = (name: string): string => name.padEnd(22, '0')function ref(name: string, team: string = TEAM): string {return `imageurl:${team}:${hash(name)}`}-class FakeSightings implements SightingStore {+class FakeCrawlHistory implements CrawlHistoryStore {public readonly stored = new Map<string, number>()public readFailure: Error | null = nullpublic writeFailure: Error | null = null/** Keys whose individual write reports a per-command failure, as ioredis does inside a pipeline. */public partialWriteFailures = new Set<string>()+ /** Keys whose read did not complete, so the store can say nothing about them. */+ public partialReadFailures = new Set<string>()public reads = 0- read(keys: string[]): Promise<{ known: Set<number>; failed: number }> {+ read(keys: string[]): Promise<CrawlHistoryReadResult> {this.reads++if (this.readFailure) {return Promise.reject(this.readFailure)}const known = new Set<number>()+ const failed = new Set<number>()keys.forEach((key, index) => {- if (this.stored.has(key)) {+ if (this.partialReadFailures.has(key)) {+ failed.add(index)+ } else if (this.stored.has(key)) {known.add(index)}})- return Promise.resolve({ known, failed: 0 })+ return Promise.resolve({ known, failed })}record(keys: string[], nowMs: number): Promise<{ failed: Set<number> }> {@@ -52,7 +60,7 @@ class FakeSightings implements SightingStore {}}-/** A real Message, so a field the consumer starts reading cannot be missing without the type saying so. */+/** A real Message, so the type fails if the consumer starts to read a field this omits. */function message(value: Buffer | null, key: string | null): Message {return {value,@@ -82,61 +90,124 @@ function url(name: string, host = 'cdn.example.com'): { ref: string; url: string}describe('UrlFetchConsumer', () => {- let sightings: FakeSightings+ let crawlHistory: FakeCrawlHistorylet consumer: UrlFetchConsumer+ let republished: { reason: string; waitMs: number }[]+ let publisher: FrontierPublisherconst build = (dedupMaxRefs = 1000): UrlFetchConsumer =>- new UrlFetchConsumer(sightings, {+ new UrlFetchConsumer(crawlHistory, publisher, {maxAgeMs: 6 * 60 * 60 * 1000,dedupMaxRefs,dryRun: true,})beforeEach(() => {- sightings = new FakeSightings()+ crawlHistory = new FakeCrawlHistory()+ republished = []+ publisher = {+ republish: (_c: unknown, _t: unknown, reason: string, waitMs: number) => {+ republished.push({ reason, waitMs })+ return Promise.resolve(true)+ },+ } as unknown as FrontierPublisherconsumer = build()})const hashOf = (key: string): string => key.split(':').pop() as stringit.each([NaN, 0, -1])('refuses to start with an age limit of %p', (maxAgeMs) => {- // The knob arrives from env, where a typo parses to NaN. A NaN limit makes every comparison- // false, so the lane silently stops shedding a backlog instead of failing.- expect(() => new UrlFetchConsumer(sightings, { maxAgeMs, dedupMaxRefs: 10, dryRun: true })).toThrow(- 'SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS'- )+ // The limit arrives from env, where a typo parses to NaN. A NaN limit makes every comparison+ // false, so the lane stops shedding a backlog rather than fails.+ expect(+ () => new UrlFetchConsumer(crawlHistory, publisher, { maxAgeMs, dedupMaxRefs: 10, dryRun: true })+ ).toThrow('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS')})it('writes one ledger entry per URL it would fetch', async () => {await consumer.handleBatch([record([url('a'), url('b')])], NOW)- expect([...sightings.stored.keys()].map(hashOf).sort()).toEqual([hash('a'), hash('b')])+ expect([...crawlHistory.stored.keys()].map(hashOf).sort()).toEqual([hash('a'), hash('b')])})it('does not re-record a URL another pod already reached', async () => {- sightings.stored.set(sightingKey(TEAM, hash('a')), NOW - 1000)+ crawlHistory.stored.set(crawlHistoryKey(TEAM, hash('a')), NOW - 1000)await consumer.handleBatch([record([url('a'), url('b')])], NOW)- // 'a' keeps the earlier entry rather than being counted and written again, which is what- // makes the ledger measure the hit rate instead of the sighting rate.- expect(sightings.stored.get(sightingKey(TEAM, hash('a')))).toBe(NOW - 1000)- expect(sightings.stored.get(sightingKey(TEAM, hash('b')))).toBe(NOW)+ // The earlier entry survives, so the store measures the hit rate rather than the rate of+ // first arrivals.+ expect(crawlHistory.stored.get(crawlHistoryKey(TEAM, hash('a')))).toBe(NOW - 1000)+ expect(crawlHistory.stored.get(crawlHistoryKey(TEAM, hash('b')))).toBe(NOW)})it('collapses a repeated URL inside one batch into a single ledger write', async () => {await consumer.handleBatch([record([url('a')]), record([url('a')]), record([url('a')])], NOW)- expect([...sightings.stored.keys()]).toEqual([sightingKey(TEAM, hash('a'))])+ expect([...crawlHistory.stored.keys()]).toEqual([crawlHistoryKey(TEAM, hash('a'))])})it('does not consult the store for a URL this pod already handled', async () => {await consumer.handleBatch([record([url('a')])], NOW)- const readsAfterFirst = sightings.reads+ const readsAfterFirst = crawlHistory.readsawait consumer.handleBatch([record([url('a')])], NOW)- expect(sightings.reads).toBe(readsAfterFirst)+ expect(crawlHistory.reads).toBe(readsAfterFirst)+ })++ it.each([+ ['still waiting out its delay', NOW + 60_000, 0, [{ reason: 'not_ready', waitMs: 60_000 }]],+ ['past its delay', NOW - 1, 1, []],+ ])(+ 'handles a retry that is %s (requirement 15)',+ async (_name, notBeforeMs, expectedWrites, expectedRepublishes) => {+ // A record can come back before its wait is over, because a wait longer than the longest+ // delay topic goes round that topic again. An early fetch would reach a site that asked+ // to be left alone, and a crawl history entry would stop the trip the URL still makes.+ // It goes back for the rest of the wait, because nothing else holds it.+ const body = {+ v: 1,+ pseudoTeam: TEAM,+ capturedAtMs: NOW,+ notBeforeMs,+ urls: [url('a')],+ }+ const early = message(Buffer.from(JSON.stringify(body)), 'example.com')++ await consumer.handleBatch([early], NOW)++ expect(crawlHistory.stored.size).toBe(expectedWrites)+ expect(republished).toEqual(expectedRepublishes)+ }+ )++ it('records a URL that is not ready and has no hops left (requirements 12 and 24)', async () => {+ // It cannot go round again, and nothing else holds it. Without an entry it comes back on+ // every session that refers to the image and is dropped again each time.+ const body = {+ v: 1,+ pseudoTeam: TEAM,+ capturedAtMs: NOW,+ notBeforeMs: NOW + 60_000,+ hopsRemaining: 1,+ urls: [url('a')],+ }+ const spent = message(Buffer.from(JSON.stringify(body)), 'example.com')++ await consumer.handleBatch([spent], NOW)++ expect([...crawlHistory.stored.keys()].map(hashOf)).toEqual([hash('a')])+ expect(republished).toEqual([])+ })++ it('fails the batch when a URL that is not ready cannot be sent back (requirement 21)', async () => {+ publisher = { republish: () => Promise.resolve(false) } as unknown as FrontierPublisher+ const body = { v: 1, pseudoTeam: TEAM, capturedAtMs: NOW, notBeforeMs: NOW + 60_000, urls: [url('a')] }+ const early = message(Buffer.from(JSON.stringify(body)), 'example.com')++ await expect(build().handleBatch([early], NOW)).rejects.toThrow('account for 1')+ expect(crawlHistory.stored.size).toBe(0)})it('drops a URL older than the age limit without recording it', async () => {@@ -144,7 +215,7 @@ describe('UrlFetchConsumer', () => {await consumer.handleBatch([record([url('a')], { capturedAtMs: sevenHoursAgo })], NOW)- expect(sightings.stored.size).toBe(0)+ expect(crawlHistory.stored.size).toBe(0)})it.each([@@ -155,7 +226,7 @@ describe('UrlFetchConsumer', () => {])('drops %s without throwing', async (_name, message) => {await expect(consumer.handleBatch([message], NOW)).resolves.toBeUndefined()- expect(sightings.stored.size).toBe(0)+ expect(crawlHistory.stored.size).toBe(0)})it.each([@@ -172,22 +243,30 @@ describe('UrlFetchConsumer', () => {{ ref: ref('a'), url: 'https://evil.example.net/a.png', host: 'cdn.example.com' },],['a scheme we never fetch', { ref: ref('a'), url: 'ftp://cdn.example.com/a.png', host: 'cdn.example.com' }],+ [+ 'a port the scheme does not own',+ { ref: ref('a'), url: 'https://cdn.example.com:11211/a.png', host: 'cdn.example.com' },+ ],+ [+ 'a url carrying credentials',+ { ref: ref('a'), url: 'https://user:[email protected]/a.png', host: 'cdn.example.com' },+ ],])('rejects %s while keeping the rest of the record', async (_name, bad) => {await consumer.handleBatch([record([bad as ReturnType<typeof url>, url('good')])], NOW)- expect([...sightings.stored.keys()].map(hashOf)).toEqual([hash('good')])+ expect([...crawlHistory.stored.keys()].map(hashOf)).toEqual([hash('good')])})it('does not mark the pod cache for a URL whose write failed', async () => {- sightings.partialWriteFailures.add(sightingKey(TEAM, hash('a')))+ crawlHistory.partialWriteFailures.add(crawlHistoryKey(TEAM, hash('a')))await consumer.handleBatch([record([url('a')])], NOW)- const readsAfterFirst = sightings.reads+ const readsAfterFirst = crawlHistory.readsawait consumer.handleBatch([record([url('a')])], NOW)- // The URL is in no durable store, so the next sighting has to reach the store again rather- // than be suppressed locally and vanish from the measurement.- expect(sightings.reads).toBe(readsAfterFirst + 1)+ // No durable store holds the URL, so the next arrival must reach the store again rather than+ // stop in this pod and vanish from the measurement.+ expect(crawlHistory.reads).toBe(readsAfterFirst + 1)})it('rejects a host outside the domain the record is keyed by', async () => {@@ -197,7 +276,7 @@ describe('UrlFetchConsumer', () => {NOW)- expect([...sightings.stored.keys()].map(hashOf)).toEqual([hash('good')])+ expect([...crawlHistory.stored.keys()].map(hashOf)).toEqual([hash('good')])})it('drops a record carrying more URLs than any producer sends', async () => {@@ -205,18 +284,98 @@ describe('UrlFetchConsumer', () => {await consumer.handleBatch([record(many)], NOW)- expect(sightings.stored.size).toBe(0)+ expect(crawlHistory.stored.size).toBe(0)})- it('treats a URL as unseen when the store read fails, rather than stalling the partition', async () => {- sightings.readFailure = new Error('redis down')+ it('holds back a URL whose dedup read failed, rather than treating it as new', async () => {+ // To count it as new would fetch it. A store outage would then make every batch send the+ // full un-deduped volume at customer sites, because our own store is down.+ crawlHistory.partialReadFailures.add(crawlHistoryKey(TEAM, hash('a')))++ await expect(consumer.handleBatch([record([url('a'), url('b')])], NOW)).resolves.toBeUndefined()++ expect([...crawlHistory.stored.keys()].map(hashOf)).toEqual([hash('b')])+ })++ it('commits a batch the store could not answer for, rather than replaying it forever', async () => {+ // A store that answers nothing answers nothing for the next batch too, so a replay stops+ // the lane instead of saving the URL. Nothing is recorded, so the mirror offers it again.+ crawlHistory.readFailure = new Error('redis down')await expect(consumer.handleBatch([record([url('a')])], NOW)).resolves.toBeUndefined()++ expect(crawlHistory.stored.size).toBe(0)})- it('survives a store write failure', async () => {- sightings.writeFailure = new Error('redis down')+ it('commits a batch whose store write failed, because the URL was fetched', async () => {+ // A missing crawl history entry costs one duplicate fetch later, which requirement 22+ // allows. A replay would cost the same duplicate and stall the partition too.+ crawlHistory.writeFailure = new Error('redis down')await expect(consumer.handleBatch([record([url('a')])], NOW)).resolves.toBeUndefined()})++ it('replays the batch when the pass could not put a URL back, rather than committing past it', async () => {+ // Requirement 21. Nothing else holds a URL whose republish failed, so its offset must not+ // commit.+ const runner: FetchPass = {+ run: (candidates: FetchCandidate[]) =>+ Promise.resolve(+ candidates.map((candidate) => ({+ candidate,+ outcome: 'timeout' as AttemptOutcome,+ finished: false,+ lost: true,+ }))+ ),+ }+ const fetching = new UrlFetchConsumer(+ crawlHistory,+ publisher,+ { maxAgeMs: 6 * 60 * 60 * 1000, dedupMaxRefs: 1000, dryRun: false },+ runner+ )++ await expect(fetching.handleBatch([record([url('lost')])], NOW)).rejects.toThrow('account for 1')+ // No crawl history entry, so the replay fetches the URL rather than skips it.+ expect(crawlHistory.stored.size).toBe(0)+ })++ it('refuses to leave dry run without a way to send the requests', () => {+ expect(+ () => new UrlFetchConsumer(crawlHistory, publisher, { maxAgeMs: 1000, dedupMaxRefs: 10, dryRun: false })+ ).toThrow('fetch runner')+ })++ it('records only the URLs the fetch pass finished with', async () => {+ const outcomes: Record<string, AttemptOutcome> = {+ [hash('done')]: 'ok',+ [hash('gone')]: 'not_found',+ [hash('later')]: 'deadline',+ [hash('slow')]: 'timeout',+ }+ const runner: FetchPass = {+ run: (candidates: FetchCandidate[]) =>+ Promise.resolve(+ candidates.map((candidate) => ({+ candidate,+ outcome: outcomes[candidate.urlHash],+ finished: isTerminal(outcomes[candidate.urlHash]),+ lost: false,+ }))+ ),+ }+ const fetching = new UrlFetchConsumer(+ crawlHistory,+ publisher,+ { maxAgeMs: 6 * 60 * 60 * 1000, dedupMaxRefs: 1000, dryRun: false },+ runner+ )++ await fetching.handleBatch([record([url('done'), url('gone'), url('later'), url('slow')])], NOW)++ // A crawl history entry stops this lane from ever reading a URL again, so an answered URL+ // gets one and a URL that only ran out of time does not.+ expect([...crawlHistory.stored.keys()].map(hashOf).sort()).toEqual([hash('done'), hash('gone')])+ })})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.tsindex 3d40236c145d..861ffef64b9b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts@@ -3,51 +3,58 @@ import { Message } from 'node-rdkafka'import { logger } from '~/common/utils/logger'import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'-import { FetchCandidate, parseCollectedUrlsRecord } from './collected-urls-record'-import { ImageFetchConsumerMetrics, UrlDropReason } from './metrics'-import { SIGHTING_TTL_SECONDS, SightingStore, sightingKey } from './url-sightings'+import { FetchCandidate, MAX_HOPS, parseCollectedUrlsRecord } from './collected-urls-record'+import { CRAWL_HISTORY_TTL_SECONDS, CrawlHistoryStore, crawlHistoryKey } from './crawl-history'+import { FetchPass, HOPS_EXHAUSTED } from './fetch-runner'+import { FrontierPublisher } from './frontier-publisher'+import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics, ImageFetchTeamMetrics, UrlDropReason } from './metrics'+import { TeamVolume } from './team-volume'export interface UrlFetchConsumerOptions {- /** A URL older than this is dropped rather than fetched, so a backlog sheds work instead of downloading stale work. */+ /** The lane drops a URL older than this, so a backlog sheds work instead of fetching stale URLs. */maxAgeMs: numberdedupMaxRefs: number- /** While true no request leaves this process. Everything else, including the sighting write, still runs. */+ /** While true, no request leaves this process. Everything else still runs, including the crawl history write. */dryRun: boolean}/**- * The dry run of the image fetch lane.+ * The image fetch lane.*- * It runs every decision the fetcher will make up to the point of sending a request, and stops- * there. What survives to the end is counted as `fetchable`, which is the offered request rate that- * phase 0 exists to measure, and recorded so the rate phase 1 sees is the rate after dedup rather- * than before it.- *- * A bad record and an unreachable Redis are both handled rather than thrown. This lane shares a+ * The consumer handles a bad record and an unreachable Redis instead of throwing. This lane shares a* partition with every site whose URLs key to it, and a throw here stops the consumer, replays the* same batch, and holds that partition against all of them.*/export class UrlFetchConsumer {private readonly seenRefs: RefDedupCache+ /** Bounded on purpose: one series for each busy team, one for the rest, one estimate. Requirement 31. */+ private readonly teamVolume = new TeamVolume()constructor(- private readonly sightings: SightingStore,- private readonly options: UrlFetchConsumerOptions+ private readonly crawlHistory: CrawlHistoryStore,+ private readonly publisher: FrontierPublisher,+ private readonly options: UrlFetchConsumerOptions,+ /** Absent in dry run, so the dry run sends nothing. The lane reads no flag for each URL. */+ private readonly runner?: FetchPass) {// These arrive from env, where a typo parses to NaN. A NaN age limit makes every comparison- // false, which silently disables the shed that lets the lane drop a backlog.+ // false, which disables the shed that lets the lane drop a backlog.if (!Number.isFinite(options.maxAgeMs) || options.maxAgeMs <= 0) {throw new Error(`SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS must be a positive number, got ${options.maxAgeMs}`)}+ if (!options.dryRun && !runner) {+ throw new Error('the image fetch lane needs a fetch runner once dry run is cleared')+ }this.seenRefs = new RefDedupCache('image_fetch_consumer', options.dedupMaxRefs)ImageFetchConsumerMetrics.setDryRun(options.dryRun)+ ImageFetchTeamMetrics.track(this.teamVolume)}public async handleBatch(messages: Message[], nowMs: number): Promise<void> {- // Wall clock, not the caller's nowMs: nowMs dates the URLs and a test is free to set it far- // from the present, which would make the duration meaningless.+ // Wall clock, not the caller's nowMs: nowMs dates the URLs, and a test can set it far from+ // the present, which would make the duration meaningless.const startedAt = process.hrtime.bigint()const drops = new Map<UrlDropReason, number>()const countDrop = (reason: UrlDropReason, count = 1): void => {@@ -57,6 +64,7 @@ export class UrlFetchConsumer {const domains = new Set<string>()const seenInBatch = new Set<string>()const candidates: FetchCandidate[] = []+ const notReady: FetchCandidate[] = []let dedupedInBatch = 0let dedupedInPod = 0@@ -76,6 +84,12 @@ export class UrlFetchConsumer {countDrop('stale')continue}+ if (candidate.notBeforeMs > nowMs) {+ // A wait longer than the longest tier, so the tier it came out of covered only+ // part of it. It goes back for the rest and spends a hop. Requirement 15.+ notReady.push(candidate)+ continue+ }if (seenInBatch.has(candidate.ref)) {dedupedInBatch++continue@@ -86,21 +100,24 @@ export class UrlFetchConsumer {continue}// After dedup, so the distribution describes the URLs this lane acts on rather than- // being weighted by how often a popular image reappears.+ // how often a popular image reappears.ImageFetchConsumerMetrics.observeAge(Math.max(0, nowMs - candidate.capturedAtMs) / 1000)+ this.teamVolume.record(candidate.pseudoTeam)candidates.push(candidate)}}- const { fetchable, readFailed } = await this.removeAlreadySeen(candidates)+ const fetchable = await this.removeAlreadySeen(candidates)if (fetchable.length > 0) {ImageFetchConsumerMetrics.incFetchable(fetchable.length)}- // A store that just failed a read gets no writes: the un-deduped write volume is the largest- // this lane ever offers, and sending it to a struggling Redis makes it slower still.- if (fetchable.length > 0 && !readFailed) {- await this.recordSightings(fetchable, nowMs)+ const pass = this.runner ? await this.fetchAll(this.runner, fetchable) : { finished: fetchable, lost: 0 }+ const held = await this.rescheduleNotReady(notReady, nowMs)+ const finished = [...pass.finished, ...held.exhausted]+ if (finished.length > 0) {+ await this.recordFetched(finished, nowMs)}+ const lost = pass.lost + held.lostif (dedupedInBatch > 0) {ImageFetchConsumerMetrics.incDeduped('batch', dedupedInBatch)@@ -112,54 +129,146 @@ export class UrlFetchConsumer {ImageFetchConsumerMetrics.incDropped(reason, count)}ImageFetchConsumerMetrics.observeBatch(domains.size, Number(process.hrtime.bigint() - startedAt) / 1e9)++ if (lost > 0) {+ // Thrown last, so the counts above publish first. The consumer stores offsets only after+ // this returns, so a throw replays the batch on the pod that takes the partition next.+ // Requirement 21.+ //+ // The replay costs little: the URLs already fetched carry a crawl history entry now, and+ // the read at the top of the batch removes them. A URL is a duplicate at worst, which+ // requirement 22 allows, and the alternative is a lost URL.+ throw new Error(`the image fetch lane could not account for ${lost} URLs`)+ }}/**- * A URL whose read failed comes back as fetchable, which overstates the offered rate. That is- * the safe direction while nothing is being sent, and it is not once requests go out, so the- * failure is counted rather than only logged.+ * A URL left out of `finished` and not counted in `lost` is on its way back through Kafka, so+ * nothing here has to hold it.+ */+ /**+ * Never throws. Requirement 23.+ *+ * The parser reads the url policy out of a native addon, so a build that shipped without it+ * raises rather than returning a reason. That must read as a record this lane cannot use, not+ * as a reason to stop the partition.*/- private async removeAlreadySeen(+ private parse(message: Message): ReturnType<typeof parseCollectedUrlsRecord> {+ try {+ return parseCollectedUrlsRecord(message.value, message.key?.toString() ?? null)+ } catch (error) {+ logger.error('🌐', 'ml_image_fetch_record_parse_threw', {+ error: error instanceof Error ? error.name : 'unknown',+ })+ return { ok: false, reason: 'malformed' }+ }+ }++ private async fetchAll(+ runner: FetchPass,candidates: FetchCandidate[]- ): Promise<{ fetchable: FetchCandidate[]; readFailed: boolean }> {+ ): Promise<{ finished: FetchCandidate[]; lost: number }> {+ let attempts+ try {+ attempts = await runner.run(candidates)+ } catch (error) {+ // The pass answers with outcomes rather than a throw, so reaching here means a defect.+ // The log holds the error name only, because an error from the pass can carry a URL.+ logger.error('🌐', 'ml_image_fetch_pass_failed', {+ count: candidates.length,+ error: error instanceof Error ? error.name : 'unknown',+ })+ // The batch commits rather than replays, unlike a failed republish. A defect here is the+ // same on every read, so a replay would stop the partition rather than recover it.+ return { finished: [], lost: 0 }+ }+ return {+ finished: attempts.filter((attempt) => attempt.finished).map((attempt) => attempt.candidate),+ lost: attempts.filter((attempt) => attempt.lost).length,+ }+ }++ /**+ * A URL whose read failed is neither fetched nor counted as new. To count it as new would fetch+ * it, and a store outage would then send the full un-deduped volume at customer sites, in every+ * batch, because our own store is down. It counts as unaccounted instead, which holds the batch+ * rather than loses it. Requirement 21.+ */+ private async removeAlreadySeen(candidates: FetchCandidate[]): Promise<FetchCandidate[]> {if (candidates.length === 0) {- return { fetchable: [], readFailed: false }+ return []}- const keys = candidates.map((candidate) => sightingKey(candidate.pseudoTeam, candidate.urlHash))+ const keys = candidates.map((candidate) => crawlHistoryKey(candidate.pseudoTeam, candidate.urlHash))let resulttry {- result = await this.sightings.read(keys)+ result = await this.crawlHistory.read(keys)} catch (error) {ImageFetchConsumerMetrics.incStoreError('read', keys.length)- logger.warn('🌐', 'ml_image_fetch_sighting_read_failed', { count: keys.length, error: String(error) })- return { fetchable: candidates, readFailed: true }+ logger.warn('🌐', 'ml_image_fetch_crawl_history_read_failed', { count: keys.length, error: String(error) })+ return []}- if (result.failed > 0) {- ImageFetchConsumerMetrics.incStoreError('read', result.failed)+ if (result.failed.size > 0) {+ ImageFetchConsumerMetrics.incStoreError('read', result.failed.size)}if (result.known.size > 0) {ImageFetchConsumerMetrics.incDeduped('store', result.known.size)}- return {- fetchable: candidates.filter((_candidate, index) => !result.known.has(index)),- readFailed: result.failed > 0,+ return candidates.filter((_candidate, index) => !result.known.has(index) && !result.failed.has(index))+ }++ /**+ * A URL waiting out a delay has no crawl history entry and no other copy in Kafka, so a drop+ * here loses it until a session refers to the same image again. Requirements 15 and 21.+ *+ * One with no hops left cannot go round again. The lane records it and stops, exactly as the+ * fetch pass does with a URL that runs out mid-chain. Requirements 12 and 24.+ */+ private async rescheduleNotReady(+ candidates: FetchCandidate[],+ nowMs: number+ ): Promise<{ lost: number; exhausted: FetchCandidate[] }> {+ const exhausted: FetchCandidate[] = []+ const held: FetchCandidate[] = []+ for (const candidate of candidates) {+ if (candidate.hopsRemaining <= 1) {+ ImageFetchRequestMetrics.incOutcome(HOPS_EXHAUSTED)+ ImageFetchRequestMetrics.observeHops(MAX_HOPS)+ exhausted.push(candidate)+ } else {+ held.push(candidate)+ }}+ // Together rather than one after another. A batch can carry a whole delay tier's worth of+ // records that arrived early, and one awaited produce for each would run past+ // `max.poll.interval.ms` and lose the partition in the middle of the batch.+ const sent = await Promise.all(+ held.map((candidate) =>+ this.publisher.republish(+ candidate,+ { url: candidate.url, host: candidate.host, domain: candidate.domain },+ 'not_ready',+ candidate.notBeforeMs - nowMs+ )+ )+ )+ return { lost: sent.filter((ok) => !ok).length, exhausted }}/**- * The pod cache is marked only for a URL whose sighting was stored. A URL held locally but- * absent from the shared store is invisible to every other pod and to this one after a restart,- * so marking it before the write is confirmed would drop it from the measurement and, later,+ * This marks the pod cache only for a URL whose crawl history entry reached the store.+ *+ * A URL held only in this pod is invisible to every other pod, and to this one after a restart.+ * A mark before the store confirms the write would drop the URL from the measurement, and later* from fetching.*/- private async recordSightings(candidates: FetchCandidate[], nowMs: number): Promise<void> {- const keys = candidates.map((candidate) => sightingKey(candidate.pseudoTeam, candidate.urlHash))+ private async recordFetched(candidates: FetchCandidate[], nowMs: number): Promise<void> {+ const keys = candidates.map((candidate) => crawlHistoryKey(candidate.pseudoTeam, candidate.urlHash))let failed: Set<number>try {- failed = (await this.sightings.record(keys, nowMs, SIGHTING_TTL_SECONDS)).failed+ failed = (await this.crawlHistory.record(keys, nowMs, CRAWL_HISTORY_TTL_SECONDS)).failed} catch (error) {ImageFetchConsumerMetrics.incStoreError('write', keys.length)- logger.warn('🌐', 'ml_image_fetch_sighting_write_failed', { count: keys.length, error: String(error) })+ logger.warn('🌐', 'ml_image_fetch_crawl_history_write_failed', { count: keys.length, error: String(error) })return}if (failed.size > 0) {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 6d00d5858613..9008bbbcf840 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -84,9 +84,78 @@ export type MlMirrorConfig = {SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS: number/** Capacity of the per-pod seen-ref cache that sits in front of the Redis ledger. */SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS: number- /** Bounds one round trip to the sighting store, including waiting for a pooled connection, so a Redis stall cannot hold the poll loop. */+ /** Bounds one round trip to the crawl history, including waiting for a pooled connection, so a Redis stall cannot hold the poll loop. */SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS: number+ /**+ * What one registrable domain receives from one pod.+ *+ * Every value below is a politeness control, so all of them are environment variables. An+ * incident must change the load this lane puts on a customer site in minutes, and a deploy+ * takes longer than that.+ *+ * One request each second is far below the rate a browser puts on the same site. This lane+ * works at that rate because one fetch serves every session that refers to the image, and+ * because nothing waits on the result.+ */+ SESSION_RECORDING_ML_IMAGE_FETCH_REQUESTS_PER_SECOND: number+ /** Tokens a domain holds while idle, so a site seen once an hour gets a short run rather than one request. */+ SESSION_RECORDING_ML_IMAGE_FETCH_BURST: number+ /** Also the worker count of one back queue, so the connection limit and the worker count cannot disagree. */+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN: number+ /**+ * Requests this pod holds open across every domain at once.+ *+ * Nothing caps the number of domains, because the topic keys by registrable domain, so a domain+ * lands on one partition and one pod, and its rate limit lives there. A pod that owns many+ * domains must serve them all, because each has its own allowance and none waits on the others.+ *+ * This bounds the pod instead. A body reads into a buffer, so the resident peak is roughly this+ * times SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES, and the sockets and the DNS lookups+ * scale with it too. Raise the pod's memory before you raise this.+ */+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS: number+ /**+ * Wall time the fetch pass of one poll batch may take.+ *+ * A batch can hold more URLs for one domain than a polite rate carries in this time. What the+ * pass does not reach goes to a delay topic and spends a hop. The value sits well inside Kafka's+ * max.poll.interval.ms of 300s, which the crawl history round trips share.+ */+ SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS: number+ /** Refused before the body when the response declares more, and abandoned mid-body when it declares nothing. */+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES: number+ /** Covers one URL including its redirects, separate from the connect timeout of the shared request layer. */+ SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS: number+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_REDIRECTS: number+ /** Consecutive failures of one domain before this pod stops sending to it. */+ SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_FAILURES: number+ SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_COOLDOWN_MS: number+ /** The longest a domain stays blocked, whether the breaker or a site's own `Retry-After` blocked it. */+ SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_MAX_COOLDOWN_MS: number+ /** Held after a 429 or a 503 that named no period. */+ SESSION_RECORDING_ML_IMAGE_FETCH_DEFAULT_RETRY_AFTER_MS: number+ /** Domains one pod holds rate-limit state for. Past this the least recently used entry goes, and the pod forgets that the domain was blocked. */+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_DOMAINS: number++ /**+ * The delay topic one retry pod drains, and the period every record in it waits.+ *+ * One server runs every tier, so three deployments of one image cover 1 minute, 10 minutes, and+ * one hour. The pod's `max.poll.interval.ms` must exceed the period, or the broker evicts the+ * consumer while it sleeps.+ */+ SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_TOPIC: string+ SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_DELAY_MS: number+ /**+ * One record per batch, so the poll interval the server computes is exact.+ *+ * A batch of many records can hold records written hours apart, and that batch waits once for+ * each of them. Sizing the poll interval for that case means multiplying the tier's period by+ * the batch size, which soon passes what Kafka accepts at the 1 hour tier.+ */+ SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE: number+/*** Capacity of the mirror's produced-URL ref cache, which bounds re-produces onto the fetch* topic. Tunable for the same reason as its image-lane twin below: it trades memory for topic@@ -168,6 +237,22 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS: 6 * 60 * 60 * 1000,SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS: 500_000,SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS: 5_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_REQUESTS_PER_SECOND: 1,+ SESSION_RECORDING_ML_IMAGE_FETCH_BURST: 5,+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN: 6,+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS: 300,+ SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS: 20_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES: 2 * 1024 * 1024,+ SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS: 10_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_REDIRECTS: 3,+ SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_FAILURES: 5,+ SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_COOLDOWN_MS: 60_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_MAX_COOLDOWN_MS: 2 * 60 * 60 * 1000,+ SESSION_RECORDING_ML_IMAGE_FETCH_DEFAULT_RETRY_AFTER_MS: 60_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_DOMAINS: 20_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_TOPIC: '',+ SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_DELAY_MS: 60_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE: 1,SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX: 500_000,SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: 'session-replay-ml-image-scrub',SESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: 'scrubbed-images',diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.tsindex d05a46b86bca..bee0cde5e745 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts@@ -11,24 +11,22 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-de/*** The same trade as the image lane's cache, at a much lower cost per entry: a record here holds a* ref of approximately 60 bytes and no image bytes. A ref that this cache drops before its next- * sighting produces a second time, which costs topic volume and one more ledger read in the+ * arrival produces a second time, which costs topic volume and one more ledger read in the* fetcher, but never correctness. The fetcher dedupes on the same ref again.*/const PRODUCED_REF_CACHE_MAX = 500_000/**- * Bytes of URL payload one record may carry, against the 1,000,000 byte `message.max.bytes` default- * that this producer does not override. The rest absorbs the envelope.- *- * A URL may be anything up to `MAX_URL_LEN`, so a fixed count is either unsafe for the longest URLs- * or wasteful for ordinary ones.+ * The URL payload one record may carry. The `message.max.bytes` default is 1,000,000 bytes and this+ * producer does not override it, so the remainder holds the envelope. The budget counts bytes+ * rather than URLs, because a URL can be as long as `MAX_URL_LEN`.*/const MAX_RECORD_URL_BYTES = 512 * 1024/**- * URLs one record may carry, whatever their size. Without this the collector's cap, which lives in- * another crate, would decide it, and raising it there would produce records the fetcher refuses- * whole. Must stay below MAX_URLS_PER_RECORD in `ml-mirror-image-fetch/collected-urls-record.ts`.+ * The URL count one record may carry. Without it the collector's cap in another crate decides the+ * count, and an increase there makes records the fetcher refuses whole. Keep it below+ * `MAX_URLS_PER_RECORD` in `ml-mirror-image-fetch/collected-urls-record.ts`.*/const MAX_RECORD_URLS = 512@@ -197,8 +195,8 @@ export function createProduceCollectedUrlsStep<}/**- * An entry always goes somewhere, even alone in a record over the budget, because dropping it here- * would lose an image every earlier check accepted. `MAX_URL_LEN` bounds that case under the broker+ * An entry always goes into a record, even alone in one above the budget, because a drop here loses+ * an image that every earlier check accepted. `MAX_URL_LEN` keeps that record under the broker* limit.*/function packByBytes(entries: RecordUrl[], maxBytes: number): RecordUrl[][] {@@ -222,11 +220,9 @@ function packByBytes(entries: RecordUrl[], maxBytes: number): RecordUrl[][] {}/**- * The JSON punctuation around the three fields, so packing measures what the record will hold.- *- * `JSON.stringify` widens a quote or a backslash, so this is a lower bound. Canonicalization- * percent-encodes those upstream and the budget is half the broker limit, so the gap has room.- * `ml_url_record_bytes` is what would show it closing.+ * `JSON.stringify` widens a quote or a backslash, so this count is a lower bound. Canonicalization+ * percent-encodes both upstream, and the budget is half the broker limit, so the estimate has room.+ * The `ml_url_record_bytes` metric shows that margin if it shrinks.*/const ENTRY_OVERHEAD_BYTES = '{"ref":"","url":"","host":""},'.lengthdiff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.tsnew file mode 100644index 000000000000..98d27e995c66--- /dev/null+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts@@ -0,0 +1,166 @@+import { initializePrometheusLabels } from '~/common/api/router'+import {+ KAFKA_SESSION_REPLAY_IMAGE_FETCH,+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M,+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,+} from '~/common/config/kafka-topics'+import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'+import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'+import { logger } from '~/common/utils/logger'+import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'+import { RetryDelayConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer'+import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'+import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'++import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'+import {+ IngestionSessionReplayMlMirrorServerConfig,+ buildMlMirrorServerConfig,+} from './ingestion-session-replay-ml-mirror-server'++/**+ * Headroom on top of the sleeping a batch can do, for the publishing between the sleeps.+ *+ * librdkafka rejects a `max.poll.interval.ms` above one day, so a tier and a batch size whose+ * product passes that is a configuration error rather than something to clamp silently.+ */+const POLL_INTERVAL_MARGIN_MS = 60_000+const MAX_POLL_INTERVAL_MS = 86_400_000++/**+ * One delay tier of the image fetch lane.+ *+ * The same server runs every tier. The topic and the period come from the environment, so three+ * deployments of one image cover 1 minute, 10 minutes, and one hour. See the lane's README.+ *+ * One setting belongs to the deployment rather than to this file: one pod, and no more. A lag+ * trigger assumes more consumers drain a topic faster, which is false here, because these records+ * are waiting on purpose.+ */+/** The topics the publisher writes to. A pod drains one of these and nothing else. */+const DELAY_TOPICS = [+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M,+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,+]++export class IngestionSessionReplayMlImageFetchRetryServer implements NodeServer {+ readonly lifecycle: ServerLifecycle+ private config: IngestionSessionReplayMlMirrorServerConfig+ private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>++ constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {+ this.config = buildMlMirrorServerConfig(config)+ this.lifecycle = new ServerLifecycle(this.config)+ }++ async start(): Promise<void> {+ return this.lifecycle.start(+ () => this.startServices(),+ () => this.getCleanupResources()+ )+ }++ async stop(error?: Error): Promise<void> {+ return this.lifecycle.stop(() => this.getCleanupResources(), error)+ }++ private async startServices(): Promise<void> {+ initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)++ const topic = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_TOPIC+ const delayMs = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_DELAY_MS+ const batchSize = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE+ // A typo here reads as an empty topic name, and librdkafka would subscribe to it and sit+ // idle while the tier filled. Naming the three the publisher writes to also stops a pod+ // draining the frontier itself, which has no period and would publish every record straight+ // back to it.+ if (!DELAY_TOPICS.includes(topic)) {+ throw new Error(+ `SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_TOPIC must name one of ${DELAY_TOPICS.join(', ')}, got "${topic}"`+ )+ }+ // The whole batch is held one record at a time, so the poll interval below has to cover+ // every record in it. A tier can hold records written hours apart, and each of those waits+ // its own period. The deployment sets this to 1 and there is no reason to raise it: the work+ // is one publish, and a record whose wait is spent waits for nothing.+ if (batchSize !== 1) {+ throw new Error(+ `SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE must be 1, because one batch is held record by record, got ${batchSize}`+ )+ }++ this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)+ const producer = this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER)++ const consumerConfig: KafkaConsumerConfig = {+ topic,+ groupId: `${this.config.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID}-retry-${delayMs}`,+ autoCommit: true,+ // Stored per record by the consumer rather than for the whole batch, so a record it+ // abandoned mid-wait is read again instead of being committed and lost. Requirement 21.+ autoOffsetStore: false,+ fetchBatchSize: batchSize,+ }+ // Set here rather than left to the deployment. This consumer sleeps for the period of its+ // topic inside one batch, and the shared default of 300s would evict the 10m and 1h tiers+ // mid-sleep, then replay the partition into a consumer that sleeps just as long.+ //+ // One record per batch keeps this bound exact. A sparse topic can hold records written hours+ // apart, and such a batch waits once per record. Throughput does not matter here, because+ // the work is one publish and a ready record waits for nothing.+ const pollIntervalMs = delayMs + POLL_INTERVAL_MARGIN_MS+ const consumer = new KafkaConsumer(consumerConfig, { 'max.poll.interval.ms': pollIntervalMs })+ // The shutdown handler sets this before it disconnects the consumer, so a stopping pod+ // abandons the wait it holds rather than making the rolling deploy wait out a tier period.+ let stopping = false+ const delayConsumer = new RetryDelayConsumer(producer, {+ isStopping: () => stopping,+ storeOffset: (message) => {+ try {+ // The next offset to read, which is what librdkafka stores.+ consumer.offsetsStore([+ { topic: message.topic, partition: message.partition, offset: message.offset + 1 },+ ])+ } catch (error) {+ // Thrown when the partition was revoked while this batch ran. Another pod owns+ // the record now, so it is not lost. Letting the throw out would stop this pod.+ logger.warn('🌐', 'ml_image_fetch_retry_offset_store_failed', {+ topic: message.topic,+ partition: message.partition,+ error: error instanceof Error ? error.name : 'unknown',+ })+ }+ },+ frontierTopic: KAFKA_SESSION_REPLAY_IMAGE_FETCH,+ delayMs,+ heartbeat: () => consumer.reportDeliberateWait(),+ })+ if (pollIntervalMs > MAX_POLL_INTERVAL_MS) {+ throw new Error(+ `a delay of ${delayMs}ms needs a poll interval of ${pollIntervalMs}ms, which is past what Kafka allows`+ )+ }+ logger.info('🌐', 'ml_image_fetch_retry_started', { topic, delayMs, pollIntervalMs })++ await consumer.connect((messages) => delayConsumer.handleBatch(messages))++ this.lifecycle.services.push({+ id: 'session-replay-ml-image-fetch-retry',+ onShutdown: () => {+ stopping = true+ return consumer.disconnect()+ },+ healthcheck: () => consumer.isHealthy(),+ })+ }++ private getCleanupResources(): CleanupResources {+ return {+ kafkaProducers: [],+ redisPools: [],+ additionalCleanup: () => this.producerRegistry?.disconnectAll(),+ }+ }+}diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.tsindex e66db4f9c428..fe7f48724a99 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts@@ -1,11 +1,26 @@import { initializePrometheusLabels } from '~/common/api/router'-import { KAFKA_SESSION_REPLAY_IMAGE_FETCH } from '~/common/config/kafka-topics'+import {+ KAFKA_SESSION_REPLAY_IMAGE_FETCH,+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M,+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,+} from '~/common/config/kafka-topics'import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'+import { KafkaProducerWrapper } from '~/common/kafka/producer'+import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { createRedisPoolFromConfig } from '~/common/utils/db/redis'import { logger } from '~/common/utils/logger'+import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'+import { CrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'+import { FetchRunner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner'+import { FrontierPublisher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher'+import { HostBudget } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget'+import { HttpImageFetcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'+import { assertUrlPolicyLoaded } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key'import { UrlFetchConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer'-import { UrlSightings } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-sightings'import { resolveMlMirrorRedisConnection } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'+import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'+import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'import { RedisPool } from '../types'import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'@@ -21,13 +36,72 @@ const BATCH_HEARTBEAT_INTERVAL_MS = 10_000/*** How long the store may spend on one batch, well inside Kafka's max.poll.interval.ms of 300s.*- * That is the bound that matters rather than the health check, because the heartbeat above keeps the- * health check satisfied through a long batch. A batch that passes the poll interval gets the- * partition revoked mid-batch and replayed by a pod that will be just as slow, so the lane sheds the- * rest of a batch instead.+ * The poll interval binds rather than the health check, because the heartbeat above keeps the health+ * check satisfied through a long batch. A batch that passes the poll interval loses the partition+ * mid-batch to a pod that will be just as slow, so the lane sheds the rest of the batch instead.*/const STORE_BATCH_BUDGET_MS = 50_000+/** Matches MAX_URL_LEN in the crate, which is what the collector applied to the first candidate. */+const MAX_REDIRECT_URL_LENGTH = 2048++/** The addon holds a 15 MB native library and `index.ts` imports every server, so it loads on first use. */+let anonymizer: typeof import('@posthog/replay-anonymizer') | undefined+function getAnonymizer(): typeof import('@posthog/replay-anonymizer') {+ if (!anonymizer) {+ anonymizer = require('@posthog/replay-anonymizer') as typeof import('@posthog/replay-anonymizer')+ if (typeof anonymizer.isPublicHost !== 'function') {+ throw new Error('the replay-anonymizer addon has no isPublicHost: rebuild index.node')+ }+ }+ return anonymizer+}++export function buildFrontierPublisher(producer: KafkaProducerWrapper): FrontierPublisher {+ return new FrontierPublisher(producer, {+ frontierTopic: KAFKA_SESSION_REPLAY_IMAGE_FETCH,+ delayTiers: [+ { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M, delayMs: 60_000 },+ { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M, delayMs: 600_000 },+ { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H, delayMs: 3_600_000 },+ ],+ })+}++export function buildFetchRunner(+ config: IngestionSessionReplayMlMirrorServerConfig,+ publisher: FrontierPublisher+): FetchRunner {+ const budget = new HostBudget({+ requestsPerSecond: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUESTS_PER_SECOND,+ burst: config.SESSION_RECORDING_ML_IMAGE_FETCH_BURST,+ maxConcurrent: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN,+ breakerFailures: config.SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_FAILURES,+ breakerCooldownMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_COOLDOWN_MS,+ breakerMaxCooldownMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_MAX_COOLDOWN_MS,+ maxTrackedDomains: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_DOMAINS,+ })+ return new FetchRunner(+ new HttpImageFetcher({+ maxUrlLength: MAX_REDIRECT_URL_LENGTH,+ // The crate's rule, so a redirect target meets the check the collector already applied+ // to the first candidate rather than a second answer to the same question.+ isPublicHost: (host) => getAnonymizer().isPublicHost(host),+ }),+ budget,+ {+ maxConcurrentPerDomain: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN,+ maxInFlightRequests: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS,+ batchBudgetMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS,+ maxBytes: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES,+ requestTimeoutMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS,+ maxRedirects: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_REDIRECTS,+ defaultRetryAfterMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_DEFAULT_RETRY_AFTER_MS,+ },+ publisher+ )+}+export function buildImageFetchConsumerConfig(config: IngestionSessionReplayMlMirrorServerConfig): KafkaConsumerConfig {return {topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH,@@ -43,14 +117,12 @@ export function buildImageFetchConsumerConfig(config: IngestionSessionReplayMlMi** It has its own deployment because it waits on network IO and wants many small pods, where the* scrub sidecar it feeds uses CPU and ML models and wants few large ones.- *- * The lane starts in dry run and sends no request. See- * `SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN`.*/export class IngestionSessionReplayMlImageFetchServer implements NodeServer {readonly lifecycle: ServerLifecycleprivate config: IngestionSessionReplayMlMirrorServerConfig- private sightingPool?: RedisPool+ private crawlHistoryPool?: RedisPool+ private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {this.config = buildMlMirrorServerConfig(config)@@ -70,37 +142,53 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {private async startServices(): Promise<void> {initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)+ // Here rather than on the first record. The parser calls into this addon for every URL, and+ // it must answer with a reason rather than raise, so a build that shipped without the addon+ // has to stop the pod at startup instead.+ assertUrlPolicyLoaded()- // Before anything connects: a cleared flag is a configuration mistake, and this lane has no- // request path yet, so it would report itself as fetching while downloading nothing.const dryRun = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUNif (!dryRun) {- throw new Error('SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN cannot be cleared yet: this lane cannot fetch')+ throw new Error(+ 'SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN cannot be cleared yet: this lane obeys no robots.txt and produces no images'+ )}- // The ml-mirror's instance, which is deliberately not the cluster that serves the primary- // replay lane: this store holds one key per distinct image URL, and its eviction pressure+ // The ml-mirror's instance, and deliberately not the cluster that serves the primary replay+ // lane, because this store holds one key per distinct image URL and its eviction pressure// must not be able to reach the lane that gates replay ingestion.const connection = resolveMlMirrorRedisConnection(this.config)if (!connection) {throw new Error('SESSION_RECORDING_ML_REDIS_HOST must be set for the image-fetch consumer')}const redisTimeoutMs = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_REDIS_TIMEOUT_MS- this.sightingPool = createRedisPoolFromConfig({- // The lane's own command timeout, not the mirror's 200ms: one round trip here carries a- // whole chunk of keys rather than a single per-session command.+ this.crawlHistoryPool = createRedisPoolFromConfig({+ // The lane's own command timeout rather than the mirror's 200ms, because one round trip+ // here carries a whole chunk of keys rather than one per-session command.connection: { ...connection, options: { ...connection.options, commandTimeout: redisTimeoutMs } },poolMinSize: this.config.REDIS_POOL_MIN_SIZE,poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,acquireTimeoutMillis: redisTimeoutMs,})- const sightings = new UrlSightings(this.sightingPool, redisTimeoutMs, STORE_BATCH_BUDGET_MS)+ const crawlHistory = new CrawlHistory(this.crawlHistoryPool, redisTimeoutMs, STORE_BATCH_BUDGET_MS)- const fetchConsumer = new UrlFetchConsumer(sightings, {- maxAgeMs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS,- dedupMaxRefs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS,- dryRun,- })+ // Built even in dry run, so the wiring is exercised by every start rather than only by the+ // one that clears the flag.+ this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)+ const publisher = buildFrontierPublisher(+ this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER)+ )++ const fetchConsumer = new UrlFetchConsumer(+ crawlHistory,+ publisher,+ {+ maxAgeMs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS,+ dedupMaxRefs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS,+ dryRun,+ },+ dryRun ? undefined : buildFetchRunner(this.config, publisher)+ )logger.info('🌐', 'ml_image_fetch_started', { dryRun })const consumer = new KafkaConsumer(buildImageFetchConsumerConfig(this.config))@@ -119,7 +207,8 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {private getCleanupResources(): CleanupResources {return {kafkaProducers: [],- redisPools: this.sightingPool ? [this.sightingPool] : [],+ redisPools: this.crawlHistoryPool ? [this.crawlHistoryPool] : [],+ additionalCleanup: () => this.producerRegistry?.disconnectAll(),}}}diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex db0482fc0a88..a194f4063932 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8973,7 +8973,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.4.3"+version = "0.4.4"dependencies = ["ahash 0.8.12","anyhow",diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex b749d4b3304a..1ef6d1e1b4e3 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -169,3 +169,31 @@ export async function anonymizeKafkaPayload(}return { ...result, timings }}++/**+ * The politeness unit for a host: the registrable domain, or the host itself when it has none.+ *+ * The fetch lane rate limits by this value and the fetch topic keys on it, so both must get the+ * same answer from one public suffix list, which is why the value comes from the Rust crate. The+ * private section of that list keeps `user.github.io` and `d111.cloudfront.net` out of a shared+ * budget with the other tenants of the same provider.+ *+ * An IP literal has no registrable domain and comes back unchanged, because the address is the+ * operator.+ */+export function politenessKey(host: string): string {+ return native.politenessKey(host)+}++/**+ * Whether the fetch lane may send a request to a host.+ *+ * The collector applies this rule before a URL reaches the topic. A redirect target has not been+ * through it, so the fetcher calls the same function rather than deriving a second answer.+ *+ * It refuses a private or reserved address, a single-label name, and a name under a suffix that+ * resolves only inside one network, which is the split-horizon DNS case.+ */+export function isPublicHost(host: string): boolean {+ return native.isPublicHost(host)+}diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rsindex 91d3f0a7f64c..aab284314b57 100644--- a/rust/replay-anonymizer-node/src/lib.rs+++ b/rust/replay-anonymizer-node/src/lib.rs@@ -12,7 +12,8 @@ use std::sync::RwLock;use neon::prelude::*;use neon::types::buffer::TypedArray;use posthog_replay_anonymizer::{- snapshot, AllowLists, FailKind, ImageCollection, ImagePolicy, PhaseTimings, UrlCollection,+ is_public_host, politeness_key, snapshot, AllowLists, FailKind, ImageCollection, ImagePolicy,+ PhaseTimings, UrlCollection,};use serde::Deserialize;@@ -237,9 +238,25 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {Ok(promise)}+/// The registrable domain of a host. It needs no initialized state, so a lane that only fetches+/// never calls `initAnonymizer`.+fn politeness_key_ffi(mut cx: FunctionContext) -> JsResult<JsString> {+ let host = cx.argument::<JsString>(0)?.value(&mut cx);+ Ok(cx.string(politeness_key(&host)))+}++/// Whether the fetch lane may send a request to a host. It needs no initialized state, so a lane+/// that only fetches never calls `initAnonymizer`.+fn is_public_host_ffi(mut cx: FunctionContext) -> JsResult<JsBoolean> {+ let host = cx.argument::<JsString>(0)?.value(&mut cx);+ Ok(cx.boolean(is_public_host(&host)))+}+#[neon::main]fn main(mut cx: ModuleContext) -> NeonResult<()> {cx.export_function("initAnonymizer", init_anonymizer)?;cx.export_function("anonymizeKafkaPayload", anonymize_kafka_payload_ffi)?;+ cx.export_function("politenessKey", politeness_key_ffi)?;+ cx.export_function("isPublicHost", is_public_host_ffi)?;Ok(())}diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex 49a7923436b6..69c826fe0a96 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-replay-anonymizer"-version = "0.4.3"+version = "0.4.4"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"license = "MIT"diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rsindex 9811ee43fed2..883dd00399b4 100644--- a/rust/replay-anonymizer/src/lib.rs+++ b/rust/replay-anonymizer/src/lib.rs@@ -82,7 +82,7 @@ pub use timings::{PhaseTimings, PhaseTimingsSnapshot};#[cfg(feature = "typed-parse")]pub use typed::{parse_scrubbed_event, parse_scrubbed_event_with_ctx};pub use url_collect::{CollectedUrl, UrlCollection};-pub use url_policy::{canonicalize, is_public_host, CanonicalUrl};+pub use url_policy::{canonicalize, is_public_host, politeness_key, CanonicalUrl};/// Shared helpers for the image-neutralization tests across modules.#[cfg(test)]diff --git a/rust/replay-anonymizer/src/url_policy.rs b/rust/replay-anonymizer/src/url_policy.rsindex 0ae524f33725..1f30d646b44c 100644--- a/rust/replay-anonymizer/src/url_policy.rs+++ b/rust/replay-anonymizer/src/url_policy.rs@@ -106,6 +106,10 @@ pub const MAX_URL_LEN: usize = 2048;/// An IP literal has no registrable domain and returns unchanged, which is right: the address is/// the operator.pub fn politeness_key(host: &str) -> String {+ // `example.com.` and `example.com` are one operator, so two spellings must not take two+ // budgets, two breakers, and two partitions. Brackets stay, because an IPv6 literal keys in the+ // form the URL carries.+ let host = host.strip_suffix('.').unwrap_or(host);if host.parse::<IpAddr>().is_ok() || host.starts_with('[') {return host.to_string();}@@ -277,8 +281,10 @@ pub enum Decline {/// Not parseable as an absolute URL. A relative `src` lands here, because the recording does/// not carry the base it would need to resolve against.NotAbsolute,- /// A scheme we do not fetch, such as `data:`, `blob:` or `ftp:`.+ /// A scheme we do not fetch. Only `https` passes, so plain `http` lands here too.BadScheme,+ /// A port the scheme does not own. See the port check in [`try_canonicalize`].+ BadPort,/// No host at all.NoHost,/// Loopback, private, link-local or an internal-only name. See [`is_public_host`].@@ -292,6 +298,7 @@ impl Decline {Decline::TooLong => "too_long",Decline::NotAbsolute => "not_absolute",Decline::BadScheme => "bad_scheme",+ Decline::BadPort => "bad_port",Decline::NoHost => "no_host",Decline::NonPublicHost => "non_public_host",}@@ -308,13 +315,33 @@ pub fn try_canonicalize(raw: &str) -> Result<CanonicalUrl, Decline> {return Err(Decline::TooLong);}let mut url = Url::parse(raw).map_err(|_| Decline::NotAbsolute)?;- if !matches!(url.scheme(), "http" | "https") {+ // The browser blocks a plain `http` image on an HTTPS page as mixed content, so it never+ // rendered for the person we recorded, and a fetch puts the request on the wire in clear text+ // from our egress addresses.+ if url.scheme() != "https" {return Err(Decline::BadScheme);}- let host = url.host_str().ok_or(Decline::NoHost)?.to_string();+ // A port the scheme does not own makes the fetcher a port prober: a page names any host and+ // port, the connection leaves our egress addresses, and the outcome metric shows what answered.+ // Too few images are served on other ports to be worth that.+ //+ // This check limits which service on a host we reach. `is_public_host` and the address check at+ // request time limit which hosts we reach, because DNS for a name the attacker owns can point+ // anywhere.+ if url.port().is_some() {+ return Err(Decline::BadPort);+ }+ // `example.com.` and `example.com` name the same host, and the consumer compares the two as+ // strings in more than one place. The dot comes off the URL as well as off the host, so+ // everything downstream sees one spelling.+ let host_str = url.host_str().ok_or(Decline::NoHost)?;+ let host = host_str.strip_suffix('.').unwrap_or(host_str).to_string();if !is_public_host(&host) {return Err(Decline::NonPublicHost);}+ if host != host_str {+ url.set_host(Some(&host)).map_err(|_| Decline::NoHost)?;+ }remove_credentials_and_fragment(&mut url);let fetch = url.to_string();@@ -465,6 +492,17 @@ mod tests {assert!(volatile("expires", "cdn.example.com", &["signature"]));}+ #[test]+ fn only_https_on_its_own_port_is_collected() {+ assert_eq!(canonicalize("https://cdn.example.com:11211/a.png"), None);+ assert_eq!(canonicalize("https://cdn.example.com:8443/a.png"), None);+ assert_eq!(canonicalize("http://cdn.example.com/a.png"), None);+ assert_eq!(canonicalize("http://cdn.example.com:80/a.png"), None);+ // The parser normalizes the default port away, so `url.port()` is None and `:443` passes.+ assert!(canonicalize("https://cdn.example.com:443/a.png").is_some());+ assert!(canonicalize("https://cdn.example.com/a.png").is_some());+ }+#[test]fn the_politeness_key_is_the_operator_not_the_dns_label() {// A CDN that shards over numbered subdomains must share one budget.@@ -489,6 +527,13 @@ mod tests {assert_eq!(politeness_key("worker.workers.dev"), "worker.workers.dev");}+ #[test]+ fn a_fully_qualified_host_keys_the_same_as_the_bare_one() {+ assert_eq!(politeness_key("example.com."), "example.com");+ assert_eq!(politeness_key("img1.cdn.example.com."), "example.com");+ assert_eq!(politeness_key("user.github.io."), "user.github.io");+ }+#[test]fn an_ip_literal_is_its_own_operator() {assert_eq!(politeness_key("203.0.113.7"), "203.0.113.7");@@ -515,47 +560,59 @@ mod tests {#[test]fn a_non_public_host_is_never_collected() {- // The URL set comes from page content, and the fetch lane runs inside our network.+ // The URL set comes from page content, and the fetch lane runs inside our network. Every+ // one is https, or the scheme rule would refuse it before the host rule was reached.for raw in [- "http://169.254.169.254/latest/meta-data/iam/security-credentials/",- "http://localhost:8000/admin/export.png",- "http://127.0.0.1/i.png",- "http://10.0.0.5/i.png",- "http://192.168.1.1/i.png",- "http://172.16.0.1/i.png",- "http://[::1]/i.png",- "http://[fd00::1]/i.png",- "http://metadata.internal/i.png",- "http://buildserver/i.png",+ "https://169.254.169.254/latest/meta-data/iam/security-credentials/",+ "https://localhost/admin/export.png",+ "https://127.0.0.1/i.png",+ "https://10.0.0.5/i.png",+ "https://192.168.1.1/i.png",+ "https://172.16.0.1/i.png",+ "https://[::1]/i.png",+ "https://[fd00::1]/i.png",+ "https://metadata.internal/i.png",+ "https://buildserver/i.png",// A trailing dot makes a name fully qualified and resolves the same way. It used to// walk past the name list, because the label after the final dot is empty.- "http://localhost./i.png",- "http://metadata.internal./i.png",- "http://LOCALHOST./i.png",+ "https://localhost./i.png",+ "https://metadata.internal./i.png",+ "https://LOCALHOST./i.png",// IPv6 offers several ways to write an IPv4 address. Each one used to skip the IPv4// rules entirely.- "http://[::ffff:0.0.0.0]/i.png",- "http://[::ffff:127.0.0.1]/i.png",- "http://[::ffff:10.0.0.5]/i.png",- "http://[::ffff:100.64.0.1]/i.png",- "http://[::127.0.0.1]/i.png",- "http://[2002:7f00:1::]/i.png",- "http://[64:ff9b::7f00:1]/i.png",- "http://[ff02::1]/i.png",+ "https://[::ffff:0.0.0.0]/i.png",+ "https://[::ffff:127.0.0.1]/i.png",+ "https://[::ffff:10.0.0.5]/i.png",+ "https://[::ffff:100.64.0.1]/i.png",+ "https://[::127.0.0.1]/i.png",+ "https://[2002:7f00:1::]/i.png",+ "https://[64:ff9b::7f00:1]/i.png",+ "https://[ff02::1]/i.png",// Ranges we would never legitimately fetch from.- "http://224.0.0.1/i.png",- "http://240.0.0.1/i.png",- "http://198.18.0.1/i.png",- "http://192.0.0.1/i.png",- "http://0.0.0.0/i.png",+ "https://224.0.0.1/i.png",+ "https://240.0.0.1/i.png",+ "https://198.18.0.1/i.png",+ "https://192.0.0.1/i.png",+ "https://0.0.0.0/i.png",] {assert!(canonicalize(raw).is_none(), "{raw} must not be collected");}assert!(canonicalize("https://cdn.example.com/i.png").is_some());// A public name with a trailing dot is still public, so the fix must not over-reject.assert!(canonicalize("https://cdn.example.com./i.png").is_some());- assert!(canonicalize("http://[2606:4700::1111]/i.png").is_some());- assert!(canonicalize("http://8.8.8.8/i.png").is_some());+ // The address rule accepts a public address. Both use https, because the scheme rule+ // refuses plain http on its own.+ assert!(canonicalize("https://[2606:4700::1111]/i.png").is_some());+ assert!(canonicalize("https://8.8.8.8/i.png").is_some());+ }++ #[test]+ fn a_fully_qualified_host_survives_the_whole_lane() {+ let c = canonicalize("https://cdn.example.com./i.png").expect("collected");+ // The consumer compares `new URL(fetch).hostname` with `host`. A dot on one side only+ // makes every fully qualified host fail that comparison.+ assert_eq!(c.host, "cdn.example.com");+ assert_eq!(c.fetch, "https://cdn.example.com/i.png");}#[test]diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rsindex 1398856d6fcc..1e2637d8fe15 100644--- a/rust/replay-anonymizer/tests/url_collection.rs+++ b/rust/replay-anonymizer/tests/url_collection.rs@@ -310,7 +310,9 @@ fn every_refusal_is_counted_with_a_reason() {let mut bytes = payload_tagged("img",json!({- "src": "http://169.254.169.254/meta.png",+ // https, so this refusal counts as an address refusal. The scheme check runs first, so+ // over http it would count as a scheme refusal instead.+ "src": "https://169.254.169.254/meta.png","rr_src": "ftp://files.example.com/a.png","poster": "/relative/a.png"}),