Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: move to system-only release documents #7824

Merged
merged 3 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import {useCallback, useMemo} from 'react'
import {useRouter} from 'sanity/router'

import {resolveBundlePerspective} from '../../util/resolvePerspective'
import {useReleases} from '../store'
import {type ReleaseDocument} from '../store/types'
import {useReleases} from '../store/useReleases'
import {LATEST} from '../util/const'
import {getBundleIdFromReleaseDocumentId} from '../util/getBundleIdFromReleaseDocumentId'
import {isPublishedPerspective} from '../util/util'
Expand Down
5 changes: 0 additions & 5 deletions packages/sanity/src/core/releases/store/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,3 @@
// eslint-disable-next-line @typescript-eslint/prefer-as-const
export const RELEASE_DOCUMENT_TYPE: 'system.release' = 'system.release'
export const RELEASE_DOCUMENTS_PATH = '_.releases'

// api extractor take issues with 'as const' for literals
// eslint-disable-next-line @typescript-eslint/prefer-as-const
export const RELEASE_METADATA_TMP_DOC_TYPE: 'system-tmp.release' = 'system-tmp.release'
export const RELEASE_METADATA_TMP_DOC_PATH = 'system-tmp-releases'
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@ import {
type IdentifiedSanityDocumentStub,
type SanityClient,
} from '@sanity/client'
import {type User} from '@sanity/types'

import {getVersionId} from '../../util'
import {getBundleIdFromReleaseDocumentId} from '../index'
import {RELEASE_METADATA_TMP_DOC_PATH, RELEASE_METADATA_TMP_DOC_TYPE} from './constants'
import {getBundleIdFromReleaseDocumentId, type ReleaseDocument} from '../index'
import {type EditableReleaseDocument} from './types'

