Skip to content

Commit

Permalink
Merge pull request #11 from statelyai/mellson/sta-5342-do-we-need-run…
Browse files Browse the repository at this point in the history
…onsky-in-the-api

Remove unused/unneeded `runOnSky` option
  • Loading branch information
mellson authored Nov 8, 2023
2 parents bcff4eb + 2a9016d commit cb3ab98
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 90 deletions.
5 changes: 5 additions & 0 deletions .changeset/eight-avocados-cheat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@statelyai/sky': patch
---

Remove unused/unneeded `runOnSky` option.
175 changes: 85 additions & 90 deletions packages/sky-core/src/actorFromStately.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,12 @@ export async function actorFromStately<T extends AnyStateMachine>(
apiKey: _apiKey,
url,
sessionId,
runOnSky = true,
onPlayerJoined,
onPlayerLeft,
}: {
apiKey?: string;
url: string;
sessionId: string;
runOnSky?: boolean;
onPlayerJoined?: ({ numberOfPlayers }: { numberOfPlayers: number }) => void;
onPlayerLeft?: ({ numberOfPlayers }: { numberOfPlayers: number }) => void;
},
Expand All @@ -34,100 +32,97 @@ export async function actorFromStately<T extends AnyStateMachine>(
`You need to run xstate sky "src/**/*.ts?(x)" before you can use the Stately Sky actor with url ${url}`,
);
}
if (!runOnSky) {
return createActor(skyConfig.machine);
} else {
let actor: AnyActor | undefined;
let partySocket: PartySocket | undefined;

// Get the host for Partykit and the API base URL for Stately Studio
const { host, apiBaseURL } = skyConnectionInfo();
const { actorId, machine } = skyConfig;
const apiKey = _apiKey ?? SKY_API_KEY;
let actor: AnyActor | undefined;
let partySocket: PartySocket | undefined;

if (!apiKey) {
throw new Error(
`You need to provide an API key to use the Stately Sky actor with url ${url}`,
);
}
// Get the host for Partykit and the API base URL for Stately Studio
const { host, apiBaseURL } = skyConnectionInfo();
const { actorId, machine } = skyConfig;
const apiKey = _apiKey ?? SKY_API_KEY;

return new Promise<Actor<T>>((resolve, reject) => {
// Close the previous socket if it exists, this can easily happen when using React
if (partySocket && partySocket.OPEN) {
partySocket.close();
}
// Create a unique room for this actor run
const room = `${actorId}-${sessionId}`;
partySocket = new PartySocket({ host, room });
partySocket.onerror = (err) => reject(err);
partySocket.onopen = () => {
if (!partySocket) return;
return sendToSky(partySocket, {
apiKey,
type: 'actor.init',
apiBaseURL,
actorId,
sessionId,
});
};
if (!apiKey) {
throw new Error(
`You need to provide an API key to use the Stately Sky actor with url ${url}`,
);
}

// TODO: test what happens on reconnect
// TODO: handle eventual consistency if users manage to get into different states
partySocket.onmessage = (evt) => {
const skyEvent = superjson.parse<SkyServerEvent>(evt.data);
if (skyEvent.apiKey !== apiKey) return;
switch (skyEvent.type) {
case 'player.joined': {
onPlayerJoined?.({ numberOfPlayers: skyEvent.numberOfPlayers });
break;
}
case 'player.left': {
onPlayerLeft?.({ numberOfPlayers: skyEvent.numberOfPlayers });
break;
}
case 'actor.error': {
throw new Error(skyEvent.error);
}
case 'actor.start': {
// Start the actor with the initial value from Sky
actor = createActor(machine, {
state: skyEvent.persistedState,
});
return new Promise<Actor<T>>((resolve, reject) => {
// Close the previous socket if it exists, this can easily happen when using React
if (partySocket && partySocket.OPEN) {
partySocket.close();
}
// Create a unique room for this actor run
const room = `${actorId}-${sessionId}`;
partySocket = new PartySocket({ host, room });
partySocket.onerror = (err) => reject(err);
partySocket.onopen = () => {
if (!partySocket) return;
return sendToSky(partySocket, {
apiKey,
type: 'actor.init',
apiBaseURL,
actorId,
sessionId,
});
};

// TODO: test what happens on reconnect
// TODO: handle eventual consistency if users manage to get into different states
partySocket.onmessage = (evt) => {
const skyEvent = superjson.parse<SkyServerEvent>(evt.data);
if (skyEvent.apiKey !== apiKey) return;
switch (skyEvent.type) {
case 'player.joined': {
onPlayerJoined?.({ numberOfPlayers: skyEvent.numberOfPlayers });
break;
}
case 'player.left': {
onPlayerLeft?.({ numberOfPlayers: skyEvent.numberOfPlayers });
break;
}
case 'actor.error': {
throw new Error(skyEvent.error);
}
case 'actor.start': {
// Start the actor with the initial value from Sky
actor = createActor(machine, {
state: skyEvent.persistedState,
});

// Send all events from the actor to Sky except for events that originate from Sky
const originalSend = actor.send;
actor.send = function (
event: EventFromLogic<T> & { sendToSky?: boolean },
) {
// Send the event to the actor
originalSend.call(this, event);
// Send all events from the actor to Sky except for events that originate from Sky
const originalSend = actor.send;
actor.send = function (
event: EventFromLogic<T> & { sendToSky?: boolean },
) {
// Send the event to the actor
originalSend.call(this, event);

// Don't start an infinite loop by sending events back to Sky
if (event.sendToSky === false || !partySocket) return;
// Don't start an infinite loop by sending events back to Sky
if (event.sendToSky === false || !partySocket) return;

sendToSky(partySocket, {
apiKey,
type: 'actor.send',
event,
});
};
resolve(actor);
break;
}
case 'actor.send': {
// When we receive an event from Sky, we don't want to send it back - we only want to send it to the local actor
actor?.send({
...skyEvent.event,
sendToSky: false,
} as EventFromLogic<T>);
break;
}
case 'actor.stop': {
actor?.stop();
break;
}
sendToSky(partySocket, {
apiKey,
type: 'actor.send',
event,
});
};
resolve(actor);
break;
}
};
});
}
case 'actor.send': {
// When we receive an event from Sky, we don't want to send it back - we only want to send it to the local actor
actor?.send({
...skyEvent.event,
sendToSky: false,
} as EventFromLogic<T>);
break;
}
case 'actor.stop': {
actor?.stop();
break;
}
}
};
});
}

0 comments on commit cb3ab98

Please sign in to comment.