@igorjpimenta/winch 2026.11.22-beta.3 → 2026.11.23-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.migrations/0013_webhook_delivery_tables.sql +2 -0
- package/.migrations/meta/0013_snapshot.json +1900 -0
- package/.migrations/meta/_journal.json +8 -1
- package/README.md +27 -43
- package/package.json +1 -1
- package/plugins/README.md +2 -2
- package/src/cli.js +5 -16
- package/src/config.js +3 -7
- package/src/schema.js +3 -3
- package/src/store/delivery.js +16 -16
- package/src/store/events.js +1 -1
- package/src/store/index.js +2 -2
- package/src/tools/assign.js +1 -1
- package/src/tools/definitions.js +0 -1
- package/src/watcher.js +3 -13
- package/src/{dispatch.js → webhook/core.js} +4 -12
- package/src/{dispatch-webhook.js → webhook/delivery.js} +2 -2
- package/src/webhook/envelope.js +131 -0
- package/src/{dispatch-server.js → webhook/server.js} +8 -12
- package/src/events-ws.js +0 -269
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// envelope.js — the event envelope: stored transition rows in, subscriber
|
|
2
|
+
// envelopes out. No socket here. Webhook wakes are the main event driver
|
|
3
|
+
// (delivery.js via server.js); the store write hook and the
|
|
4
|
+
// dispatch boot catch-up share this one shape.
|
|
5
|
+
//
|
|
6
|
+
// kindForEvent: stable kind for a stored transition. Structural inference
|
|
7
|
+
// covers task.* (created, claimed, progressed, completed, released, blocked,
|
|
8
|
+
// cancelled, updated) and gate.* (opened, resolved, dissolved); producers may
|
|
9
|
+
// store story.*, deps.* and release.*. A stored `kind` wins; otherwise the row
|
|
10
|
+
// maps by transition structure alone. Notes are free text and can change, so
|
|
11
|
+
// no branch here may read note content — a renamed note must never
|
|
12
|
+
// reclassify history.
|
|
13
|
+
//
|
|
14
|
+
// Pre-standardization rows still carry `todo` as a task status; map it with
|
|
15
|
+
// `ready` so the append-only history keeps the meaning it was recorded with.
|
|
16
|
+
|
|
17
|
+
import { collectStoryArtifacts } from "../tools/index.js";
|
|
18
|
+
import { depsResolved } from "../deps.js";
|
|
19
|
+
import { HUMAN_AGENT } from "../reserved.js";
|
|
20
|
+
|
|
21
|
+
export const HISTORY_LIMIT = 200;
|
|
22
|
+
|
|
23
|
+
export function lastEventId(store) {
|
|
24
|
+
return store.event.lastEventId();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function eventsSince(store, id, limit = HISTORY_LIMIT) {
|
|
28
|
+
return store.event.since(id, limit);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function eventsLatest(store, limit = HISTORY_LIMIT) {
|
|
32
|
+
return store.event.latest(limit);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function kindForEvent(row) {
|
|
36
|
+
if (row.kind) return row.kind;
|
|
37
|
+
const from = row.from_status;
|
|
38
|
+
const to = row.to_status;
|
|
39
|
+
if (from == null) return "task.created";
|
|
40
|
+
if ((from === "ready" || from === "todo") && to === "in_progress") return "task.claimed";
|
|
41
|
+
if (from === "in_progress" && to === "in_progress") return "task.progressed";
|
|
42
|
+
if (to === "done") return "task.completed";
|
|
43
|
+
if (to === "cancelled") return "task.cancelled";
|
|
44
|
+
if (to === "blocked") return "task.blocked";
|
|
45
|
+
if (to === "ready" || to === "todo") return "task.released";
|
|
46
|
+
return "task.updated";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// One envelope shape for history and live rows alike: the stored transition
|
|
50
|
+
// plus the task, story and epic context a subscriber would otherwise fetch
|
|
51
|
+
// once per row. Artifacts come from the same collector the claim handoff
|
|
52
|
+
// uses, so both paths agree on what "the artifacts" means.
|
|
53
|
+
function unblockedFor(store, row, kind) {
|
|
54
|
+
const terminal = row.to_status === "done" || row.to_status === "cancelled";
|
|
55
|
+
const claims = terminal
|
|
56
|
+
|| kind === "task.released" || kind === "task.appended"
|
|
57
|
+
|| kind === "deps.resolved" || kind === "gate.resolved";
|
|
58
|
+
if (!claims) return [];
|
|
59
|
+
|
|
60
|
+
const ids = new Set();
|
|
61
|
+
if (terminal) {
|
|
62
|
+
for (const edge of store.dep.listIncoming(row.item_id)) ids.add(edge.from_id);
|
|
63
|
+
} else if (row.item_id) {
|
|
64
|
+
ids.add(row.item_id);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const id of ids) {
|
|
69
|
+
const task = store.task.get(id);
|
|
70
|
+
if (!task || task.status !== "ready" || !task.assignee_agent || task.assignee_agent === HUMAN_AGENT) continue;
|
|
71
|
+
if (!depsResolved(store, id)) continue;
|
|
72
|
+
out.push({ id: task.id, assigned: task.assignee_agent, assigneeHarness: task.assignee_harness });
|
|
73
|
+
if (out.length === 20) break;
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function toEventMessage(store, row, { includeArtifacts = true, includeUnblocked = true } = {}) {
|
|
79
|
+
const kind = kindForEvent(row);
|
|
80
|
+
const item = !row.item_id ? null : store.item.get(row.item_id);
|
|
81
|
+
const itemKind = item?.kind ?? null;
|
|
82
|
+
const task = itemKind === "task" ? item : null;
|
|
83
|
+
const story = itemKind === "story" ? item : task?.story_id ? store.story.get(task.story_id) : null;
|
|
84
|
+
const epic = itemKind === "epic" ? item : story?.epic_id ? store.epic.get(story.epic_id) : item?.epic_id ? store.epic.get(item.epic_id) : null;
|
|
85
|
+
const actorSession = row.session_id ? store.session.get(row.session_id) : null;
|
|
86
|
+
return {
|
|
87
|
+
type: "event",
|
|
88
|
+
kind,
|
|
89
|
+
id: row.id,
|
|
90
|
+
at: row.created_at,
|
|
91
|
+
fromStatus: row.from_status ?? null,
|
|
92
|
+
toStatus: row.to_status,
|
|
93
|
+
// Normalised item: a dispatcher routes assignment and review wakes without
|
|
94
|
+
// knowing which level the row is about.
|
|
95
|
+
item: item
|
|
96
|
+
? {
|
|
97
|
+
id: item.id,
|
|
98
|
+
kind: itemKind,
|
|
99
|
+
title: item.title,
|
|
100
|
+
status: item.status,
|
|
101
|
+
assigned: item.assignee_agent ?? null,
|
|
102
|
+
assigneeHarness: item.assignee_harness ?? null,
|
|
103
|
+
createdBy: item.created_by ?? null,
|
|
104
|
+
}
|
|
105
|
+
: null,
|
|
106
|
+
epicId: epic?.id ?? null,
|
|
107
|
+
epicCreatedBy: epic?.created_by ?? null,
|
|
108
|
+
epicAssigneeHarness: epic?.assignee_harness ?? null,
|
|
109
|
+
storyId: story?.id ?? null,
|
|
110
|
+
storyAssigned: story?.assignee_agent ?? null,
|
|
111
|
+
storyAssigneeHarness: story?.assignee_harness ?? null,
|
|
112
|
+
// Work a transition just made claimable: a dispatcher wakes these without
|
|
113
|
+
// recomputing the dependency graph. Creation and direct assignment already
|
|
114
|
+
// route their own item, so only a close looks at incoming edges.
|
|
115
|
+
unblocked: includeUnblocked ? unblockedFor(store, row, kind) : [],
|
|
116
|
+
task: task
|
|
117
|
+
? {
|
|
118
|
+
id: task.id,
|
|
119
|
+
title: task.title,
|
|
120
|
+
story: story ? story.title : null,
|
|
121
|
+
epic: epic ? epic.title : null,
|
|
122
|
+
acceptance: story ? story.acceptance : null,
|
|
123
|
+
artifacts: includeArtifacts && story ? collectStoryArtifacts(store, story.id) : [],
|
|
124
|
+
assignee: task.assignee_agent,
|
|
125
|
+
}
|
|
126
|
+
: null,
|
|
127
|
+
actor: row.actor,
|
|
128
|
+
actorHarness: actorSession?.harness ?? null,
|
|
129
|
+
note: row.note,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
//
|
|
2
|
-
// Executors register here and winch POSTs wakes from here;
|
|
3
|
-
//
|
|
1
|
+
// server.js — HTTP dispatch endpoints and the admission queue pump.
|
|
2
|
+
// Executors register here and winch POSTs webhook wakes from here; webhook
|
|
3
|
+
// delivery is the main event driver.
|
|
4
4
|
|
|
5
5
|
import http from "node:http";
|
|
6
|
-
import { observe, recover, tick as dispatchTick } from "./
|
|
7
|
-
import { deliverDue, deliverWake } from "./
|
|
8
|
-
import { StaleRegistrationError } from "
|
|
9
|
-
import { eventsSince, lastEventId, toEventMessage, HISTORY_LIMIT } from "./
|
|
6
|
+
import { observe, recover, tick as dispatchTick } from "./core.js";
|
|
7
|
+
import { deliverDue, deliverWake } from "./delivery.js";
|
|
8
|
+
import { StaleRegistrationError } from "../store/webhook.js";
|
|
9
|
+
import { eventsSince, lastEventId, toEventMessage, HISTORY_LIMIT } from "./envelope.js";
|
|
10
10
|
|
|
11
11
|
export const DEFAULT_DISPATCH_PORT = 38293;
|
|
12
12
|
|
|
@@ -16,7 +16,7 @@ export function startDispatchServer({ store, port = null, host = "127.0.0.1", in
|
|
|
16
16
|
const pollMs = intervalMs ?? cfg.dispatchIntervalMs ?? 1000;
|
|
17
17
|
const sweepMs = cfg.dispatchSweepMs ?? 30000;
|
|
18
18
|
const consumerTtlMs = cfg.dispatchConsumerTtlMs ?? 90000;
|
|
19
|
-
const histLimit = cfg.
|
|
19
|
+
const histLimit = cfg.eventHistoryLimit ?? HISTORY_LIMIT;
|
|
20
20
|
const authToken = String(process.env.WINCH_DISPATCH_TOKEN ?? "").trim() || null;
|
|
21
21
|
const loopback = host === "127.0.0.1" || host === "::1" || host === "localhost";
|
|
22
22
|
if (!loopback && !authToken) {
|
|
@@ -128,10 +128,6 @@ export function startDispatchServer({ store, port = null, host = "127.0.0.1", in
|
|
|
128
128
|
managed: true,
|
|
129
129
|
fresh,
|
|
130
130
|
});
|
|
131
|
-
if (executorId && id !== executorId) {
|
|
132
|
-
const legacy = store.webhook.get({ topic: "dispatch", id: executorId });
|
|
133
|
-
if (legacy?.executorId === executorId) store.webhook.remove({ topic: "dispatch", id: executorId });
|
|
134
|
-
}
|
|
135
131
|
json(res, 201, {
|
|
136
132
|
ok: true, topic: row.topic, id: row.id, harness: row.harness,
|
|
137
133
|
executorId: row.executorId, instanceId: row.instanceId,
|
package/src/events-ws.js
DELETED
|
@@ -1,269 +0,0 @@
|
|
|
1
|
-
// events-ws.js — the read-only event pipe.
|
|
2
|
-
// Tails the item_events ledger and broadcasts every new row; dispatch wakes
|
|
3
|
-
// leave over executor webhooks served by dispatch-server.js, not this socket.
|
|
4
|
-
//
|
|
5
|
-
// Wire protocol (JSON text frames):
|
|
6
|
-
// server → client:
|
|
7
|
-
// {"type":"welcome","payload":"v3","lastEventId":N}
|
|
8
|
-
// {"type":"history","events":[...]} backlog of envelopes, oldest-first
|
|
9
|
-
// {"type":"event","kind":...,"item":{...},...} one flat envelope per new row, in id order
|
|
10
|
-
//
|
|
11
|
-
// Clients track their own seen state: reconnecting replays history, so a
|
|
12
|
-
// missed frame costs a re-read, never a lost event. The admission queue owns
|
|
13
|
-
// wake delivery and retry; MCP claim remains the work-level guard. No auth
|
|
14
|
-
// in-process — bind localhost, or put a bearer-checked reverse proxy in front.
|
|
15
|
-
|
|
16
|
-
import http from "node:http";
|
|
17
|
-
import crypto from "node:crypto";
|
|
18
|
-
import { collectStoryArtifacts } from "./tools/index.js";
|
|
19
|
-
import { depsResolved } from "./deps.js";
|
|
20
|
-
import { HUMAN_AGENT } from "./reserved.js";
|
|
21
|
-
|
|
22
|
-
const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
23
|
-
export const DEFAULT_WS_PORT = 38291;
|
|
24
|
-
export const HISTORY_LIMIT = 200;
|
|
25
|
-
|
|
26
|
-
function acceptKey(key) {
|
|
27
|
-
return crypto.createHash("sha1").update(key + WS_GUID).digest("base64");
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// Server → client frames are never masked (RFC 6455 §5.3).
|
|
31
|
-
function encodeFrame(text) {
|
|
32
|
-
const payload = Buffer.from(text, "utf8");
|
|
33
|
-
const len = payload.length;
|
|
34
|
-
let header;
|
|
35
|
-
if (len < 126) {
|
|
36
|
-
header = Buffer.from([0x81, len]);
|
|
37
|
-
} else if (len < 65536) {
|
|
38
|
-
header = Buffer.alloc(4);
|
|
39
|
-
header[0] = 0x81;
|
|
40
|
-
header[1] = 126;
|
|
41
|
-
header.writeUInt16BE(len, 2);
|
|
42
|
-
} else {
|
|
43
|
-
header = Buffer.alloc(10);
|
|
44
|
-
header[0] = 0x81;
|
|
45
|
-
header[1] = 127;
|
|
46
|
-
header.writeBigUInt64BE(BigInt(len), 2);
|
|
47
|
-
}
|
|
48
|
-
return Buffer.concat([header, payload]);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export function lastEventId(store) {
|
|
52
|
-
return store.event.lastEventId();
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export function eventsSince(store, id, limit = HISTORY_LIMIT) {
|
|
56
|
-
return store.event.since(id, limit);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
export function eventsLatest(store, limit = HISTORY_LIMIT) {
|
|
60
|
-
return store.event.latest(limit);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// Stable kind for a stored transition. Structural inference covers task.*
|
|
64
|
-
// (created, claimed, progressed, completed, released, blocked, cancelled,
|
|
65
|
-
// updated) and gate.* (opened, resolved, dissolved); producers may store
|
|
66
|
-
// story.*, deps.* and release.*. A stored `kind` wins; otherwise the row maps
|
|
67
|
-
// by transition structure alone. Notes are free text and can change, so no
|
|
68
|
-
// branch here may read note content —
|
|
69
|
-
// a renamed note must never reclassify history.
|
|
70
|
-
//
|
|
71
|
-
// Pre-standardization rows still carry `todo` as a task status; map it with
|
|
72
|
-
// `ready` so the append-only history keeps the meaning it streamed with.
|
|
73
|
-
export function kindForEvent(row) {
|
|
74
|
-
if (row.kind) return row.kind;
|
|
75
|
-
const from = row.from_status;
|
|
76
|
-
const to = row.to_status;
|
|
77
|
-
if (from == null) return "task.created";
|
|
78
|
-
if ((from === "ready" || from === "todo") && to === "in_progress") return "task.claimed";
|
|
79
|
-
if (from === "in_progress" && to === "in_progress") return "task.progressed";
|
|
80
|
-
if (to === "done") return "task.completed";
|
|
81
|
-
if (to === "cancelled") return "task.cancelled";
|
|
82
|
-
if (to === "blocked") return "task.blocked";
|
|
83
|
-
if (to === "ready" || to === "todo") return "task.released";
|
|
84
|
-
return "task.updated";
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// One envelope shape for history and live rows alike: the stored transition
|
|
88
|
-
// plus the task, story and epic context a subscriber would otherwise fetch
|
|
89
|
-
// once per row. Artifacts come from the same collector the claim handoff
|
|
90
|
-
// uses, so both paths agree on what "the artifacts" means.
|
|
91
|
-
function unblockedFor(store, row, kind) {
|
|
92
|
-
const terminal = row.to_status === "done" || row.to_status === "cancelled";
|
|
93
|
-
const claims = terminal
|
|
94
|
-
|| kind === "task.released" || kind === "task.appended"
|
|
95
|
-
|| kind === "deps.resolved" || kind === "gate.resolved";
|
|
96
|
-
if (!claims) return [];
|
|
97
|
-
|
|
98
|
-
const ids = new Set();
|
|
99
|
-
if (terminal) {
|
|
100
|
-
for (const edge of store.dep.listIncoming(row.item_id)) ids.add(edge.from_id);
|
|
101
|
-
} else if (row.item_id) {
|
|
102
|
-
ids.add(row.item_id);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const out = [];
|
|
106
|
-
for (const id of ids) {
|
|
107
|
-
const task = store.task.get(id);
|
|
108
|
-
if (!task || task.status !== "ready" || !task.assignee_agent || task.assignee_agent === HUMAN_AGENT) continue;
|
|
109
|
-
if (!depsResolved(store, id)) continue;
|
|
110
|
-
out.push({ id: task.id, assigned: task.assignee_agent, assigneeHarness: task.assignee_harness });
|
|
111
|
-
if (out.length === 20) break;
|
|
112
|
-
}
|
|
113
|
-
return out;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
export function toEventMessage(store, row, { includeArtifacts = true, includeUnblocked = true } = {}) {
|
|
117
|
-
const kind = kindForEvent(row);
|
|
118
|
-
const item = !row.item_id ? null : store.item.get(row.item_id);
|
|
119
|
-
const itemKind = item?.kind ?? null;
|
|
120
|
-
const task = itemKind === "task" ? item : null;
|
|
121
|
-
const story = itemKind === "story" ? item : task?.story_id ? store.story.get(task.story_id) : null;
|
|
122
|
-
const epic = itemKind === "epic" ? item : story?.epic_id ? store.epic.get(story.epic_id) : item?.epic_id ? store.epic.get(item.epic_id) : null;
|
|
123
|
-
const actorSession = row.session_id ? store.session.get(row.session_id) : null;
|
|
124
|
-
return {
|
|
125
|
-
type: "event",
|
|
126
|
-
kind,
|
|
127
|
-
id: row.id,
|
|
128
|
-
at: row.created_at,
|
|
129
|
-
fromStatus: row.from_status ?? null,
|
|
130
|
-
toStatus: row.to_status,
|
|
131
|
-
// Normalised item: a dispatcher routes assignment and review wakes without
|
|
132
|
-
// knowing which level the row is about.
|
|
133
|
-
item: item
|
|
134
|
-
? {
|
|
135
|
-
id: item.id,
|
|
136
|
-
kind: itemKind,
|
|
137
|
-
title: item.title,
|
|
138
|
-
status: item.status,
|
|
139
|
-
assigned: item.assignee_agent ?? null,
|
|
140
|
-
assigneeHarness: item.assignee_harness ?? null,
|
|
141
|
-
createdBy: item.created_by ?? null,
|
|
142
|
-
}
|
|
143
|
-
: null,
|
|
144
|
-
epicId: epic?.id ?? null,
|
|
145
|
-
epicCreatedBy: epic?.created_by ?? null,
|
|
146
|
-
epicAssigneeHarness: epic?.assignee_harness ?? null,
|
|
147
|
-
storyId: story?.id ?? null,
|
|
148
|
-
storyAssigned: story?.assignee_agent ?? null,
|
|
149
|
-
storyAssigneeHarness: story?.assignee_harness ?? null,
|
|
150
|
-
// Work a transition just made claimable: a dispatcher wakes these without
|
|
151
|
-
// recomputing the dependency graph. Creation and direct assignment already
|
|
152
|
-
// route their own item, so only a close looks at incoming edges.
|
|
153
|
-
unblocked: includeUnblocked ? unblockedFor(store, row, kind) : [],
|
|
154
|
-
task: task
|
|
155
|
-
? {
|
|
156
|
-
id: task.id,
|
|
157
|
-
title: task.title,
|
|
158
|
-
story: story ? story.title : null,
|
|
159
|
-
epic: epic ? epic.title : null,
|
|
160
|
-
acceptance: story ? story.acceptance : null,
|
|
161
|
-
artifacts: includeArtifacts && story ? collectStoryArtifacts(store, story.id) : [],
|
|
162
|
-
assignee: task.assignee_agent,
|
|
163
|
-
}
|
|
164
|
-
: null,
|
|
165
|
-
actor: row.actor,
|
|
166
|
-
actorHarness: actorSession?.harness ?? null,
|
|
167
|
-
note: row.note,
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export function startEventServer({ store, port = null, host = "127.0.0.1", intervalMs = null, historyLimit = null, logger } = {}) {
|
|
172
|
-
const cfg = store.config ?? {};
|
|
173
|
-
const listenPort = port ?? cfg.wsPort ?? DEFAULT_WS_PORT;
|
|
174
|
-
const pollMs = intervalMs ?? cfg.wsIntervalMs ?? 1000;
|
|
175
|
-
const histLimit = historyLimit ?? cfg.wsHistoryLimit ?? HISTORY_LIMIT;
|
|
176
|
-
const clients = new Map();
|
|
177
|
-
let closing = false;
|
|
178
|
-
let cursor = lastEventId(store);
|
|
179
|
-
|
|
180
|
-
function send(socket, obj) {
|
|
181
|
-
if (socket.destroyed || !socket.writable) return false;
|
|
182
|
-
try {
|
|
183
|
-
socket.write(encodeFrame(JSON.stringify(obj)));
|
|
184
|
-
return true;
|
|
185
|
-
} catch {
|
|
186
|
-
return false;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
function broadcast(obj) {
|
|
191
|
-
const frame = encodeFrame(JSON.stringify(obj));
|
|
192
|
-
for (const client of [...clients.values()]) {
|
|
193
|
-
const sock = client.socket;
|
|
194
|
-
if (sock.destroyed || !sock.writable) {
|
|
195
|
-
clients.delete(sock);
|
|
196
|
-
continue;
|
|
197
|
-
}
|
|
198
|
-
sock.write(frame);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
const server = http.createServer((req, res) => {
|
|
203
|
-
res.writeHead(404, { "content-type": "application/json" });
|
|
204
|
-
res.end(JSON.stringify({ error: "not found" }));
|
|
205
|
-
});
|
|
206
|
-
|
|
207
|
-
server.on("upgrade", (req, socket) => {
|
|
208
|
-
const key = req.headers["sec-websocket-key"];
|
|
209
|
-
if ((req.headers.upgrade || "").toLowerCase() !== "websocket" || !key) {
|
|
210
|
-
socket.destroy();
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
socket.write(
|
|
214
|
-
"HTTP/1.1 101 Switching Protocols\r\n" +
|
|
215
|
-
"Upgrade: websocket\r\n" +
|
|
216
|
-
"Connection: Upgrade\r\n" +
|
|
217
|
-
`Sec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`
|
|
218
|
-
);
|
|
219
|
-
const client = { socket, connectedAt: Date.now() };
|
|
220
|
-
clients.set(socket, client);
|
|
221
|
-
logger?.info?.(`winch: ws subscriber connected (${clients.size} total)`);
|
|
222
|
-
try {
|
|
223
|
-
send(socket, { type: "welcome", payload: "v3", lastEventId: cursor });
|
|
224
|
-
send(socket, { type: "history", events: eventsLatest(store, histLimit).map((row) => toEventMessage(store, row)) });
|
|
225
|
-
} catch {
|
|
226
|
-
clients.delete(socket);
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
const drop = () => {
|
|
230
|
-
clients.delete(socket);
|
|
231
|
-
if (closing) return;
|
|
232
|
-
};
|
|
233
|
-
socket.on("close", drop);
|
|
234
|
-
socket.on("error", drop);
|
|
235
|
-
});
|
|
236
|
-
|
|
237
|
-
const timer = setInterval(() => {
|
|
238
|
-
try {
|
|
239
|
-
const rows = eventsSince(store, cursor, histLimit);
|
|
240
|
-
if (rows.length) {
|
|
241
|
-
cursor = rows[rows.length - 1].id;
|
|
242
|
-
for (const row of rows) {
|
|
243
|
-
broadcast(toEventMessage(store, row));
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
} catch (err) {
|
|
247
|
-
logger?.warn?.(`winch: event poll failed: ${err?.message ?? err}`);
|
|
248
|
-
}
|
|
249
|
-
}, pollMs);
|
|
250
|
-
if (typeof timer.unref === "function") timer.unref();
|
|
251
|
-
|
|
252
|
-
return new Promise((resolve, reject) => {
|
|
253
|
-
server.once("error", reject);
|
|
254
|
-
server.listen(listenPort, host, () => {
|
|
255
|
-
resolve({
|
|
256
|
-
port: server.address().port,
|
|
257
|
-
host,
|
|
258
|
-
clients: () => clients.size,
|
|
259
|
-
close: () =>
|
|
260
|
-
new Promise((res) => {
|
|
261
|
-
closing = true;
|
|
262
|
-
clearInterval(timer);
|
|
263
|
-
for (const client of clients.values()) client.socket.destroy();
|
|
264
|
-
server.close(() => res());
|
|
265
|
-
}),
|
|
266
|
-
});
|
|
267
|
-
});
|
|
268
|
-
});
|
|
269
|
-
}
|