Compare commits

5 Commits

Author SHA1 Message Date
Ivan Li
243b0d7b8d feat: v0.1.1 2021-06-27 19:48:09 +08:00
Ivan Li
653d779efb feat(pipelines): edit view. 2021-06-27 00:27:57 +08:00
Ivan Li
120a720be5 feat: f**k the __typename :) 2021-06-26 23:30:09 +08:00
Ivan Li
dee2c97ba4 feat(commit-list): stop task. 2021-06-20 15:42:03 +08:00
Ivan Li
6bc9f787f3 feat(pipeline-task): 实时展示执行日志 2021-06-06 22:41:56 +08:00
16 changed files with 834 additions and 63 deletions

38
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "fennec-bs", "name": "fennec-bs",
"version": "0.1.0", "version": "0.1.1",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "fennec-bs", "name": "fennec-bs",
"version": "0.1.0", "version": "0.1.1",
"dependencies": { "dependencies": {
"@apollo/client": "^3.3.15", "@apollo/client": "^3.3.15",
"@curi/react-dom": "^2.0.4", "@curi/react-dom": "^2.0.4",
@@ -52,7 +52,8 @@
"@graphql-codegen/typescript": "1.21.1", "@graphql-codegen/typescript": "1.21.1",
"@graphql-codegen/typescript-operations": "1.17.15", "@graphql-codegen/typescript-operations": "1.17.15",
"@graphql-codegen/typescript-react-apollo": "2.2.3", "@graphql-codegen/typescript-react-apollo": "2.2.3",
"@types/ramda": "^0.27.40", "@types/date-fns": "^2.6.0",
"@types/ramda": "^0.27.41",
"@types/yup": "^0.29.11", "@types/yup": "^0.29.11",
"autoprefixer": "^9.8.6", "autoprefixer": "^9.8.6",
"postcss": "^7.0.35" "postcss": "^7.0.35"
@@ -4129,6 +4130,16 @@
"@babel/types": "^7.3.0" "@babel/types": "^7.3.0"
} }
}, },
"node_modules/@types/date-fns": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@types/date-fns/-/date-fns-2.6.0.tgz",
"integrity": "sha1-sGLKRlYgApCb4MY6ZGftFzE2rME=",
"deprecated": "This is a stub types definition for date-fns (https://github.com/date-fns/date-fns). date-fns provides its own type definitions, so you don't need @types/date-fns installed!",
"dev": true,
"dependencies": {
"date-fns": "*"
}
},
"node_modules/@types/eslint": { "node_modules/@types/eslint": {
"version": "7.2.10", "version": "7.2.10",
"resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-7.2.10.tgz", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-7.2.10.tgz",
@@ -4276,9 +4287,9 @@
"integrity": "sha512-1HcDas8SEj4z1Wc696tH56G8OlRaH/sqZOynNNB+HF0WOeXPaxTtbYzJY2oEfiUxjSKjhCKr+MvR7dCHcEelug==" "integrity": "sha512-1HcDas8SEj4z1Wc696tH56G8OlRaH/sqZOynNNB+HF0WOeXPaxTtbYzJY2oEfiUxjSKjhCKr+MvR7dCHcEelug=="
}, },
"node_modules/@types/ramda": { "node_modules/@types/ramda": {
"version": "0.27.40", "version": "0.27.41",
"resolved": "https://registry.npmjs.org/@types/ramda/-/ramda-0.27.40.tgz", "resolved": "https://registry.npmjs.org/@types/ramda/-/ramda-0.27.41.tgz",
"integrity": "sha512-V99ZfTH2tqVYdLDAlgh2uT+N074HPgqnAsMjALKSBqogYd0HbuuGMqNukJ6fk9Ml/Htaus76fsc4Yh3p7q1VdQ==", "integrity": "sha512-SxKnQzrPmA5ly2BvHrTE5BvZEkQgs3kSYBcscWUOWP9FGVDGVdzlWXpiSBJhzBxe0pFQ/amM4cjFRi9R5PFoQg==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"ts-toolbelt": "^6.15.1" "ts-toolbelt": "^6.15.1"
@@ -28526,6 +28537,15 @@
"@babel/types": "^7.3.0" "@babel/types": "^7.3.0"
} }
}, },
"@types/date-fns": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@types/date-fns/-/date-fns-2.6.0.tgz",
"integrity": "sha1-sGLKRlYgApCb4MY6ZGftFzE2rME=",
"dev": true,
"requires": {
"date-fns": "*"
}
},
"@types/eslint": { "@types/eslint": {
"version": "7.2.10", "version": "7.2.10",
"resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-7.2.10.tgz", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-7.2.10.tgz",
@@ -28673,9 +28693,9 @@
"integrity": "sha512-1HcDas8SEj4z1Wc696tH56G8OlRaH/sqZOynNNB+HF0WOeXPaxTtbYzJY2oEfiUxjSKjhCKr+MvR7dCHcEelug==" "integrity": "sha512-1HcDas8SEj4z1Wc696tH56G8OlRaH/sqZOynNNB+HF0WOeXPaxTtbYzJY2oEfiUxjSKjhCKr+MvR7dCHcEelug=="
}, },
"@types/ramda": { "@types/ramda": {
"version": "0.27.40", "version": "0.27.41",
"resolved": "https://registry.npmjs.org/@types/ramda/-/ramda-0.27.40.tgz", "resolved": "https://registry.npmjs.org/@types/ramda/-/ramda-0.27.41.tgz",
"integrity": "sha512-V99ZfTH2tqVYdLDAlgh2uT+N074HPgqnAsMjALKSBqogYd0HbuuGMqNukJ6fk9Ml/Htaus76fsc4Yh3p7q1VdQ==", "integrity": "sha512-SxKnQzrPmA5ly2BvHrTE5BvZEkQgs3kSYBcscWUOWP9FGVDGVdzlWXpiSBJhzBxe0pFQ/amM4cjFRi9R5PFoQg==",
"dev": true, "dev": true,
"requires": { "requires": {
"ts-toolbelt": "^6.15.1" "ts-toolbelt": "^6.15.1"

View File

@@ -1,6 +1,6 @@
{ {
"name": "fennec-bs", "name": "fennec-bs",
"version": "0.1.0", "version": "0.1.1",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@apollo/client": "^3.3.15", "@apollo/client": "^3.3.15",
@@ -73,7 +73,8 @@
"@graphql-codegen/typescript": "1.21.1", "@graphql-codegen/typescript": "1.21.1",
"@graphql-codegen/typescript-operations": "1.17.15", "@graphql-codegen/typescript-operations": "1.17.15",
"@graphql-codegen/typescript-react-apollo": "2.2.3", "@graphql-codegen/typescript-react-apollo": "2.2.3",
"@types/ramda": "^0.27.40", "@types/date-fns": "^2.6.0",
"@types/ramda": "^0.27.41",
"@types/yup": "^0.29.11", "@types/yup": "^0.29.11",
"autoprefixer": "^9.8.6", "autoprefixer": "^9.8.6",
"postcss": "^7.0.35" "postcss": "^7.0.35"

View File

@@ -3,6 +3,7 @@ import { Link, useResponse, useRouter } from "@curi/react-dom";
import { faPlayCircle, faVial } from "@fortawesome/free-solid-svg-icons"; import { faPlayCircle, faVial } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { import {
Backdrop,
CircularProgress, CircularProgress,
Collapse, Collapse,
IconButton, IconButton,
@@ -14,12 +15,14 @@ import {
ListItemText, ListItemText,
makeStyles, makeStyles,
useTheme, useTheme,
withStyles,
} from "@material-ui/core"; } from "@material-ui/core";
import { import {
Cancel, Cancel,
CheckCircle, CheckCircle,
CloudDownload, CloudDownload,
ShoppingCart, ShoppingCart,
Stop,
Timer, Timer,
} from "@material-ui/icons"; } from "@material-ui/icons";
import { format } from "date-fns"; import { format } from "date-fns";
@@ -28,6 +31,7 @@ import { complement, equals, find, propEq, takeWhile } from "ramda";
import { import {
FC, FC,
Fragment, Fragment,
MouseEventHandler,
ReactNode, ReactNode,
useCallback, useCallback,
useMemo, useMemo,
@@ -41,7 +45,7 @@ import {
TaskStatuses, TaskStatuses,
PipelineUnits, PipelineUnits,
} from "../generated/graphql"; } from "../generated/graphql";
import { CREATE_PIPELINE_TASK } from "./mutations"; import { CREATE_PIPELINE_TASK, STOP_PIPELINE_TASK } from "./mutations";
import { COMMITS } from "./queries"; import { COMMITS } from "./queries";
import { SYNC_COMMITS } from "./subscriptions"; import { SYNC_COMMITS } from "./subscriptions";
@@ -229,6 +233,20 @@ const TaskItem: FC<{ task: PipelineTask }> = ({ task }) => {
); );
} }
})(); })();
const [stopTask, { loading: stopTaskWaiting }] = useMutation(
STOP_PIPELINE_TASK,
{
variables: { taskId: task.id },
}
);
const stop: MouseEventHandler = useCallback(
(event) => {
event.stopPropagation();
event.preventDefault();
stopTask();
},
[stopTask]
);
return ( return (
<ListItem button className={classes.nested}> <ListItem button className={classes.nested}>
<ListItemIcon>{statusIcon}</ListItemIcon> <ListItemIcon>{statusIcon}</ListItemIcon>
@@ -237,6 +255,20 @@ const TaskItem: FC<{ task: PipelineTask }> = ({ task }) => {
task.startedAt && format(task.startedAt, "yyyy-MM-dd HH:mm:ss") task.startedAt && format(task.startedAt, "yyyy-MM-dd HH:mm:ss")
} }
/> />
<ListItemSecondaryAction>
{task.status === TaskStatuses.Working && (
<IconButton edge="end" aria-label="stop" onClick={stop}>
<Stop />
</IconButton>
)}
</ListItemSecondaryAction>
<LimitedBackdrop open={stopTaskWaiting} />
</ListItem> </ListItem>
); );
}; };
const LimitedBackdrop = withStyles({
root: {
position: "absolute",
zIndex: 1,
},
})(Backdrop);

