Skip to content

Commit c682d4f

Browse files
committed
clean
1 parent e3967cd commit c682d4f

File tree

7 files changed

+8
-248
lines changed

7 files changed

+8
-248
lines changed

workers/src/durable.ts

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export class FlightDO extends DurableObject<Env, DOProps> {
3333
private resetCache() {
3434
Object.assign(this.ctx.props, {
3535
cache: {},
36-
debug: false
36+
debug: false,
3737
})
3838
}
3939

@@ -107,32 +107,18 @@ export class FlightDO extends DurableObject<Env, DOProps> {
107107
*/
108108
async alarm(): Promise<void> {
109109
this.resetCache() // Reset at start of each alarm
110-
const alarmId = Math.random().toString(36).substring(7)
111110
const currentCount = this.getAlarmCount()
112111
const newCount = currentCount + 1
113-
114-
// Check if there's already an alarm scheduled (potential race condition)
115-
const existingAlarm = await this.ctx.storage.getAlarm()
116-
let alarmMessage = `⏰ [ALARM-${alarmId}] Alarm fired! Previous count: ${currentCount}, New count: ${newCount}\nCurrent time: ${new Date().toISOString()}`
117-
118-
if (existingAlarm) {
119-
alarmMessage += `\n⚠️ WARNING: Existing alarm found at ${new Date(existingAlarm).toISOString()}`
120-
}
121-
122-
await sendAdmin(alarmMessage, this.env, this.ctx)
123112

124113
runScheduledJob(this.env, this.ctx)
125114

126115
this.setAlarmCount(newCount)
127116

128117
const period = CRON_PERIOD_SECONDS * 1000
129118
const nextAlarmTime = Date.now() + period
130-
await sendAdmin(`⏰ [ALARM-${alarmId}] Setting next alarm for ${period}ms from now (${new Date(nextAlarmTime).toISOString()})`, this.env, this.ctx)
131119
await this.ctx.storage.setAlarm(nextAlarmTime)
132-
await sendAdmin(`✅ [ALARM-${alarmId}] Alarm completed`, this.env, this.ctx)
133120
}
134121

135-
136122
/**
137123
* Example method using SQLite-backed SQL API (official API)
138124
* Demonstrates proper SQL query execution

workers/src/handlers/alerts.ts

Lines changed: 4 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -7,37 +7,26 @@ export const sendFlightAlerts = async (
77
env: Env,
88
ctx: DurableObjectState<DOProps>
99
) => {
10-
const alertId = Math.random().toString(36).substring(7)
11-
12-
const subsResult = ctx.storage.sql.exec(
13-
'SELECT flight_id, telegram_id FROM subscriptions'
14-
)
10+
const subsResult = ctx.storage.sql.exec('SELECT flight_id, telegram_id FROM subscriptions')
1511
const allSubs = subsResult.toArray() as { flight_id: string; telegram_id: string }[]
16-
17-
// Check for duplicate subscriptions
12+
1813
const subscriptionMap = new Map<string, Set<string>>()
1914
for (const sub of allSubs) {
2015
if (!subscriptionMap.has(sub.flight_id)) {
2116
subscriptionMap.set(sub.flight_id, new Set())
2217
}
2318
subscriptionMap.get(sub.flight_id)!.add(sub.telegram_id)
2419
}
25-
20+
2621
let duplicateCount = 0
2722
const duplicates: string[] = []
2823
for (const [flightId, subscribers] of subscriptionMap) {
29-
const subs = allSubs.filter(s => s.flight_id === flightId)
24+
const subs = allSubs.filter((s) => s.flight_id === flightId)
3025
if (subs.length !== subscribers.size) {
3126
duplicateCount += subs.length - subscribers.size
3227
duplicates.push(flightId)
3328
}
3429
}
35-
36-
await sendAdmin(
37-
`🚨 [ALERT-${alertId}] Starting to send flight alerts for ${Object.keys(changesByFlight).length} flights\nFound ${allSubs.length} total subscriptions${duplicateCount > 0 ? ` (${duplicateCount} duplicates for flights: ${duplicates.join(', ')})` : ''}`,
38-
env,
39-
ctx
40-
)
4130

4231
const trackingMap: Record<string, string[]> = {} // flight_id -> users
4332

@@ -51,31 +40,11 @@ export const sendFlightAlerts = async (
5140
const subscribers = trackingMap[flightChange.flight.id]
5241

5342
if (subscribers && subscribers.length > 0) {
54-
await sendAdmin(
55-
`🚨 [ALERT-${alertId}] Flight ${flightChange.flight.flight_number} (${flightId}) changes:\n${flightChange.changes.join(', ')}\nSubscribers: ${subscribers.join(', ')}`,
56-
env,
57-
ctx
58-
)
59-
60-
// Send alerts to all subscribers
6143
for (const telegram_id of subscribers) {
6244
await sendAlert(Number(telegram_id), flightChange.flight, flightChange.changes, env)
63-
await sendAdmin(
64-
`📤 [ALERT-${alertId}] Sent alert to user ${telegram_id} for flight ${flightChange.flight.flight_number}`,
65-
env,
66-
ctx
67-
)
6845
}
69-
} else {
70-
await sendAdmin(
71-
`⚠️ [ALERT-${alertId}] No subscribers found for flight ${flightChange.flight.flight_number} (${flightId})`,
72-
env,
73-
ctx
74-
)
7546
}
7647
}
77-
78-
await sendAdmin(`✅ [ALERT-${alertId}] Alert sending completed`, env, ctx)
7948
}
8049

8150
const sendAlert = async (userId: number, flight: Flight, changes: string[], env: Env) => {

workers/src/handlers/commands.ts

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ export const isTextMessage = (message: Message) => {
2323
return 'text' in message
2424
}
2525

26-
// Shared function to build status message - eliminates code duplication
2726
const buildStatusMessage = async (env: Env, ctx: DurableObjectState<DOProps>) => {
2827
const version = (await env.METADATA.get('version')) || 'Unknown'
2928
const lastDeployDate = (await env.METADATA.get('last_deploy_date')) || 'Unknown'
@@ -82,7 +81,6 @@ export const handleCommand = async (request: Request, env: Env, ctx: DurableObje
8281
if ('callback_query' in update && update.callback_query) {
8382
const callbackQuery = update.callback_query
8483
if (!callbackQuery.message) {
85-
// Try to answer the callback query but handle the case where the message is too old
8684
try {
8785
await ofetch(`${getTelegramUrl(env)}/answerCallbackQuery`, {
8886
method: 'POST',
@@ -329,20 +327,10 @@ export const handleCommand = async (request: Request, env: Env, ctx: DurableObje
329327
],
330328
}
331329
} else if (data === 'show_suggestions') {
332-
// Reset pagination cursor when showing suggestions fresh
333330
ctx.storage.kv.put(`pagination_cursor_${chatId}`, '0')
334331

335332
const eligibleFlights = getNotTrackedFlightsFromStatus(chatId, ctx)
336333

337-
// SEND DEBUG MESSAGE TO YOUR CHAT
338-
//await sendAdmin(
339-
// `🐛 DEBUG INFO:\n` +
340-
// `Total eligible flights: ${eligibleFlights.length}\n` +
341-
//`Will show Next button: ${eligibleFlights.length > 5 ? '✅ YES' : '❌ NO'}\n` +
342-
//`Showing flights: 1-${Math.min(5, eligibleFlights.length)}`,
343-
//env
344-
//)
345-
346334
const { text, replyMarkup: suggestionsMarkup } = formatFlightSuggestions(
347335
eligibleFlights.slice(0, 5),
348336
0,

workers/src/handlers/cron.ts

Lines changed: 1 addition & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,36 +16,21 @@ import { getCurrentIdtTime } from '../utils/dateTime'
1616

1717
export const runScheduledJob = async (env: Env, ctx: DurableObjectState<DOProps>) => {
1818
const jobId = Math.random().toString(36).substring(7)
19-
19+
2020
try {
2121
initializeSchema(ctx)
2222

23-
// Fetch new data from API
2423
const currentFlights = await fetchLatestFlights(env, ctx)
25-
await sendAdmin(`🔍 [JOB-${jobId}] Fetched ${currentFlights.length} current flights`, env, ctx)
26-
2724
writeStatusData(ctx, currentFlights.length)
2825

2926
const previousFlights = getCurrentFlightsFromStatus(ctx)
30-
await sendAdmin(`🔍 [JOB-${jobId}] Retrieved ${previousFlights.length} previous flights`, env, ctx)
31-
32-
// 2. Store current flights as JSON (single SQLite write!)
3327
storeFlightsInStatus(currentFlights, ctx)
34-
await sendAdmin(`🔍 [JOB-${jobId}] Stored current flights to status`, env, ctx)
35-
36-
await sendAdmin(
37-
`🔍 [JOB-${jobId}] Comparing ${currentFlights.length} current flights with ${previousFlights.length} previous flights`,
38-
env,
39-
ctx
40-
)
4128

42-
// 3. Get subscribed flight IDs to filter change detection
4329
const subscribedResult = ctx.storage.sql.exec('SELECT DISTINCT flight_id FROM subscriptions')
4430
const subscribedFlightIds = new Set(
4531
subscribedResult.toArray().map((row) => (row as { flight_id: string }).flight_id)
4632
)
4733

48-
// 4. Build change maps (only for subscribed flights to reduce noise)
4934
const previousFlightsMap = Object.fromEntries(
5035
previousFlights.filter((f) => subscribedFlightIds.has(f.id)).map((f) => [f.id, f])
5136
) as Record<string, Flight>
@@ -69,21 +54,14 @@ export const runScheduledJob = async (env: Env, ctx: DurableObjectState<DOProps>
6954
}
7055
}
7156

72-
// Send alerts if there are changes
7357
if (Object.keys(changesByFlight).length > 0) {
7458
let changeMessage = `🔍 [JOB-${jobId}] Changes detected for ${Object.keys(changesByFlight).length} flights:\n`
7559
for (const [flightId, change] of Object.entries(changesByFlight)) {
7660
changeMessage += `• Flight ${flightId}: ${change.changes.join(', ')}\n`
7761
}
78-
await sendAdmin(changeMessage, env, ctx)
79-
8062
await sendFlightAlerts(changesByFlight, env, ctx)
81-
await sendAdmin(`🔍 [JOB-${jobId}] Alerts sent for ${Object.keys(changesByFlight).length} flights`, env, ctx)
82-
} else {
83-
await sendAdmin(`🔍 [JOB-${jobId}] No changes detected`, env, ctx)
8463
}
8564

86-
// Clean up completed flights every 10 minutes
8765
const lastCleanupResult = ctx.storage.sql.exec("SELECT value FROM status WHERE key = 'last_cleanup_time'")
8866
const lastCleanupRow = lastCleanupResult.toArray()[0] as { value: string } | undefined
8967
const lastCleanupTime = lastCleanupRow ? parseInt(lastCleanupRow.value) : 0
@@ -94,17 +72,14 @@ export const runScheduledJob = async (env: Env, ctx: DurableObjectState<DOProps>
9472
console.log('Running cleanup (10 minute interval)')
9573
cleanupCompletedFlightsFromStatus(env, ctx)
9674

97-
// Update last cleanup time
9875
ctx.storage.sql.exec(
9976
"INSERT INTO status (key, value) VALUES ('last_cleanup_time', ?) ON CONFLICT(key) DO UPDATE SET value = EXCLUDED.value",
10077
now.toString()
10178
)
10279
}
10380

104-
await sendAdmin(`✅ [JOB-${jobId}] Job completed successfully`, env, ctx)
10581
return new Response('Cron job completed')
10682
} catch (error) {
107-
await sendAdmin(`❌ [JOB-${jobId}] Cron job failed: ${error instanceof Error ? error.message : 'Unknown error'}`, env, ctx, 'log')
10883
writeErrorStatus(ctx, error instanceof Error ? error : 'Unknown error')
10984
return new Response('Cron job failed', { status: 500 })
11085
}

0 commit comments

Comments
 (0)