Newer
Older
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
/**
* Cache the contents of the database into redis keys
*
* Each cache chunk should aim be 100x100 pixels
*/
import { parentPort } from "node:worker_threads";
import { getLogger } from "../lib/Logger";
import { Redis } from "../lib/redis";
import { prisma } from "../lib/prisma";
// TODO: config maybe?
// <!> this value is hardcoded in #getCanvasSectionFromCoords
const canvasSectionSize = [100, 100];
type Message =
| { type: "id"; workerId: number }
| {
type: "cache";
start: [x: number, y: number];
end: [x: number, y: number];
callbackId: string;
}
| {
type: "write_pixel";
};
let Logger = getLogger("CANVAS_WORK");
/**
* We run the connection directly instead of via class functions to prevent side effects
*/
const redis = Redis.client;
redis.connect().then(() => {
Logger.info("Connected to Redis");
});
let workerId: number;
parentPort?.on("message", (msg: Message) => {
switch (msg.type) {
case "id":
workerId = msg.workerId;
Logger = getLogger("CANVAS_WORK", workerId);
Logger.info("Received worker ID assignment: " + workerId);
startWriteQueue().then(() => {});
break;
case "cache":
doCache(msg.start, msg.end).then(() => {
parentPort?.postMessage({
type: "callback",
callbackId: msg.callbackId,
});
});
break;
}
});
/**
* Get canvas section from coordinates
*
* @note This is hardcoded to expect the section size to be 100x100 pixels
*
* @param x
* @param y
*/
const getCanvasSectionFromCoords = (
x: number,
y: number
): { start: [x: number, y: number]; end: [x: number, y: number] } => {
// since we are assuming the section size is 100x100
// we can get the start position based on the hundreds position
const baseX = Math.floor((x % 1000) / 100); // get the hundreds
const baseY = Math.floor((y % 1000) / 100); // get the hundreds
return {
start: [baseX * 100, baseY * 100],
end: [baseX * 100 + 100, baseY * 100 + 100],
};
};
const startWriteQueue = async () => {
const item = await redis.lPop(
Redis.key("canvas_cache_write_queue", workerId)
);
if (!item) {
setTimeout(() => {
startWriteQueue();
}, 250);
return;
}
const x = parseInt(item.split(",")[0]);
const y = parseInt(item.split(",")[1]);
const color = item.split(",")[2];
const section = getCanvasSectionFromCoords(x, y);
const pixels: string[] = (
(await redis.get(
Redis.key("canvas_section", section.start, section.end)
)) || ""
).split(",");
const arrX = x - section.start[0];
const arrY = y - section.start[1];
pixels[canvasSectionSize[0] * arrY + arrX] = color;
await redis.set(
Redis.key("canvas_section", section.start, section.end),
pixels.join(",")
);
startWriteQueue();
};
const doCache = async (
start: [x: number, y: number],
end: [x: number, y: number]
) => {
const now = Date.now();
Logger.info(
"starting cache of section " + start.join(",") + " -> " + end.join(",")
);
const dbpixels = await prisma.pixel.findMany({
where: {
x: {
gte: start[0],
lt: end[0],
},
y: {
gte: start[1],
lt: end[1],
},
isTop: true,
},
});
const pixels: string[] = [];
// (y -> x) because of how the conversion needs to be done later
// if this is inverted, the map will flip when rebuilding the cache (5 minute expiry)
// fixes #24
for (let y = start[1]; y < end[1]; y++) {
for (let x = start[0]; x < end[0]; x++) {
pixels.push(
dbpixels.find((px) => px.x === x && px.y === y)?.color || "transparent"
);
}
}
await redis.set(Redis.key("canvas_section", start, end), pixels.join(","));
Logger.info(
"finished cache of section " +
start.join(",") +
" -> " +
end.join(",") +
" in " +
((Date.now() - now) / 1000).toFixed(2) +
"s"
);
};