Skip to content

Commit

Permalink
Remove crypto from OSDK (#1051)
Browse files Browse the repository at this point in the history
* Remove crypto dependency

* Changeset

* Update tests

* remove unused
  • Loading branch information
nihalbhatnagar authored Dec 11, 2024
1 parent 2ffa338 commit a7a4aef
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 35 deletions.
5 changes: 5 additions & 0 deletions .changeset/red-carpets-wave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@osdk/client": patch
---

Removes dependency on crypto
29 changes: 13 additions & 16 deletions packages/client/src/objectSet/ObjectSetListenerWebsocket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ describe("ObjectSetListenerWebsocket", async () => {
listener,
);

subReq1 = await expectSingleSubscribeMessage(ws);
subReq1 = await expectSubscribeMessages(ws, 2);
});

afterEach(() => {
Expand All @@ -211,7 +211,7 @@ describe("ObjectSetListenerWebsocket", async () => {
respondSuccessToSubscribe(ws, subReq1);
// actually this is broken FIXME
unsubscribe();
expect(ws.send).not.toHaveBeenCalled();
expect(ws.send).toHaveBeenCalledTimes(1);
});

it("correctly requests regular object properties", () => {
Expand Down Expand Up @@ -248,7 +248,7 @@ describe("ObjectSetListenerWebsocket", async () => {

describe("subscribe and respond", () => {
beforeEach(async () => {
const subReq2 = await expectSingleSubscribeMessage(ws);
const subReq2 = await expectSubscribeMessages(ws);
respondSuccessToSubscribe(ws, subReq2);
});

Expand Down Expand Up @@ -356,7 +356,7 @@ describe("ObjectSetListenerWebsocket", async () => {
["employeeId"],
);

subReq2 = await expectSingleSubscribeMessage(ws);
subReq2 = await expectSubscribeMessages(ws);

respondSuccessToSubscribe(ws, subReq2);
});
Expand Down Expand Up @@ -390,7 +390,7 @@ describe("ObjectSetListenerWebsocket", async () => {
]);
setWebSocketState(ws, "open");

const subReq2 = await expectSingleSubscribeMessage(ws);
const subReq2 = await expectSubscribeMessages(ws);
respondSuccessToSubscribe(ws, subReq2);
});

Expand Down Expand Up @@ -510,10 +510,16 @@ function expectEqualRemoveAndAddListeners(ws: MockedWebSocket) {
);
}

async function expectSingleSubscribeMessage(
async function expectSubscribeMessages(
ws: MockedWebSocket,
times: number = 1,
): Promise<ObjectSetStreamSubscribeRequests> {
return await consumeSingleSend(ws);
return await vi.waitFor(() => {
expect(ws.send).toBeCalledTimes(times);
const result = JSON.parse(ws.send.mock.lastCall![0].toString());
ws.send.mockClear();
return result;
});
}

async function subscribeAndExpectWebSocket(
Expand Down Expand Up @@ -557,15 +563,6 @@ async function expectWebSocketConstructed(): Promise<MockedWebSocket> {
return ws;
}

async function consumeSingleSend(ws: any) {
return await vi.waitFor(() => {
expect(ws.send).toBeCalledTimes(1);
const result = JSON.parse(ws.send.mock.lastCall![0].toString());
ws.send.mockClear();
return result;
});
}

function createMockWebSocketConstructor(
OriginalWebSocket: WebSocket,
logger: Logger,
Expand Down
40 changes: 21 additions & 19 deletions packages/client/src/objectSet/ObjectSetListenerWebsocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ export class ObjectSetListenerWebsocket {
string,
Subscription<any, any>
>();

#endedSubscriptions = new Set<
string
>();

#maybeDisconnectTimeout: ReturnType<typeof setTimeout> | undefined;

// DO NOT CONSTRUCT DIRECTLY. ONLY EXPOSED AS A TESTING SEAM
Expand Down Expand Up @@ -171,12 +176,6 @@ export class ObjectSetListenerWebsocket {
listener: ObjectSetListener<Q, P>,
properties: Array<P> = [],
): Promise<() => void> {
if (process.env.TARGET !== "browser") {
// Node 18 does not expose 'crypto' on globalThis, so we need to do it ourselves. This
// will not be needed after our minimum version is 19 or greater.
globalThis.crypto ??= (await import("node:crypto")).webcrypto as any;
}

const objDef = objectType.type === "object"
? await this.#client.ontologyProvider.getObjectDefinition(
objectType.apiName,
Expand Down Expand Up @@ -216,7 +215,7 @@ export class ObjectSetListenerWebsocket {
status: "preparing",
// Since we don't have a real subscription id yet but we need to keep
// track of this reference, we can just use a random uuid.
subscriptionId: `TMP-${crypto.randomUUID()}`,
subscriptionId: `TMP-${nextUuid()}}`,
interfaceApiName: objDef.type === "object"
? undefined
: objDef.apiName,
Expand Down Expand Up @@ -275,18 +274,7 @@ export class ObjectSetListenerWebsocket {
// so we filter those out.
const readySubs = [...this.#subscriptions.values()].filter(isReady);

if (readySubs.length === 0) {
if (process.env.NODE_ENV !== "production") {
this.#logger?.trace(
"#sendSubscribeMessage(): aborting due to no ready subscriptions",
);
}

return;
}

// Assumes the node 18 crypto fallback to globalThis in `subscribe` has happened.
const id = crypto.randomUUID();
const id = nextUuid();
// responses come back as an array of subIds, so we need to know the sources
this.#pendingSubscriptions.set(id, readySubs);

Expand Down Expand Up @@ -327,11 +315,16 @@ export class ObjectSetListenerWebsocket {
// if we are already done, we don't need to do anything
return;
}

sub.status = newStatus;

// make sure listeners do nothing now
sub.listener = fillOutListener<Q, any>({});

this.#subscriptions.delete(sub.subscriptionId);
this.#endedSubscriptions.add(sub.subscriptionId);
this.#sendSubscribeMessage();

// If we have no more subscriptions, we can disconnect the websocket
// however we should wait a bit to see if we get any more subscriptions.
// For example, when switching between react views, you may unsubscribe
Expand Down Expand Up @@ -595,6 +588,7 @@ export class ObjectSetListenerWebsocket {

#handleMessage_subscriptionClosed(payload: SubscriptionClosed) {
const sub = this.#subscriptions.get(payload.id);
if (sub == null && this.#endedSubscriptions.has(payload.id)) return;
invariant(sub, `Expected subscription id ${payload.id}`);
this.#tryCatchOnError(sub, true, payload.cause);
this.#unsubscribe(sub, "error");
Expand Down Expand Up @@ -688,3 +682,11 @@ export function constructWebsocketUrl(
url.protocol = url.protocol.replace("https", "wss");
return url;
}

let uuidCounter = 0;

function nextUuid() {
return `00000000-0000-0000-0000-${
(uuidCounter++).toString().padStart(12, "0")
}`;
}

0 comments on commit a7a4aef

Please sign in to comment.