Skip to content

WebSocketを使い回す #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions browser/websocket/deletePage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Socket, socketIO, wrap } from "../../deps/socket.ts";
import { connect, disconnect } from "./socket.ts";
import { getProjectId, getUserId } from "./id.ts";
import { pull } from "./pull.ts";
import { pushWithRetry } from "./_fetch.ts";

export interface DeletePageOptions {
socket?: Socket;
}

/** 指定したページを削除する
*
* @param project 削除したいページのproject
* @param title 削除したいページのタイトル
* @param options 使用したいSocketがあれば指定する
*/
export async function deletePage(
project: string,
title: string,
options?: DeletePageOptions,
): Promise<void> {
const [
{ pageId, commitId: parentId, persistent },
projectId,
userId,
] = await Promise.all([
pull(project, title),
getProjectId(project),
getUserId(),
]);

if (!persistent) return;

const injectedSocket = options?.socket;
const socket = injectedSocket ?? await socketIO();
await connect(socket);
const { request } = wrap(socket);
try {
await pushWithRetry(request, [{ deleted: true }], {
projectId,
pageId,
parentId,
userId,
project,
title,
});
} finally {
if (!injectedSocket) await disconnect(socket);
}
}
54 changes: 54 additions & 0 deletions browser/websocket/listen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import {
ProjectUpdatesStreamCommit,
ProjectUpdatesStreamEvent,
Socket,
socketIO,
wrap,
} from "../../deps/socket.ts";
import { connect, disconnect } from "./socket.ts";
import { getProjectId } from "./id.ts";
export type {
ProjectUpdatesStreamCommit,
ProjectUpdatesStreamEvent,
} from "../../deps/socket.ts";

export interface ListenStreamOptions {
socket?: Socket;
}

/** Streamを購読する
*
* @param project 購読したいproject
* @param events 購読したいevent。配列で指定する
* @param options 使用したいSocketがあれば指定する
*/
export async function* listenStream(
project: string,
events: ["commit" | "event", ...("commit" | "event")[]],
options?: ListenStreamOptions,
): AsyncGenerator<
ProjectUpdatesStreamEvent | ProjectUpdatesStreamCommit,
void,
unknown
> {
const projectId = await getProjectId(project);

const injectedSocket = options?.socket;
const socket = injectedSocket ?? await socketIO();
await connect(socket);
const { request, response } = wrap(socket);

try {
// 部屋に入って購読し始める
await request("socket.io-request", {
method: "room:join",
data: { projectId, pageId: null, projectUpdatesStream: true },
});

yield* response(
...events.map((event) => `projectUpdatesStream:${event}` as const),
);
} finally {
if (!injectedSocket) await disconnect(socket);
}
}
6 changes: 4 additions & 2 deletions browser/websocket/mod.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export * from "./room.ts";
export * from "./shortcuts.ts";
export * from "./stream.ts";
export * from "./patch.ts";
export * from "./deletePage.ts";
export * from "./pin.ts";
export * from "./listen.ts";
93 changes: 93 additions & 0 deletions browser/websocket/patch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { Socket, socketIO, wrap } from "../../deps/socket.ts";
import { connect, disconnect } from "./socket.ts";
import { getProjectId, getUserId } from "./id.ts";
import { makeChanges } from "./makeChanges.ts";
import { HeadData, pull } from "./pull.ts";
import type { Line } from "../../deps/scrapbox.ts";
import { pushCommit, pushWithRetry } from "./_fetch.ts";

export interface PatchOptions {
socket?: Socket;
}

