Skip to content

Commit

Permalink
[DT-1423] Send signal input payload to data encoder (#1671)
Browse files Browse the repository at this point in the history
* Fix spacing on even details row

* Encode signal input if codec configured

* Handle and show error if encoding fails

* Clear signal input on close

* Check response for ok

* Set default value for signal input and refactor hard to read conditional

* Add resetView to CodeBlock  and reset on hide signal modal

* Default signal input to empty strings
  • Loading branch information
laurakwhit authored Oct 11, 2023
1 parent 15cfcbc commit 44ed7e4
Show file tree
Hide file tree
Showing 7 changed files with 117 additions and 29 deletions.
2 changes: 1 addition & 1 deletion src/lib/components/event/event-details-row.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
>
{#if typeof value === 'object'}
<div
class="flex w-full flex-wrap items-center justify-between pr-1 xl:flex-nowrap xl:gap-4"
class="flex w-full flex-wrap items-center justify-between gap-1 pr-1 xl:flex-nowrap xl:gap-4"
>
<p class="min-w-fit text-sm">
{format(key)}
Expand Down
27 changes: 23 additions & 4 deletions src/lib/components/workflow-actions.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@
} from '$lib/services/workflow-service';
import { authUser } from '$lib/stores/auth-user';
import { coreUserStore } from '$lib/stores/core-user';
import {
codecEndpoint,
includeCredentials,
passAccessToken,
} from '$lib/stores/data-encoder-config';
import { resetEvents } from '$lib/stores/events';
import { resetWorkflows } from '$lib/stores/reset-workflows';
import { settings } from '$lib/stores/settings';
Expand All @@ -40,8 +45,11 @@
export let cancelInProgress: boolean;
export let isRunning: boolean;
const getDefaultSignalInput = () =>
$codecEndpoint ? '{"metadata": {"encoding": ""}, "data": ""}' : '';
let reason = '';
let signalInput = '';
let signalInput = getDefaultSignalInput();
let signalName = '';
let cancelConfirmationModalOpen = false;
let terminateConfirmationModalOpen = false;
Expand All @@ -53,6 +61,7 @@
let resetReason: string;
let loading = false;
let resetTooltipText: string;
let signalInputCodeBlock: CodeBlock;
$: cancelEnabled = workflowCancelEnabled($page.data.settings);
$: signalEnabled = workflowSignalEnabled($page.data.settings);
Expand All @@ -64,8 +73,9 @@
};
const hideSignalModal = () => {
signalInput = '';
signalInput = getDefaultSignalInput();
signalName = '';
signalInputCodeBlock?.resetView(signalInput);
};
const hideResetModal = () => {
Expand Down Expand Up @@ -139,18 +149,26 @@
runId: workflow.runId,
signalInput,
signalName,
settings: {
...$page.data.settings,
codec: {
endpoint: $codecEndpoint,
includeCredentials: $includeCredentials,
passAccessToken: $passAccessToken,
},
},
accessToken: $authUser.accessToken,
});
signalConfirmationModalOpen = false;
$refresh = Date.now();
toaster.push({
message: translate('workflows', 'signal-success'),
id: 'workflow-signal-success-toast',
});
hideSignalModal();
} catch (err) {
error = err?.message ?? translate('unknown-error');
}
hideSignalModal();
};
const reset = async () => {
Expand Down Expand Up @@ -383,6 +401,7 @@
on:change={handleSignalInputChange}
editable
copyable={false}
bind:this={signalInputCodeBlock}
/>
</div>
</div>
Expand Down
14 changes: 11 additions & 3 deletions src/lib/holocene/code-block.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,10 @@
return stringifyWithBigInt(parsedData, undefined, inline ? 0 : 2);
};
$: value = language === 'json' ? formatJSON(content) : content;
const formatValue = ({ value, language }) =>
language === 'json' ? formatJSON(value) : value;
$: value = formatValue({ value: content, language });
const createEditorView = (): EditorView => {
return new EditorView({
Expand Down Expand Up @@ -127,10 +130,15 @@
view = createEditorView();
});
export const resetView = (value = '', format = true) => {
const formattedValue = format ? formatValue({ value, language }) : value;
const newState = createEditorState(formattedValue);
view.setState(newState);
};
const setView = () => {
if (view && !editable) {
const newState = createEditorState(value);
view.setState(newState);
resetView(value, false);
}
};
Expand Down
2 changes: 2 additions & 0 deletions src/lib/i18n/locales/en/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ export const Strings = {
timeline: 'Timeline',
'equal-to': 'Equal to',
'not-equal-to': 'Not equal to',
'encode-failed': 'Data encoding failed',
'decode-failed': 'Data decoding failed',
'job-id': 'Job ID',
'auto-refresh': 'Auto refresh',
'auto-refresh-tooltip': '{{ interval }} second page refresh',
Expand Down
27 changes: 22 additions & 5 deletions src/lib/services/data-encoder.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { translate } from '$lib/i18n/translate';
import {
setLastDataEncoderFailure,
setLastDataEncoderSuccess,
} from '$lib/stores/data-encoder-config';
import type { Settings } from '$lib/types/global';
import type { NetworkError, Settings } from '$lib/types/global';
import { has } from '$lib/utilities/has';
import { validateHttps } from '$lib/utilities/is-http';
import { stringifyWithBigInt } from '$lib/utilities/parse-with-big-int';

Expand All @@ -13,11 +15,13 @@ export async function convertPayloadsWithCodec({
namespace,
settings,
accessToken,
encode = false,
}: {
payloads: PotentialPayloads;
namespace: string;
settings: Settings;
accessToken: string;
encode?: boolean;
}): Promise<PotentialPayloads> {
const endpoint = settings?.codec?.endpoint;
const passAccessToken = settings?.codec?.passAccessToken;
Expand Down Expand Up @@ -51,17 +55,30 @@ export async function convertPayloadsWithCodec({
};

const encoderResponse: Promise<PotentialPayloads> = fetch(
endpoint + '/decode',
endpoint + (encode ? '/encode' : '/decode'),
requestOptions,
)
.then((r) => r.json())
.then((response) => {
if (has(response, 'ok') && !response.ok) {
throw {
statusCode: response.status,
statusText: response.statusText,
response,
message: encode
? translate('encode-failed')
: translate('decode-failed'),
} as NetworkError;
} else {
return response.json();
}
})
.then((response) => {
setLastDataEncoderSuccess();

return response;
})
.catch(() => {
setLastDataEncoderFailure();
.catch((err: unknown) => {
setLastDataEncoderFailure(err);

return payloads;
});
Expand Down
63 changes: 48 additions & 15 deletions src/lib/services/workflow-service.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import { noop } from 'svelte/internal';
import { get } from 'svelte/store';

import { v4 } from 'uuid';

import { translate } from '$lib/i18n/translate';
import type { ResetReapplyType } from '$lib/models/workflow-actions';
import {
toWorkflowExecution,
toWorkflowExecutions,
} from '$lib/models/workflow-execution';
import { convertPayloadsWithCodec } from '$lib/services/data-encoder';
import {
lastDataEncoderError,
lastDataEncoderStatus,
} from '$lib/stores/data-encoder-config';
import type { ResetWorkflowRequest } from '$lib/types';
import type {
ValidWorkflowEndpoints,
ValidWorkflowParameters,
} from '$lib/types/api';
import type { NamespaceScopedRequest, Replace } from '$lib/types/global';
import type {
NamespaceScopedRequest,
Replace,
Settings,
} from '$lib/types/global';
import type {
ArchiveFilterParameters,
ListWorkflowExecutionsResponse,
Expand All @@ -26,10 +37,8 @@ import {
} from '$lib/utilities/handle-error';
import { stringifyWithBigInt } from '$lib/utilities/parse-with-big-int';
import { toListWorkflowQuery } from '$lib/utilities/query/list-workflow-query';
import {
type ErrorCallback,
requestFromAPI,
} from '$lib/utilities/request-from-api';
import type { ErrorCallback } from '$lib/utilities/request-from-api';
import { requestFromAPI } from '$lib/utilities/request-from-api';
import { base, pathForApi, routeForApi } from '$lib/utilities/route-for-api';

export type GetWorkflowExecutionRequest = NamespaceScopedRequest & {
Expand All @@ -55,6 +64,8 @@ type SignalWorkflowOptions = {
runId: string;
signalName: string;
signalInput: string;
settings: Settings;
accessToken: string;
};

type TerminateWorkflowOptions = {
Expand Down Expand Up @@ -293,30 +304,52 @@ export async function signalWorkflow({
runId,
signalName,
signalInput,
settings,
accessToken,
}: SignalWorkflowOptions) {
const route = routeForApi('workflow.signal', {
namespace,
workflowId,
runId,
});

let payloads = null;

if (signalInput) {
if (settings?.codec?.endpoint) {
const awaitData = await convertPayloadsWithCodec({
payloads: { payloads: [JSON.parse(signalInput)] },
namespace,
settings,
accessToken,
encode: true,
});
if (get(lastDataEncoderStatus) === 'error') {
throw new Error(
get(lastDataEncoderError) || translate('encode-failed'),
);
}
payloads = awaitData?.payloads ?? null;
} else {
payloads = [
{
metadata: {
encoding: btoa('json/plain'),
},
data: btoa(signalInput),
},
];
}
}

return requestFromAPI(route, {
notifyOnError: false,
options: {
method: 'POST',
body: stringifyWithBigInt({
signalName,
input: {
payloads: signalInput
? [
{
metadata: {
encoding: btoa('json/plain'),
},
data: btoa(signalInput),
},
]
: null,
payloads,
},
}),
},
Expand Down
11 changes: 10 additions & 1 deletion src/lib/stores/data-encoder-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { writable } from 'svelte/store';

import { persistStore } from '$lib/stores/persist-store';
import type { DataEncoderStatus } from '$lib/types/global';
import { has } from '$lib/utilities/has';

export const codecEndpoint = persistStore('endpoint', null, true);

Expand All @@ -26,8 +27,16 @@ export const overrideRemoteCodecConfiguration = persistStore<boolean>(
export const lastDataEncoderStatus =
writable<DataEncoderStatus>('notRequested');

export function setLastDataEncoderFailure(): void {
export const lastDataEncoderError = writable<string>('');

export function setLastDataEncoderFailure(error?: unknown): void {
lastDataEncoderStatus.set('error');

if (error && has(error, 'message') && typeof error.message === 'string') {
lastDataEncoderError.set(error.message);
} else {
lastDataEncoderError.set('');
}
}

export function setLastDataEncoderSuccess(): void {
Expand Down

1 comment on commit 44ed7e4

@vercel
Copy link

@vercel vercel bot commented on 44ed7e4 Oct 11, 2023

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

holocene – ./

holocene-git-main.preview.thundergun.io
holocene.preview.thundergun.io

Please sign in to comment.