-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.ts
184 lines (152 loc) · 4.19 KB
/
counter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// file: src/server/counter.ts
import { CONTEXT_SESSION_ID } from './session';
import type { EventHandlerRequest, H3Event } from 'h3';
type RequestEvent = H3Event<EventHandlerRequest>;
export type CountDispatch = (count: number, id: string) => void;
export type CounterRecord = {
id: string;
lastEventId: string;
count: number;
observers: number;
};
type TaskRecord = {
id: string;
task: () => Promise<void>;
};
// --- Task Queue
const taskQueue: TaskRecord[] = [];
const locate = new (class {
id = '';
readonly withId = (record: TaskRecord) => this.id === record.id;
readonly countWithId = (count: number, record: TaskRecord) =>
this.id === record.id ? count + 1 : count;
})();
// Continue running until there are no more tasks with the same
// session IDs in taskQueue
async function runTasks(record: TaskRecord) {
for (
;
typeof record !== 'undefined';
locate.id = record.id, record = taskQueue.find(locate.withId)
) {
await record.task();
const index = taskQueue.indexOf(record);
taskQueue.splice(index, 1);
}
}
function queueTask(record: TaskRecord) {
locate.id = record.id;
const count = taskQueue.reduce(locate.countWithId, 0);
taskQueue.push(record);
// Others with identical session ID already running
if (count > 0) return;
runTasks(record);
}
// --- Storage Tnteraction
//
const CONTEXT_COUNTER = 'counter';
const STORAGE_COUNTER = 'counter';
const makeCounterRecord = (id: string, lastEventId: string): CounterRecord => ({
id,
lastEventId,
count: 0,
observers: 1,
});
// inferred return type should also included `undefined`
async function counterRecord(id: unknown): Promise<CounterRecord | void> {
if (typeof id !== 'string') return undefined;
return (
(await useStorage(STORAGE_COUNTER).getItem<CounterRecord>(id)) ?? undefined
);
}
const removeRecord = (id: string) => useStorage(STORAGE_COUNTER).removeItem(id);
const updateRecord = (record: CounterRecord) =>
useStorage(STORAGE_COUNTER).setItem<CounterRecord>(record.id, record);
// --- Tasks
//
function counterRecordFromEvent(event: RequestEvent) {
const id = event.context[CONTEXT_SESSION_ID];
const counterId = event.context[CONTEXT_COUNTER];
return new Promise<CounterRecord | void>((resolve, reject) => {
const task = async () => {
try {
const record = await counterRecord(counterId);
return resolve(record);
} catch (error) {
reject(error);
}
};
queueTask({ id, task });
});
}
function increment(event: RequestEvent) {
const id = event.context[CONTEXT_SESSION_ID];
const counterId = event.context[CONTEXT_COUNTER];
return new Promise<CounterRecord | void>((resolve, reject) => {
const task = async () => {
try {
const record = await counterRecord(counterId);
if (!record) return resolve(undefined);
record.count += 1;
record.lastEventId = String(Date.now());
await updateRecord(record);
return resolve(record);
} catch (error) {
reject(error);
}
};
queueTask({ id, task });
});
}
function addObserver(
event: RequestEvent,
refreshId: (event: RequestEvent) => Promise<string>
) {
const id = event.context[CONTEXT_SESSION_ID];
const counterId = event.context[CONTEXT_COUNTER];
return new Promise<CounterRecord>((resolve, reject) => {
const task = async () => {
try {
let record = await counterRecord(counterId);
if (record) {
record.observers += 1;
} else {
const freshId = await refreshId(event);
record = makeCounterRecord(freshId, String(Date.now()));
}
await updateRecord(record);
return resolve(record);
} catch (error) {
reject(error);
}
};
queueTask({ id, task });
});
}
function dropObserver(counterId: string, id: string) {
return new Promise<CounterRecord | void>((resolve, reject) => {
const task = async () => {
try {
const record = await counterRecord(counterId);
if (!record) return resolve(undefined);
if (record.observers < 2) {
await removeRecord(record.id);
return resolve(undefined);
}
record.observers -= 1;
await updateRecord(record);
return resolve(record);
} catch (error) {
reject(error);
}
};
queueTask({ id, task });
});
}
export {
CONTEXT_COUNTER,
addObserver,
counterRecordFromEvent,
dropObserver,
increment,
};