Skip to content
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
7 changes: 4 additions & 3 deletions packages/api/dom/elements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { attachForFocus, attachForStatus, attachForText } from './elements-html.
import { buildShadow, css, html, SignalHTMLElement, SizingElement } from 'thorish/dom';
import { rafRunner } from 'thorish';
import { globalAllDocs, globalAllDocsErrorNotify } from '../lib/global.ts';
import { clientUserInfo } from '../lib/user-info.ts';

const attrControl = (target: HTMLElement, attr: string, on?: boolean | string | number) => {
if (on) {
Expand Down Expand Up @@ -71,7 +72,7 @@ export abstract class GumnutNodeElement extends SignalHTMLElement {
get clients(): ReadonlyMap<string, UserInfo> {
const o = new Map<string, UserInfo>();
for (const clientId of this._node?.clients() ?? []) {
const data = this._node?.doc.userForClientId(clientId);
const data = clientUserInfo(clientId, this._node?.projectId);
if (data) {
o.set(clientId, data);
}
Expand Down Expand Up @@ -453,7 +454,7 @@ export class GumnutTextElement extends GumnutNodeElement {
}

protected refreshNode(signal: AbortSignal, node: GumnutNode) {
node.doc.ready.then(() => {
node.ready.then(() => {
if (!signal.aborted) {
this.firstConfigured = true;
}
Expand Down Expand Up @@ -592,7 +593,7 @@ export class GumnutFocusElement extends SignalHTMLElement {
this.main.textContent = '';

for (const clientId of d.clients()) {
const userInfo = d.userForClientId(clientId);
const userInfo = clientUserInfo(clientId, d.projectId);
const h = new GumnutUserHeadElement();
h.data = formatUserInfo(clientId, userInfo);
this.main.append(h);
Expand Down
3 changes: 2 additions & 1 deletion packages/api/dom/upgrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { changeBetween } from '../shared/helpers/ot.ts';
import { colorForPeerHue } from '../shared/helpers/color.ts';
import { fastFrameRunner, once, rafRunner } from 'thorish';
import type { GumnutMod, GumnutNode, UserInfo } from '#release';
import { clientUserInfo } from '../lib/user-info.ts';

export type UpgradeInputArgs = {
input: HTMLInputElement | HTMLTextAreaElement;
Expand Down Expand Up @@ -226,7 +227,7 @@ export function buildRenderHelper(
const prepare = () => {
const cursorsToDraw: CursorToDraw[] = [];
for (const [clientId, sel] of cursors.entries()) {
const out = formatUserInfo(clientId, node.doc.userForClientId(clientId));
const out = formatUserInfo(clientId, clientUserInfo(clientId, node.projectId));
cursorsToDraw.push({ ...out, sel });
}
render(cursorsToDraw);
Expand Down
17 changes: 3 additions & 14 deletions packages/api/lib/doc-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { GumnutProjectApi, type LowLevelDoc } from './project-api.ts';
import { clientPart, nodeAtPath, NodeToClientCache } from './node.ts';
import { useActualModel } from './secret-keys.ts';
import type { ValueOp } from '../shared/types/value.ts';
import { clientUserInfo, filterUserId } from './user-info.ts';

connectToGumnutDoc satisfies (typeof checkTypes)['connectToGumnutDoc'];

Expand All @@ -23,10 +24,6 @@ interface InternalDocArg extends DocArg {
_projectApi?: GumnutProjectApi;
}

function filterUserId(userId?: string) {
return userId && !userId.startsWith('!');
}

export function connectToGumnutDoc(arg: InternalDocArg): { doc: GumnutDoc; shutdown: () => void } {
const { docId } = arg;

Expand Down Expand Up @@ -280,20 +277,12 @@ export function connectToGumnutDoc(arg: InternalDocArg): { doc: GumnutDoc; shutd
const doc: GumnutDoc = {
...{ [useActualModel]: () => internalDoc },

userForClientId(clientId) {
const userId = clientId && internalDoc.userIdForClientId(clientId);
if (!userId || userId.startsWith('!')) {
return undefined;
}
return projectApi.userInfo(userId);
},

clients() {
// we need to filter out admin/other clients, makes this "slow"
const out: string[] = [];
for (const clientId of internalDoc.clients()) {
const ui = this.userForClientId(clientId);
if (filterUserId(ui?.userId)) {
const info = clientUserInfo(clientId);
if (info !== undefined) {
out.push(clientId);
}
}
Expand Down
7 changes: 7 additions & 0 deletions packages/api/lib/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ export function configureGumnut(arg: ConfigArg) {
globalConfig = { ...arg };
}

export function implicitProjectId(): string {
if (globalConfig === undefined) {
throw new Error(`can't get implicit projectId, not configured`);
}
return globalConfig.projectId;
}

/**
* Attempts to configure Gumnut implicitly through various env var locations.
*/
Expand Down
1 change: 1 addition & 0 deletions packages/api/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export { configureGumnut } from './global.ts';
export { connectToGumnutDoc } from './doc-api.ts';
export { buildTestToken } from './token/helpers.ts';
export { clientUserInfo } from './user-info.ts';

// -- typescript inline check below --
// TODO: does this compile out fine
Expand Down
46 changes: 20 additions & 26 deletions packages/api/lib/internal/internal.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { type NamedListeners, namedListeners, promiseWithResolvers, randomId } from 'thorish';
import type { DocType } from '../../shared/docType.js';
import type { HostRead } from './protocol.d.ts';
import { provideClientToUser, userForClient } from '../user-info.ts';

export type AuthorOp<Op> = {
clientId: string; // blank is self
Expand Down Expand Up @@ -83,26 +84,19 @@ export class InternalDoc<Doc, Op> implements GenericDoc<Doc, Op> {
this.userId.then((userId) => (this.syncUserId = userId));
}

private clientIdToUserId = new Map<string, string>();
private clientsHere = new Set<string>();

clients() {
return this.clientIdToUserId.keys();
}

/**
* Exposes the synchronous `clientId` => `userId` mapping.
*/
userIdForClientId(clientId: string): string {
return this.clientIdToUserId.get(clientId) || '';
return this.clientsHere.keys();
}

get ready() {
return this._ready.promise;
}

process(data: HostRead<Op>) {
const userId = this.syncUserId;
if (userId === undefined) {
const selfUserId = this.syncUserId;
if (selfUserId === undefined) {
throw new Error(`cannot process ops until syncUserId?`);
}

Expand Down Expand Up @@ -144,23 +138,23 @@ export class InternalDoc<Doc, Op> implements GenericDoc<Doc, Op> {

if (data.ac) {
// complete reset
for (const [clientId, userId] of this.clientIdToUserId) {
e.set(clientId, { userId, status: false });
for (const clientId of this.clientsHere.keys()) {
e.set(clientId, { userId: userForClient(clientId), status: false });
}
this.clientIdToUserId.clear();
this.clientsHere.clear();
}
for (const [clientId, userId] of Object.entries(data.c)) {
if (userId) {
this.clientIdToUserId.set(clientId, userId);
this.clientsHere.add(clientId);
provideClientToUser(clientId, userId);
if (e.get(clientId)?.status === false) {
e.delete(clientId);
} else {
e.set(clientId, { userId, status: true });
}
} else if (this.clientIdToUserId.has(clientId)) {
const userId = this.clientIdToUserId.get(clientId)!;
this.clientIdToUserId.delete(clientId);
e.set(clientId, { userId, status: false });
} else if (this.clientsHere.has(clientId)) {
this.clientsHere.delete(clientId);
e.set(clientId, { userId: userForClient(clientId), status: false });
}
}

Expand Down Expand Up @@ -188,7 +182,7 @@ export class InternalDoc<Doc, Op> implements GenericDoc<Doc, Op> {
const toApply = this.localOps.slice(0, this.sentLocalOps.count);
updateOps.push(
...toApply.map((x) => {
return { clientId: '', userId, ...x, known: true };
return { clientId: '', userId: selfUserId, ...x, known: true };
}),
);

Expand All @@ -203,7 +197,7 @@ export class InternalDoc<Doc, Op> implements GenericDoc<Doc, Op> {
} else {
// our changes were moved _but not transformed_, so we don't have a derivedDoc
for (const op of toApply) {
const change = this.docType.do(this.doc, userId, op.op);
const change = this.docType.do(this.doc, selfUserId, op.op);
op.change = change;
}
}
Expand All @@ -222,7 +216,7 @@ export class InternalDoc<Doc, Op> implements GenericDoc<Doc, Op> {
throw new Error(`dup self payload: ${entry}`);
}
hadSelfPayload = true;
authorUserId = userId;
authorUserId = selfUserId;

// this is still our key, but we got transformed
if (this.sentLocalOps?.key !== entry.k) {
Expand All @@ -237,7 +231,7 @@ export class InternalDoc<Doc, Op> implements GenericDoc<Doc, Op> {
transformOver.push(...entry.o);

// use blank string if we don't know their userId (transient user/admin/etc)
authorUserId = this.clientIdToUserId.get(entry.c) || '';
authorUserId = userForClient(entry.c);
authorClientId = entry.c;
}

Expand All @@ -261,17 +255,17 @@ export class InternalDoc<Doc, Op> implements GenericDoc<Doc, Op> {
this.derivedDoc = structuredClone(this.doc);
for (let i = 0; i < this.localOps.length; ++i) {
if (transformOver.length) {
const update = this.docType.transform(userId, this.localOps[i].op, transformOver);
const update = this.docType.transform(selfUserId, this.localOps[i].op, transformOver);
if (update) {
this.localOps[i].op = update;
}
}
const change = this.docType.do(this.derivedDoc, userId, this.localOps[i].op);
const change = this.docType.do(this.derivedDoc, selfUserId, this.localOps[i].op);
this.localOps[i].change = change;
}
updateOps.push(
...this.localOps.map((x) => {
return { clientId: '', userId, ...x, known: true };
return { clientId: '', userId: selfUserId, ...x, known: true };
}),
);
this.maybeSendOps();
Expand Down
2 changes: 1 addition & 1 deletion packages/api/lib/model/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export abstract class AbstractGumnutNodeImpl implements GumnutNode {
abstract projectId: string;
abstract docId: string;
abstract node: string;
abstract doc: GumnutDoc;
abstract ready: Promise<void>;

abstract isDirty(): boolean;

Expand Down
2 changes: 1 addition & 1 deletion packages/api/lib/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export function nodeAtPath(arg: {
projectId = projectApi.projectId;
docId = docId;
node = nodeName;
doc = doc;
ready = doc.ready; // TODO: might not be enough

addListener(type: any, cb: (x: any) => void, signal: AbortSignal) {
nodeEvents.addListener(type, cb, signal);
Expand Down
54 changes: 8 additions & 46 deletions packages/api/lib/project-api.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import type { ConfigArg, GetToken, UserInfo } from '#release';
import {
afterSignal,
asyncGeneratorQueue,
promiseWithResolvers,
SimpleCache,
timeout,
} from 'thorish';
import type { ConfigArg, GetToken } from '#release';
import { afterSignal, asyncGeneratorQueue, promiseWithResolvers, timeout } from 'thorish';
import type { ActiveCall } from '../util/keySocket.ts';
import { type PersistentKeySocket, persistentKeySocket } from '../util/persistKeySocket.ts';
import { buildTestToken, parseToken } from './token/helpers.ts';
import { buildUrl } from './url.ts';
import { createBackoff } from '../util/backoff.ts';
import { type InternalUserInfo, provideUserInfo } from './user-info.ts';

/**
* Keep a connection open for this long while it is not being used.
Expand All @@ -34,9 +29,10 @@ export class GumnutProjectApi {
public isLocalDev: boolean;

constructor(arg: ConfigArg, extraArg?: { connTimeout?: number }) {
arg = { ...arg };
const connTimeout = extraArg?.connTimeout ?? CONN_TIMEOUT;

this.c = new ConnectionByUserMap(arg, this.processUserInfo.bind(this), connTimeout);
this.c = new ConnectionByUserMap(arg, connTimeout);
this.projectId = arg.projectId;
this.isLocalDev = Boolean(arg.localDevKey);
}
Expand Down Expand Up @@ -145,27 +141,6 @@ export class GumnutProjectApi {

safeRefreshCall();
}

private users = new SimpleCache<string, Readonly<UserInfo>>((userId) => {
return Object.freeze({ userId, info: {} });
});

private processUserInfo(i: InternalUserInfo) {
const curr = this.users.get(i.u);
Object.assign(curr.info, i.r || {});
}

/**
* Synchronously reads user information.
*
* This always returns the same ref for the given userId.
*/
userInfo(userId: string): UserInfo | undefined {
if (!userId) {
return undefined;
}
return this.users.get(userId);
}
}

class TokenManager {
Expand Down Expand Up @@ -266,11 +241,7 @@ class TokenManager {
}

class ConnectionByUserMap {
constructor(
private arg: ConfigArg,
private processUserInfo: (u: InternalUserInfo) => void,
private connTimeout: number,
) {}
constructor(private arg: ConfigArg, private connTimeout: number) {}

private active: Map<
string,
Expand All @@ -296,7 +267,7 @@ class ConnectionByUserMap {
}

const c = new AbortController();
const outer = this;
const projectId = this.arg.projectId;

const sock = persistentKeySocket({
signal: c.signal,
Expand All @@ -306,7 +277,7 @@ class ConnectionByUserMap {
if ('userInfo' in message) {
const ui = message.userInfo as InternalUserInfo[];
for (const u of ui ?? []) {
outer.processUserInfo(u);
provideUserInfo(u, projectId);
}
}
},
Expand Down Expand Up @@ -336,12 +307,3 @@ class ConnectionByUserMap {
prev.safe = () => clearTimeout(t);
}
}

type InternalUserInfo = {
u: string;
r?: {
name?: string;
email?: string;
picture?: string;
};
};
Loading