Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow to validate sent packets using zod #306

Merged
merged 5 commits into from
Nov 12, 2024
Merged
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
6 changes: 6 additions & 0 deletions packages/web-core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@
- Server to Client log events
- Latency reporting support
- S2C logs added to conversation history
- Allow to validate sent packets using zod

### Changed

- Improve connection management

### Fixed

- Fix regenration of expired token
- Wait for one-to-one conversation loading on data sending

## [2.8.0] - 2024-08-13

### Fixed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const createWebSocket = (props: {
onReady,
onMessage: props.onMessage || onMessage,
onDisconnect,
eventFactory,
});
};

Expand Down Expand Up @@ -473,6 +474,7 @@ describe('open', () => {
onReady,
onMessage,
onDisconnect,
eventFactory,
});
jest.spyOn(WebSocket.prototype, 'send').mockImplementation(jest.fn());

Expand Down
16 changes: 8 additions & 8 deletions packages/web-core/__tests__/factories/event.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ describe('event types', () => {
});

test('should generate session control capabilities', () => {
const event = EventFactory.sessionControl({
const event = factory.sessionControl({
capabilities: capabilitiesProps,
});

Expand All @@ -317,7 +317,7 @@ describe('event types', () => {

test('should generate session control session configuration', () => {
const sessionConfiguration = { gameSessionId: v4() };
const event = EventFactory.sessionControl({ sessionConfiguration });
const event = factory.sessionControl({ sessionConfiguration });

expect(event).toHaveProperty('routing');
expect(event).toHaveProperty('timestamp');
Expand All @@ -337,7 +337,7 @@ describe('event types', () => {
version: v4(),
description: v4(),
};
const event = EventFactory.sessionControl({ clientConfiguration });
const event = factory.sessionControl({ clientConfiguration });

expect(event).toHaveProperty('routing');
expect(event).toHaveProperty('timestamp');
Expand All @@ -357,7 +357,7 @@ describe('event types', () => {
fullName: v4(),
profile: { fields: [{ id: v4(), value: v4() }] },
};
const event = EventFactory.sessionControl({ userConfiguration });
const event = factory.sessionControl({ userConfiguration });

expect(event).toHaveProperty('routing');
expect(event).toHaveProperty('timestamp');
Expand All @@ -384,7 +384,7 @@ describe('event types', () => {
continuationType:
ContinuationContinuationType.CONTINUATION_TYPE_DIALOG_HISTORY,
};
const event = EventFactory.sessionControl({ continuation });
const event = factory.sessionControl({ continuation });

expect(event).toHaveProperty('routing');
expect(event).toHaveProperty('timestamp');
Expand All @@ -404,7 +404,7 @@ describe('event types', () => {
continuationType:
ContinuationContinuationType.CONTINUATION_TYPE_EXTERNALLY_SAVED_STATE,
};
const event = EventFactory.sessionControl({ continuation });
const event = factory.sessionControl({ continuation });

expect(event).toHaveProperty('routing');
expect(event).toHaveProperty('timestamp');
Expand All @@ -420,7 +420,7 @@ describe('event types', () => {

test('should generate session control history', () => {
const sessionHistory = {};
const event = EventFactory.sessionControl({ sessionHistory });
const event = factory.sessionControl({ sessionHistory });

expect(event).toHaveProperty('routing');
expect(event).toHaveProperty('timestamp');
Expand All @@ -434,7 +434,7 @@ describe('event types', () => {

test('should generate conversation start event', () => {
const characters = [v4(), v4()];
const event = EventFactory.conversation(characters, {
const event = factory.conversation(characters, {
conversationId,
});
expect(event.control?.action).toEqual(
Expand Down
9 changes: 6 additions & 3 deletions packages/web-core/__tests__/services/entity.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ beforeEach(() => {
});

test('should create or update items', async () => {
const createOrUpdateItems = jest.spyOn(EventFactory, 'createOrUpdateItems');
const createOrUpdateItems = jest.spyOn(
EventFactory.prototype,
'createOrUpdateItems',
);

const items = [
{
Expand Down Expand Up @@ -67,7 +70,7 @@ test('should create or update items', async () => {
});

test('should remove items', async () => {
const removeItems = jest.spyOn(EventFactory, 'removeItems');
const removeItems = jest.spyOn(EventFactory.prototype, 'removeItems');

const ids = [v4(), v4()];

Expand All @@ -82,7 +85,7 @@ test.each([
ItemsInEntitiesOperationType.REMOVE,
ItemsInEntitiesOperationType.REPLACE,
])('shout execute $type', async (type) => {
const itemsInEntities = jest.spyOn(EventFactory, 'itemsInEntities');
const itemsInEntities = jest.spyOn(EventFactory.prototype, 'itemsInEntities');

const itemIds = [v4(), v4()];
const entityNames = [v4(), v4()];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1287,17 +1287,11 @@ describe('character', () => {
test('should set current character', async () => {
jest
.spyOn(service, 'getCurrentCharacter')
.mockImplementationOnce(() => Promise.resolve(undefined!));
const setCurrentCharacter = jest
.spyOn(eventFactory, 'setCurrentCharacter')
.mockImplementation(jest.fn());
.mockImplementationOnce(() => Promise.resolve(characters[0]!));
const updateParticipants = jest
.spyOn(ConversationService.prototype, 'updateParticipants')
.mockImplementation(jest.fn());

await service.setCurrentCharacter(characters[0]);
expect(setCurrentCharacter.mock.calls[0][0]).toEqual(characters[0]);

const conversationService = await service.getCurrentConversation();

connection.conversations.set(conversationService.getConversationId(), {
Expand Down
3 changes: 2 additions & 1 deletion packages/web-core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@inworld/web-core",
"version": "2.9.0-beta.8",
"version": "2.9.0-beta.9",
"license": "SEE LICENSE IN LICENSE.md",
"main": "build/src/index.js",
"types": "build/src/index.d.ts",
Expand Down Expand Up @@ -45,6 +45,7 @@
"dependencies": {
"base64-arraybuffer": "^1.0.2",
"defer-promise": "^3.0.0",
"snakecase-keys": "^8.0.1",
"uuid": "^9.0.0",
"zod": "^3.23.8"
}
Expand Down
8 changes: 8 additions & 0 deletions packages/web-core/src/common/data_structures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export interface ClientConfiguration {
capabilities?: Capabilities;
audioPlayback?: AudioPlaybackConfig;
history?: HistoryConfig;
validateData?: boolean;
}

export interface InternalClientConfiguration {
Expand All @@ -116,6 +117,7 @@ export interface InternalClientConfiguration {
capabilities: CapabilitiesConfiguration;
audioPlayback?: AudioPlaybackConfig;
history?: HistoryConfig;
validateData?: boolean;
}

export interface CancelResponses {
Expand Down Expand Up @@ -222,6 +224,12 @@ export enum ConversationState {
INACTIVE = 'INACTIVE',
}

export enum ConversationIntializeState {
ACTIVE = 'ACTIVE',
PROCESSING = 'PROCESSING',
INACTIVE = 'INACTIVE',
}

export interface PacketQueueItem {
getPacket: () => ProtoPacket;
afterWriting: (packet: ProtoPacket) => void;
Expand Down
18 changes: 13 additions & 5 deletions packages/web-core/src/connection/web-socket.connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { EventFactory } from '../factories/event';

const INWORLD_USER_ID = 'inworldUserId';
const SESSION_PATH = '/v1/session/open';
const NORMAL_CLOSURE_CODE = 1000;

interface OpenSessionProps {
name: string;
Expand All @@ -54,6 +55,7 @@ interface ConnectionProps<
onError: (err: InworldError) => Awaitable<void>;
onMessage: (packet: ProtoPacket) => Awaitable<void>;
extension: Extension<InworldPacketT, HistoryItemT>;
eventFactory: EventFactory;
}

export interface QueueItem<InworldPacketT> {
Expand Down Expand Up @@ -207,7 +209,7 @@ export class WebSocketConnection<

async close(): Promise<void> {
if (this.isActive()) {
this.ws.close();
this.ws.close(NORMAL_CLOSURE_CODE, 'Client closed the connection');
this.connectionProps.onDisconnect();
}

Expand Down Expand Up @@ -302,7 +304,11 @@ export class WebSocketConnection<
resolve: (value: LoadedScene) => void;
reject: (reason: InworldError) => void;
}) {
const { parseEvent, onMessage } = this;
const {
parseEvent,
onMessage,
connectionProps: { eventFactory },
} = this;
let historyLoaded = true;
let sceneStatus: CurrentSceneStatus;

Expand All @@ -329,7 +335,7 @@ export class WebSocketConnection<
if (!!sceneStatus && !historyLoaded && needHistory) {
write({
getPacket: () =>
EventFactory.sessionControl({ sessionHistory: {} }),
eventFactory.sessionControl({ sessionHistory: {} }),
});
} else {
ws.removeEventListener('message', this);
Expand All @@ -353,12 +359,14 @@ export class WebSocketConnection<
gameSessionId?: string;
useDefaultClient?: boolean;
}) {
const { eventFactory } = this.connectionProps;

const continuation = this.getContinuation({
sessionContinuation: props.sessionContinuation,
});

const packets: ProtoPacket[] = [
EventFactory.sessionControl({
eventFactory.sessionControl({
...(props.capabilities && {
capabilities: props.capabilities,
}),
Expand All @@ -375,7 +383,7 @@ export class WebSocketConnection<
}),
...(continuation && { continuation }),
}),
EventFactory.loadScene(props.name),
eventFactory.loadScene(props.name),
];

return this.extension.beforeLoadScene?.(packets) || packets;
Expand Down
Loading
Loading