From d38eb97af741f990ee0acee48e9878ef5fe1b0d9 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Tue, 10 Nov 2026 19:54:52 -0500 Subject: [PATCH] fix(merge): keep legacy blob records intact and map the video uploader's errors Profile edits read the stored record instead of the SDK's strict read, which fails on a legacy blob reference and then replaces the whole profile with the update. Feeds accept a post record that still holds a legacy image reference. The single-request video uploader's errors reach the translated messages again. --- .../contacts/screens/GetContacts.tsx | 2 +- src/lib/api/__tests__/community-post.test.ts | 46 +++++- src/lib/api/__tests__/upsert-profile.test.ts | 137 ++++++++++++++++++ src/lib/api/community-post.ts | 5 +- src/lib/api/upsert-profile.ts | 62 ++++++++ src/screens/Onboarding/StepFinished/index.tsx | 3 +- src/state/queries/profile.ts | 9 +- src/state/session/create-account.ts | 3 +- .../__tests__/video-upload-errors.test.ts | 59 ++++++++ src/view/com/composer/state/video.ts | 12 +- 10 files changed, 323 insertions(+), 15 deletions(-) create mode 100644 src/lib/api/__tests__/upsert-profile.test.ts create mode 100644 src/lib/api/upsert-profile.ts create mode 100644 src/view/com/composer/state/__tests__/video-upload-errors.test.ts diff --git a/src/components/contacts/screens/GetContacts.tsx b/src/components/contacts/screens/GetContacts.tsx index 4d66262e5..ef011a5a0 100644 --- a/src/components/contacts/screens/GetContacts.tsx +++ b/src/components/contacts/screens/GetContacts.tsx @@ -5,13 +5,13 @@ import * as Contacts from 'expo-contacts/legacy' import {type Un$Typed} from '@atproto/lex' import {type Client} from '@atproto/lex' import {toDatetimeString} from '@atproto/syntax' -import {upsertProfile} from '@bsky/sdk' import {msg, t} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {Trans} from '@lingui/react/macro' import {useMutation, useQueryClient} from '@tanstack/react-query' import {uploadBlob} from '#/lib/api' +import {upsertProfile} from '#/lib/api/upsert-profile' import {cleanError, isNetworkError} from '#/lib/strings/errors' import {matchXrpcError} from '#/lib/xrpc-error' import {logger} from '#/logger' diff --git a/src/lib/api/__tests__/community-post.test.ts b/src/lib/api/__tests__/community-post.test.ts index 546a62c68..e7aba447d 100644 --- a/src/lib/api/__tests__/community-post.test.ts +++ b/src/lib/api/__tests__/community-post.test.ts @@ -1,4 +1,11 @@ -import {getCommunitySpaceUri, isPeerModLabelableUri} from '../community-post' +// The repo-wide stub of this module rejects the CID in a legacy blob reference. +jest.unmock('multiformats/cid') + +import { + getCommunitySpaceUri, + isPeerModLabelableUri, + isRenderablePostRecord, +} from '../community-post' const post = (communitySpace?: unknown) => ({ @@ -44,3 +51,40 @@ describe(isPeerModLabelableUri, () => { expect(isPeerModLabelableUri(uri)).toBe(false) }) }) + +describe(isRenderablePostRecord, () => { + const view = (record: unknown) => + ({uri: 'at://did:plc:author/app.bsky.feed.post/3m2post', record}) as never + + it('accepts a public post that still holds a legacy image reference', () => { + expect( + isRenderablePostRecord( + view({ + $type: 'app.bsky.feed.post', + text: 'hello', + createdAt: '2023-01-01T00:00:00.000Z', + embed: { + $type: 'app.bsky.embed.images', + images: [ + { + image: { + cid: 'bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku', + mimeType: 'image/jpeg', + }, + alt: '', + }, + ], + }, + }), + ), + ).toBe(true) + }) + + it('rejects a public post record that is missing required fields', () => { + expect( + isRenderablePostRecord( + view({$type: 'app.bsky.feed.post', text: 'hello'}), + ), + ).toBe(false) + }) +}) diff --git a/src/lib/api/__tests__/upsert-profile.test.ts b/src/lib/api/__tests__/upsert-profile.test.ts new file mode 100644 index 000000000..1e8650c51 --- /dev/null +++ b/src/lib/api/__tests__/upsert-profile.test.ts @@ -0,0 +1,137 @@ +// The repo-wide stub of this module rejects every CID the client validates. +jest.unmock('multiformats/cid') + +import {createLexClient} from '#/lib/lexClient' +import {getErrorStatus} from '#/lib/xrpc-error' +import {upsertProfile} from '../upsert-profile' + +const DID = 'did:plc:me' +const CID = 'bafyreiacsg6vsw7ppwbnowzsdgstulhrwftirtcnvkcbnfgvhwjrnzfmsu' +const BLOB = 'bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku' +const LEGACY_AVATAR = {cid: BLOB, mimeType: 'image/jpeg'} + +function json(body: unknown, status = 200) { + return new Response(JSON.stringify(body), { + status, + headers: {'content-type': 'application/json'}, + }) +} + +function stored(value: Record) { + return json({ + uri: `at://${DID}/app.bsky.actor.profile/self`, + cid: CID, + value: {$type: 'app.bsky.actor.profile', ...value}, + }) +} + +const written = () => + json({uri: `at://${DID}/app.bsky.actor.profile/self`, cid: CID}) + +function mockClient() { + const fetchHandler = jest.fn, [string, RequestInit]>() + const client = createLexClient({did: DID, fetchHandler}) + const puts = () => + fetchHandler.mock.calls + .filter(([path]) => path.includes('com.atproto.repo.putRecord')) + .map( + ([, init]) => + JSON.parse(init.body as string) as { + record: Record + swapRecord?: string + }, + ) + return {client, fetchHandler, puts} +} + +describe('upsertProfile', () => { + it('keeps a legacy blob reference and every untouched field', async () => { + const {client, fetchHandler, puts} = mockClient() + fetchHandler + .mockResolvedValueOnce( + stored({displayName: 'Old', description: 'bio', avatar: LEGACY_AVATAR}), + ) + .mockResolvedValueOnce(written()) + + await client.call(upsertProfile, existing => ({ + ...existing, + displayName: 'New', + })) + + expect(puts()).toEqual([ + { + repo: DID, + collection: 'app.bsky.actor.profile', + rkey: 'self', + swapRecord: CID, + record: { + $type: 'app.bsky.actor.profile', + displayName: 'New', + description: 'bio', + avatar: LEGACY_AVATAR, + }, + }, + ]) + }) + + it('creates the profile when there is none', async () => { + const {client, fetchHandler, puts} = mockClient() + fetchHandler + .mockResolvedValueOnce( + json({error: 'RecordNotFound', message: 'no record'}, 400), + ) + .mockResolvedValueOnce(written()) + const update = jest.fn(() => ({displayName: 'New'})) + + await client.call(upsertProfile, update) + + expect(update).toHaveBeenCalledWith(undefined) + expect(puts()).toHaveLength(1) + expect(puts()[0].record).toEqual({ + $type: 'app.bsky.actor.profile', + displayName: 'New', + }) + expect(puts()[0].swapRecord).toBeUndefined() + }) + + it('writes nothing when the profile cannot be read', async () => { + const {client, fetchHandler, puts} = mockClient() + fetchHandler.mockResolvedValue( + json({error: 'InternalServerError', message: 'down'}, 500), + ) + const update = jest.fn(() => ({displayName: 'New'})) + + const failure: unknown = await client + .call(upsertProfile, update) + .catch((e: unknown) => e) + + expect(getErrorStatus(failure)).toBe(500) + expect(update).not.toHaveBeenCalled() + expect(puts()).toHaveLength(0) + }) + + it('reads again and retries after a concurrent write', async () => { + const {client, fetchHandler, puts} = mockClient() + fetchHandler + .mockResolvedValueOnce(stored({displayName: 'Old'})) + .mockResolvedValueOnce( + json({error: 'InvalidSwap', message: 'record changed'}, 400), + ) + .mockResolvedValueOnce( + stored({displayName: 'Old', description: 'new bio'}), + ) + .mockResolvedValueOnce(written()) + + await client.call(upsertProfile, existing => ({ + ...existing, + displayName: 'New', + })) + + expect(puts()).toHaveLength(2) + expect(puts()[1].record).toEqual({ + $type: 'app.bsky.actor.profile', + displayName: 'New', + description: 'new bio', + }) + }) +}) diff --git a/src/lib/api/community-post.ts b/src/lib/api/community-post.ts index 9511b1b2d..0d60d181a 100644 --- a/src/lib/api/community-post.ts +++ b/src/lib/api/community-post.ts @@ -35,7 +35,7 @@ export function isCommunityPostUri(uri: string | undefined): boolean { * reply and quote refs are permissioned-space URIs rather than AT-URIs. The * public lexicon validator therefore cannot validate those otherwise valid * records. Space responses are already validated by the AppView endpoint; - * retain the fields the renderer requires here while keeping strict lexicon + * retain the fields the renderer requires here while keeping lexicon * validation for public posts. */ export function isRenderablePostRecord( @@ -43,7 +43,8 @@ export function isRenderablePostRecord( ): post is app.bsky.feed.defs.PostView & {record: app.bsky.feed.post.Main} { if (!bsky.isType(app.bsky.feed.post, post.record)) return false if (!isSpaceRecordUri(post.uri)) { - return bsky.matches(app.bsky.feed.post, post.record) + // Lenient so a record that still holds a legacy blob reference renders. + return bsky.matches(app.bsky.feed.post, post.record, {strict: false}) } return ( typeof post.record.text === 'string' && diff --git a/src/lib/api/upsert-profile.ts b/src/lib/api/upsert-profile.ts new file mode 100644 index 000000000..e1ba71973 --- /dev/null +++ b/src/lib/api/upsert-profile.ts @@ -0,0 +1,62 @@ +import {type Action, type Un$Typed, XrpcResponseError} from '@atproto/lex' + +import {app, com} from '#/lexicons' +import * as bsky from '#/types/bsky' + +type Profile = Un$Typed + +type UpsertProfileInput = ( + existing: Profile | undefined, +) => Profile | Promise + +const COLLECTION = app.bsky.actor.profile.$type +const MAX_ATTEMPTS = 5 + +function isError(e: unknown, name: string): boolean { + return e instanceof XrpcResponseError && e.error === name +} + +/* + * The SDK's `upsertProfile` reads the record with strict validation and treats + * any failed read as "no profile yet". A profile that still holds a legacy blob + * reference fails that read, so the SDK would replace it with the update alone + * and drop its avatar, banner and every untouched field. This reads the record + * as stored and only treats a missing record as missing. + */ +export const upsertProfile: Action = async ( + client, + updateFn, +) => { + const repo = client.assertDid + for (let attempt = 1; ; attempt++) { + const existing = await client + .call(com.atproto.repo.getRecord, { + repo, + collection: COLLECTION, + rkey: 'self', + }) + .catch((e: unknown) => { + if (isError(e, 'RecordNotFound')) return undefined + throw e + }) + const value = existing?.value + const updated = await updateFn( + bsky.matches(app.bsky.actor.profile, value, {strict: false}) + ? value + : undefined, + ) + try { + await client.call(com.atproto.repo.putRecord, { + repo, + collection: COLLECTION, + rkey: 'self', + record: {...updated, $type: COLLECTION}, + swapRecord: existing?.cid, + }) + return + } catch (e) { + if (attempt < MAX_ATTEMPTS && isError(e, 'InvalidSwap')) continue + throw e + } + } +} diff --git a/src/screens/Onboarding/StepFinished/index.tsx b/src/screens/Onboarding/StepFinished/index.tsx index c951309b7..b8c3c9db5 100644 --- a/src/screens/Onboarding/StepFinished/index.tsx +++ b/src/screens/Onboarding/StepFinished/index.tsx @@ -3,13 +3,14 @@ import {View} from 'react-native' import {TID} from '@atproto/common-web' import {type Un$Typed} from '@atproto/lex' import {type AtUriString, toDatetimeString} from '@atproto/syntax' -import {overwriteSavedFeeds, setInterestsPref, upsertProfile} from '@bsky/sdk' +import {overwriteSavedFeeds, setInterestsPref} from '@bsky/sdk' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {Trans} from '@lingui/react/macro' import {useQueryClient} from '@tanstack/react-query' import {uploadBlob} from '#/lib/api' +import {upsertProfile} from '#/lib/api/upsert-profile' import {useBrand} from '#/lib/community/BrandContext' import { BLACKSKY_COMMUNITY_DID, diff --git a/src/state/queries/profile.ts b/src/state/queries/profile.ts index 9f5ae9619..7a6cc0875 100644 --- a/src/state/queries/profile.ts +++ b/src/state/queries/profile.ts @@ -7,13 +7,7 @@ import { type DidString, toDatetimeString, } from '@atproto/syntax' -import { - deleteFollow, - follow, - muteActor, - unmuteActor, - upsertProfile, -} from '@bsky/sdk' +import {deleteFollow, follow, muteActor, unmuteActor} from '@bsky/sdk' import { type InfiniteData, keepPreviousData, @@ -24,6 +18,7 @@ import { } from '@tanstack/react-query' import {uploadBlob} from '#/lib/api' +import {upsertProfile} from '#/lib/api/upsert-profile' import {until} from '#/lib/async/until' import {PUBLIC_BSKY_API} from '#/lib/constants' import {BLUESKY_APPVIEW_PINNED_OPTS} from '#/lib/constants' diff --git a/src/state/session/create-account.ts b/src/state/session/create-account.ts index 1e0bdbfa1..0601338ff 100644 --- a/src/state/session/create-account.ts +++ b/src/state/session/create-account.ts @@ -2,8 +2,9 @@ import {TID} from '@atproto/common-web' import {type Client} from '@atproto/lex' import {PasswordSession} from '@atproto/lex-password-session' import {toDatetimeString} from '@atproto/syntax' -import {overwriteSavedFeeds, setPersonalDetails, upsertProfile} from '@bsky/sdk' +import {overwriteSavedFeeds, setPersonalDetails} from '@bsky/sdk' +import {upsertProfile} from '#/lib/api/upsert-profile' import {networkRetry} from '#/lib/async/retry' import {DEFAULT_BRAND_CONFIG} from '#/lib/community/BrandContext' import {IS_PROD_SERVICE} from '#/lib/constants' diff --git a/src/view/com/composer/state/__tests__/video-upload-errors.test.ts b/src/view/com/composer/state/__tests__/video-upload-errors.test.ts new file mode 100644 index 000000000..d8f834a46 --- /dev/null +++ b/src/view/com/composer/state/__tests__/video-upload-errors.test.ts @@ -0,0 +1,59 @@ +import {type Client} from '@atproto/lex' +import {type I18n} from '@lingui/core' + +import {compressVideo} from '#/lib/media/video/compress' +import {ServerError} from '#/lib/media/video/errors' +import {type VideoTelemetry} from '#/lib/media/video/telemetry' +import {uploadVideo} from '#/lib/media/video/upload' +import {processVideo, type VideoAction} from '../video' + +jest.mock('#/lib/media/video/compress', () => ({compressVideo: jest.fn()})) +jest.mock('#/lib/media/video/upload', () => ({uploadVideo: jest.fn()})) +jest.mock('#/lib/media/video/util', () => ({ + createTokenlessVideoServiceClient: jest.fn(), +})) +jest.mock('#/logger', () => ({logger: {error: jest.fn(), debug: jest.fn()}})) + +const i18n = { + _: (descriptor: {message?: string}) => descriptor.message ?? '', +} as unknown as I18n + +const telemetry = new Proxy( + {}, + {get: () => () => {}}, +) as unknown as VideoTelemetry + +async function errorFor(e: unknown) { + jest.mocked(compressVideo).mockResolvedValue({ + size: 1, + mimeType: 'video/mp4', + } as never) + jest.mocked(uploadVideo).mockRejectedValue(e) + const actions: VideoAction[] = [] + await processVideo( + {} as never, + action => actions.push(action), + {assertDid: 'did:plc:me'} as unknown as Client, + 'https://video.example', + new AbortController().signal, + i18n, + false, + telemetry, + ) + const failure = actions.find(action => action.type === 'to_error') + return failure?.type === 'to_error' ? failure.error : undefined +} + +describe('video upload errors', () => { + it('translates a permission refusal from the single-request uploader', async () => { + await expect( + errorFor(new ServerError('User is not allowed to upload videos')), + ).resolves.toBe('You are not allowed to upload videos.') + }) + + it('translates an unverified-email refusal', async () => { + await expect( + errorFor(new ServerError('Confirm your email address to upload videos')), + ).resolves.toBe('Please confirm your email address to upload videos.') + }) +}) diff --git a/src/view/com/composer/state/video.ts b/src/view/com/composer/state/video.ts index 8b3908eaa..b0c61ee55 100644 --- a/src/view/com/composer/state/video.ts +++ b/src/view/com/composer/state/video.ts @@ -6,7 +6,11 @@ import {msg} from '@lingui/core/macro' import {AbortError} from '#/lib/async/cancelable' import {VIDEO_MAX_SIZE_MB} from '#/lib/constants' import {compressVideo} from '#/lib/media/video/compress' -import {UploadLimitError, VideoTooLargeError} from '#/lib/media/video/errors' +import { + ServerError, + UploadLimitError, + VideoTooLargeError, +} from '#/lib/media/video/errors' import {MultipartUploadError} from '#/lib/media/video/multipart/api' import {type VideoTelemetry} from '#/lib/media/video/telemetry' import {type CompressedVideo} from '#/lib/media/video/types' @@ -510,7 +514,11 @@ function getUploadErrorMessage(e: unknown, i18n: I18n): string | null { if (e instanceof AbortError) { return null } - if (e instanceof MultipartUploadError || e instanceof UploadLimitError) { + if ( + e instanceof ServerError || + e instanceof MultipartUploadError || + e instanceof UploadLimitError + ) { // https://github.com/bluesky-social/tango/blob/lumi/lumi/worker/permissions.go#L77 switch (e.message) { case 'User is not allowed to upload videos': -- knotmirror 0.0.1