@asteby/metacore-runtime-react 53.1.0 → 53.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/api-context.d.ts.map +1 -1
- package/dist/api-context.js +15 -1
- package/dist/cache-coherence.d.ts +65 -0
- package/dist/cache-coherence.d.ts.map +1 -0
- package/dist/cache-coherence.js +191 -0
- package/dist/dynamic-columns-helpers.d.ts +32 -0
- package/dist/dynamic-columns-helpers.d.ts.map +1 -1
- package/dist/dynamic-columns-helpers.js +33 -0
- package/dist/dynamic-columns.d.ts.map +1 -1
- package/dist/dynamic-columns.js +25 -3
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/query-batch.d.ts +7 -0
- package/dist/query-batch.d.ts.map +1 -1
- package/dist/query-batch.js +10 -0
- package/package.json +3 -3
- package/src/__tests__/cache-coherence.test.tsx +248 -0
- package/src/__tests__/stage-column-labels.test.ts +54 -0
- package/src/api-context.tsx +22 -1
- package/src/cache-coherence.ts +215 -0
- package/src/dynamic-columns-helpers.ts +48 -0
- package/src/dynamic-columns.tsx +26 -3
- package/src/index.ts +1 -0
- package/src/query-batch.ts +10 -0
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// Client side of the server's cache epoch: what runtime-react drops when it
|
|
4
|
+
// moves, how react-query is invalidated per addon, and the stale-plan retry of
|
|
5
|
+
// the ApiProvider interceptor.
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
7
|
+
import { cleanup, render } from '@testing-library/react'
|
|
8
|
+
import { QueryClient } from '@tanstack/react-query'
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
CACHE_EPOCH_CHANGED_EVENT,
|
|
12
|
+
CACHE_EPOCH_OBSERVED_EVENT,
|
|
13
|
+
dropAddonDerivedCaches,
|
|
14
|
+
epochFromAxiosHeaders,
|
|
15
|
+
invalidateAddonQueries,
|
|
16
|
+
isStaleStateError,
|
|
17
|
+
onCacheEpochChanged,
|
|
18
|
+
queryKeyBelongsToAddon,
|
|
19
|
+
reportCacheEpoch,
|
|
20
|
+
STALE_RETRIED_FLAG,
|
|
21
|
+
useCacheEpochSync,
|
|
22
|
+
} from '../cache-coherence'
|
|
23
|
+
import { ApiProvider, type ApiClient } from '../api-context'
|
|
24
|
+
import { useMetadataCache } from '../metadata-cache'
|
|
25
|
+
import { invalidateQueryBatchAll } from '../query-batch'
|
|
26
|
+
import { onOptionsCacheInvalidated } from '../use-options-resolver'
|
|
27
|
+
|
|
28
|
+
afterEach(cleanup)
|
|
29
|
+
|
|
30
|
+
function emitChanged(detail = { epoch: 'b', previous: 'a', source: 'header' as const }) {
|
|
31
|
+
window.dispatchEvent(new CustomEvent(CACHE_EPOCH_CHANGED_EVENT, { detail }))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
describe('window protocol', () => {
|
|
35
|
+
it('reportCacheEpoch dispatches the observed event and ignores junk', () => {
|
|
36
|
+
const seen: unknown[] = []
|
|
37
|
+
const h = (e: Event) => seen.push((e as CustomEvent).detail)
|
|
38
|
+
window.addEventListener(CACHE_EPOCH_OBSERVED_EVENT, h)
|
|
39
|
+
reportCacheEpoch('tok.1.2')
|
|
40
|
+
reportCacheEpoch('')
|
|
41
|
+
reportCacheEpoch(undefined)
|
|
42
|
+
reportCacheEpoch(7)
|
|
43
|
+
window.removeEventListener(CACHE_EPOCH_OBSERVED_EVENT, h)
|
|
44
|
+
expect(seen).toEqual([{ epoch: 'tok.1.2' }])
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('onCacheEpochChanged receives the change and unsubscribes', () => {
|
|
48
|
+
const fn = vi.fn()
|
|
49
|
+
const off = onCacheEpochChanged(fn)
|
|
50
|
+
emitChanged()
|
|
51
|
+
expect(fn).toHaveBeenCalledWith({ epoch: 'b', previous: 'a', source: 'header' })
|
|
52
|
+
off()
|
|
53
|
+
emitChanged()
|
|
54
|
+
expect(fn).toHaveBeenCalledTimes(1)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('reads the header from axios bags', () => {
|
|
58
|
+
expect(epochFromAxiosHeaders({ 'x-cache-epoch': 'a.1' })).toBe('a.1')
|
|
59
|
+
expect(epochFromAxiosHeaders({ get: (k: string) => (k === 'x-cache-epoch' ? 'a.2' : undefined) })).toBe('a.2')
|
|
60
|
+
expect(epochFromAxiosHeaders(undefined)).toBeUndefined()
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
describe('dropping what the epoch makes stale', () => {
|
|
65
|
+
beforeEach(() => useMetadataCache.getState().clearAll())
|
|
66
|
+
|
|
67
|
+
it('clears metadata, the read batch and the option lists', () => {
|
|
68
|
+
useMetadataCache.getState().setMetadata('suppliers', { title: 'Old' } as never)
|
|
69
|
+
expect(useMetadataCache.getState().getMetadata('suppliers')).toBeDefined()
|
|
70
|
+
const optionsDropped = vi.fn()
|
|
71
|
+
const off = onOptionsCacheInvalidated(optionsDropped)
|
|
72
|
+
dropAddonDerivedCaches()
|
|
73
|
+
off()
|
|
74
|
+
expect(useMetadataCache.getState().getMetadata('suppliers')).toBeUndefined()
|
|
75
|
+
expect(optionsDropped).toHaveBeenCalledTimes(1)
|
|
76
|
+
expect(() => invalidateQueryBatchAll()).not.toThrow()
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('useCacheEpochSync drops the caches and invalidates react-query when the epoch moves', () => {
|
|
80
|
+
useMetadataCache.getState().setMetadata('suppliers', { title: 'Old' } as never)
|
|
81
|
+
const qc = { invalidateQueries: vi.fn().mockResolvedValue(undefined) }
|
|
82
|
+
const onChange = vi.fn()
|
|
83
|
+
function Host() {
|
|
84
|
+
useCacheEpochSync({ queryClient: qc, onChange })
|
|
85
|
+
return null
|
|
86
|
+
}
|
|
87
|
+
render(<Host />)
|
|
88
|
+
emitChanged()
|
|
89
|
+
expect(useMetadataCache.getState().getMetadata('suppliers')).toBeUndefined()
|
|
90
|
+
expect(qc.invalidateQueries).toHaveBeenCalledTimes(1)
|
|
91
|
+
expect(onChange).toHaveBeenCalledWith({ epoch: 'b', previous: 'a', source: 'header' })
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
it('stops listening on unmount', () => {
|
|
95
|
+
const qc = { invalidateQueries: vi.fn().mockResolvedValue(undefined) }
|
|
96
|
+
function Host() {
|
|
97
|
+
useCacheEpochSync({ queryClient: qc })
|
|
98
|
+
return null
|
|
99
|
+
}
|
|
100
|
+
const { unmount } = render(<Host />)
|
|
101
|
+
unmount()
|
|
102
|
+
emitChanged()
|
|
103
|
+
expect(qc.invalidateQueries).not.toHaveBeenCalled()
|
|
104
|
+
})
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
describe('per-addon react-query invalidation', () => {
|
|
108
|
+
it('matches keys that mention the addon, by exact name or namespaced prefix', () => {
|
|
109
|
+
expect(queryKeyBelongsToAddon(['crm'], 'crm')).toBe(true)
|
|
110
|
+
expect(queryKeyBelongsToAddon(['data', 'crm.Lead', { page: 1 }], 'crm')).toBe(true)
|
|
111
|
+
expect(queryKeyBelongsToAddon(['x', 'crm:Lead'], 'crm')).toBe(true)
|
|
112
|
+
expect(queryKeyBelongsToAddon(['addon', { settings: '/addons/crm/settings' }], 'crm')).toBe(true)
|
|
113
|
+
expect(queryKeyBelongsToAddon(['data', 'crmx.Lead'], 'crm')).toBe(false)
|
|
114
|
+
expect(queryKeyBelongsToAddon(['data', 'pos.Order'], 'crm')).toBe(false)
|
|
115
|
+
expect(queryKeyBelongsToAddon(['data'], '')).toBe(false)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it('invalidates the addon queries and the shell roots, not unrelated data', async () => {
|
|
119
|
+
const qc = new QueryClient()
|
|
120
|
+
const seed = (key: unknown[]) => qc.setQueryData(key, 'x')
|
|
121
|
+
seed(['crm', 'leads'])
|
|
122
|
+
seed(['data', 'crm.Lead'])
|
|
123
|
+
seed(['marketplace', 'installed'])
|
|
124
|
+
seed(['navigation'])
|
|
125
|
+
seed(['data', 'pos.Order'])
|
|
126
|
+
seed(['customers', 'list'])
|
|
127
|
+
await invalidateAddonQueries(qc, 'crm')
|
|
128
|
+
const state = (key: unknown[]) => qc.getQueryState(key)?.isInvalidated
|
|
129
|
+
expect(state(['crm', 'leads'])).toBe(true)
|
|
130
|
+
expect(state(['data', 'crm.Lead'])).toBe(true)
|
|
131
|
+
expect(state(['marketplace', 'installed'])).toBe(true)
|
|
132
|
+
expect(state(['navigation'])).toBe(true)
|
|
133
|
+
expect(state(['data', 'pos.Order'])).toBeFalsy()
|
|
134
|
+
expect(state(['customers', 'list'])).toBeFalsy()
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
it('extra roots are honoured', async () => {
|
|
138
|
+
const qc = new QueryClient()
|
|
139
|
+
qc.setQueryData(['my-shell-thing'], 1)
|
|
140
|
+
await invalidateAddonQueries(qc, 'crm', { extraRoots: ['my-shell-thing'] })
|
|
141
|
+
expect(qc.getQueryState(['my-shell-thing'])?.isInvalidated).toBe(true)
|
|
142
|
+
})
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
describe('stale server state', () => {
|
|
146
|
+
it('recognises the incident error in the shapes it arrives in', () => {
|
|
147
|
+
const msg = 'ERROR: cached plan must not change result type (SQLSTATE 0A000)'
|
|
148
|
+
expect(isStaleStateError(new Error(msg))).toBe(true)
|
|
149
|
+
expect(isStaleStateError({ response: { status: 500, data: { error: { message: msg } } } })).toBe(true)
|
|
150
|
+
expect(isStaleStateError({ response: { data: { message: 'prepared statement "s" does not exist' } } })).toBe(true)
|
|
151
|
+
expect(isStaleStateError(new Error('duplicate key'))).toBe(false)
|
|
152
|
+
expect(isStaleStateError(undefined)).toBe(false)
|
|
153
|
+
})
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
describe('ApiProvider interceptor', () => {
|
|
157
|
+
function axiosLike() {
|
|
158
|
+
let onOk: (r: any) => any = (r) => r
|
|
159
|
+
let onErr: (e: any) => any = (e) => Promise.reject(e)
|
|
160
|
+
const eject = vi.fn()
|
|
161
|
+
const request = vi.fn()
|
|
162
|
+
const client = {
|
|
163
|
+
get: vi.fn(),
|
|
164
|
+
post: vi.fn(),
|
|
165
|
+
put: vi.fn(),
|
|
166
|
+
delete: vi.fn(),
|
|
167
|
+
request,
|
|
168
|
+
interceptors: {
|
|
169
|
+
response: {
|
|
170
|
+
use: (a: any, b: any) => {
|
|
171
|
+
onOk = a
|
|
172
|
+
onErr = b
|
|
173
|
+
return 3
|
|
174
|
+
},
|
|
175
|
+
eject,
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
return { client: client as unknown as ApiClient, ok: (r: any) => onOk(r), err: (e: any) => onErr(e), request, eject }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
it('reports the epoch of every answer, ok or failed', async () => {
|
|
183
|
+
const ax = axiosLike()
|
|
184
|
+
const seen: string[] = []
|
|
185
|
+
const h = (e: Event) => seen.push((e as CustomEvent).detail.epoch)
|
|
186
|
+
window.addEventListener(CACHE_EPOCH_OBSERVED_EVENT, h)
|
|
187
|
+
render(
|
|
188
|
+
<ApiProvider client={ax.client} batch={false}>
|
|
189
|
+
<div />
|
|
190
|
+
</ApiProvider>,
|
|
191
|
+
)
|
|
192
|
+
ax.ok({ headers: { 'x-cache-epoch': 'e.1' }, config: { method: 'get', url: '/x' } })
|
|
193
|
+
await ax.err({ response: { headers: { 'x-cache-epoch': 'e.2' } }, config: { method: 'get', url: '/x' } }).catch(() => {})
|
|
194
|
+
window.removeEventListener(CACHE_EPOCH_OBSERVED_EVENT, h)
|
|
195
|
+
expect(seen).toEqual(['e.1', 'e.2'])
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
it('re-sends a request that hit a stale plan exactly once', async () => {
|
|
199
|
+
vi.useFakeTimers()
|
|
200
|
+
try {
|
|
201
|
+
const ax = axiosLike()
|
|
202
|
+
render(
|
|
203
|
+
<ApiProvider client={ax.client} batch={false}>
|
|
204
|
+
<div />
|
|
205
|
+
</ApiProvider>,
|
|
206
|
+
)
|
|
207
|
+
const config: Record<string, unknown> = { method: 'post', url: '/addresses' }
|
|
208
|
+
const stale = {
|
|
209
|
+
config,
|
|
210
|
+
response: { status: 500, data: { error: { message: 'cached plan must not change result type (SQLSTATE 0A000)' } } },
|
|
211
|
+
}
|
|
212
|
+
ax.request.mockResolvedValueOnce({ data: 'saved', config })
|
|
213
|
+
const p = ax.err(stale)
|
|
214
|
+
await vi.advanceTimersByTimeAsync(300)
|
|
215
|
+
await expect(p).resolves.toMatchObject({ data: 'saved' })
|
|
216
|
+
expect(ax.request).toHaveBeenCalledTimes(1)
|
|
217
|
+
expect(config[STALE_RETRIED_FLAG]).toBe(true)
|
|
218
|
+
// the same request failing again is not retried again
|
|
219
|
+
await expect(ax.err(stale)).rejects.toBe(stale)
|
|
220
|
+
expect(ax.request).toHaveBeenCalledTimes(1)
|
|
221
|
+
} finally {
|
|
222
|
+
vi.useRealTimers()
|
|
223
|
+
}
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
it('does not retry ordinary failures', async () => {
|
|
227
|
+
const ax = axiosLike()
|
|
228
|
+
render(
|
|
229
|
+
<ApiProvider client={ax.client} batch={false}>
|
|
230
|
+
<div />
|
|
231
|
+
</ApiProvider>,
|
|
232
|
+
)
|
|
233
|
+
const e = { config: { method: 'get', url: '/x' }, response: { status: 403, data: { message: 'forbidden' } } }
|
|
234
|
+
await expect(ax.err(e)).rejects.toBe(e)
|
|
235
|
+
expect(ax.request).not.toHaveBeenCalled()
|
|
236
|
+
})
|
|
237
|
+
|
|
238
|
+
it('ejects the interceptor on unmount', () => {
|
|
239
|
+
const ax = axiosLike()
|
|
240
|
+
const { unmount } = render(
|
|
241
|
+
<ApiProvider client={ax.client} batch={false}>
|
|
242
|
+
<div />
|
|
243
|
+
</ApiProvider>,
|
|
244
|
+
)
|
|
245
|
+
unmount()
|
|
246
|
+
expect(ax.eject).toHaveBeenCalledWith(3)
|
|
247
|
+
})
|
|
248
|
+
})
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Enum/status cells never show the raw value: a stage column with no options
|
|
3
|
+
// paints the translated stage label («Listo»), and an option whose label is an
|
|
4
|
+
// unresolved catalog key is translated (or humanized), never printed as a key.
|
|
5
|
+
import { describe, expect, it } from 'vitest'
|
|
6
|
+
import { resolveColumnOptions } from '../dynamic-columns-helpers'
|
|
7
|
+
|
|
8
|
+
const catalog: Record<string, string> = {
|
|
9
|
+
'channel_orders.stage.ready': 'Listo',
|
|
10
|
+
'channel_orders.stage.fulfilled': 'Cumplido',
|
|
11
|
+
'channel_orders.option.channel.web': 'Web',
|
|
12
|
+
}
|
|
13
|
+
const t = (key: string, o?: { defaultValue?: string }) => catalog[key] ?? o?.defaultValue ?? key
|
|
14
|
+
|
|
15
|
+
const stages = [
|
|
16
|
+
{ key: 'imported', label: 'channel_orders.stage.imported', color: 'slate' },
|
|
17
|
+
{ key: 'ready', label: 'channel_orders.stage.ready', color: 'cyan' },
|
|
18
|
+
{ key: 'fulfilled', label: 'Cumplido (literal)', color: 'green' },
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
describe('resolveColumnOptions', () => {
|
|
22
|
+
it('la columna de etapa sin options usa las etiquetas traducidas de stages', () => {
|
|
23
|
+
const opts = resolveColumnOptions({ columnKey: 'status', stages, stageField: 'status', translate: t })!
|
|
24
|
+
expect(opts.map((o) => [o.value, o.label])).toEqual([
|
|
25
|
+
['imported', 'Imported'], // sin traducción en el catálogo: humanizada, nunca la clave
|
|
26
|
+
['ready', 'Listo'],
|
|
27
|
+
['fulfilled', 'Cumplido (literal)'],
|
|
28
|
+
])
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('otra columna no toma las etapas', () => {
|
|
32
|
+
expect(resolveColumnOptions({ columnKey: 'channel', stages, stageField: 'status', translate: t })).toBeUndefined()
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('labelKey no resuelta por el servidor se traduce en el cliente', () => {
|
|
36
|
+
const opts = resolveColumnOptions({
|
|
37
|
+
columnKey: 'channel',
|
|
38
|
+
options: [{ value: 'web', label: 'Web', labelKey: 'channel_orders.option.channel.web' }],
|
|
39
|
+
translate: t,
|
|
40
|
+
})!
|
|
41
|
+
expect(opts[0].label).toBe('Web')
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it('las options propias de la columna ganan sobre las etapas', () => {
|
|
45
|
+
const opts = resolveColumnOptions({
|
|
46
|
+
columnKey: 'status',
|
|
47
|
+
options: [{ value: 'ready', label: 'Propia' }],
|
|
48
|
+
stages,
|
|
49
|
+
stageField: 'status',
|
|
50
|
+
translate: t,
|
|
51
|
+
})!
|
|
52
|
+
expect(opts).toEqual([{ value: 'ready', label: 'Propia' }])
|
|
53
|
+
})
|
|
54
|
+
})
|
package/src/api-context.tsx
CHANGED
|
@@ -5,6 +5,13 @@
|
|
|
5
5
|
import React, { createContext, useContext, useEffect, useMemo } from 'react'
|
|
6
6
|
import { batchGet, invalidateQueryBatchData } from './query-batch'
|
|
7
7
|
import { invalidateOptionsCache } from './use-options-resolver'
|
|
8
|
+
import {
|
|
9
|
+
epochFromAxiosHeaders,
|
|
10
|
+
isStaleStateError,
|
|
11
|
+
reportCacheEpoch,
|
|
12
|
+
STALE_RETRIED_FLAG,
|
|
13
|
+
STALE_RETRY_DELAY_MS,
|
|
14
|
+
} from './cache-coherence'
|
|
8
15
|
|
|
9
16
|
/** Minimal axios-compatible client shape consumed by runtime-react. */
|
|
10
17
|
export interface ApiClient {
|
|
@@ -42,11 +49,24 @@ export function ApiProvider({ client, batch = true, children }: ApiProviderProps
|
|
|
42
49
|
}
|
|
43
50
|
const id = interceptors.use(
|
|
44
51
|
(res: any) => {
|
|
52
|
+
// Every answer carries the server's cache epoch: a token that
|
|
53
|
+
// moved means an addon changed since this tab last looked.
|
|
54
|
+
reportCacheEpoch(epochFromAxiosHeaders(res?.headers))
|
|
45
55
|
onSettled(res?.config)
|
|
46
56
|
return res
|
|
47
57
|
},
|
|
48
|
-
(err: any) => {
|
|
58
|
+
async (err: any) => {
|
|
59
|
+
reportCacheEpoch(epochFromAxiosHeaders(err?.response?.headers))
|
|
49
60
|
onSettled(err?.config)
|
|
61
|
+
// A prepared plan outdated by an addon migration fails ONCE
|
|
62
|
+
// (SQLSTATE 0A000 / 26000) before the statement runs and the
|
|
63
|
+
// server drops it: re-send the request one time.
|
|
64
|
+
const config = err?.config as Record<string, unknown> | undefined
|
|
65
|
+
if (config && !config[STALE_RETRIED_FLAG] && isStaleStateError(err) && typeof (client as AxiosLike).request === 'function') {
|
|
66
|
+
config[STALE_RETRIED_FLAG] = true
|
|
67
|
+
await new Promise((r) => setTimeout(r, STALE_RETRY_DELAY_MS))
|
|
68
|
+
return (client as AxiosLike).request!(config)
|
|
69
|
+
}
|
|
50
70
|
return Promise.reject(err)
|
|
51
71
|
},
|
|
52
72
|
)
|
|
@@ -60,6 +80,7 @@ export function ApiProvider({ client, batch = true, children }: ApiProviderProps
|
|
|
60
80
|
}
|
|
61
81
|
|
|
62
82
|
interface AxiosLike {
|
|
83
|
+
request?: (config: any) => Promise<any>
|
|
63
84
|
interceptors?: {
|
|
64
85
|
response?: {
|
|
65
86
|
use?: (onFulfilled: (res: any) => any, onRejected: (err: any) => any) => number
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// Client side of the backend's cache coherence (metacore-kernel
|
|
2
|
+
// `cachecoherence`): the server keeps one epoch that moves whenever something
|
|
3
|
+
// the UI is derived from changes (addon installed / upgraded / enabled /
|
|
4
|
+
// disabled / uninstalled, server restarted) and tells the browser through
|
|
5
|
+
// `X-Cache-Epoch` on every response and a `CACHE_EPOCH_CHANGED` WebSocket frame.
|
|
6
|
+
//
|
|
7
|
+
// `@asteby/metacore-sdk` owns the comparison (`observeCacheEpoch`,
|
|
8
|
+
// `onCacheEpochChange`, `wireCacheEpochPush`). This package talks to it through
|
|
9
|
+
// the window-event protocol it documents, so neither needs to import the other:
|
|
10
|
+
//
|
|
11
|
+
// "metacore:cache-epoch-observed" { detail: { epoch } } -> report a token
|
|
12
|
+
// "metacore:cache-epoch-changed" { detail: { epoch, previous, source } }
|
|
13
|
+
//
|
|
14
|
+
// What runtime-react adds is what to DROP when the epoch moves: the metadata
|
|
15
|
+
// cache, the read batch (rows, metadata, i18n), the option lists, and the
|
|
16
|
+
// react-query cache.
|
|
17
|
+
|
|
18
|
+
import { useEffect } from 'react'
|
|
19
|
+
import type { QueryClient } from '@tanstack/react-query'
|
|
20
|
+
import { useMetadataCache } from './metadata-cache'
|
|
21
|
+
import { invalidateOptionsCache } from './use-options-resolver'
|
|
22
|
+
import { invalidateQueryBatchAll } from './query-batch'
|
|
23
|
+
|
|
24
|
+
export const CACHE_EPOCH_HEADER = 'x-cache-epoch'
|
|
25
|
+
export const CACHE_EPOCH_OBSERVED_EVENT = 'metacore:cache-epoch-observed'
|
|
26
|
+
export const CACHE_EPOCH_CHANGED_EVENT = 'metacore:cache-epoch-changed'
|
|
27
|
+
|
|
28
|
+
/** Report the epoch token of a response (the SDK core compares it). */
|
|
29
|
+
export function reportCacheEpoch(token: unknown): void {
|
|
30
|
+
if (typeof token !== 'string' || !token.trim()) return
|
|
31
|
+
if (typeof window === 'undefined' || typeof window.dispatchEvent !== 'function') return
|
|
32
|
+
try {
|
|
33
|
+
window.dispatchEvent(new CustomEvent(CACHE_EPOCH_OBSERVED_EVENT, { detail: { epoch: token } }))
|
|
34
|
+
} catch {
|
|
35
|
+
/* non-DOM environment */
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Reads the token out of an axios headers bag (plain object or AxiosHeaders). */
|
|
40
|
+
export function epochFromAxiosHeaders(headers: unknown): string | undefined {
|
|
41
|
+
if (!headers || typeof headers !== 'object') return undefined
|
|
42
|
+
const h = headers as { get?: (k: string) => unknown } & Record<string, unknown>
|
|
43
|
+
if (typeof h.get === 'function') {
|
|
44
|
+
const v = h.get(CACHE_EPOCH_HEADER)
|
|
45
|
+
if (typeof v === 'string') return v
|
|
46
|
+
}
|
|
47
|
+
const v = h[CACHE_EPOCH_HEADER] ?? h['X-Cache-Epoch']
|
|
48
|
+
return typeof v === 'string' ? v : undefined
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface CacheEpochChange {
|
|
52
|
+
epoch: string
|
|
53
|
+
previous: string | null
|
|
54
|
+
source: 'header' | 'push' | 'event'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Subscribe to "the epoch moved". Returns the unsubscribe fn. */
|
|
58
|
+
export function onCacheEpochChanged(listener: (change: CacheEpochChange) => void): () => void {
|
|
59
|
+
if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return () => {}
|
|
60
|
+
const handler = (e: Event) => listener((e as CustomEvent<CacheEpochChange>).detail)
|
|
61
|
+
window.addEventListener(CACHE_EPOCH_CHANGED_EVENT, handler)
|
|
62
|
+
return () => window.removeEventListener(CACHE_EPOCH_CHANGED_EVENT, handler)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Drops every cache this package derives from installed addons: table/modal
|
|
67
|
+
* metadata, the read batch (rows, metadata, i18n) and the option lists. Mounted
|
|
68
|
+
* components refetch on their next render/mount.
|
|
69
|
+
*/
|
|
70
|
+
export function dropAddonDerivedCaches(): void {
|
|
71
|
+
useMetadataCache.getState().clearAll()
|
|
72
|
+
invalidateQueryBatchAll()
|
|
73
|
+
invalidateOptionsCache()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Query keys that belong to the shell rather than to one addon: the installed
|
|
78
|
+
* list, manifests, navigation, permissions, capabilities, metadata, i18n. An
|
|
79
|
+
* addon change can alter any of them.
|
|
80
|
+
*/
|
|
81
|
+
export const SHELL_QUERY_ROOTS: readonly string[] = [
|
|
82
|
+
'marketplace',
|
|
83
|
+
'metacore',
|
|
84
|
+
'manifests',
|
|
85
|
+
'navigation',
|
|
86
|
+
'sidebar',
|
|
87
|
+
'permissions',
|
|
88
|
+
'capabilities',
|
|
89
|
+
'metadata',
|
|
90
|
+
'i18n',
|
|
91
|
+
'installed-addons',
|
|
92
|
+
'addons',
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
function keyStrings(key: readonly unknown[]): string[] {
|
|
96
|
+
const out: string[] = []
|
|
97
|
+
const walk = (v: unknown, depth: number) => {
|
|
98
|
+
if (depth > 4 || v == null) return
|
|
99
|
+
if (typeof v === 'string') out.push(v)
|
|
100
|
+
else if (Array.isArray(v)) v.forEach((x) => walk(x, depth + 1))
|
|
101
|
+
else if (typeof v === 'object') Object.values(v as Record<string, unknown>).forEach((x) => walk(x, depth + 1))
|
|
102
|
+
}
|
|
103
|
+
walk(key, 0)
|
|
104
|
+
return out
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** True when a react-query key refers to `addonKey` (exact or `<key>.`, `<key>:`, `<key>/` prefixed). */
|
|
108
|
+
export function queryKeyBelongsToAddon(queryKey: readonly unknown[], addonKey: string): boolean {
|
|
109
|
+
if (!addonKey) return false
|
|
110
|
+
return keyStrings(queryKey).some(
|
|
111
|
+
(s) =>
|
|
112
|
+
s === addonKey ||
|
|
113
|
+
s.startsWith(`${addonKey}.`) ||
|
|
114
|
+
s.startsWith(`${addonKey}:`) ||
|
|
115
|
+
s.startsWith(`${addonKey}/`) ||
|
|
116
|
+
s.includes(`/${addonKey}/`) ||
|
|
117
|
+
s.endsWith(`/${addonKey}`),
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Invalidate every query that depends on an addon: the ones whose key mentions
|
|
123
|
+
* it, plus the shell roots (installed list, manifests, navigation, permissions,
|
|
124
|
+
* metadata...). Call after install / upgrade / enable / disable / uninstall.
|
|
125
|
+
* Resolves when the refetches of the active queries settle.
|
|
126
|
+
*/
|
|
127
|
+
export function invalidateAddonQueries(
|
|
128
|
+
queryClient: Pick<QueryClient, 'invalidateQueries'>,
|
|
129
|
+
addonKey: string,
|
|
130
|
+
options: { extraRoots?: readonly string[] } = {},
|
|
131
|
+
): Promise<void> {
|
|
132
|
+
const roots = new Set([...SHELL_QUERY_ROOTS, ...(options.extraRoots ?? [])])
|
|
133
|
+
return queryClient.invalidateQueries({
|
|
134
|
+
predicate: (query) => {
|
|
135
|
+
const key = query.queryKey as readonly unknown[]
|
|
136
|
+
if (queryKeyBelongsToAddon(key, addonKey)) return true
|
|
137
|
+
const root = key[0]
|
|
138
|
+
return typeof root === 'string' && roots.has(root)
|
|
139
|
+
},
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface UseCacheEpochSyncOptions {
|
|
144
|
+
/** When given, the react-query cache is invalidated too. */
|
|
145
|
+
queryClient?: Pick<QueryClient, 'invalidateQueries'>
|
|
146
|
+
/** Extra work on a change (re-prefetch metadata, reload manifests, ...). */
|
|
147
|
+
onChange?: (change: CacheEpochChange) => void
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Mount once high in the tree. When the server's cache epoch moves, every
|
|
152
|
+
* runtime cache derived from installed addons is dropped and react-query is
|
|
153
|
+
* invalidated, so the open tab stops showing the previous world.
|
|
154
|
+
*
|
|
155
|
+
* useCacheEpochSync({ queryClient })
|
|
156
|
+
* useCacheEpochPush(ws) // from @asteby/metacore-sdk/react, optional
|
|
157
|
+
*/
|
|
158
|
+
export function useCacheEpochSync({ queryClient, onChange }: UseCacheEpochSyncOptions = {}): void {
|
|
159
|
+
useEffect(
|
|
160
|
+
() =>
|
|
161
|
+
onCacheEpochChanged((change) => {
|
|
162
|
+
dropAddonDerivedCaches()
|
|
163
|
+
void queryClient?.invalidateQueries()
|
|
164
|
+
onChange?.(change)
|
|
165
|
+
}),
|
|
166
|
+
[queryClient, onChange],
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---------------------------------------------------------------------------
|
|
171
|
+
// Stale server state (mirrors @asteby/metacore-sdk `isStaleStateError`)
|
|
172
|
+
// ---------------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
const STALE_PATTERNS = [
|
|
175
|
+
/cached plan must not change result type/i,
|
|
176
|
+
/SQLSTATE\s*0A000/i,
|
|
177
|
+
/prepared statement\s+"?[^"\s]*"?\s+does not exist/i,
|
|
178
|
+
/SQLSTATE\s*26000/i,
|
|
179
|
+
/stale[_ -]?(?:plan|state|epoch)/i,
|
|
180
|
+
]
|
|
181
|
+
|
|
182
|
+
function collectText(err: unknown, out: string[], depth = 0): void {
|
|
183
|
+
if (err == null || depth > 4) return
|
|
184
|
+
if (typeof err === 'string') {
|
|
185
|
+
out.push(err)
|
|
186
|
+
return
|
|
187
|
+
}
|
|
188
|
+
if (typeof err !== 'object') return
|
|
189
|
+
const o = err as Record<string, unknown>
|
|
190
|
+
for (const k of ['message', 'error', 'code', 'detail', 'details']) {
|
|
191
|
+
const v = o[k]
|
|
192
|
+
if (typeof v === 'string') out.push(v)
|
|
193
|
+
else if (v && typeof v === 'object') collectText(v, out, depth + 1)
|
|
194
|
+
}
|
|
195
|
+
if (o.response) collectText(o.response, out, depth + 1)
|
|
196
|
+
if (o.data) collectText(o.data, out, depth + 1)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* True when an error says the SERVER's cached state was out of date (a prepared
|
|
201
|
+
* plan outdated by a migration, SQLSTATE 0A000 / 26000). Those failures happen
|
|
202
|
+
* before the statement ran, and the server has already dropped the stale state,
|
|
203
|
+
* so one retry is safe and enough.
|
|
204
|
+
*/
|
|
205
|
+
export function isStaleStateError(err: unknown): boolean {
|
|
206
|
+
const texts: string[] = []
|
|
207
|
+
collectText(err, texts)
|
|
208
|
+
return texts.some((t) => STALE_PATTERNS.some((re) => re.test(t)))
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Marker on a request config that already had its one stale-state retry. */
|
|
212
|
+
export const STALE_RETRIED_FLAG = '__metacoreStaleRetried'
|
|
213
|
+
|
|
214
|
+
/** Pause before the retry, ms. */
|
|
215
|
+
export const STALE_RETRY_DELAY_MS = 200
|
|
@@ -100,3 +100,51 @@ export function localizeFieldLabel(
|
|
|
100
100
|
if (!CATALOG_KEY_RE.test(label)) return label
|
|
101
101
|
return translateMetadataLabel(label, translate)
|
|
102
102
|
}
|
|
103
|
+
|
|
104
|
+
/** An option as the table cell paints it (`labelKey` is the unresolved catalog key the host could not translate). */
|
|
105
|
+
export interface CellOption {
|
|
106
|
+
value: string | boolean
|
|
107
|
+
label: string
|
|
108
|
+
labelKey?: string
|
|
109
|
+
icon?: string
|
|
110
|
+
color?: string
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The options a table cell must use to paint an enum/status value, so the cell
|
|
115
|
+
* never shows the raw value («Ready») when a translated label exists:
|
|
116
|
+
*
|
|
117
|
+
* 1. the column's own `options`, or — for the model's stage column
|
|
118
|
+
* (`stage_field`) with none — the `stages[]` labels (Listo, Cumplido…);
|
|
119
|
+
* 2. every label is resolved: an unresolved catalog key (`labelKey`, or a
|
|
120
|
+
* label that is itself a key) goes through the client catalog and, failing
|
|
121
|
+
* that, is humanized. A human label is returned untouched.
|
|
122
|
+
*
|
|
123
|
+
* Returns undefined when there is nothing to paint from (the cell then
|
|
124
|
+
* humanizes the token as its last resort).
|
|
125
|
+
*/
|
|
126
|
+
export function resolveColumnOptions(args: {
|
|
127
|
+
columnKey: string
|
|
128
|
+
options?: CellOption[]
|
|
129
|
+
stages?: { key: string; label?: string; color?: string }[]
|
|
130
|
+
stageField?: string
|
|
131
|
+
translate?: MetadataTranslator
|
|
132
|
+
}): CellOption[] | undefined {
|
|
133
|
+
const { columnKey, options, stages, stageField, translate } = args
|
|
134
|
+
let base: CellOption[] | undefined = options && options.length > 0 ? options : undefined
|
|
135
|
+
if (!base && stageField && columnKey === stageField && stages && stages.length > 0) {
|
|
136
|
+
base = stages
|
|
137
|
+
.filter((st) => st && st.key)
|
|
138
|
+
.map((st) => ({ value: st.key, label: st.label || '', color: st.color }))
|
|
139
|
+
}
|
|
140
|
+
if (!base) return undefined
|
|
141
|
+
return base.map((opt) => {
|
|
142
|
+
const source = opt.labelKey || opt.label
|
|
143
|
+
const label = opt.labelKey
|
|
144
|
+
? translateMetadataLabel(opt.labelKey, translate)
|
|
145
|
+
: opt.label
|
|
146
|
+
? localizeFieldLabel(opt.label, translate)
|
|
147
|
+
: humanizeToken(String(opt.value))
|
|
148
|
+
return source === label && !opt.labelKey ? opt : { ...opt, label }
|
|
149
|
+
})
|
|
150
|
+
}
|
package/src/dynamic-columns.tsx
CHANGED
|
@@ -40,7 +40,7 @@ import {
|
|
|
40
40
|
import { Progress } from './dialogs/_primitives'
|
|
41
41
|
import { useSystemActor } from './org-runtime-context'
|
|
42
42
|
import { AuthorshipCell, hasSpecialAuthorship } from './provenance'
|
|
43
|
-
import { humanizeToken, translateMetadataLabel } from './dynamic-columns-helpers'
|
|
43
|
+
import { humanizeToken, resolveColumnOptions, translateMetadataLabel } from './dynamic-columns-helpers'
|
|
44
44
|
import { objectLabel } from './dynamic-relation-helpers'
|
|
45
45
|
import {
|
|
46
46
|
OptionBadge,
|
|
@@ -1004,10 +1004,33 @@ export function makeDefaultGetDynamicColumns(
|
|
|
1004
1004
|
},
|
|
1005
1005
|
]
|
|
1006
1006
|
|
|
1007
|
-
metadata
|
|
1007
|
+
const stageField = lifecycleStageField(metadata)
|
|
1008
|
+
metadata.columns.forEach((rawCol) => {
|
|
1008
1009
|
// Honors both the legacy `hidden` boolean and the kernel's
|
|
1009
1010
|
// `visibility` scope (skips `'modal'` and `'list'`).
|
|
1010
|
-
if (!isColumnVisibleInTable(
|
|
1011
|
+
if (!isColumnVisibleInTable(rawCol)) return
|
|
1012
|
+
|
|
1013
|
+
// Enum/status cells paint from translated option labels: the
|
|
1014
|
+
// column's own options, or the stage labels for the stage column
|
|
1015
|
+
// («Listo», not the humanized raw value «Ready»).
|
|
1016
|
+
const resolvedOptions = resolveColumnOptions({
|
|
1017
|
+
columnKey: rawCol.key,
|
|
1018
|
+
options: rawCol.options as any,
|
|
1019
|
+
stages: metadata.stages,
|
|
1020
|
+
stageField,
|
|
1021
|
+
translate: t,
|
|
1022
|
+
})
|
|
1023
|
+
const fromStages = !!resolvedOptions && !(rawCol.options && rawCol.options.length > 0)
|
|
1024
|
+
const col: typeof rawCol = resolvedOptions
|
|
1025
|
+
? {
|
|
1026
|
+
...rawCol,
|
|
1027
|
+
options: resolvedOptions as any,
|
|
1028
|
+
// A stage column served as plain text paints as a status badge.
|
|
1029
|
+
...(fromStages && !rawCol.cellStyle && (!rawCol.type || rawCol.type === 'text')
|
|
1030
|
+
? { type: 'status' as any }
|
|
1031
|
+
: {}),
|
|
1032
|
+
} as typeof rawCol
|
|
1033
|
+
: rawCol
|
|
1011
1034
|
|
|
1012
1035
|
const translatedLabel = translateMetadataLabel(col.label, t)
|
|
1013
1036
|
const filterConfig = filterConfigs?.get(col.key)
|
package/src/index.ts
CHANGED
|
@@ -418,6 +418,7 @@ export * from './org-runtime-provider'
|
|
|
418
418
|
export * from './navigation-builder'
|
|
419
419
|
export * from './i18n-provider'
|
|
420
420
|
export * from './api-context'
|
|
421
|
+
export * from './cache-coherence'
|
|
421
422
|
export * from './use-addon-settings'
|
|
422
423
|
export * from './use-edge-device'
|
|
423
424
|
export * from './use-print-document'
|