@stacksjs/defaults 0.75.487 → 0.75.490
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/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +27 -2
- package/ai/skills/stacks-native/CATALOG.md +9 -9
- package/ai/skills/stacks-search-engine/SKILL.md +14 -0
- package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
- package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
- package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
- package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
- package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
- package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
- package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
- package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
- package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
- package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
- package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
- package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
- package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
- package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
- package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
- package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
- package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
- package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
- package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
- package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
- package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
- package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
- package/app/Actions/Dashboard/Content/content-list.ts +10 -0
- package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
- package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
- package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
- package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
- package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
- package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
- package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
- package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
- package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
- package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
- package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
- package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
- package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
- package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +9 -6
- package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
- package/app/Actions/Dashboard/Queue/queue-stats.ts +10 -0
- package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
- package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
- package/app/Actions/Dashboard/named-search.test.ts +36 -0
- package/app/Actions/Dashboard/named-search.ts +80 -0
- package/app/Models/QueueWorker.ts +1 -0
- package/app/Models/Request.ts +4 -2
- package/bootstrap.ts +6 -1
- package/functions/commerce/shippings/dashboard-resource.ts +12 -1
- package/functions/commerce/shippings/delivery-routes.ts +1 -0
- package/functions/commerce/shippings/license-keys.ts +1 -0
- package/functions/dashboard-list.test.ts +132 -1
- package/functions/dashboard-list.ts +198 -1
- package/functions/queue.ts +2 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +2 -2
- package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
- package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
- package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
- package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
- package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
- package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
- package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
- package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
- package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
- package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
- package/resources/components/Dashboard/Queue/QueueDashboard.stx +8 -2
- package/resources/functions/dashboard/sidebar.ts +26 -1
- package/routes/dashboard-api.ts +11 -0
- package/views/dashboard/stores/kanban.ts +38 -6
|
@@ -2,19 +2,23 @@ import { describe, expect, it } from 'bun:test'
|
|
|
2
2
|
import { homeStats, orderActivityStatus, serializeHealthCheck, settleEach, summarizeHttpRequests } from './DashboardHomeAction'
|
|
3
3
|
|
|
4
4
|
describe('dashboard HTTP metrics', () => {
|
|
5
|
-
it('summarizes captured
|
|
6
|
-
const metrics = summarizeHttpRequests(12_345,
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
5
|
+
it('summarizes every captured request, as the database counted them', () => {
|
|
6
|
+
const metrics = summarizeHttpRequests({ total: 12_345, successful: 9_876, failed: 2_469, averageDuration: 24.6 })
|
|
7
|
+
|
|
8
|
+
expect(metrics.map(metric => metric.value)).toEqual(['12,345', '25ms', '80.0%', '20.0%'])
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('takes the rates over all requests, not a sample, and says so', () => {
|
|
12
|
+
// A request with no recorded status is neither a success nor a failure,
|
|
13
|
+
// so the two rates need not add up to 100%.
|
|
14
|
+
const metrics = summarizeHttpRequests({ total: 4, successful: 2, failed: 1, averageDuration: 10 })
|
|
12
15
|
|
|
13
|
-
expect(metrics.map(metric => metric.value)).toEqual(['
|
|
16
|
+
expect(metrics.map(metric => metric.value)).toEqual(['4', '10ms', '50.0%', '25.0%'])
|
|
17
|
+
expect(metrics[1]?.detail).toBe('All captured requests')
|
|
14
18
|
})
|
|
15
19
|
|
|
16
20
|
it('returns explicit empty-state metrics', () => {
|
|
17
|
-
expect(summarizeHttpRequests(0,
|
|
21
|
+
expect(summarizeHttpRequests({ total: 0, successful: 0, failed: 0, averageDuration: 0 }).map(metric => metric.value)).toEqual(['0', '0ms', 'N/A', 'N/A'])
|
|
18
22
|
})
|
|
19
23
|
|
|
20
24
|
it('serializes only probed service health', () => {
|
|
@@ -5,23 +5,35 @@ import { checkApplicationHealth, type ApplicationHealthCheck } from '@stacksjs/r
|
|
|
5
5
|
import { formatRelative, safeGet } from '../../../resources/functions/dashboard/data'
|
|
6
6
|
import { dashboardOperationalIssue } from './dashboard-response'
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
/** Totals over every captured request, counted by the database. */
|
|
9
|
+
export interface HttpRequestTotals {
|
|
10
|
+
total: number
|
|
11
|
+
/** 2xx and 3xx responses. */
|
|
12
|
+
successful: number
|
|
13
|
+
/** 4xx and 5xx responses. */
|
|
14
|
+
failed: number
|
|
15
|
+
/** Mean `duration_ms`, or 0 with no requests. */
|
|
16
|
+
averageDuration: number
|
|
11
17
|
}
|
|
12
18
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
+
/**
|
|
20
|
+
* The Home page's request cards, over all captured requests.
|
|
21
|
+
*
|
|
22
|
+
* The rates and the average used to come from the newest 1,000 rows, fetched
|
|
23
|
+
* whole on every visit and averaged here, while the cards beside them said
|
|
24
|
+
* "All captured requests" and the Requests page counted every row. So the two
|
|
25
|
+
* pages disagreed, and the rates' labels did not say they were a sample. Every
|
|
26
|
+
* card now reads the same totals the Requests page does.
|
|
27
|
+
*/
|
|
28
|
+
export function summarizeHttpRequests(totals: HttpRequestTotals) {
|
|
29
|
+
const { total, successful, failed } = totals
|
|
30
|
+
const rate = (count: number) => total > 0 ? `${((count / total) * 100).toFixed(1)}%` : 'N/A'
|
|
19
31
|
|
|
20
32
|
return [
|
|
21
33
|
{ title: 'HTTP Requests', value: total.toLocaleString(), detail: 'All captured requests', icon: 'i-hugeicons-global' },
|
|
22
|
-
{ title: 'Average Response', value: `${averageDuration}ms`, detail:
|
|
23
|
-
{ title: 'Success Rate', value:
|
|
24
|
-
{ title: 'Error Rate', value:
|
|
34
|
+
{ title: 'Average Response', value: `${Math.round(totals.averageDuration)}ms`, detail: 'All captured requests', icon: 'i-hugeicons-clock-01' },
|
|
35
|
+
{ title: 'Success Rate', value: rate(successful), detail: '2xx and 3xx responses', icon: 'i-hugeicons-checkmark-circle-02' },
|
|
36
|
+
{ title: 'Error Rate', value: rate(failed), detail: '4xx and 5xx responses', icon: 'i-hugeicons-alert-02' },
|
|
25
37
|
]
|
|
26
38
|
}
|
|
27
39
|
|
|
@@ -105,7 +117,9 @@ export default new Action({
|
|
|
105
117
|
recentOrders,
|
|
106
118
|
recentUsers,
|
|
107
119
|
requestCount,
|
|
108
|
-
|
|
120
|
+
successfulRequests,
|
|
121
|
+
failedRequests,
|
|
122
|
+
averageDuration,
|
|
109
123
|
] = await settleEach([
|
|
110
124
|
() => User.count(),
|
|
111
125
|
commerce ? () => Product.count() : none,
|
|
@@ -114,18 +128,23 @@ export default new Action({
|
|
|
114
128
|
commerce ? () => Order.orderBy('created_at', 'desc').limit(5).get() : async () => [],
|
|
115
129
|
() => User.orderBy('created_at', 'desc').limit(5).get(),
|
|
116
130
|
() => Request.count(),
|
|
117
|
-
() => Request.
|
|
131
|
+
() => Request.where('status_code', '>=', 200).where('status_code', '<', 400).count(),
|
|
132
|
+
() => Request.where('status_code', '>=', 400).count(),
|
|
133
|
+
() => Request.avg('duration_ms'),
|
|
118
134
|
] as const)
|
|
119
135
|
const healthResult = await Promise.allSettled([checkApplicationHealth()])
|
|
120
136
|
|
|
121
137
|
const stats = homeStats({ users: userCount, products: productCount, revenue: totalRevenue, orders: orderCount }, commerce)
|
|
122
138
|
|
|
123
|
-
const httpMetrics = requestCount.status === 'fulfilled' &&
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
139
|
+
const httpMetrics = requestCount.status === 'fulfilled' && successfulRequests.status === 'fulfilled'
|
|
140
|
+
&& failedRequests.status === 'fulfilled' && averageDuration.status === 'fulfilled'
|
|
141
|
+
? summarizeHttpRequests({
|
|
142
|
+
total: Number(requestCount.value) || 0,
|
|
143
|
+
successful: Number(successfulRequests.value) || 0,
|
|
144
|
+
failed: Number(failedRequests.value) || 0,
|
|
145
|
+
averageDuration: Number(averageDuration.value) || 0,
|
|
146
|
+
})
|
|
147
|
+
: summarizeHttpRequests({ total: 0, successful: 0, failed: 0, averageDuration: 0 })
|
|
129
148
|
|
|
130
149
|
const health = healthResult[0]
|
|
131
150
|
const services = health.status === 'fulfilled'
|
|
@@ -177,7 +196,9 @@ export default new Action({
|
|
|
177
196
|
['Recent orders', recentOrders],
|
|
178
197
|
['Recent users', recentUsers],
|
|
179
198
|
['Request count', requestCount],
|
|
180
|
-
['
|
|
199
|
+
['Successful requests', successfulRequests],
|
|
200
|
+
['Failed requests', failedRequests],
|
|
201
|
+
['Average response', averageDuration],
|
|
181
202
|
]
|
|
182
203
|
const issues = sources
|
|
183
204
|
.map(([source, result]) => issue(source, result))
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
2
|
import { FailedJob, Job } from '@stacksjs/orm'
|
|
3
|
-
import { aggregateWorkerMetrics
|
|
3
|
+
import { aggregateWorkerMetrics } from '@stacksjs/queue'
|
|
4
4
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
5
|
+
import { readDashboardWorkerSnapshots } from '../Queue/worker-snapshots'
|
|
5
6
|
|
|
6
7
|
export default new Action({
|
|
7
8
|
name: 'JobStatsAction',
|
|
@@ -14,7 +15,8 @@ export default new Action({
|
|
|
14
15
|
FailedJob.count(),
|
|
15
16
|
])
|
|
16
17
|
|
|
17
|
-
const
|
|
18
|
+
const workers = await readDashboardWorkerSnapshots()
|
|
19
|
+
const metrics = aggregateWorkerMetrics(workers.snapshots)
|
|
18
20
|
const completedSeen = metrics.counts.completed
|
|
19
21
|
const failedSeen = metrics.counts.failed
|
|
20
22
|
const totalSeen = completedSeen + failedSeen
|
|
@@ -31,6 +33,7 @@ export default new Action({
|
|
|
31
33
|
avgProcessingTime,
|
|
32
34
|
jobsPerMinute: metrics.throughputPerMinute,
|
|
33
35
|
failureRate,
|
|
36
|
+
workersMigrated: workers.migrated,
|
|
34
37
|
// The composable doesn't render a chart, so we omit the synthetic
|
|
35
38
|
// throughput/waitTime arrays the previous handler returned. If you
|
|
36
39
|
// need historical data, persist completion events and serve them
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
1
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
|
-
import {
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
3
4
|
import { kanbanActionError } from './kanban-response'
|
|
5
|
+
import { parseKanbanUserQuery, readKanbanUsers } from './kanban-users'
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* `GET /api/dashboard/kanban/users`.
|
|
7
9
|
*
|
|
8
|
-
*
|
|
10
|
+
* Searchable user list for the assignee picker on the card detail
|
|
9
11
|
* modal. Returns `{ id, name, email }` only — no roles, no profile,
|
|
10
12
|
* no avatars. The modal renders initials from `name`, so anything
|
|
11
13
|
* heavier would be wasted bytes.
|
|
@@ -20,14 +22,16 @@ export default new Action({
|
|
|
20
22
|
description: 'Lightweight user list for the kanban assignee picker.',
|
|
21
23
|
method: 'GET',
|
|
22
24
|
apiResponse: true,
|
|
23
|
-
async handle() {
|
|
25
|
+
async handle(request: RequestInstance) {
|
|
26
|
+
const query = parseKanbanUserQuery(key => request.get<unknown>(key, ''))
|
|
27
|
+
if ('error' in query)
|
|
28
|
+
return response.json({ message: query.error }, 422)
|
|
29
|
+
|
|
24
30
|
try {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return {
|
|
29
|
-
users: (rows ?? []).map(r => ({ id: r.id, name: r.name, email: r.email })),
|
|
30
|
-
}
|
|
31
|
+
// `?q=` searches name and email; `limit` bounds the answer, and `total`
|
|
32
|
+
// says how many matched (kanban-users.ts).
|
|
33
|
+
const { users, total } = await readKanbanUsers(query)
|
|
34
|
+
return { users, total, limit: query.limit }
|
|
31
35
|
}
|
|
32
36
|
catch (err) {
|
|
33
37
|
return kanbanActionError(err, 'UsersListAction')
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { KANBAN_TABLES, kanbanActionError, kanbanNotMigratedMessage, missingKanbanTables } from './kanban-response'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A Kanban action that fails on a database without its tables says which
|
|
6
|
+
* tables and the command that creates them, instead of a generic 500
|
|
7
|
+
* (stacksjs/stacks#3217). Anything else keeps the generic answer, with no
|
|
8
|
+
* database error text in it.
|
|
9
|
+
*/
|
|
10
|
+
describe('kanbanActionError', () => {
|
|
11
|
+
test('missing tables answer 503 naming them and ./buddy migrate', async () => {
|
|
12
|
+
const reply = await kanbanActionError(new Error('relation "card_assignees" does not exist'), 'BoardShowAction', async () => ['card_labels', 'card_assignees'])
|
|
13
|
+
expect(reply.status).toBe(503)
|
|
14
|
+
const body = await reply.json() as { error: string, missingTables: string[] }
|
|
15
|
+
expect(body.missingTables).toEqual(['card_labels', 'card_assignees'])
|
|
16
|
+
expect(body.error).toBe('Kanban is not set up yet: the card_labels and card_assignees tables do not exist. Run ./buddy migrate to create them.')
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
test('with every table present it is the generic 500, and the error text stays out', async () => {
|
|
20
|
+
const reply = await kanbanActionError(new Error('deadlock detected on cards'), 'CardUpdateAction', async () => [])
|
|
21
|
+
expect(reply.status).toBe(500)
|
|
22
|
+
const body = await reply.json() as { error: string }
|
|
23
|
+
expect(body.error).toBe('The Kanban request could not be completed.')
|
|
24
|
+
expect(JSON.stringify(body)).not.toContain('deadlock')
|
|
25
|
+
})
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
describe('missingKanbanTables', () => {
|
|
29
|
+
test('asks about every Kanban table and keeps their order', async () => {
|
|
30
|
+
const asked: string[] = []
|
|
31
|
+
const missing = await missingKanbanTables(async (table) => { asked.push(table); return table.startsWith('card_') })
|
|
32
|
+
expect(asked).toEqual([...KANBAN_TABLES])
|
|
33
|
+
expect(missing).toEqual(['card_labels', 'card_assignees', 'card_comments', 'card_attachments'])
|
|
34
|
+
})
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
test('the message reads naturally for one table and for several', () => {
|
|
38
|
+
expect(kanbanNotMigratedMessage(['boards'])).toBe('Kanban is not set up yet: the boards table does not exist. Run ./buddy migrate to create them.')
|
|
39
|
+
expect(kanbanNotMigratedMessage(['a', 'b', 'c'])).toBe('Kanban is not set up yet: the a, b and c tables do not exist. Run ./buddy migrate to create them.')
|
|
40
|
+
})
|
|
@@ -1,11 +1,63 @@
|
|
|
1
1
|
import type { ResponseStatus } from '@stacksjs/bun-router'
|
|
2
2
|
import { response } from '@stacksjs/router'
|
|
3
|
+
import { isUnmigratedTable } from '../Models/model-migration'
|
|
3
4
|
|
|
4
5
|
export function kanbanError(error: string, status: ResponseStatus): Response {
|
|
5
6
|
return response.json({ error }, status)
|
|
6
7
|
}
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Every table a Kanban board reads or writes. All of them are the dashboard
|
|
11
|
+
* feature's, so one `./buddy migrate` creates the lot. `card_labels` and
|
|
12
|
+
* `card_assignees` are pivots with no model of their own.
|
|
13
|
+
*/
|
|
14
|
+
export const KANBAN_TABLES = [
|
|
15
|
+
'boards',
|
|
16
|
+
'board_columns',
|
|
17
|
+
'cards',
|
|
18
|
+
'labels',
|
|
19
|
+
'card_labels',
|
|
20
|
+
'card_assignees',
|
|
21
|
+
'card_comments',
|
|
22
|
+
'card_attachments',
|
|
23
|
+
'feedback_tokens',
|
|
24
|
+
] as const
|
|
25
|
+
|
|
26
|
+
/** The Kanban tables the catalog says are missing, in `KANBAN_TABLES` order. */
|
|
27
|
+
export async function missingKanbanTables(isMissing: (table: string) => Promise<boolean> = isUnmigratedTable): Promise<string[]> {
|
|
28
|
+
const missing: string[] = []
|
|
29
|
+
for (const table of KANBAN_TABLES) {
|
|
30
|
+
if (await isMissing(table))
|
|
31
|
+
missing.push(table)
|
|
32
|
+
}
|
|
33
|
+
return missing
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function kanbanNotMigratedMessage(tables: string[]): string {
|
|
37
|
+
const list = tables.length === 1 ? `the ${tables[0]} table does not` : `the ${tables.slice(0, -1).join(', ')} and ${tables.at(-1)} tables do not`
|
|
38
|
+
return `Kanban is not set up yet: ${list} exist. Run ./buddy migrate to create them.`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The response for a Kanban action that failed.
|
|
43
|
+
*
|
|
44
|
+
* Asked only after a failure: if the catalog reports Kanban tables missing, the
|
|
45
|
+
* answer names them and the command, with status 503, because nothing is wrong
|
|
46
|
+
* that a migration does not fix. A board could be created and then neither
|
|
47
|
+
* opened nor deleted, each saying only "could not be completed"
|
|
48
|
+
* (stacksjs/stacks#3217). Any other failure, including a catalog check that
|
|
49
|
+
* fails too, is logged and answered with the generic 500, so an outage is never
|
|
50
|
+
* relabelled as a migrate hint and no database error text reaches the page.
|
|
51
|
+
*/
|
|
52
|
+
export async function kanbanActionError(
|
|
53
|
+
error: unknown,
|
|
54
|
+
action: string,
|
|
55
|
+
missing: () => Promise<string[]> = missingKanbanTables,
|
|
56
|
+
): Promise<Response> {
|
|
57
|
+
const tables = await missing()
|
|
58
|
+
if (tables.length > 0)
|
|
59
|
+
return response.json({ error: kanbanNotMigratedMessage(tables), missingTables: tables }, 503)
|
|
60
|
+
|
|
9
61
|
console.error(`[dashboard/kanban] ${action} failed:`, error)
|
|
10
62
|
return kanbanError('The Kanban request could not be completed.', 500)
|
|
11
63
|
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { KanbanUserRunner } from './kanban-users'
|
|
5
|
+
import { containsPattern } from '../Content/content-list'
|
|
6
|
+
import { parseKanbanUserQuery, readKanbanUsers } from './kanban-users'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The assignee picker's search, against each dialect's real engine
|
|
10
|
+
* (stacksjs/stacks#3216): case-insensitive over name and email, wildcards
|
|
11
|
+
* taken literally, bounded, with the full match count.
|
|
12
|
+
*/
|
|
13
|
+
const USERS: Array<[string | null, string]> = [
|
|
14
|
+
['Ava Stone', 'ava@example.com'],
|
|
15
|
+
['ben carter', 'BEN@Example.com'],
|
|
16
|
+
['Cara 100% Sure', 'cara@example.com'],
|
|
17
|
+
['Dan_Under', 'dan@example.com'],
|
|
18
|
+
// These two are what an unescaped pattern would wrongly match: `n_u` with
|
|
19
|
+
// `_` as a wildcard matches "n u", and `100%` matches "1000".
|
|
20
|
+
['Dan Under', 'danunder@example.com'],
|
|
21
|
+
['Cara 1000 Sure', 'cara1000@example.com'],
|
|
22
|
+
['Dana Undertow', 'dana@example.com'],
|
|
23
|
+
[null, 'nameless@example.com'],
|
|
24
|
+
['Émile Zola', 'emile@example.com'],
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
async function exercise(run: KanbanUserRunner, dialect: 'sqlite' | 'postgres' | 'mysql') {
|
|
28
|
+
const read = (q: string, limit = 25) => readKanbanUsers({ search: q, limit }, run, dialect)
|
|
29
|
+
|
|
30
|
+
const all = await read('')
|
|
31
|
+
expect(all.total).toBe(USERS.length)
|
|
32
|
+
expect(all.users.map(user => user.email)).toContain('nameless@example.com')
|
|
33
|
+
|
|
34
|
+
// Case is ignored on both columns.
|
|
35
|
+
expect((await read('BEN')).users.map(user => user.email)).toEqual(['BEN@Example.com'])
|
|
36
|
+
expect((await read('example.com')).total).toBe(USERS.length)
|
|
37
|
+
|
|
38
|
+
// `%` and `_` are characters to find, not wildcards.
|
|
39
|
+
expect((await read('100%')).users.map(user => user.name)).toEqual(['Cara 100% Sure'])
|
|
40
|
+
expect((await read('n_u')).users.map(user => user.name)).toEqual(['Dan_Under'])
|
|
41
|
+
|
|
42
|
+
// A user with no name is found by email.
|
|
43
|
+
expect((await read('nameless')).users).toEqual([expect.objectContaining({ name: null, email: 'nameless@example.com' })])
|
|
44
|
+
|
|
45
|
+
// The limit bounds the rows; the total still counts every match.
|
|
46
|
+
const limited = await read('a', 2)
|
|
47
|
+
expect(limited.users).toHaveLength(2)
|
|
48
|
+
expect(limited.total).toBeGreaterThan(2)
|
|
49
|
+
|
|
50
|
+
// Nothing matches is an empty page, not an error.
|
|
51
|
+
expect(await read('zzzz-nobody')).toEqual({ users: [], total: 0 })
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
describe('readKanbanUsers on SQLite', () => {
|
|
55
|
+
test('searches, bounds and counts', async () => {
|
|
56
|
+
const database = new Database(':memory:')
|
|
57
|
+
database.run('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)')
|
|
58
|
+
for (const [name, email] of USERS)
|
|
59
|
+
database.query('INSERT INTO users (name, email) VALUES (?, ?)').run(name, email)
|
|
60
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as string[])) }) }, 'sqlite')
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
65
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
66
|
+
|
|
67
|
+
test.skipIf(!connection)(`readKanbanUsers on ${dialect} searches, bounds and counts`, async () => {
|
|
68
|
+
const url = new URL(connection!)
|
|
69
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
70
|
+
throw new Error('Kanban user tests require a local disposable database server')
|
|
71
|
+
|
|
72
|
+
const name = `stacks_kanban_users_${crypto.randomUUID().replaceAll('-', '')}`
|
|
73
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
74
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
75
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
76
|
+
const scoped = new URL(url.href)
|
|
77
|
+
scoped.pathname = `/${name}`
|
|
78
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
79
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
await database.unsafe(dialect === 'mysql'
|
|
83
|
+
? 'CREATE TABLE users (id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NULL, email VARCHAR(255) NULL) CHARACTER SET utf8mb4'
|
|
84
|
+
: 'CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT, email TEXT)')
|
|
85
|
+
for (const [userName, email] of USERS)
|
|
86
|
+
await database.unsafe(`INSERT INTO users (name, email) VALUES (${dialect === 'postgres' ? '$1, $2' : '?, ?'})`, [userName, email])
|
|
87
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
await database.close()
|
|
91
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
92
|
+
finally { await admin.close() }
|
|
93
|
+
}
|
|
94
|
+
}, 30_000)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
describe('parseKanbanUserQuery', () => {
|
|
98
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
99
|
+
|
|
100
|
+
test('defaults to an unfiltered page of 25', () => {
|
|
101
|
+
expect(parseKanbanUserQuery(reader({}))).toEqual({ search: '', limit: 25 })
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
test('rejects a limit out of range and an over-long search', () => {
|
|
105
|
+
expect(parseKanbanUserQuery(reader({ limit: '0' }))).toHaveProperty('error')
|
|
106
|
+
expect(parseKanbanUserQuery(reader({ limit: '101' }))).toHaveProperty('error')
|
|
107
|
+
expect(parseKanbanUserQuery(reader({ limit: 'ten' }))).toHaveProperty('error')
|
|
108
|
+
expect(parseKanbanUserQuery(reader({ q: 'x'.repeat(201) }))).toHaveProperty('error')
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
test('the pattern escapes its own wildcards and lowercases', () => {
|
|
112
|
+
expect(containsPattern('A_b%c!d')).toBe('%a!_b!%c!!d%')
|
|
113
|
+
})
|
|
114
|
+
})
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import type { QueryReader } from '../Content/content-list'
|
|
3
|
+
import type { NamedRow, NamedSearchQuery, NamedSearchRunner } from '../named-search'
|
|
4
|
+
import { NAMED_SEARCH_LIMIT, NAMED_SEARCH_MAX_LIMIT, parseNamedSearchQuery, searchNamedRows } from '../named-search'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The users the card dialog's assignee picker offers.
|
|
8
|
+
*
|
|
9
|
+
* It used to load the first 500 users by name, once, with no search: in an app
|
|
10
|
+
* with more, everyone past the 500th could not be assigned, and nothing said
|
|
11
|
+
* so (stacksjs/stacks#3216). Now the picker asks the database through the
|
|
12
|
+
* shared name and email search (`named-search.ts`).
|
|
13
|
+
*/
|
|
14
|
+
export const KANBAN_USER_LIMIT = NAMED_SEARCH_LIMIT
|
|
15
|
+
export const KANBAN_USER_MAX_LIMIT = NAMED_SEARCH_MAX_LIMIT
|
|
16
|
+
|
|
17
|
+
export type KanbanUserQuery = NamedSearchQuery
|
|
18
|
+
export type KanbanUser = NamedRow
|
|
19
|
+
export type KanbanUserRunner = NamedSearchRunner
|
|
20
|
+
|
|
21
|
+
export function parseKanbanUserQuery(read: QueryReader): KanbanUserQuery | { error: string } {
|
|
22
|
+
return parseNamedSearchQuery(read)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function readKanbanUsers(
|
|
26
|
+
query: KanbanUserQuery,
|
|
27
|
+
runner?: KanbanUserRunner,
|
|
28
|
+
dialect?: QueryBuilderDialect,
|
|
29
|
+
): Promise<{ users: KanbanUser[], total: number }> {
|
|
30
|
+
const { rows, total } = await searchNamedRows('users', query, runner, dialect)
|
|
31
|
+
return { users: rows, total }
|
|
32
|
+
}
|
|
@@ -5,6 +5,7 @@ import { response as routerResponse } from '@stacksjs/router'
|
|
|
5
5
|
import { safeGet } from '../../../../resources/functions/dashboard/data'
|
|
6
6
|
import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
|
|
7
7
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
8
|
+
import { isUnmigratedTable } from './model-migration'
|
|
8
9
|
import { isValidModelSlug, type ModelCreateField, type ModelWriteCapabilities, modelCreateFields, modelSchemaColumns, modelWritableColumns, modelWriteCapabilities, slugToPascal } from './model-write'
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -56,6 +57,8 @@ interface ResponseShape {
|
|
|
56
57
|
writeCapabilities: ModelWriteCapabilities
|
|
57
58
|
createFields: ModelCreateField[]
|
|
58
59
|
updateColumns: string[]
|
|
60
|
+
/** False when the model's table does not exist yet: `./buddy migrate` creates it. */
|
|
61
|
+
migrated: boolean
|
|
59
62
|
error: string | null
|
|
60
63
|
}
|
|
61
64
|
|
|
@@ -214,6 +217,7 @@ export default new Action({
|
|
|
214
217
|
writeCapabilities: { create: false, update: false, destroy: false },
|
|
215
218
|
createFields: [],
|
|
216
219
|
updateColumns: [],
|
|
220
|
+
migrated: true,
|
|
217
221
|
error: null,
|
|
218
222
|
}
|
|
219
223
|
|
|
@@ -296,6 +300,10 @@ export default new Action({
|
|
|
296
300
|
})
|
|
297
301
|
}
|
|
298
302
|
catch (error) {
|
|
303
|
+
// Not an error to report: the table simply has not been created yet, and
|
|
304
|
+
// the page says so and names the command that creates it.
|
|
305
|
+
if (await isUnmigratedTable(response.tableName))
|
|
306
|
+
return { ...response, columns: [], rows: [], migrated: false }
|
|
299
307
|
return dashboardOperationalError(error, `${modelName} records could not be loaded.`, 'ModelShowAction.query')
|
|
300
308
|
}
|
|
301
309
|
|
|
@@ -4,6 +4,7 @@ import { resolveModelSources } from '@stacksjs/database/model-sources'
|
|
|
4
4
|
import { countRows } from '../../../../resources/functions/dashboard/data'
|
|
5
5
|
import { dashboardOperationalError, dashboardOperationalIssue } from '../dashboard-response'
|
|
6
6
|
import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
|
|
7
|
+
import { isUnmigratedTable } from './model-migration'
|
|
7
8
|
import { modelApiConfiguration } from './model-api'
|
|
8
9
|
|
|
9
10
|
/**
|
|
@@ -32,6 +33,8 @@ interface ModelRow {
|
|
|
32
33
|
source: 'userland' | 'framework'
|
|
33
34
|
apiUri: string
|
|
34
35
|
apiRoutes: string[]
|
|
36
|
+
/** False when the model's table does not exist yet. Its count is `null`, and it is not an error. */
|
|
37
|
+
migrated: boolean
|
|
35
38
|
error: string | null
|
|
36
39
|
}
|
|
37
40
|
|
|
@@ -91,6 +94,7 @@ function unavailableModelRow(model: DiscoveredModel, error: string): ModelRow {
|
|
|
91
94
|
source: model.source,
|
|
92
95
|
apiUri: '',
|
|
93
96
|
apiRoutes: [],
|
|
97
|
+
migrated: true,
|
|
94
98
|
error,
|
|
95
99
|
}
|
|
96
100
|
}
|
|
@@ -138,18 +142,25 @@ export default new Action({
|
|
|
138
142
|
dashboardOperationalIssue(error, 'Model metadata could not be loaded.', `ModelsIndexAction.metadata.${m.name}`),
|
|
139
143
|
)
|
|
140
144
|
}
|
|
145
|
+
const table = String(Model.table || pluralize(pascalToSnake(m.name)))
|
|
141
146
|
let count: number | null = null
|
|
142
147
|
let error: string | null = null
|
|
148
|
+
let migrated = true
|
|
143
149
|
try {
|
|
144
150
|
count = await countRows(Model)
|
|
145
151
|
}
|
|
146
152
|
catch (cause) {
|
|
147
|
-
|
|
153
|
+
// A table that was never migrated is reported as that, without logging
|
|
154
|
+
// a driver error for it on every visit to this page.
|
|
155
|
+
if (await isUnmigratedTable(table))
|
|
156
|
+
migrated = false
|
|
157
|
+
else
|
|
158
|
+
error = dashboardOperationalIssue(cause, 'Model count could not be loaded.', `ModelsIndexAction.count.${m.name}`)
|
|
148
159
|
}
|
|
149
160
|
|
|
150
161
|
return {
|
|
151
162
|
name: m.name,
|
|
152
|
-
table
|
|
163
|
+
table,
|
|
153
164
|
href: `/models/${pascalToKebab(m.name)}`,
|
|
154
165
|
count,
|
|
155
166
|
attributeCount: Object.keys(Model.attributes || {}).length,
|
|
@@ -157,6 +168,7 @@ export default new Action({
|
|
|
157
168
|
source: m.source,
|
|
158
169
|
apiUri: api.uri ? `/api/${api.uri}` : '',
|
|
159
170
|
apiRoutes: api.routes,
|
|
171
|
+
migrated,
|
|
160
172
|
error,
|
|
161
173
|
}
|
|
162
174
|
}))
|
|
@@ -168,6 +180,7 @@ export default new Action({
|
|
|
168
180
|
const totalRecords = enriched.reduce((sum, m) => sum + (m.count ?? 0), 0)
|
|
169
181
|
const userlandCount = enriched.filter(m => m.source === 'userland').length
|
|
170
182
|
const unavailableModels = enriched.filter(m => m.error !== null).length
|
|
183
|
+
const unmigratedModels = enriched.filter(m => !m.migrated).length
|
|
171
184
|
|
|
172
185
|
const groupMap = new Map<string, ModelRow[]>()
|
|
173
186
|
for (const m of enriched) {
|
|
@@ -192,6 +205,7 @@ export default new Action({
|
|
|
192
205
|
totalRecords,
|
|
193
206
|
userlandCount,
|
|
194
207
|
unavailableModels,
|
|
208
|
+
unmigratedModels,
|
|
195
209
|
categoryGroups,
|
|
196
210
|
}
|
|
197
211
|
},
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { isUnmigratedTable } from './model-migration'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The models pages answer "not migrated" instead of a 503 only when the
|
|
6
|
+
* catalog says the table is missing. Anything less certain must keep the
|
|
7
|
+
* original error, so a real outage is never relabelled as a migrate hint.
|
|
8
|
+
*/
|
|
9
|
+
describe('isUnmigratedTable', () => {
|
|
10
|
+
test('a table the catalog does not have is unmigrated', async () => {
|
|
11
|
+
expect(await isUnmigratedTable('menus', async () => false)).toBeTrue()
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
test('a table the catalog has is not, so its failure stays an error', async () => {
|
|
15
|
+
expect(await isUnmigratedTable('users', async () => true)).toBeFalse()
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
test('a catalog check that fails too keeps the original error', async () => {
|
|
19
|
+
expect(await isUnmigratedTable('users', async () => { throw new Error('connection refused') })).toBeFalse()
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
test('the table it asks about is the one it was given', async () => {
|
|
23
|
+
const asked: string[] = []
|
|
24
|
+
await isUnmigratedTable('usage_events', async (table) => { asked.push(table); return false })
|
|
25
|
+
expect(asked).toEqual(['usage_events'])
|
|
26
|
+
})
|
|
27
|
+
})
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { tableExists } from '@stacksjs/database/runtime'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Whether a model's query failed because its table was never migrated.
|
|
5
|
+
*
|
|
6
|
+
* Asked only after a query has already failed, so a working page pays nothing.
|
|
7
|
+
* The answer comes from the catalog (`tableExists`), not the error's wording.
|
|
8
|
+
* A catalog check that fails too answers `false`, so the original error is
|
|
9
|
+
* reported as it was rather than replaced by a migrate hint.
|
|
10
|
+
*
|
|
11
|
+
* A framework model whose feature an app has not migrated is normal, not an
|
|
12
|
+
* outage: the dashboard lists every model the framework ships, and a fresh
|
|
13
|
+
* app has migrated only some of them. Reporting each as a 503 made every such
|
|
14
|
+
* page look broken and logged a full driver error for it on every request.
|
|
15
|
+
*/
|
|
16
|
+
export async function isUnmigratedTable(table: string, exists: (table: string) => Promise<boolean> = tableExists): Promise<boolean> {
|
|
17
|
+
try {
|
|
18
|
+
return !(await exists(table))
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return false
|
|
22
|
+
}
|
|
23
|
+
}
|