Skip to content
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
20 changes: 20 additions & 0 deletions functions/api/time.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export const onRequest = async () => {
const now = new Date()

return new Response(
JSON.stringify({
timestamp: now.toISOString(),
timezone: 'Asia/Tokyo',
unix: Math.floor(now.getTime() / 1000),
milliseconds: now.getTime(),
}),
{
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
},
}
)
}
29 changes: 25 additions & 4 deletions src/components/models/pageContext.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { now } from '@/utils/time'
import {
now,
nowAccurate,
hasSignificantDrift,
startTimeSync,
} from '@/utils/time'
import { Dayjs } from 'dayjs'
import {
PropsWithChildren,
Expand All @@ -14,6 +19,7 @@ type PageCtxType = {
goNextPage: () => void
setTotalPage: (totalPage: number) => void
now: Dayjs
hasTimeDrift: boolean
}

export const PageCtx = createContext<PageCtxType>({
Expand All @@ -22,21 +28,35 @@ export const PageCtx = createContext<PageCtxType>({
goNextPage: () => {},
setTotalPage: () => {},
now: now(),
hasTimeDrift: false,
})

export const PageCtxProvider = (props: PropsWithChildren) => {
const [current, setCurrent] = useState<number>(0)
const [totalPage, setTotalPage] = useState<number>(0)
const [currentTime, setCurrentTime] = useState<Dayjs>(now())
const [timeDrift, setTimeDrift] = useState<boolean>(false)

const goNextPage = useCallback(() => {
setCurrent((current + 1) % totalPage)
}, [current, setCurrent, totalPage])

useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(now())
}, 1000)
// Start time synchronization process (5-second retries for 30 seconds)
startTimeSync()

const updateTime = () => {
const accurateTime = nowAccurate()
setCurrentTime(accurateTime)
setTimeDrift(hasSignificantDrift())
}

// Initial time update
updateTime()

// Regular updates every second (using cached/calculated time)
const timer = setInterval(updateTime, 1000)

return () => {
clearInterval(timer)
}
Expand All @@ -48,6 +68,7 @@ export const PageCtxProvider = (props: PropsWithChildren) => {
goNextPage,
setTotalPage,
now: currentTime,
hasTimeDrift: timeDrift,
}

return <PageCtx.Provider value={ctx}>{props.children}</PageCtx.Provider>
Expand Down
22 changes: 22 additions & 0 deletions src/pages/api/time.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextRequest } from 'next/server'

export const runtime = 'edge'

export default function handler(_req: NextRequest) {
const now = new Date()

return new Response(
JSON.stringify({
timestamp: now.toISOString(),
timezone: 'Asia/Tokyo',
unix: Math.floor(now.getTime() / 1000),
milliseconds: now.getTime(),
}),
{
status: 200,
headers: {
'Content-Type': 'application/json',
},
}
)
}
93 changes: 93 additions & 0 deletions src/utils/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,95 @@ dayjs.extend(timezone)
dayjs.extend(utc)
dayjs.tz.setDefault('Asia/Tokyo')

interface ServerTimeResponse {
timestamp: string
timezone: string
unix: number
milliseconds: number
}

// Configuration constants - easy to modify
const TIME_SYNC_CONFIG = {
RETRY_INTERVAL: 5000, // 5 seconds between retries
MAX_ATTEMPTS: 6, // Maximum retry attempts (30 seconds total)
SIGNIFICANT_DRIFT_THRESHOLD: 30000, // 30 seconds
} as const

let timeOffset: number = 0
let isSynced: boolean = false
let syncAttempts: number = 0
let syncInterval: NodeJS.Timeout | null = null

async function attemptTimeSync(): Promise<boolean> {
try {
const response = await fetch('/api/time')
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}

const data: ServerTimeResponse = await response.json()
const serverTime = dayjs(data.timestamp).tz('Asia/Tokyo')
const localTime = dayjs().tz('Asia/Tokyo')

timeOffset = serverTime.diff(localTime)
isSynced = true

console.log(`Time synced successfully. Offset: ${timeOffset}ms`)
return true
} catch (error) {
console.warn(`Time sync attempt ${syncAttempts + 1} failed:`, error)
return false
}
}

export function startTimeSync(): void {
if (syncInterval) return // Already started

syncInterval = setInterval(async () => {
syncAttempts++

const success = await attemptTimeSync()

if (success || syncAttempts >= TIME_SYNC_CONFIG.MAX_ATTEMPTS) {
if (syncInterval) {
clearInterval(syncInterval)
syncInterval = null
}

if (!success) {
console.warn(
`Time sync failed after ${(TIME_SYNC_CONFIG.MAX_ATTEMPTS * TIME_SYNC_CONFIG.RETRY_INTERVAL) / 1000} seconds, using local time`
)
}
}
}, TIME_SYNC_CONFIG.RETRY_INTERVAL)

// Also try immediately
attemptTimeSync().then((success) => {
if (success && syncInterval) {
clearInterval(syncInterval)
syncInterval = null
}
})
}

export function getAccurateTime(): Dayjs {
const localTime = dayjs().tz('Asia/Tokyo')
return isSynced ? localTime.add(timeOffset, 'millisecond') : localTime
}

export function getTimeDrift(): number {
return timeOffset
}

export function hasSignificantDrift(): boolean {
return Math.abs(timeOffset) > TIME_SYNC_CONFIG.SIGNIFICANT_DRIFT_THRESHOLD
}

export function isTimeSynced(): boolean {
return isSynced
}

export function getTimeStr(time: string): string {
return dayjs(time).tz().format('HH:mm')
}
Expand All @@ -17,3 +106,7 @@ export function getTime(time: string) {
export function now(): Dayjs {
return dayjs().tz()
}

export function nowAccurate(): Dayjs {
return getAccurateTime()
}