-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathDeploymentRevisionHistoryTab.tsx
More file actions
692 lines (667 loc) · 21.1 KB
/
DeploymentRevisionHistoryTab.tsx
File metadata and controls
692 lines (667 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/**
@license
Copyright (c) 2015-2026 Lablup Inc. All rights reserved.
*/
import type { DeploymentRevisionDetail_revision$key } from '../__generated__/DeploymentRevisionDetail_revision.graphql';
import { DeploymentRevisionHistoryTabActivateMutation } from '../__generated__/DeploymentRevisionHistoryTabActivateMutation.graphql';
import {
DeploymentRevisionHistoryTabListQuery,
ModelRevisionOrderBy,
} from '../__generated__/DeploymentRevisionHistoryTabListQuery.graphql';
import type { DeploymentRevisionHistoryTab_deployment$key } from '../__generated__/DeploymentRevisionHistoryTab_deployment.graphql';
import { convertToOrderBy } from '../helper';
import { useBAISettingUserState } from '../hooks/useBAISetting';
import DeploymentRevisionDetailDrawer from './DeploymentRevisionDetailDrawer';
import QuestionIconWithTooltip from './QuestionIconWithTooltip';
import { LoadingOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { App, Button, Typography, theme } from 'antd';
import {
type BAIColumnType,
BAIFetchKeyButton,
BAIFlex,
BAIGraphQLPropertyFilter,
BAINameActionCell,
BAITable,
BAITag,
BAIUnmountAfterClose,
BAIId,
INITIAL_FETCH_KEY,
type GraphQLFilter,
filterOutNullAndUndefined,
isValidUUID,
toLocalId,
useBAILogger,
useFetchKey,
BAIText,
} from 'backend.ai-ui';
import dayjs from 'dayjs';
import * as _ from 'lodash-es';
import {
parseAsInteger,
parseAsString,
parseAsStringLiteral,
useQueryStates,
} from 'nuqs';
import React, { useState, useTransition } from 'react';
import { useTranslation } from 'react-i18next';
import {
graphql,
useFragment,
useLazyLoadQuery,
useMutation,
} from 'react-relay';
type RevisionNode = NonNullable<
NonNullable<
NonNullable<
NonNullable<
DeploymentRevisionHistoryTabListQuery['response']['deployment']
>['revisionHistory']
>['edges'][number]
>['node']
>;
const availableRevisionSorterKeys = [
'revisionNumber',
'createdAt',
'clusterMode',
'runtimeVariantName',
] as const;
const availableRevisionSorterValues = [
...availableRevisionSorterKeys,
...availableRevisionSorterKeys.map((key) => `-${key}` as const),
] as const;
export interface DeploymentRevisionHistoryTabProps {
deploymentFrgmt: DeploymentRevisionHistoryTab_deployment$key;
deploymentId: string;
isDeploymentDestroying?: boolean;
fetchKey?: string;
}
/**
* Revision history tab for a model deployment detail page.
*
* Lists all revisions of the deployment (current revision highlighted),
* and lets operators roll back to any earlier revision. Rollback is
* executed via the `updateModelDeployment` mutation with the target
* `activeRevisionId` — there is no dedicated rollback mutation in the
* schema; switching the active revision atomically replaces the current
* one. See FR-2678 and spec.md §Flow 5.
*/
const DeploymentRevisionHistoryTab: React.FC<
DeploymentRevisionHistoryTabProps
> = ({
deploymentFrgmt,
deploymentId,
isDeploymentDestroying = false,
fetchKey,
}) => {
'use memo';
const { t } = useTranslation();
const { token } = theme.useToken();
const { modal, message } = App.useApp();
const { logger } = useBAILogger();
const [isPending, startTransition] = useTransition();
const [rollingBackRevisionId, setRollingBackRevisionId] = useState<
string | null
>(null);
const [drawerRevision, setDrawerRevision] = useState<{
frgmt: RevisionNode & DeploymentRevisionDetail_revision$key;
status: 'current' | 'deploying' | 'none';
} | null>(null);
const [columnOverrides, setColumnOverrides] = useBAISettingUserState(
'table_column_overrides.DeploymentRevisionHistoryTab',
);
const [queryParams, setQueryParams] = useQueryStates(
{
current: parseAsInteger.withDefault(1),
pageSize: parseAsInteger.withDefault(10),
order: parseAsStringLiteral(availableRevisionSorterValues),
rvFilter: parseAsString,
},
{
history: 'replace',
urlKeys: {
current: 'rCurrent',
pageSize: 'rPageSize',
order: 'rvOrder',
rvFilter: 'rvFilter',
},
},
);
const deployment = useFragment(
graphql`
fragment DeploymentRevisionHistoryTab_deployment on ModelDeployment {
id
}
`,
deploymentFrgmt,
);
const parseRevisionFilter = (filter: string | null) => {
if (!filter) return null;
try {
const parsed = JSON.parse(filter);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed
: null;
} catch {
return null;
}
};
const stringifyRevisionFilter = (
filter: GraphQLFilter | undefined,
): string => {
if (!filter || Object.keys(filter).length === 0) return '';
return JSON.stringify(filter);
};
const [queryVars, setQueryVars] = useState(() => ({
filter: queryParams.rvFilter
? parseRevisionFilter(queryParams.rvFilter)
: null,
orderBy: convertToOrderBy<ModelRevisionOrderBy>(queryParams.order) ?? [
{ field: 'REVISION_NUMBER', direction: 'DESC' } as ModelRevisionOrderBy,
],
limit: queryParams.pageSize,
offset:
queryParams.current > 1
? (queryParams.current - 1) * queryParams.pageSize
: 0,
}));
const [internalFetchKey, updateInternalFetchKey] = useFetchKey();
const combinedFetchKey = `${fetchKey ?? ''}${internalFetchKey}`;
const isInitialFetch =
(fetchKey === undefined || fetchKey === INITIAL_FETCH_KEY) &&
internalFetchKey === INITIAL_FETCH_KEY;
const { deployment: listData } =
useLazyLoadQuery<DeploymentRevisionHistoryTabListQuery>(
graphql`
query DeploymentRevisionHistoryTabListQuery(
$deploymentId: ID!
$filter: ModelRevisionFilter
$orderBy: [ModelRevisionOrderBy!]
$limit: Int
$offset: Int
) {
deployment(id: $deploymentId) {
currentRevisionId
deployingRevisionId
revisionHistory(
filter: $filter
orderBy: $orderBy
limit: $limit
offset: $offset
) {
count
edges {
node {
id
revisionNumber
createdAt
clusterConfig {
mode
size
}
modelRuntimeConfig {
runtimeVariant {
name
}
}
modelDefinition {
models {
name
metadata {
version
}
}
}
imageV2 {
id
identity {
canonicalName
}
}
modelMountConfig {
vfolderId
vfolder {
id
name
}
}
...DeploymentRevisionDetail_revision
}
}
}
}
}
`,
{ deploymentId, ...queryVars },
{
fetchKey: combinedFetchKey,
fetchPolicy: isInitialFetch ? 'store-and-network' : 'network-only',
},
);
const [commitActivate] =
useMutation<DeploymentRevisionHistoryTabActivateMutation>(graphql`
mutation DeploymentRevisionHistoryTabActivateMutation(
$input: ActivateRevisionInput!
) {
activateDeploymentRevision(input: $input) {
deployment {
id
currentRevisionId
deployingRevisionId
currentRevision @since(version: "26.4.3") {
id
...DeploymentRevisionDetail_revision
}
deployingRevision @since(version: "26.4.3") {
id
...DeploymentRevisionDetail_revision
}
}
previousRevisionId
activatedRevisionId
}
}
`);
const currentRevisionId = listData?.currentRevisionId;
const deployingRevisionId = listData?.deployingRevisionId;
const revisionHistory = listData?.revisionHistory;
const revisions: RevisionNode[] = filterOutNullAndUndefined(
_.map(revisionHistory?.edges, 'node'),
);
const doRefetch = (overrides?: {
filter?: ReturnType<typeof parseRevisionFilter>;
orderBy?: ReturnType<typeof convertToOrderBy<ModelRevisionOrderBy>>;
limit?: number;
offset?: number;
}) => {
startTransition(() => {
setQueryVars((prev) => ({ ...prev, ...overrides }));
});
};
const handleRefresh = () => {
startTransition(() => updateInternalFetchKey());
};
const handleRollback = (revision: RevisionNode): Promise<boolean> => {
return new Promise<boolean>((resolveOuter) => {
modal.confirm({
title: t('deployment.Deploy'),
content: t('deployment.DeployConfirm', {
revisionNumber: revision.revisionNumber,
}),
okText: t('deployment.Deploy'),
okButtonProps: {
danger: true,
},
onCancel: () => resolveOuter(false),
onOk: () => {
return new Promise<void>((resolve) => {
setRollingBackRevisionId(revision.id);
commitActivate({
variables: {
input: {
deploymentId: toLocalId(deployment.id),
revisionId: toLocalId(revision.id),
},
},
onCompleted: (_res, errors) => {
setRollingBackRevisionId(null);
if (errors && errors.length > 0) {
logger.error(errors[0]);
message.error(
errors[0]?.message || t('general.ErrorOccurred'),
);
resolveOuter(false);
resolve();
return;
}
message.success(
t('deployment.DeploySuccess', {
revisionNumber: revision.revisionNumber,
}),
);
handleRefresh();
resolveOuter(true);
resolve();
},
onError: (error) => {
setRollingBackRevisionId(null);
logger.error(error);
message.error(error?.message || t('general.ErrorOccurred'));
resolveOuter(false);
resolve();
},
});
});
},
});
});
};
const columns: BAIColumnType<RevisionNode>[] = [
{
title: (
<BAIFlex gap="xxs" align="center">
{t('deployment.RevisionNumberWithID')}
<QuestionIconWithTooltip
title={t('deployment.RevisionNumberTooltip')}
/>
</BAIFlex>
),
dataIndex: 'revisionNumber',
key: 'revisionNumber',
fixed: 'left',
sorter: true,
render: (_value, record) => {
// `currentRevisionId` and `deployingRevisionId` come back as raw
// UUIDs from the scalar fields, while `record.id` is the
// Strawberry global id (`ModelRevision:<uuid>` base64). Compare
// in the same shape so the disable check actually matches.
const recordLocalId = toLocalId(record.id);
const isCurrent = recordLocalId === currentRevisionId;
const isDeploying = recordLocalId === deployingRevisionId;
const deployDisabledReason =
isCurrent || isDeploying ? t('deployment.DeployDisabled') : undefined;
const isDeployDisabled =
isCurrent ||
isDeploying ||
isDeploymentDestroying ||
rollingBackRevisionId === record.id;
return (
<BAINameActionCell
title={
<BAIFlex gap="xs" align="center">
<Typography.Link
onClick={() =>
setDrawerRevision({
frgmt: record as RevisionNode &
DeploymentRevisionDetail_revision$key,
status: isCurrent
? 'current'
: isDeploying
? 'deploying'
: 'none',
})
}
>
{record.revisionNumber != null
? `#${record.revisionNumber}`
: '-'}
</Typography.Link>
<BAIFlex gap={0} align="center">
{'('}
<BAIId globalId={record.id} />
{')'}
</BAIFlex>
{isCurrent ? (
<BAITag color="success">{t('deployment.Current')}</BAITag>
) : null}
{isDeploying && !isCurrent ? (
// Skip the "Deploying" tag when this revision is also
// the current one — the server briefly leaves
// `deployingRevisionId` set after promotion until the
// reconciler clears it, and showing both tags side by
// side reads as a contradiction.
<BAITag color="warning" icon={<LoadingOutlined spin />}>
{t('deployment.Deploying')}
</BAITag>
) : null}
</BAIFlex>
}
showActions="always"
actions={[
{
key: 'deploy',
title: t('deployment.Deploy'),
icon: <PlayCircleOutlined />,
disabled: isDeployDisabled,
disabledReason: deployDisabledReason,
onClick: () => {
void handleRollback(record);
},
},
]}
/>
);
},
},
{
title: t('general.CreatedAt'),
dataIndex: 'createdAt',
key: 'createdAt',
sorter: true,
render: (value: string | null | undefined) =>
value ? dayjs(value).format('lll') : '-',
},
{
title: t('deployment.ModelVersion'),
key: 'modelVersion',
defaultHidden: true,
render: (_value, record) => {
const model = record.modelDefinition?.models?.[0];
if (!model) return '-';
const name = model.name ?? '-';
// metadata.version is typed as JSON — coerce to a display string
// when present; fall back to name only otherwise.
const rawVersion = model.metadata?.version;
const version =
typeof rawVersion === 'string'
? rawVersion
: rawVersion != null
? String(rawVersion)
: null;
return version ? `${name} (${version})` : name;
},
},
{
title: t('deployment.RuntimeVariant'),
key: 'runtimeVariantName',
dataIndex: 'runtimeVariantName',
sorter: true,
render: (_value, record) =>
record.modelRuntimeConfig?.runtimeVariant?.name ?? '-',
},
{
title: t('deployment.Image'),
key: 'image',
defaultHidden: true,
render: (_value, record) => {
const canonicalName = record.imageV2?.identity?.canonicalName;
const imageGlobalId = record.imageV2?.id;
if (!canonicalName && !imageGlobalId) return '-';
return (
<BAIFlex gap="xs" align="center" wrap="wrap">
{canonicalName ? (
<BAIText
copyable
ellipsis={{ tooltip: canonicalName }}
style={{ maxWidth: 180 }}
>
{canonicalName}
</BAIText>
) : null}
{imageGlobalId ? (
<BAIFlex gap={0} align="center">
{'('}
<BAIId globalId={imageGlobalId} />
{')'}
</BAIFlex>
) : null}
</BAIFlex>
);
},
},
{
title: t('deployment.ModelFolder'),
key: 'modelFolder',
defaultHidden: true,
render: (_value, record) => {
const vfolder = record.modelMountConfig?.vfolder;
const vfolderId = record.modelMountConfig?.vfolderId;
if (!vfolder?.name && !vfolderId) return '-';
return (
<BAIFlex gap="xs" align="center" wrap="wrap">
{vfolder?.name ? (
<Typography.Text>{vfolder.name}</Typography.Text>
) : null}
{vfolder?.id ? (
<BAIFlex gap={0} align="center">
{'('}
<BAIId globalId={vfolder.id} />
{')'}
</BAIFlex>
) : vfolderId ? (
<Typography.Text type="secondary">{vfolderId}</Typography.Text>
) : null}
</BAIFlex>
);
},
},
{
title: (
<BAIFlex gap="xxs" align="center">
{t('deployment.ClusterMode')}
<QuestionIconWithTooltip title={t('deployment.ClusterModeTooltip')} />
</BAIFlex>
),
key: 'clusterMode',
dataIndex: 'clusterMode',
sorter: true,
render: (_value, record) => {
const mode = record.clusterConfig?.mode;
const size = record.clusterConfig?.size;
if (mode == null && size == null) return '-';
if (mode == null) return `${size}`;
if (size == null) return mode;
return `${mode} / ${size}`;
},
},
];
const uuidRule = {
message: t('general.InvalidUUID'),
validate: (value: string) => isValidUUID(value.toLowerCase()),
};
const filterProperties = [
{
key: 'revisionNumber',
propertyLabel: t('deployment.RevisionNumber'),
type: 'number' as const,
},
{
key: 'createdAt',
propertyLabel: t('general.CreatedAt'),
type: 'datetime' as const,
operators: ['after' as const, 'before' as const],
defaultOperator: 'after' as const,
},
{
key: 'clusterMode',
propertyLabel: t('deployment.ClusterMode'),
type: 'string' as const,
},
{
key: 'imageId',
propertyLabel: t('deployment.Image'),
type: 'uuid' as const,
fixedOperator: 'equals' as const,
rule: uuidRule,
},
{
key: 'modelVfolderId',
propertyLabel: t('deployment.ModelFolder'),
type: 'uuid' as const,
fixedOperator: 'equals' as const,
rule: uuidRule,
},
];
const filterValue: GraphQLFilter | undefined = queryParams.rvFilter
? (parseRevisionFilter(queryParams.rvFilter) ?? undefined)
: undefined;
return (
<>
<BAIUnmountAfterClose>
<DeploymentRevisionDetailDrawer
revisionFrgmt={drawerRevision?.frgmt}
status={drawerRevision?.status}
open={!!drawerRevision}
onClose={() => setDrawerRevision(null)}
extra={
drawerRevision ? (
<Button
type="primary"
icon={<PlayCircleOutlined />}
disabled={
drawerRevision.status === 'current' ||
drawerRevision.status === 'deploying' ||
isDeploymentDestroying ||
!!rollingBackRevisionId
}
onClick={async () => {
const success = await handleRollback(drawerRevision.frgmt);
if (success) setDrawerRevision(null);
}}
>
{t('deployment.Deploy')}
</Button>
) : undefined
}
/>
</BAIUnmountAfterClose>
<BAIFlex
justify="between"
align="center"
gap="xs"
style={{ marginBottom: token.marginSM }}
wrap="wrap"
>
<BAIGraphQLPropertyFilter
filterProperties={filterProperties}
value={filterValue}
onChange={(next) => {
const str = stringifyRevisionFilter(next);
const parsed = parseRevisionFilter(str || null);
setQueryParams({ rvFilter: str || null, current: 1 });
doRefetch({ filter: parsed, offset: 0 });
}}
/>
<BAIFetchKeyButton
loading={isPending}
value=""
onChange={() => handleRefresh()}
/>
</BAIFlex>
<BAITable
rowKey="id"
dataSource={revisions}
columns={columns}
loading={isPending}
size="small"
scroll={{ x: 'max-content' }}
tableSettings={{
columnOverrides,
onColumnOverridesChange: setColumnOverrides,
}}
order={queryParams.order ?? undefined}
onChangeOrder={(newOrder) => {
setQueryParams({
order: newOrder as
| (typeof availableRevisionSorterValues)[number]
| null,
});
doRefetch({
orderBy: convertToOrderBy<ModelRevisionOrderBy>(newOrder),
});
}}
pagination={{
pageSize: queryParams.pageSize,
current: queryParams.current,
total: revisionHistory?.count ?? 0,
showSizeChanger: true,
onChange: (current, pageSize) => {
const nextOffset = current > 1 ? (current - 1) * pageSize : 0;
setQueryParams({ current, pageSize });
doRefetch({ limit: pageSize, offset: nextOffset });
},
}}
/>
</>
);
};
export default DeploymentRevisionHistoryTab;