View File

@@ -9,4 +9,9 @@ export const CREATE_PIPELINE_TASK = gql`
endedAt endedAt
} }
} }
` `;
export const STOP_PIPELINE_TASK = gql`
mutation StopPipelineTask($taskId: String!) {
stopPipelineTask(id: $taskId)
}
`;

View File

@@ -15,15 +15,28 @@ import { onError } from "@apollo/client/link/error";
import { WebSocketLink } from "@apollo/client/link/ws"; import { WebSocketLink } from "@apollo/client/link/ws";
import { getMainDefinition } from "@apollo/client/utilities"; import { getMainDefinition } from "@apollo/client/utilities";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { deepOmit } from "../../utils/deep-omit";
const schema = buildClientSchema( const schema = buildClientSchema(
(introspectionResult as unknown) as IntrospectionQuery introspectionResult as unknown as IntrospectionQuery
); );
const typesMap = { const typesMap = {
DateTime: DateTimeResolver, DateTime: DateTimeResolver,
}; };
const cleanTypeName = new ApolloLink((operation, forward) => {
if (operation.variables) {
operation.variables = deepOmit(["__typename"], operation.variables);
}
const rt = forward(operation);
return (
rt.map?.((data) => {
return data;
}) ?? rt
);
});
export const FennecApolloClientProvider: FC = ({ children }) => { export const FennecApolloClientProvider: FC = ({ children }) => {
const { enqueueSnackbar } = useSnackbar(); const { enqueueSnackbar } = useSnackbar();
const errorLink = onError(({ graphQLErrors, networkError }) => { const errorLink = onError(({ graphQLErrors, networkError }) => {
@@ -70,13 +83,30 @@ export const FennecApolloClientProvider: FC = ({ children }) => {
); );
const link = ApolloLink.from([ const link = ApolloLink.from([
errorLink, errorLink,
(withScalars({ schema, typesMap }) as unknown) as ApolloLink, withScalars({ schema, typesMap }) as unknown as ApolloLink,
cleanTypeName,
splitLink, splitLink,
]); ]);
const client = new ApolloClient({ const client = new ApolloClient({
connectToDevTools: true,
ssrMode: typeof window === "undefined", ssrMode: typeof window === "undefined",
link, link,
cache: new InMemoryCache(), cache: new InMemoryCache({
typePolicies: {
// PipelineTaskLogs: {
// keyFields: ["unit"],
// },
// PipelineTask: {
// fields: {
// logs: {
// merge(existing = [], incoming: any[]) {
// return [...existing, ...incoming];
// },
// },
// },
// },
},
}),
}); });
return <ApolloProvider client={client}>{children}</ApolloProvider>; return <ApolloProvider client={client}>{children}</ApolloProvider>;

View File

@@ -718,7 +718,7 @@
"description": null, "description": null,
"args": [ "args": [
{ {
"name": "Pipeline", "name": "pipeline",
"description": null, "description": null,
"type": { "type": {
"kind": "NON_NULL", "kind": "NON_NULL",
@@ -1144,6 +1144,22 @@
}, },
"isDeprecated": false, "isDeprecated": false,
"deprecationReason": null "deprecationReason": null
},
{
"name": "runOn",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
} }
], ],
"inputFields": null, "inputFields": null,
@@ -1156,6 +1172,54 @@
"name": "PipelineTaskEvent", "name": "PipelineTaskEvent",
"description": null, "description": null,
"fields": [ "fields": [
{
"name": "taskId",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "pipelineId",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "projectId",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{ {
"name": "unit", "name": "unit",
"description": null, "description": null,
@@ -1168,6 +1232,54 @@
"isDeprecated": false, "isDeprecated": false,
"deprecationReason": null "deprecationReason": null
}, },
{
"name": "emittedAt",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "DateTime",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "message",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "messageType",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{ {
"name": "status", "name": "status",
"description": null, "description": null,
@@ -2137,7 +2249,7 @@
"name": null, "name": null,
"ofType": { "ofType": {
"kind": "SCALAR", "kind": "SCALAR",
"name": "Float", "name": "Int",
"ofType": null "ofType": null
} }
}, },
@@ -2174,6 +2286,16 @@
"enumValues": null, "enumValues": null,
"possibleTypes": null "possibleTypes": null
}, },
{
"kind": "SCALAR",
"name": "Int",
"description": "The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{ {
"kind": "INPUT_OBJECT", "kind": "INPUT_OBJECT",
"name": "WorkUnitMetadataInput", "name": "WorkUnitMetadataInput",
@@ -2185,7 +2307,7 @@
"description": null, "description": null,
"type": { "type": {
"kind": "SCALAR", "kind": "SCALAR",
"name": "Float", "name": "Int",
"ofType": null "ofType": null
}, },
"defaultValue": "1", "defaultValue": "1",

View File

@@ -99,7 +99,7 @@ export type MutationCreatePipelineArgs = {
export type MutationUpdatePipelineArgs = { export type MutationUpdatePipelineArgs = {
Pipeline: UpdatePipelineInput; pipeline: UpdatePipelineInput;
}; };
@@ -138,11 +138,18 @@ export type PipelineTask = {
status: TaskStatuses; status: TaskStatuses;
startedAt?: Maybe<Scalars['DateTime']>; startedAt?: Maybe<Scalars['DateTime']>;
endedAt?: Maybe<Scalars['DateTime']>; endedAt?: Maybe<Scalars['DateTime']>;
runOn: Scalars['String'];
}; };
export type PipelineTaskEvent = { export type PipelineTaskEvent = {
__typename?: 'PipelineTaskEvent'; __typename?: 'PipelineTaskEvent';
taskId: Scalars['String'];
pipelineId: Scalars['String'];
projectId: Scalars['String'];
unit?: Maybe<PipelineUnits>; unit?: Maybe<PipelineUnits>;
emittedAt: Scalars['DateTime'];
message: Scalars['String'];
messageType: Scalars['String'];
status: TaskStatuses; status: TaskStatuses;
}; };
@@ -277,11 +284,11 @@ export type WorkUnitInput = {
export type WorkUnitMetadata = { export type WorkUnitMetadata = {
__typename?: 'WorkUnitMetadata'; __typename?: 'WorkUnitMetadata';
version: Scalars['Float']; version: Scalars['Int'];
units: Array<WorkUnit>; units: Array<WorkUnit>;
}; };
export type WorkUnitMetadataInput = { export type WorkUnitMetadataInput = {
version?: Maybe<Scalars['Float']>; version?: Maybe<Scalars['Int']>;
units: Array<WorkUnitInput>; units: Array<WorkUnitInput>;
}; };

View File

@@ -1,9 +1,16 @@
import { gql, useQuery } from "@apollo/client"; import { gql, useQuery, useSubscription } from "@apollo/client";
import { LinearProgress, makeStyles, Typography } from "@material-ui/core"; import { LinearProgress, makeStyles, Typography } from "@material-ui/core";
import { format } from 'date-fns'; import { format } from "date-fns";
import React, { FC } from "react"; import { FC, useState } from "react";
import { ErrorPage } from "../commons/fallbacks/error-page"; import { ErrorPage } from "../commons/fallbacks/error-page";
import { PipelineTask, PipelineTaskLogs } from "../generated/graphql"; import {
PipelineTask,
PipelineTaskEvent,
PipelineTaskLogs,
TaskStatuses,
} from "../generated/graphql";
import { PIPELINE_TASK_EVENT } from "./subscriptions";
import { clone, find, propEq } from "ramda";
interface Props { interface Props {
taskId: string; taskId: string;
@@ -30,30 +37,111 @@ const PIPELINE_TASK = gql`
`; `;
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
root: { root: {},
},
groupTitle: { groupTitle: {
backgroundColor: 'white', backgroundColor: "white",
fontWeight: 500, fontWeight: 500,
borderTop: '1px solid #eee', borderTop: "1px solid #eee",
fontSize: '16px', fontSize: "16px",
padding: '12px', padding: "12px",
marginLeft: '1px', marginLeft: "1px",
}, },
logText: { logText: {
fontFamily: 'Menlo, Monaco, "Courier New", monospace', fontFamily: 'Menlo, Monaco, "Courier New", monospace',
whiteSpace: 'pre-wrap', whiteSpace: "pre-wrap",
border: 'none', border: "none",
margin: '6px 12px', margin: "6px 12px",
display: "block" display: "block",
}, },
})); }));
export const PipelineTaskDetail: FC<Props> = ({ taskId }) => { export const PipelineTaskDetail: FC<Props> = ({ taskId }) => {
const { data, loading, error } = useQuery<{ pipelineTask: PipelineTask }>( const [taskEvents, setTaskEvents] = useState(
PIPELINE_TASK, () => new Array<PipelineTaskEvent>()
);
const { data, loading, error, client } = useQuery<{
pipelineTask: PipelineTask;
}>(PIPELINE_TASK, {
variables: { taskId },
});
const task = data?.pipelineTask;
useSubscription<{ pipelineTaskEvent: PipelineTaskEvent }>(
PIPELINE_TASK_EVENT,
{ {
variables: { taskId }, variables: { taskId },
onSubscriptionData({ subscriptionData: { data } }) {
const event = data?.pipelineTaskEvent;
console.log(event);
if (event && task) {
setTaskEvents((prev) => [...prev, event]);
if (event.unit) {
// event of running scripts
client.cache.modify({
id: client.cache.identify(task!),
fields: {
logs(before: PipelineTaskLogs[]) {
before = clone(before);
let l = find(propEq("unit", event.unit), before);
if (l) {
l.logs += event.message;
} else {
l = {
unit: event.unit!,
logs: event.message,
status: event.status,
startedAt: event.emittedAt,
endedAt: null,
__typename: "PipelineTaskLogs",
};
before.push(l);
}
if (event.status === TaskStatuses.Working) {
l.startedAt || (l.startedAt = event.emittedAt);
}
if (
[TaskStatuses.Failed, TaskStatuses.Success].includes(
event.status
)
) {
l.startedAt && (l.startedAt = event.emittedAt);
l.endedAt = event.emittedAt;
}
l.status = event.status;
return before;
},
},
});
} else {
// event of task status change
client.cache.modify({
id: client.cache.identify(task!),
fields: {
status() {
return event.status;
},
startedAt(before) {
if (event.status === TaskStatuses.Working) {
return event.emittedAt;
} else {
return before;
}
},
endedAt(before) {
if (
[TaskStatuses.Success, TaskStatuses.Failed].includes(
event.status
)
) {
return event.emittedAt;
} else {
return before;
}
},
},
});
}
}
},
} }
); );
const classes = useStyles(); const classes = useStyles();
@@ -71,8 +159,15 @@ export const PipelineTaskDetail: FC<Props> = ({ taskId }) => {
<Typography variant="h4" component="h2"> <Typography variant="h4" component="h2">
{taskId} detail {taskId} detail
</Typography> </Typography>
<Typography variant="h5" component="h3">
{task?.status}
</Typography>
<Typography variant="h5" component="h3">
{task?.startedAt && format(task?.startedAt, "yyyy-MM-dd HH:mm:ss.SSS")}-
{task?.endedAt && format(task?.endedAt, "yyyy-MM-dd HH:mm:ss.SSS")}
</Typography>
{data?.pipelineTask.logs.map((logs) => ( {task?.logs.map((logs) => (
<LogGroup key={logs.unit} logs={logs} /> <LogGroup key={logs.unit} logs={logs} />
))} ))}
</div> </div>
@@ -84,7 +179,9 @@ const LogGroup: FC<{ logs: PipelineTaskLogs }> = ({ logs }) => {
return ( return (
<div> <div>
<div className={classes.groupTitle}> <div className={classes.groupTitle}>
{logs.unit} {format(logs.startedAt, 'yyyy-MM-dd HH:mm:ss')} {logs.status} {logs.unit}{" "}
{logs.startedAt && format(logs.startedAt, "yyyy-MM-dd HH:mm:ss")}{" "}
{logs.endedAt && format(logs.endedAt, "yyyy-MM-dd HH:mm:ss")} {logs.status}
</div> </div>
<code className={classes.logText}>{logs.logs}</code> <code className={classes.logText}>{logs.logs}</code>
</div> </div>

View File

@@ -0,0 +1,16 @@
import { gql } from "@apollo/client";
export const PIPELINE_TASK_EVENT = gql`
subscription PipelineTaskEvent($taskId: String!) {
pipelineTaskEvent(taskId: $taskId) {
taskId
pipelineId
projectId
unit
emittedAt
message
messageType
status
}
}
`;

View File

@@ -0,0 +1,43 @@
import { gql } from "@apollo/client";
export const CREATE_PIPELINE = gql`
mutation CreatePipeline($pipeline: CreatePipelineInput!) {
createPipeline(pipeline: $pipeline) {
id
projectId
branch
name
workUnitMetadata {
version
units {
type
scripts
}
}
}
}
`;
export const UPDATE_PIPELINE = gql`
mutation UpdatePipeline($pipeline: UpdatePipelineInput!) {
updatePipeline(pipeline: $pipeline) {
id
projectId
branch
name
workUnitMetadata {
version
units {
type
scripts
}
}
}
}
`;
export const DELETE_PIPELINE = gql`
mutation DeletePipeline($id: String!) {
deletePipeline(id: $id)
}
`;

View File

@@ -0,0 +1,285 @@
import { gql, Reference, useMutation, useQuery } from "@apollo/client";
import { useRouter } from "@curi/react-dom";
import {
Button,
Grid,
IconButton,
LinearProgress,
makeStyles,
Paper,
Portal,
Typography,
} from "@material-ui/core";
import { Delete } from "@material-ui/icons";
import { FormikHelpers, Formik, Form, Field } from "formik";
import { TextField, TextFieldProps } from "formik-material-ui";
import { TextField as MuiTextField } from "@material-ui/core";
import { useConfirm } from "material-ui-confirm";
import { useSnackbar } from "notistack";
import { not, omit } from "ramda";
import { ChangeEvent, FC } from "react";
import {
Pipeline,
WorkUnitMetadata,
PipelineUnits,
} from "../generated/graphql";
import { useHeaderContainer } from "../layouts";
import { CREATE_PIPELINE, DELETE_PIPELINE, UPDATE_PIPELINE } from "./mutations";
import { PIPELINE } from "./queries";
import * as Yup from "yup";
import { useField } from "formik";
type Values = Partial<Pipeline>;
interface Props {
pipeline: Values;
}
const useStyles = makeStyles((theme) => ({
root: {
flex: "1 1 100%",
},
nested: {
paddingLeft: theme.spacing(4),
},
form: {
margin: 16,
},
metadataList: {
padding: 0,
},
metadataItem: {
listStyle: "none",
},
metadataContainer: {
padding: "10px 30px",
margin: "10px 0",
},
}));
export const PipelineEditor: FC<Props> = ({ pipeline }) => {
const { enqueueSnackbar } = useSnackbar();
const isCreate = not("id" in pipeline);
const [createPipeline] = useMutation<{ createPipeline: Pipeline }>(
CREATE_PIPELINE,
{
update(cache, { data }) {
cache.modify({
fields: {
pipelines(exiting = []) {
const pipelineRef = cache.writeFragment({
data: data!.createPipeline,
fragment: gql`
fragment newPipeline on Pipeline {
id
projectId
branch
name
workUnitMetadata {
version
units {
type
scripts
}
}
}
`,
});
return [pipelineRef, ...exiting];
},
},
});
},
}
);
const [updatePipeline] = useMutation(UPDATE_PIPELINE);
const router = useRouter();
const submitForm = async (
values: Values,
formikHelpers: FormikHelpers<Values>
) => {
try {
let pipelineId = pipeline.id;
let projectId = pipeline.projectId;
if (isCreate) {
await createPipeline({
variables: {
input: values,
},
}).then(({ data }) => {
pipelineId = data!.createPipeline.id;
projectId = data!.createPipeline.projectId;
});
} else {
await updatePipeline({
variables: {
pipeline: omit(["projectId"], values),
},
});
}
enqueueSnackbar("Saved successfully", {
variant: "success",
});
router.navigate({
url: router.url({
name: "pipeline-commits",
params: {
pipelineId,
projectId,
},
}),
method: "replace",
});
} finally {
formikHelpers.setSubmitting(false);
}
};
const [deletePipeline, { loading: deleting }] = useMutation(DELETE_PIPELINE, {
variables: { id: pipeline.id },
update(cache) {
cache.modify({
fields: {
projects(exiting: Reference[] = [], { readField }) {
return exiting.filter(
(ref) => pipeline.id !== readField("id", ref)
);
},
},
});
},
});
const confirm = useConfirm();
const handleDelete = async () => {
try {
await confirm({ description: `This will delete ${pipeline.name}.` });
await deletePipeline();
enqueueSnackbar("Deleted successfully", {
variant: "success",
});
router.navigate({
url: router.url({
name: "dashboard",
}),
});
} catch {}
};
const headerContainer = useHeaderContainer();
const units = [
PipelineUnits.Checkout,
PipelineUnits.InstallDependencies,
PipelineUnits.Test,
PipelineUnits.Deploy,
PipelineUnits.CleanUp,
];
const classes = useStyles();
return (
<Paper className={classes.root}>
<Portal container={headerContainer}>
<Grid container justify="space-between" alignItems="center">
<Typography variant="h6" component="h1">
{isCreate ? "Create" : "Edit"} Pipeline
</Typography>
{isCreate ? null : (
<IconButton
color="inherit"
onClick={handleDelete}
disabled={deleting}
>
<Delete />
</IconButton>
)}
</Grid>
</Portal>
<Formik
initialValues={pipeline}
validationSchema={Yup.object({
name: Yup.string()
.max(32, "Must be 32 characters or less")
.required("Required"),
branch: Yup.string()
.max(32, "Must be 32 characters or less")
.required("Required"),
})}
onSubmit={submitForm}
>
{({ submitForm, isSubmitting, values }) => {
return (
<Form className={classes.form}>
<Field component={TextField} name="name" label="Name" fullWidth />
<Field
component={TextField}
name="branch"
label="Branch"
fullWidth
margin="normal"
/>
<Paper className={classes.metadataContainer}>
<Field
component={TextField}
name="workUnitMetadata.version"
label="Version"
fullWidth
readonly
margin="normal"
/>
<ol className={classes.metadataList}>
{units.map((unit, index) => {
return (
<li key={unit} className={classes.metadataItem}>
<Field
name={`workUnitMetadata.units[${index}].scripts]`}
component={ScriptsField}
label={`${unit} Scripts`}
fullWidth
multiline
margin="normal"
/>
</li>
);
})}
</ol>
</Paper>
{isSubmitting && <LinearProgress />}
<Button
variant="contained"
color="primary"
disabled={isSubmitting}
onClick={submitForm}
fullWidth
>
Submit
</Button>
</Form>
);
}}
</Formik>
</Paper>
);
};
const ScriptsField: FC<TextFieldProps> = ({ field, form, meta, ...props }) => {
return (
<TextField
{...props}
form={form}
meta={meta}
field={{
...field,
value: field.value?.join("\n") ?? "",
onChange: (ev: ChangeEvent<HTMLInputElement>) =>
form.setFieldValue(
field.name,
ev.target.value?.split("\n").map((it) => it.trim()) ?? []
),
}}
/>
);
};

View File

@@ -1,9 +1,18 @@
import { gql, useQuery } from '@apollo/client'; import { gql, useQuery } from "@apollo/client";
import { Link } from '@curi/react-dom'; import { Link, useRouter } from "@curi/react-dom";
import { List, ListItem, Typography, ListItemText } from '@material-ui/core'; import {
import { FC } from 'react'; List,
import { Pipeline } from '../generated/graphql'; ListItem,
import { CallMerge } from '@material-ui/icons'; Typography,
ListItemText,
ListItemSecondaryAction,
IconButton,
} from "@material-ui/core";
import { FC, MouseEventHandler, useMemo } from "react";
import { Pipeline, Project } from "../generated/graphql";
import { CallMerge, Edit } from "@material-ui/icons";
import { clone } from "ramda";
import { useEffect } from "react";
interface Props { interface Props {
projectId: string; projectId: string;
@@ -16,16 +25,28 @@ const PIPELINES = gql`
name name
branch branch
} }
project(id: $projectId) {
id
} }
` }
`;
export const PipelineList: FC<Props> = ({ projectId }) => { export const PipelineList: FC<Props> = ({ projectId }) => {
const {data, loading} = useQuery<{pipelines: Pipeline[]}, {projectId: string}>(PIPELINES, { const { data, loading } = useQuery<
variables: {projectId} { pipelines: Pipeline[]; project: Project },
}) { projectId: string }
>(PIPELINES, {
variables: { projectId },
});
const pipelines = useMemo(() => {
return data?.pipelines?.map((pipeline) => ({
...pipeline,
project: data?.project,
}));
}, [data]);
return ( return (
<List> <List>
{data?.pipelines.map((pipeline) => ( {pipelines?.map((pipeline) => (
<Link <Link
name="pipeline-commits" name="pipeline-commits"
params={{ pipelineId: pipeline.id, projectId: projectId }} params={{ pipelineId: pipeline.id, projectId: projectId }}
@@ -36,10 +57,19 @@ export const PipelineList: FC<Props> = ({ projectId }) => {
))} ))}
</List> </List>
); );
} };
const Item = ({pipeline}: {pipeline: Pipeline}) => {
const Item = ({ pipeline }: { pipeline: Pipeline }) => {
const { navigate, url } = useRouter();
const modify: MouseEventHandler = (ev) => {
ev.preventDefault();
navigate({
url: url({
name: "edit-pipeline",
params: { pipelineId: pipeline.id, projectId: pipeline.project.id },
}),
});
};
return ( return (
<ListItem button> <ListItem button>
<ListItemText <ListItemText
@@ -51,6 +81,11 @@ const Item = ({pipeline}: {pipeline: Pipeline}) => {
</Typography> </Typography>
} }
/> />
<ListItemSecondaryAction>
<IconButton edge="end" aria-label="edit" onClick={modify}>
<Edit />
</IconButton>
</ListItemSecondaryAction>
</ListItem> </ListItem>
); );
} };

View File

@@ -5,6 +5,7 @@ export const PIPELINE = gql`
pipeline(id: $id) { pipeline(id: $id) {
id id
name name
projectId
branch branch
workUnitMetadata { workUnitMetadata {
version version
@@ -15,4 +16,4 @@ export const PIPELINE = gql`
} }
} }
} }
` `;

View File

@@ -60,12 +60,17 @@ export const ProjectDetail: FC<Props> = ({ project, children }) => {
alignItems="stretch" alignItems="stretch"
className={classes.root} className={classes.root}
> >
<Grid item lg={1} style={{ height: "100%", display: "flex" }}> <Grid item xs={3} lg={2} style={{ height: "100%", display: "flex" }}>
<Paper className={classes.pipelineListContainer}> <Paper className={classes.pipelineListContainer}>
<PipelineList projectId={project.id} /> <PipelineList projectId={project.id} />
</Paper> </Paper>
</Grid> </Grid>
<Grid item xs={10} lg={11} style={{ height: "100%", display: "flex", overflowY: 'auto' }}> <Grid
item
xs={9}
lg={10}
style={{ height: "100%", display: "flex", overflowY: "auto" }}
>
{children} {children}
</Grid> </Grid>
</Grid> </Grid>

View File

@@ -1,12 +1,19 @@
import { ApolloClient, InMemoryCache } from "@apollo/client"; import { ApolloClient, InMemoryCache } from "@apollo/client";
import { prepareRoutes } from "@curi/router"; import { prepareRoutes } from "@curi/router";
import { omit } from 'ramda'; import { omit } from 'ramda';
import React from 'react'; import React from "react";
import { CreateProjectInput, Pipeline, Project } from './generated/graphql';
import { ProjectDetail, ProjectEditor, PROJECT } from "./projects"; import { ProjectDetail, ProjectEditor, PROJECT } from "./projects";
import { COMMIT_LIST_QUERY } from './commons/graphql/queries'; import { COMMIT_LIST_QUERY } from './commons/graphql/queries';
import { CommitList } from './commits/commit-list'; import { CommitList } from './commits/commit-list';
import { PipelineTaskDetail } from './pipeline-tasks/pipeline-task-detail'; import { PipelineTaskDetail } from './pipeline-tasks/pipeline-task-detail';
import { PipelineEditor } from "./pipelines/pipeline-editor";
import {
CreatePipelineInput,
CreateProjectInput,
Pipeline,
Project,
} from "./generated/graphql";
import { PIPELINE } from "./pipelines";
export default prepareRoutes([ export default prepareRoutes([
{ {
@@ -51,6 +58,49 @@ export default prepareRoutes([
return resolved; return resolved;
}, },
}, // edit-project }, // edit-project
{
name: "create-pipeline",
path: "projects/:projectId/pipelines/create",
async resolve(
matched,
{ client }: { client: ApolloClient<InMemoryCache> }
) {
const input: CreatePipelineInput = {
name: "",
branch: "",
projectId: matched!.params.projectId,
workUnitMetadata: {
version: 1,
units: [],
},
};
return {
body: () => <PipelineEditor pipeline={input as any} />,
};
},
respond({ resolved }) {
return resolved;
},
}, // create-pipeline
{
name: "edit-pipeline",
path: "projects/:projectId/pipelines/:pipelineId/edit",
async resolve(
matched,
{ client }: { client: ApolloClient<InMemoryCache> }
) {
const { data } = await client.query<{ pipeline: Pipeline }>({
query: PIPELINE,
variables: { id: matched?.params.pipelineId },
});
return {
body: () => <PipelineEditor pipeline={data.pipeline} />,
};
},
respond({ resolved }) {
return resolved;
},
}, // edit-pipeline
{ {
name: "project-detail", name: "project-detail",
path: "projects/:projectId", path: "projects/:projectId",
@@ -100,7 +150,7 @@ export default prepareRoutes([
respond({ resolved, error }) { respond({ resolved, error }) {
return resolved || <div>Failed</div>; return resolved || <div>Failed</div>;
}, },
}, }, // pipeline-commits
{ {
name: "pipeline-task-detail", name: "pipeline-task-detail",
path: "pipelines/:pipelineId/tasks/:taskId", path: "pipelines/:pipelineId/tasks/:taskId",
@@ -129,7 +179,7 @@ export default prepareRoutes([
respond({ resolved, error }) { respond({ resolved, error }) {
return resolved || <div>Failed</div>; return resolved || <div>Failed</div>;
}, },
}, }, // pipeline-task-detail
], ],
}, // project-detail }, // project-detail
]); ]);

22
src/utils/deep-omit.ts Normal file
View File

@@ -0,0 +1,22 @@
import { fromPairs, map, omit, pipe, toPairs, type } from "ramda";
export const deepOmit = <T = any, K = any>(
names: readonly string[],
value: K
): T => {
switch (type(value)) {
case "Array":
return (value as unknown as Array<any>).map((item: any) =>
deepOmit(names, item)
) as unknown as T;
case "Object":
return pipe(
omit(names),
toPairs,
map(([key, val]) => [key, deepOmit(names, val)] as any),
fromPairs
)(value) as unknown as T;
default:
return value as unknown as T;
}
};