Skip to content
This repository has been archived by the owner on Feb 25, 2024. It is now read-only.

Netlify Edge Functions POC (do not merge) #384

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/CanvasContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
PointDelta,
} from './dragSessionTracker';
import { AnyState } from './types';
import { Box, BoxProps } from '@chakra-ui/react';

const dragModel = createModel(
{
Expand Down Expand Up @@ -272,9 +273,12 @@ const getCursorByState = (state: AnyState) =>
) as { cursor?: CSSProperties['cursor'] }
)?.cursor;

export const CanvasContainer: React.FC<{ panModeEnabled: boolean }> = ({
type CanvasContainerProps = { panModeEnabled: boolean } & BoxProps;

export const CanvasContainer: React.FC<CanvasContainerProps> = ({
children,
panModeEnabled,
...boxProps
}) => {
const canvasService = useCanvas();
const embed = useEmbed();
Expand Down Expand Up @@ -456,14 +460,15 @@ export const CanvasContainer: React.FC<{ panModeEnabled: boolean }> = ({
}, [canvasService, embed]);

return (
<div
<Box
ref={canvasRef}
style={{
cursor: getCursorByState(state),
WebkitFontSmoothing: 'auto',
}}
{...boxProps}
>
{children}
</div>
</Box>
);
};
9 changes: 8 additions & 1 deletion src/CanvasView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ export const CanvasView: React.FC = () => {
const isLayoutPending = useSelector(simService, (state) =>
state.hasTag('layoutPending'),
);
const isSimPending = useSelector(simService, (state) =>
state.hasTag('pending'),
);
const isEmpty = useSelector(simService, (state) => state.hasTag('empty'));
const digraph = useMemo(
() => (machine ? toDirectedGraph(machine) : undefined),
Expand Down Expand Up @@ -95,7 +98,11 @@ export const CanvasView: React.FC = () => {
<CanvasHeader />
</Box>
)}
<CanvasContainer panModeEnabled={panModeEnabled}>
<CanvasContainer
panModeEnabled={panModeEnabled}
opacity={isSimPending ? 0.7 : 1}
transition="opacity 0.2s ease-in-out"
>
{digraph && <Graph digraph={digraph} />}
{isLayoutPending && (
<Overlay>
Expand Down
192 changes: 139 additions & 53 deletions src/simulationMachine.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import produce from 'immer';
import {
ActorRefFrom,
AnyInterpreter,
createMachine,
EventFrom,
InterpreterStatus,
SCXML,
Expand Down Expand Up @@ -62,6 +63,13 @@ export const simModel = createModel(
},
);

async function asyncPoll(fn: () => Promise<any>, interval: number) {
while (true) {
await fn();
await new Promise((resolve) => setTimeout(resolve, interval));
}
}

export const simulationMachine = simModel.createMachine(
{

Choose a reason for hiding this comment

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

preserveActionOrder: true,
Expand All @@ -81,66 +89,144 @@ export const simulationMachine = simModel.createMachine(
invoke: {
id: 'proxy',
src: () => (sendBack, onReceive) => {
const serverUrl = new URLSearchParams(window.location.search).get(
'server',
);
const searchParams = new URLSearchParams(window.location.search);
const serverUrl = searchParams.get('server');
const functionUrl = searchParams.get('url');
const pollParam = searchParams.get('poll');
const poll = pollParam && !isNaN(+pollParam) ? +pollParam : 1000;

let receiver: InspectReceiver;
if (serverUrl) {
const [protocol, ...server] = serverUrl.split('://');
receiver = createWebSocketReceiver({
protocol: protocol as 'ws' | 'wss',
server: server.join('://'),
if (functionUrl) {
let registered = false;
let lastTimestamp: string;

asyncPoll(async () => {
try {
fetch(functionUrl)
.then((data) => data.json())
.catch((err) => {
console.error(err);
})
.then((data) => {
const machineData = data;
if (!machineData) {
console.error('No machine data received');
return;
}

const machine = createMachine(machineData.machine);
const state = machine.resolveState(machineData.state);

if (!registered) {
sendBack(
simModel.events['SERVICE.REGISTER']({
sessionId: machineData.id,
machine,
state,
parent: undefined,
source: 'inspector',
}),
);
lastTimestamp = machineData.updated_at;
registered = true;
} else {
if (lastTimestamp !== machineData.updated_at) {
sendBack(
simModel.events['SERVICE.STATE'](
machineData.id,
state,
),
);
lastTimestamp = machineData.updated_at;
}
}
sendBack({ type: 'SERVICE.READY' });
});
} catch (e) {
console.error(e);
}
}, poll);

onReceive((event) => {
if (event.type === 'xstate.event') {
fetch(functionUrl, {
method: 'POST',
body: JSON.stringify(event.event),
});
sendBack({ type: 'SERVICE.PENDING' });
}
});
} else {
receiver = createWindowReceiver({
// for some random reason the `window.top` is being rewritten to `window.self`
// looks like maybe some webpack replacement plugin (or similar) plays tricks on us
// this breaks the auto-detection of the correct `targetWindow` in the `createWindowReceiver`
// so we pass it explicitly here
targetWindow: window.opener || window.parent,
});
}

onReceive((event) => {
if (event.type === 'xstate.event') {
receiver.send({
...event,
type: 'xstate.event',
event: JSON.stringify(event.event),
if (serverUrl) {
const [protocol, ...server] = serverUrl.split('://');
receiver = createWebSocketReceiver({
protocol: protocol as 'ws' | 'wss',
server: server.join('://'),
});
} else {
receiver = createWindowReceiver({
// for some random reason the `window.top` is being rewritten to `window.self`
// looks like maybe some webpack replacement plugin (or similar) plays tricks on us
// this breaks the auto-detection of the correct `targetWindow` in the `createWindowReceiver`
// so we pass it explicitly here
targetWindow: window.opener || window.parent,
});
}
});

return receiver.subscribe((event) => {
switch (event.type) {
case 'service.register':
let state = event.machine.resolveState(event.state);
sendBack(
simModel.events['SERVICE.REGISTER']({
sessionId: event.sessionId,
machine: event.machine,
state,
parent: event.parent,
source: 'inspector',
}),
);
break;
case 'service.state':
sendBack(
simModel.events['SERVICE.STATE'](
event.sessionId,
event.state,
),
);
break;
case 'service.stop':
sendBack(simModel.events['SERVICE.STOP'](event.sessionId));
break;
default:
break;
}
}).unsubscribe;
onReceive((event) => {
if (event.type === 'xstate.event') {
receiver.send({
...event,
type: 'xstate.event',
event: JSON.stringify(event.event),
});
}
});

return receiver.subscribe((event) => {
switch (event.type) {
case 'service.register':
let state = event.machine.resolveState(event.state);
sendBack(
simModel.events['SERVICE.REGISTER']({
sessionId: event.sessionId,
machine: event.machine,
state,
parent: event.parent,
source: 'inspector',
}),
);
break;
case 'service.state':
sendBack(
simModel.events['SERVICE.STATE'](
event.sessionId,
event.state,
),
);
break;
case 'service.stop':
sendBack(simModel.events['SERVICE.STOP'](event.sessionId));
break;
default:
break;
}
}).unsubscribe;
}
},
},
initial: 'idle',
states: {
idle: {
on: {
'SERVICE.PENDING': 'pending',
},
},
pending: {
tags: 'pending',
on: {
'SERVICE.READY': 'idle',
},
},
},
},
Expand Down