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

fix: #605 - orama crashes inside web worker #606

Merged
merged 1 commit into from
Jan 12, 2024
Merged
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
23 changes: 22 additions & 1 deletion packages/orama/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,19 @@ export async function formatBytes(bytes: number, decimals = 2): Promise<string>
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
}

export function isInsideWebWorker(): boolean {
// @ts-expect-error - WebWorker global scope
return typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope
}

export function isInsideNode(): boolean {
return typeof process !== 'undefined' && process.release.name === 'node'
}

export function getNanosecondTimeViaPerformance() {
return BigInt(Math.floor(performance.now() * 1e6))
}

export async function formatNanoseconds(value: number | bigint): Promise<string> {
if (typeof value === 'number') {
value = BigInt(value)
Expand All @@ -99,12 +112,20 @@ export async function formatNanoseconds(value: number | bigint): Promise<string>
}

export async function getNanosecondsTime(): Promise<bigint> {
if (isInsideWebWorker()) {
return getNanosecondTimeViaPerformance()
}

if (isInsideNode()) {
return process.hrtime.bigint()
}

if (typeof process !== 'undefined' && process.hrtime !== undefined) {
return process.hrtime.bigint()
}

if (typeof performance !== 'undefined') {
return BigInt(Math.floor(performance.now() * 1e6))
return getNanosecondTimeViaPerformance()
}

// @todo: fallback to V8 native method to get microtime
Expand Down