mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-23 14:17:06 +00:00
Merge pull request #4660 from HeyPuter/DS/textract-region-fallback
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Benchmarks / changes (push) Canceled after 0s
Benchmarks / bench shard 1/3 (push) Canceled after 0s
Benchmarks / bench shard 2/3 (push) Canceled after 0s
Benchmarks / bench shard 3/3 (push) Canceled after 0s
Benchmarks / benchmarks (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Benchmarks / changes (push) Canceled after 0s
Benchmarks / bench shard 1/3 (push) Canceled after 0s
Benchmarks / bench shard 2/3 (push) Canceled after 0s
Benchmarks / bench shard 3/3 (push) Canceled after 0s
Benchmarks / benchmarks (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
This commit is contained in:
4 files changed
+189
-35
No files matched your search
@@ -43,6 +43,7 @@ import {
|
||||
vi,
|
||||
type MockInstance,
|
||||
} from 'vitest';
|
||||
import { CreateBucketCommand } from '@aws-sdk/client-s3';
|
||||
import {
|
||||
InvalidS3ObjectException,
|
||||
UnsupportedDocumentException,
|
||||
@@ -119,6 +120,11 @@ const S3_RATE = 150000;
|
||||
const CONFIGURED_RATE = 200000;
|
||||
const TEXTRACT_USAGE = 'aws-textract:detect-document-text:page';
|
||||
|
||||
// Regions AWS runs no Textract in, so it publishes no price list for them
|
||||
// either. The second one's price list request fails here instead.
|
||||
const NO_TEXTRACT_REGION = 'sa-east-1';
|
||||
const UNPRICED_REGION = 'af-south-1';
|
||||
|
||||
/** The fixture re-published for another region at another first-tier price. */
|
||||
const textractPriceList = (region: string, usd: string) => {
|
||||
const doc = structuredClone(textractUsWest2) as Record<string, any>;
|
||||
@@ -154,6 +160,8 @@ const priceListFetch = async (
|
||||
if (!url.startsWith(PRICE_LIST_PREFIX)) return realFetch(input, init);
|
||||
priceListRequests.push(url);
|
||||
const region = url.slice(PRICE_LIST_PREFIX.length).split('/')[0]!;
|
||||
if (region === UNPRICED_REGION)
|
||||
return new Response('unavailable', { status: 503 });
|
||||
const doc = priceLists[region];
|
||||
return doc ? Response.json(doc) : new Response('missing', { status: 404 });
|
||||
};
|
||||
@@ -164,6 +172,23 @@ const sentRegions = () =>
|
||||
(client) => (client as { region?: string }).region,
|
||||
);
|
||||
|
||||
/** Answers with `response`, except where Textract's hostname doesn't exist. */
|
||||
const textractAnswering = (response: unknown) =>
|
||||
async function (this: { region?: string }) {
|
||||
if (
|
||||
this.region === NO_TEXTRACT_REGION ||
|
||||
this.region === UNPRICED_REGION
|
||||
) {
|
||||
throw Object.assign(
|
||||
new Error(
|
||||
`getaddrinfo ENOTFOUND textract.${this.region}.amazonaws.com`,
|
||||
),
|
||||
{ code: 'ENOTFOUND', syscall: 'getaddrinfo' },
|
||||
);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
// ── Test harness ────────────────────────────────────────────────────
|
||||
|
||||
let server: PuterServer;
|
||||
@@ -184,7 +209,24 @@ beforeAll(async () => {
|
||||
},
|
||||
'mistral-ocr': { apiKey: 'mistral-key' },
|
||||
},
|
||||
// A write can place a file in either region's bucket.
|
||||
servers: {
|
||||
[NO_TEXTRACT_REGION]: {
|
||||
bucket: 'puter-south',
|
||||
bucketRegion: NO_TEXTRACT_REGION,
|
||||
},
|
||||
[UNPRICED_REGION]: {
|
||||
bucket: 'puter-cape',
|
||||
bucketRegion: UNPRICED_REGION,
|
||||
},
|
||||
},
|
||||
} as never);
|
||||
await server.clients.s3
|
||||
.get(NO_TEXTRACT_REGION)
|
||||
.send(new CreateBucketCommand({ Bucket: 'puter-south' }));
|
||||
await server.clients.s3
|
||||
.get(UNPRICED_REGION)
|
||||
.send(new CreateBucketCommand({ Bucket: 'puter-cape' }));
|
||||
driver = server.drivers.aiOcr as unknown as OCRDriver;
|
||||
});
|
||||
|
||||
@@ -445,7 +487,10 @@ describe('OCRDriver.recognize (aws-textract)', () => {
|
||||
expect(textractSendMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const writePuterImage = async (): Promise<{
|
||||
/** A Puter file in the default bucket, or in `bucketRegion`'s. */
|
||||
const writePuterImage = async (
|
||||
bucketRegion?: string,
|
||||
): Promise<{
|
||||
actor: Actor;
|
||||
path: string;
|
||||
bytes: Buffer;
|
||||
@@ -453,14 +498,20 @@ describe('OCRDriver.recognize (aws-textract)', () => {
|
||||
const { actor, userId } = await makeUser();
|
||||
const path = `/${actor.user.username}/scan.png`;
|
||||
const bytes = Buffer.from('png-bytes');
|
||||
await server.services.fs.write(userId, {
|
||||
fileMetadata: {
|
||||
path,
|
||||
size: bytes.byteLength,
|
||||
contentType: 'image/png',
|
||||
await server.services.fs.write(
|
||||
userId,
|
||||
{
|
||||
fileMetadata: {
|
||||
path,
|
||||
size: bytes.byteLength,
|
||||
contentType: 'image/png',
|
||||
},
|
||||
fileContent: bytes,
|
||||
},
|
||||
fileContent: bytes,
|
||||
});
|
||||
undefined,
|
||||
undefined,
|
||||
bucketRegion,
|
||||
);
|
||||
return { actor, path, bytes };
|
||||
};
|
||||
|
||||
@@ -623,6 +674,52 @@ describe('OCRDriver.recognize (aws-textract)', () => {
|
||||
expect(textractCharges()).toEqual([[1, CONFIGURED_RATE]]);
|
||||
});
|
||||
|
||||
it('sends a file stored where AWS runs no Textract to the configured region as bytes', async () => {
|
||||
const { actor, path, bytes } =
|
||||
await writePuterImage(NO_TEXTRACT_REGION);
|
||||
textractSendMock.mockImplementation(textractAnswering(onePage));
|
||||
|
||||
await recognizeFile(actor, path);
|
||||
|
||||
// The region's missing price list settles it before any call.
|
||||
expect(sentRegions()).toEqual([CONFIGURED_REGION]);
|
||||
expect(
|
||||
textractSendMock.mock.calls[0]![0].input.Document.Bytes,
|
||||
).toEqual(bytes);
|
||||
expect(checkedCosts()).toEqual([CONFIGURED_RATE]);
|
||||
expect(textractCharges()).toEqual([[1, CONFIGURED_RATE]]);
|
||||
});
|
||||
|
||||
it('sends the bytes to the configured region when the bucket region has no Textract host to resolve', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const { actor, path, bytes } =
|
||||
await writePuterImage(UNPRICED_REGION);
|
||||
textractSendMock.mockImplementation(textractAnswering(onePage));
|
||||
|
||||
await recognizeFile(actor, path);
|
||||
|
||||
expect(sentRegions()).toEqual([UNPRICED_REGION, CONFIGURED_REGION]);
|
||||
expect(
|
||||
textractSendMock.mock.calls[1]![0].input.Document.Bytes,
|
||||
).toEqual(bytes);
|
||||
expect(textractCharges()).toEqual([[1, CONFIGURED_RATE]]);
|
||||
});
|
||||
|
||||
it('surfaces any other failure from a bucket region that runs Textract', async () => {
|
||||
const { actor, path } = await writePuterImage();
|
||||
textractSendMock.mockRejectedValueOnce(
|
||||
Object.assign(new Error('socket hang up'), {
|
||||
code: 'ECONNRESET',
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(recognizeFile(actor, path)).rejects.toThrow(
|
||||
'socket hang up',
|
||||
);
|
||||
expect(sentRegions()).toEqual([S3_REGION]);
|
||||
expect(textractCharges()).toEqual([]);
|
||||
});
|
||||
|
||||
it('holds the bucket region rate when it is the higher of the two', async () => {
|
||||
const { actor, path } = await writePuterImage();
|
||||
priceLists[S3_REGION] = textractPriceList(
|
||||
|
||||
@@ -51,9 +51,18 @@ interface TextractBlock {
|
||||
Text?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Textract can't read the object, or the bucket's region has no Textract
|
||||
* endpoint to resolve (when its price list couldn't be loaded to tell).
|
||||
*/
|
||||
const isUnreadableS3Source = (err: unknown): boolean =>
|
||||
err instanceof InvalidS3ObjectException ||
|
||||
(err as { code?: unknown } | null)?.code === 'ENOTFOUND';
|
||||
|
||||
/**
|
||||
* AWS Textract OCR: DetectDocumentText through region-aware clients, reading a
|
||||
* Puter file straight from its S3 bucket when it has one.
|
||||
* Puter file straight from its S3 bucket when the bucket's region has
|
||||
* Textract.
|
||||
*/
|
||||
export class TextractOcrProvider implements IOcrProvider {
|
||||
/** One client per region. */
|
||||
@@ -114,19 +123,24 @@ export class TextractOcrProvider implements IOcrProvider {
|
||||
|
||||
// Both regions the call may run in are priced up front, so the hold
|
||||
// covers either and a refresh mid-call can't change the charge.
|
||||
const [configuredRate, s3Rate] = await Promise.all([
|
||||
const [listedRate, s3Rate] = await Promise.all([
|
||||
this.#rates.rate(configuredRegion),
|
||||
s3Info ? this.#rates.rate(s3Info.bucketRegion) : undefined,
|
||||
s3Info ? this.#rates.rate(s3Info.bucketRegion) : null,
|
||||
]);
|
||||
// Calls run in the configured region even if AWS lists no price there.
|
||||
const configuredRate =
|
||||
listedRate ?? OCR_COSTS[TEXTRACT_PAGE_USAGE_TYPE];
|
||||
// Textract reads S3 only in its own region, and a region with no price
|
||||
// list has no Textract, so a file stored there is sent as bytes.
|
||||
const s3Source = s3Rate === null ? null : s3Info;
|
||||
|
||||
const tryRun = async (useS3: boolean) => {
|
||||
const region =
|
||||
s3Info && useS3 ? s3Info.bucketRegion : configuredRegion;
|
||||
const client = this.#clientFor(region);
|
||||
const document =
|
||||
s3Info && useS3
|
||||
? { S3Object: { Bucket: s3Info.bucket, Name: s3Info.key } }
|
||||
: { Bytes: (await input.load()).buffer };
|
||||
const tryRun = async (s3: typeof s3Info) => {
|
||||
const client = this.#clientFor(
|
||||
s3 ? s3.bucketRegion : configuredRegion,
|
||||
);
|
||||
const document = s3
|
||||
? { S3Object: { Bucket: s3.bucket, Name: s3.key } }
|
||||
: { Bytes: (await input.load()).buffer };
|
||||
return client.send(
|
||||
new DetectDocumentTextCommand({ Document: document }),
|
||||
);
|
||||
@@ -144,12 +158,11 @@ export class TextractOcrProvider implements IOcrProvider {
|
||||
let costPerPage: number;
|
||||
try {
|
||||
try {
|
||||
response = await tryRun(Boolean(s3Info));
|
||||
response = await tryRun(s3Source);
|
||||
costPerPage = s3Rate ?? configuredRate;
|
||||
} catch (err) {
|
||||
if (!(s3Info && err instanceof InvalidS3ObjectException))
|
||||
throw err;
|
||||
response = await tryRun(false);
|
||||
if (!(s3Source && isUnreadableS3Source(err))) throw err;
|
||||
response = await tryRun(null);
|
||||
costPerPage = configuredRate;
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
@@ -321,6 +321,16 @@ describe('fetchTextractPriceList', () => {
|
||||
).rejects.toThrow('403');
|
||||
});
|
||||
|
||||
it('reads a missing price list as a region without Textract', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response('NoSuchKey', { status: 404 })),
|
||||
);
|
||||
await expect(
|
||||
fetchTextractPriceList('sa-east-1', new AbortController().signal),
|
||||
).resolves.toBe(null);
|
||||
});
|
||||
|
||||
it('rejects a body over the size cap', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
@@ -358,10 +368,18 @@ describe('fetchTextractPriceList', () => {
|
||||
describe('textractRates', () => {
|
||||
const CURATED = 150000;
|
||||
|
||||
/** Serves each region's price list from `docs`, 404 for the rest. */
|
||||
const stubPriceLists = (docs: Record<string, unknown>) => {
|
||||
/**
|
||||
* Serves each region's price list from `docs` and a 503 for the `failing`
|
||||
* ones. AWS answers 404 for a region it doesn't run Textract in.
|
||||
*/
|
||||
const stubPriceLists = (
|
||||
docs: Record<string, unknown>,
|
||||
failing = new Set<string>(),
|
||||
) => {
|
||||
const fetchMock = vi.fn(async (url: string) => {
|
||||
const region = /\/current\/([^/]+)\/index\.json$/.exec(url)?.[1];
|
||||
if (region && failing.has(region))
|
||||
return new Response('unavailable', { status: 503 });
|
||||
const doc = region ? docs[region] : undefined;
|
||||
return doc
|
||||
? Response.json(doc)
|
||||
@@ -412,12 +430,32 @@ describe('textractRates', () => {
|
||||
|
||||
it('falls back to the curated rate when a region has never loaded', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
stubPriceLists({});
|
||||
stubPriceLists({}, new Set(['us-west-2']));
|
||||
const rates = textractRates(CURATED);
|
||||
expect(await rates.rate('us-west-2')).toBe(CURATED);
|
||||
expect(rates.peek('us-west-2')).toBe(CURATED);
|
||||
});
|
||||
|
||||
it('reports no rate for a region without Textract until AWS publishes one', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const docs: Record<string, unknown> = {};
|
||||
const fetchMock = stubPriceLists(docs);
|
||||
const rates = textractRates(CURATED);
|
||||
|
||||
expect(await rates.rate('sa-east-1')).toBe(null);
|
||||
expect(rates.peek('sa-east-1')).toBe(CURATED);
|
||||
// The answer is cached like a price, not retried like a failure.
|
||||
vi.advanceTimersByTime(60 * 1000);
|
||||
expect(await rates.rate('sa-east-1')).toBe(null);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
|
||||
docs['sa-east-1'] = regionDoc('sa-east-1', '0.0020000000');
|
||||
vi.advanceTimersByTime(16 * 60 * 1000);
|
||||
expect(await rates.rate('sa-east-1')).toBe(200000);
|
||||
});
|
||||
|
||||
it('keeps a region on its last good rate when a refresh fails or loses the rate', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
@@ -425,7 +463,8 @@ describe('textractRates', () => {
|
||||
'us-west-2': regionDoc('us-west-2', '0.0020000000'),
|
||||
'eu-west-1': regionDoc('eu-west-1', '0.0030000000'),
|
||||
};
|
||||
stubPriceLists(docs);
|
||||
const failing = new Set<string>();
|
||||
stubPriceLists(docs, failing);
|
||||
const rates = textractRates(CURATED);
|
||||
expect(await rates.rate('us-west-2')).toBe(200000);
|
||||
expect(await rates.rate('eu-west-1')).toBe(300000);
|
||||
@@ -433,7 +472,7 @@ describe('textractRates', () => {
|
||||
// One region's list drops the rate, the other's starts failing.
|
||||
const zeroed = regionDoc('us-west-2', '0.0000000000');
|
||||
docs['us-west-2'] = zeroed;
|
||||
delete docs['eu-west-1'];
|
||||
failing.add('eu-west-1');
|
||||
vi.advanceTimersByTime(16 * 60 * 1000);
|
||||
|
||||
expect(await rates.rate('us-west-2')).toBe(200000);
|
||||
|
||||
@@ -201,11 +201,14 @@ export const parseTextractPriceList = (
|
||||
return found.length === 1 ? found[0] : undefined;
|
||||
};
|
||||
|
||||
/** Fetches one region's public Textract price list and reads its rate. */
|
||||
/**
|
||||
* Fetches one region's public Textract price list and reads its rate. Null when
|
||||
* AWS publishes no list for the region, as for every region without Textract.
|
||||
*/
|
||||
export const fetchTextractPriceList = async (
|
||||
region: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<number> => {
|
||||
): Promise<number | null> => {
|
||||
if (!isTextractPriceRegion(region)) {
|
||||
throw new Error('Invalid AWS region for the Textract price list');
|
||||
}
|
||||
@@ -219,6 +222,7 @@ export const fetchTextractPriceList = async (
|
||||
);
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
if (response.status === 404) return null;
|
||||
throw new Error(`AWS Textract price list returned ${response.status}`);
|
||||
}
|
||||
const body = await readBoundedBody(
|
||||
@@ -241,9 +245,10 @@ export const fetchTextractPriceList = async (
|
||||
export interface TextractRates {
|
||||
/**
|
||||
* Microcents per page in a region: its last good feed rate, else the
|
||||
* curated one.
|
||||
* curated one. Null when AWS publishes no price list for the region, which
|
||||
* means it doesn't run Textract there.
|
||||
*/
|
||||
rate(region: string): Promise<number>;
|
||||
rate(region: string): Promise<number | null>;
|
||||
/** The rate {@link rate} last settled on for a region, without fetching. */
|
||||
peek(region: string): number;
|
||||
}
|
||||
@@ -257,15 +262,15 @@ export const textractRates = (
|
||||
fallback: number,
|
||||
maxRegions: number = TEXTRACT_PRICE_MAX_REGIONS,
|
||||
): TextractRates => {
|
||||
const catalogs = new Map<string, () => Promise<number>>();
|
||||
const latest = new Map<string, number>();
|
||||
const catalogs = new Map<string, () => Promise<number | null>>();
|
||||
const latest = new Map<string, number | null>();
|
||||
|
||||
const catalogFor = (region: string) => {
|
||||
const existing = catalogs.get(region);
|
||||
if (existing) return existing;
|
||||
if (!isTextractPriceRegion(region) || catalogs.size >= maxRegions)
|
||||
return undefined;
|
||||
const catalog = cachedRemoteCatalog<number>({
|
||||
const catalog = cachedRemoteCatalog<number | null>({
|
||||
name: `AWS Textract ${region} price list`,
|
||||
fallback,
|
||||
fetch: (signal) => fetchTextractPriceList(region, signal),
|
||||
|
||||
Reference in new issue
Block a user