export interface ReleaseOperationsStore {
Expand All @@ -25,75 +23,37 @@ export interface ReleaseOperationsStore {
}

const IS_CREATE_VERSION_ACTION_SUPPORTED = false
const IS_RELEASE_METADATA_PROPERTIES_SUPPORTED = false
const IS_RELEASE_EDIT_SUPPORTED = false
// todo: change to `metadata` once the relevant PR has been deployed
const METADATA_PROPERTY_NAME = 'userMetadata'

export function createReleaseOperationsStore(options: {
client: SanityClient
currentUser: User
}): ReleaseOperationsStore {
const {client, currentUser} = options
const {client} = options
const handleCreateRelease = async (release: EditableReleaseDocument) => {
if (IS_RELEASE_METADATA_PROPERTIES_SUPPORTED) {
await requestAction(client, {
actionType: 'sanity.action.release.create',
releaseId: getBundleIdFromReleaseDocumentId(release._id),
})
await requestAction(client, {
actionType: 'sanity.action.release.create',
releaseId: getBundleIdFromReleaseDocumentId(release._id),
// @ts-expect-error - this is TBD
metadata: release,
})
} else {
// todo: remove once metadata properties are supported
const bundleId = getBundleIdFromReleaseDocumentId(release._id)
const metadataDocument = {
...release,
_id: `${RELEASE_METADATA_TMP_DOC_PATH}.${bundleId}`,
_type: RELEASE_METADATA_TMP_DOC_TYPE,
}
await requestAction(client, {
actionType: 'sanity.action.release.create',
releaseId: getBundleIdFromReleaseDocumentId(release._id),
})
await client.createIfNotExists(metadataDocument)
}
await requestAction(client, {
actionType: 'sanity.action.release.create',
releaseId: getBundleIdFromReleaseDocumentId(release._id),
[METADATA_PROPERTY_NAME]: release.metadata,
})
}

const handleUpdateRelease = async (release: EditableReleaseDocument) => {
const bundleId = getBundleIdFromReleaseDocumentId(release._id)

const unsetKeys = Object.entries(release)
.filter(([_, value]) => value === undefined)
.map(([key]) => `metadata.${key}`)

if (IS_RELEASE_EDIT_SUPPORTED) {
await requestAction(client, {
actionType: 'sanity.action.release.edit',
releaseId: bundleId,
patch: {
// todo: consider more granular updates here
set: {metadata: release.metadata},
unset: unsetKeys,
},
})
} else {
// todo: delete when `sanity.action.release.edit` action is supported for custom metadata/attributes
const metadataDocument = {
...release,
_id: `${RELEASE_METADATA_TMP_DOC_PATH}.${bundleId}`,
_type: RELEASE_METADATA_TMP_DOC_TYPE,
authorId: currentUser?.id,
}

let clientOperation = client.patch(metadataDocument._id).set(metadataDocument)
if (unsetKeys.length) {
clientOperation = clientOperation.unset(unsetKeys)
}

await clientOperation.commit()
}
.map(([key]) => `${METADATA_PROPERTY_NAME}.${key}`)

await requestAction(client, {
actionType: 'sanity.action.release.edit',
releaseId: bundleId,
patch: {
// todo: consider more granular updates here
set: {[METADATA_PROPERTY_NAME]: release.metadata},
unset: unsetKeys,
},
})
}

const handlePublishRelease = async (releaseId: string) =>
Expand Down Expand Up @@ -222,6 +182,7 @@ interface UnscheduleApiAction {
interface CreateReleaseApiAction {
actionType: 'sanity.action.release.create'
releaseId: string
[METADATA_PROPERTY_NAME]?: Partial<ReleaseDocument['metadata']>
}

interface CreateVersionReleaseApiAction {
Expand All @@ -230,7 +191,6 @@ interface CreateVersionReleaseApiAction {
attributes: IdentifiedSanityDocumentStub
}

// Todo: not supported by backend yet – this is me guessing what it will look like
interface EditReleaseApiAction {
actionType: 'sanity.action.release.edit'
releaseId: string
Expand All @@ -248,7 +208,7 @@ type ReleaseAction =
| UnarchiveApiAction
| CreateVersionReleaseApiAction

function requestAction(client: SanityClient, actions: ReleaseAction | ReleaseAction[]) {
export function requestAction(client: SanityClient, actions: ReleaseAction | ReleaseAction[]) {
const {dataset} = client.config()
return client.request({
uri: `/data/actions/${dataset}`,
Expand Down
102 changes: 64 additions & 38 deletions packages/sanity/src/core/releases/store/createReleaseStore.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import {type ListenEvent, type ListenOptions, type SanityClient} from '@sanity/client'
import {ClientError, type SanityClient} from '@sanity/client'
import {
BehaviorSubject,
catchError,
concat,
concatWith,
EMPTY,
filter,
map,
from,
merge,
type Observable,
of,
Expand All @@ -16,24 +18,23 @@ import {
tap,
timeout,
} from 'rxjs'
import {startWith} from 'rxjs/operators'
import {mergeMapArray} from 'rxjs-mergemap-array'
import {map, mergeMap, startWith, toArray} from 'rxjs/operators'

import {type DocumentPreviewStore} from '../../preview'
import {listenQuery} from '../../store/_legacy'
import {RELEASE_METADATA_TMP_DOC_PATH} from './constants'
import {RELEASE_DOCUMENT_TYPE, RELEASE_DOCUMENTS_PATH} from './constants'
import {createReleaseMetadataAggregator} from './createReleaseMetadataAggregator'
import {requestAction} from './createReleaseOperationStore'
import {releasesReducer, type ReleasesReducerAction, type ReleasesReducerState} from './reducer'
import {type ReleaseDocument, type ReleaseStore, type ReleaseSystemDocument} from './types'
import {type ReleaseDocument, type ReleaseStore} from './types'

type ActionWrapper = {action: ReleasesReducerAction}
type EventWrapper = {event: ListenEvent<ReleaseDocument>}
type ResponseWrapper = {response: ReleaseDocument[]}

export const SORT_FIELD = '_createdAt'
export const SORT_ORDER = 'desc'

const QUERY_FILTERS = [`_type=="system.release" && (_id in path("_.**"))`]
const QUERY_FILTER = `_type=="${RELEASE_DOCUMENT_TYPE}"(_id in path("${RELEASE_DOCUMENTS_PATH}.*"))`

// TODO: Extend the projection with the fields needed
const QUERY_PROJECTION = `{
Expand All @@ -43,21 +44,56 @@ const QUERY_PROJECTION = `{
// Newest releases first
const QUERY_SORT_ORDER = `order(${SORT_FIELD} ${SORT_ORDER})`

const QUERY = `*[${QUERY_FILTERS.join(' && ')}] ${QUERY_PROJECTION} | ${QUERY_SORT_ORDER}`

const LISTEN_OPTIONS: ListenOptions = {
events: ['welcome', 'mutation', 'reconnect'],
includeResult: true,
visibility: 'query',
tag: 'releases.listen',
}
const QUERY = `*[${QUERY_FILTER}] ${QUERY_PROJECTION} | ${QUERY_SORT_ORDER}`

const INITIAL_STATE: ReleasesReducerState = {
releases: new Map(),
state: 'loaded' as const,
releaseStack: [],
}

const RELEASE_METADATA_TMP_DOC_PATH = 'system-tmp-releases'
// todo: remove this after first tagged release
function migrateWith(client: SanityClient) {
return client.observable.fetch(`*[_id in path('${RELEASE_METADATA_TMP_DOC_PATH}.**')]`).pipe(
tap((tmpDocs: ReleaseDocument[]) => {
Copy link
Member Author

@bjoerge bjoerge Nov 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this migrates from old system-tmp-releases docments in the background (for projects that may have created them during testing). We should remove this shortly

// eslint-disable-next-line
console.log('Migrating %d release documents', tmpDocs.length)
}),
mergeMap((tmpDocs: ReleaseDocument[]) => {
if (tmpDocs.length === 0) {
return EMPTY
}
return from(tmpDocs).pipe(
mergeMap(async (tmpDoc) => {
const releaseId = tmpDoc._id.slice(RELEASE_METADATA_TMP_DOC_PATH.length + 1)
await requestAction(client, {
actionType: 'sanity.action.release.edit',
releaseId,
patch: {
set: {userMetadata: tmpDoc.metadata},
},
}).catch((err) => {
if (err instanceof ClientError) {
if (err.details.description == `Release "${releaseId}" was not found`) {
// ignore
return
}
}
throw err
})
await client.delete(tmpDoc._id)
}, 2),
)
}),
toArray(),
tap((migrated) => {
// eslint-disable-next-line
console.log('Migrated %d releases', migrated.length)
}),
mergeMap(() => EMPTY),
)
}
/**
* The releases store is initialised lazily when first subscribed to. Upon subscription, it will
* fetch a list of releases and create a listener to keep the locally held state fresh.
Expand All @@ -70,7 +106,7 @@ export function createReleaseStore(context: {
previewStore: DocumentPreviewStore
client: SanityClient
}): ReleaseStore {
const {client, previewStore} = context
const {client} = context

const dispatch$ = new Subject<ReleasesReducerAction>()
const fetchPending$ = new BehaviorSubject<boolean>(false)
Expand Down Expand Up @@ -100,29 +136,18 @@ export function createReleaseStore(context: {
resetOnSuccess: true,
}),
tap(() => fetchPending$.next(false)),
mergeMapArray((releaseSystemDocument: ReleaseSystemDocument) =>
previewStore
// Temporary release metadata document
.unstable_observeDocument(
`${RELEASE_METADATA_TMP_DOC_PATH}.${releaseSystemDocument.name}`,
)
.pipe(
map((metadataDocument) => ({
metadataDocument,
releaseSystemDocument,
})),
),
),
map((results) =>
results.flatMap(({metadataDocument, releaseSystemDocument}): ReleaseDocument[] => {
return metadataDocument && releaseSystemDocument
? {...(metadataDocument as any), ...releaseSystemDocument}
: []
}),
map((releases) =>
releases.map(
(releaseDoc: ReleaseDocument): ReleaseDocument => ({
...releaseDoc,
metadata: {...(releaseDoc as any).userMetadata, ...releaseDoc.metadata},
}),
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

userMetadata is going to be renamed to metadata very soon – this makes sure both works

),
),
map((response) => ({response})),
map((releases) => ({response: releases})),
),
),

catchError((error) =>
of<ActionWrapper>({
action: {
Expand Down Expand Up @@ -154,7 +179,8 @@ export function createReleaseStore(context: {
),
)

const state$ = merge(listFetch$, dispatch$).pipe(
const migrateTmpReleases = process.env.NODE_ENV === 'development' ? migrateWith(client) : EMPTY
const state$ = concat(migrateTmpReleases, merge(listFetch$, dispatch$)).pipe(
filter((action): action is ReleasesReducerAction => typeof action !== 'undefined'),
scan((state, action) => releasesReducer(state, action), INITIAL_STATE),
startWith(INITIAL_STATE),
Expand Down
10 changes: 0 additions & 10 deletions packages/sanity/src/core/releases/store/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,6 @@ export type ReleaseFinalDocumentState = {
revisionId: string
}

/**
* @internal
*/
export interface ReleaseSystemDocument {
_id: string
_type: 'system.release'
name: string
state: ReleaseState
publishAt?: string
}
/**
* @internal
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {useMemo} from 'react'

import {useClient} from '../../hooks'
import {useCurrentUser} from '../../store/user'
import {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../../studioClient'
import {createReleaseOperationsStore} from './createReleaseOperationStore'

Expand All @@ -10,15 +9,11 @@ import {createReleaseOperationsStore} from './createReleaseOperationStore'
*/
export function useReleaseOperations() {
const studioClient = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)
const currentUser = useCurrentUser()

return useMemo(
() =>
createReleaseOperationsStore({
client: studioClient,
// todo: is this non-null assertion safe?
currentUser: currentUser!,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

release store doesn't require current user anymore

}),
[currentUser, studioClient],
[studioClient],
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ vi.mock('../../../store', async (importOriginal) => ({
useReleases: vi.fn(),
}))

vi.mock('../../../store/useReleases', () => ({
useReleases: vi.fn(),
}))

vi.mock('../../../store/useReleasesMetadata', () => ({
useReleasesMetadata: vi.fn(),
}))

vi.mock('sanity/router', async (importOriginal) => ({
...(await importOriginal()),
useRouter: vi.fn().mockReturnValue({state: {}, navigate: vi.fn()}),
Expand Down
Loading
Loading