|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "regexp" |
| 5 | + "strconv" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +var uuidV7Pattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) |
| 11 | + |
| 12 | +// embeddedMillis decodes the 48-bit UUIDv7 timestamp prefix. |
| 13 | +func embeddedMillis(t *testing.T, id string) int64 { |
| 14 | + t.Helper() |
| 15 | + ms, err := strconv.ParseInt(id[0:8]+id[9:13], 16, 64) |
| 16 | + if err != nil { |
| 17 | + t.Fatalf("cannot parse timestamp bits of %s: %v", id, err) |
| 18 | + } |
| 19 | + return ms |
| 20 | +} |
| 21 | + |
| 22 | +func TestToV7IsDeterministic(t *testing.T) { |
| 23 | + a := toV7("8b1d7f2e-1111-4c3a-9c1e-000000000001", "2026-09-11T14:54:43.966Z") |
| 24 | + b := toV7("8b1d7f2e-1111-4c3a-9c1e-000000000001", "2026-09-11T14:54:43.966Z") |
| 25 | + if a != b { |
| 26 | + t.Fatalf("same inputs produced different ids: %s vs %s", a, b) |
| 27 | + } |
| 28 | + c := toV7("8b1d7f2e-1111-4c3a-9c1e-000000000002", "2026-09-11T14:54:43.966Z") |
| 29 | + if a == c { |
| 30 | + t.Fatalf("different transcript uuids produced the same id: %s", a) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +func TestToV7EmbedsEntryTimestamp(t *testing.T) { |
| 35 | + ts := "2026-09-11T14:54:43.966Z" |
| 36 | + want, _ := time.Parse(time.RFC3339Nano, ts) |
| 37 | + id := toV7("8b1d7f2e-1111-4c3a-9c1e-000000000001", ts) |
| 38 | + if !uuidV7Pattern.MatchString(id) { |
| 39 | + t.Fatalf("not a well-formed UUIDv7: %s", id) |
| 40 | + } |
| 41 | + if got := embeddedMillis(t, id); got != want.UnixMilli() { |
| 42 | + t.Fatalf("embedded timestamp %d, want %d (%s)", got, want.UnixMilli(), id) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +func TestToV7FallsBackToNowWithoutTimestamp(t *testing.T) { |
| 47 | + for _, ts := range []string{"", "not-a-timestamp"} { |
| 48 | + before := time.Now().UnixMilli() |
| 49 | + id := toV7("8b1d7f2e-1111-4c3a-9c1e-000000000001", ts) |
| 50 | + after := time.Now().UnixMilli() |
| 51 | + if !uuidV7Pattern.MatchString(id) { |
| 52 | + t.Fatalf("not a well-formed UUIDv7: %s", id) |
| 53 | + } |
| 54 | + got := embeddedMillis(t, id) |
| 55 | + if got < before || got > after { |
| 56 | + t.Fatalf("timestamp %q: embedded %d not within [%d, %d]", ts, got, before, after) |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func TestUuid7EmbedsNow(t *testing.T) { |
| 62 | + before := time.Now().UnixMilli() |
| 63 | + id := uuid7() |
| 64 | + after := time.Now().UnixMilli() |
| 65 | + if !uuidV7Pattern.MatchString(id) { |
| 66 | + t.Fatalf("not a well-formed UUIDv7: %s", id) |
| 67 | + } |
| 68 | + got := embeddedMillis(t, id) |
| 69 | + if got < before || got > after { |
| 70 | + t.Fatalf("embedded %d not within [%d, %d]", got, before, after) |
| 71 | + } |
| 72 | +} |
0 commit comments