summaryrefslogtreecommitdiffhomepage
path: root/packages/util/src
diff options
context:
space:
mode:
authorDax Raad <[email protected]>2025-12-01 16:35:03 -0500
committerDax Raad <[email protected]>2025-12-01 16:35:07 -0500
commit3d99dc78dbff982cde6dd61a0629b7ee9de1a8f3 (patch)
tree4c8dabb52db7c26d2d412c1be861f7599168a7d3 /packages/util/src
parent95c3a8b80505fcb3140989daf6fece3377aa3b95 (diff)
downloadopencode-3d99dc78dbff982cde6dd61a0629b7ee9de1a8f3.tar.gz
opencode-3d99dc78dbff982cde6dd61a0629b7ee9de1a8f3.zip
core: reduce latency when loading shared sessions through event compaction
Diffstat (limited to 'packages/util/src')
-rw-r--r--packages/util/src/identifier.ts48
1 files changed, 48 insertions, 0 deletions
diff --git a/packages/util/src/identifier.ts b/packages/util/src/identifier.ts
new file mode 100644
index 000000000..ba28a351b
--- /dev/null
+++ b/packages/util/src/identifier.ts
@@ -0,0 +1,48 @@
+import { randomBytes } from "crypto"
+
+export namespace Identifier {
+ const LENGTH = 26
+
+ // State for monotonic ID generation
+ let lastTimestamp = 0
+ let counter = 0
+
+ export function ascending() {
+ return create(false)
+ }
+
+ export function descending() {
+ return create(true)
+ }
+
+ function randomBase62(length: number): string {
+ const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+ let result = ""
+ const bytes = randomBytes(length)
+ for (let i = 0; i < length; i++) {
+ result += chars[bytes[i] % 62]
+ }
+ return result
+ }
+
+ export function create(descending: boolean, timestamp?: number): string {
+ const currentTimestamp = timestamp ?? Date.now()
+
+ if (currentTimestamp !== lastTimestamp) {
+ lastTimestamp = currentTimestamp
+ counter = 0
+ }
+ counter++
+
+ let now = BigInt(currentTimestamp) * BigInt(0x1000) + BigInt(counter)
+
+ now = descending ? ~now : now
+
+ const timeBytes = Buffer.alloc(6)
+ for (let i = 0; i < 6; i++) {
+ timeBytes[i] = Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff))
+ }
+
+ return timeBytes.toString("hex") + randomBase62(LENGTH - 12)
+ }
+}