/** ページ全体を書き換える
*
* serverには書き換え前後の差分だけを送信する
*
* @param project 書き換えたいページのproject
* @param title 書き換えたいページのタイトル
* @param update 書き換え後の本文を作成する函数。引数には現在の本文が渡される。空配列を返すとページが削除される。undefinedを返すと書き換えを中断する
* @param options 使用したいSocketがあれば指定する
*/
export async function patch(
project: string,
title: string,
update: (
lines: Line[],
metadata: HeadData,
) => string[] | undefined | Promise<string[] | undefined>,
options?: PatchOptions,
): Promise<void> {
const [
head_,
projectId,
userId,
] = await Promise.all([
pull(project, title),
getProjectId(project),
getUserId(),
]);

let head = head_;

const injectedSocket = options?.socket;
const socket = injectedSocket ?? await socketIO();
await connect(socket);
try {
const { request } = wrap(socket);

// 3回retryする
for (let i = 0; i < 3; i++) {
try {
const pending = update(head.lines, head);
const newLines = pending instanceof Promise ? await pending : pending;

if (!newLines) return;

if (newLines.length === 0) {
await pushWithRetry(request, [{ deleted: true }], {
projectId,
pageId: head.pageId,
parentId: head.commitId,
userId,
project,
title,
});
}

const changes = makeChanges(head.lines, newLines, { userId, head });
await pushCommit(request, changes, {
parentId: head.commitId,
projectId,
pageId: head.pageId,
userId,
});
break;
} catch (_e: unknown) {
if (i === 2) {
throw Error("Faild to retry pushing.");
}
console.log(
"Faild to push a commit. Retry after pulling new commits",
);
try {
head = await pull(project, title);
} catch (e: unknown) {
throw e;
}
}
}
} finally {
if (!injectedSocket) await disconnect(socket);
}
}
113 changes: 113 additions & 0 deletions browser/websocket/pin.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,115 @@
import { Socket, socketIO, wrap } from "../../deps/socket.ts";
import { connect, disconnect } from "./socket.ts";
import { getProjectId, getUserId } from "./id.ts";
import { pull } from "./pull.ts";
import { pushWithRetry } from "./_fetch.ts";

export interface PinOptions {
/** ピン留め対象のページが存在しないときの振る舞いを変えるoption
*
* -`true`: タイトルのみのページを作成してピン留めする
* - `false`: ピン留めしない
*
* @default false
*/
create?: boolean;
socket?: Socket;
}
/** 指定したページをピン留めする
*
* @param project ピン留めしたいページのproject
* @param title ピン留めしたいページのタイトル
* @param options 使用したいSocketがあれば指定する
*/
export async function pin(
project: string,
title: string,
options?: PinOptions,
): Promise<void> {
const [
head,
projectId,
userId,
] = await Promise.all([
pull(project, title),
getProjectId(project),
getUserId(),
]);

// 既にピン留めされている場合は何もしない
if (head.pin > 0 || (!head.persistent && !(options?.create ?? false))) return;

const init = {
parentId: head.commitId,
projectId,
pageId: head.pageId,
userId,
project,
title,
};
const injectedSocket = options?.socket;
const socket = injectedSocket ?? await socketIO();
await connect(socket);
const { request } = wrap(socket);

// タイトルのみのページを作る
if (!head.persistent) {
const commitId = await pushWithRetry(request, [{ title }], init);
init.parentId = commitId;
}

try {
await pushWithRetry(request, [{ pin: pinNumber() }], init);
} finally {
if (!injectedSocket) await disconnect(socket);
}
}

export interface UnPinOptions {
socket?: Socket;
}
/** 指定したページのピン留めを外す
*
* @param project ピン留めを外したいページのproject
* @param title ピン留めを外したいページのタイトル
*/
export async function unpin(
project: string,
title: string,
options: UnPinOptions,
): Promise<void> {
const [
head,
projectId,
userId,
] = await Promise.all([
pull(project, title),
getProjectId(project),
getUserId(),
]);

// 既にピンが外れているか、そもそも存在しないページの場合は何もしない
if (head.pin == 0 || !head.persistent) return;

const init = {
parentId: head.commitId,
projectId,
pageId: head.pageId,
userId,
project,
title,
};
const injectedSocket = options?.socket;
const socket = injectedSocket ?? await socketIO();
await connect(socket);
const { request } = wrap(socket);

try {
await pushWithRetry(request, [{ pin: 0 }], init);
} finally {
if (!injectedSocket) await disconnect(socket);
}
}

export const pinNumber = (): number =>
Number.MAX_SAFE_INTEGER - Math.floor(Date.now() / 1000);
Loading