File size: 7,285 Bytes
6c3af4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import type { IncomingMessage, ServerResponse } from "node:http";
import { beforeEach, describe, expect, it, vi } from "vitest";

vi.mock("./handleTokenVerification", () => ({
  handleTokenVerification: vi.fn(),
}));

vi.mock("./pageContentService", () => ({
  fetchPageContents: vi.fn(),
}));

import { handleTokenVerification } from "./handleTokenVerification";
import { pageContentEndpointServerHook } from "./pageContentEndpointServerHook";
import { fetchPageContents } from "./pageContentService";

type Handler = (
  request: IncomingMessage,
  response: ServerResponse,
  next: () => void,
) => Promise<void>;

type RecordedResponse = ServerResponse & {
  setHeader: ReturnType<typeof vi.fn>;
  end: ReturnType<typeof vi.fn>;
};

function callEndpoint(requestUrl: string) {
  const use = vi.fn();
  pageContentEndpointServerHook({
    middlewares: { use },
  } as unknown as Parameters<typeof pageContentEndpointServerHook>[0]);

  const response = {
    statusCode: 200,
    setHeader: vi.fn(),
    end: vi.fn(),
  } as unknown as RecordedResponse;
  const next = vi.fn();
  const request = {
    url: requestUrl,
    headers: { host: "localhost:7860" },
  } as unknown as IncomingMessage;

  return {
    response,
    next,
    handled: (use.mock.calls[0][0] as Handler)(request, response, next),
  };
}

function parseBody(response: RecordedResponse): unknown {
  return JSON.parse(response.end.mock.calls[0][0]);
}

describe("pageContentEndpointServerHook", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(handleTokenVerification).mockResolvedValue({
      shouldContinue: true,
    });
    vi.mocked(fetchPageContents).mockResolvedValue([]);
  });

  it("serves the endpoint", async () => {
    const { handled } = callEndpoint(
      "/page-content?q=cats&url=https%3A%2F%2Fa.example%2F&token=abc",
    );
    await handled;

    expect(fetchPageContents).toHaveBeenCalled();
  });

  it("reads a repeated URL once", async () => {
    const { handled } = callEndpoint(
      "/page-content?q=cats&url=https%3A%2F%2Fa.example%2F&url=https%3A%2F%2Fa.example%2F&url=https%3A%2F%2Fb.example%2F&token=abc",
    );
    await handled;

    expect(fetchPageContents).toHaveBeenCalledWith("cats", [
      "https://a.example/",
      "https://b.example/",
    ]);
  });

  it("counts the repeats against the URL limit before deduping them", async () => {
    // Deduping first would let a caller send any number of `url` params and
    // still get a full batch of reads out of the endpoint.
    const url = "&url=https%3A%2F%2Fa.example%2F";
    const { response, handled } = callEndpoint(
      `/page-content?q=cats${url.repeat(7)}&token=abc`,
    );
    await handled;

    expect(response.statusCode).toBe(400);
    expect(fetchPageContents).not.toHaveBeenCalled();
  });

  it("passes through a path that only starts like the endpoint", async () => {
    const { next, handled } = callEndpoint("/page-content-something-else");
    await handled;

    expect(next).toHaveBeenCalled();
    expect(fetchPageContents).not.toHaveBeenCalled();
  });

  it("passes through requests for other paths", async () => {
    const { next, handled } = callEndpoint("/status");
    await handled;

    expect(next).toHaveBeenCalled();
    expect(fetchPageContents).not.toHaveBeenCalled();
  });

  it("answers with the extracted text keyed by URL", async () => {
    vi.mocked(fetchPageContents).mockResolvedValue([
      { url: "https://a.example/", content: "text from a" },
    ]);

    const { response, handled } = callEndpoint(
      "/page-content?q=cats&url=https%3A%2F%2Fa.example%2F&url=https%3A%2F%2Fb.example%2F&token=abc",
    );
    await handled;

    expect(fetchPageContents).toHaveBeenCalledWith("cats", [
      "https://a.example/",
      "https://b.example/",
    ]);
    expect(response.setHeader).toHaveBeenCalledWith(
      "Content-Type",
      "application/json",
    );
    expect(parseBody(response)).toEqual({
      "https://a.example/": "text from a",
    });
  });

  it("rejects a request without a query", async () => {
    const { response, handled } = callEndpoint(
      "/page-content?url=https%3A%2F%2Fa.example%2F&token=abc",
    );
    await handled;

    expect(response.statusCode).toBe(400);
    expect(parseBody(response)).toEqual({ error: "Missing query parameter" });
    expect(fetchPageContents).not.toHaveBeenCalled();
  });

  it("rejects a request without any URL", async () => {
    const { response, handled } = callEndpoint(
      "/page-content?q=cats&token=abc",
    );
    await handled;

    expect(response.statusCode).toBe(400);
    expect(parseBody(response)).toEqual({ error: "Missing url parameter" });
  });

  it("rejects a URL the browser would never have produced", async () => {
    const { response, handled } = callEndpoint(
      "/page-content?q=cats&url=javascript%3Aalert(1)&token=abc",
    );
    await handled;

    expect(response.statusCode).toBe(400);
    expect(fetchPageContents).not.toHaveBeenCalled();
  });

  it("refuses to read more pages than the prompt can hold", async () => {
    const urls = Array.from(
      { length: 7 },
      (_, index) => `url=https%3A%2F%2Fexample.com%2F${index}`,
    ).join("&");

    const { response, handled } = callEndpoint(
      `/page-content?q=cats&${urls}&token=abc`,
    );
    await handled;

    expect(response.statusCode).toBe(400);
    expect(fetchPageContents).not.toHaveBeenCalled();
  });

  it("stops when token verification fails", async () => {
    vi.mocked(handleTokenVerification).mockResolvedValue({
      shouldContinue: false,
    });

    const { handled } = callEndpoint(
      "/page-content?q=cats&url=https%3A%2F%2Fa.example%2F&token=bad",
    );
    await handled;

    expect(fetchPageContents).not.toHaveBeenCalled();
  });

  it("answers 500 when reading throws", async () => {
    vi.spyOn(console, "error").mockImplementation(() => {});
    vi.mocked(fetchPageContents).mockRejectedValue(new Error("boom"));

    const { response, handled } = callEndpoint(
      "/page-content?q=cats&url=https%3A%2F%2Fa.example%2F&token=abc",
    );
    await handled;

    expect(response.statusCode).toBe(500);
    expect(parseBody(response)).toEqual({ error: "Internal server error" });
  });
  it("records whether a page-content request got anything to ground on", async () => {
    const { getPageReadStats } = await import("./pageReadsSinceLastRestart");
    const before = getPageReadStats().grounding;
    vi.mocked(handleTokenVerification).mockResolvedValue({
      shouldContinue: true,
    });

    const url = "/page-content?q=cats&url=https%3A%2F%2Fa.example%2F&token=abc";

    vi.mocked(fetchPageContents).mockResolvedValue([
      { url: "https://a.example/", content: "text worth quoting" },
    ]);
    await callEndpoint(url).handled;

    expect(getPageReadStats().grounding.withContent).toBe(
      before.withContent + 1,
    );
    expect(getPageReadStats().grounding.withoutContent).toBe(
      before.withoutContent,
    );

    vi.mocked(fetchPageContents).mockResolvedValue([]);
    await callEndpoint(url).handled;

    expect(getPageReadStats().grounding.withoutContent).toBe(
      before.withoutContent + 1,
    );
    expect(getPageReadStats().grounding.requests).toBe(before.requests + 2);
  });
});