Skip to content
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

UBERF-5140: Any workspace names #4489

Merged
merged 5 commits into from
Feb 2, 2024
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ Before you can begin, you need to create a workspace and an account and associat

```bash
cd ./tool # dev/tool in the repository root
rushx run-local create-workspace ws1 -o DevWorkspace # Create workspace
rushx run-local create-workspace ws1 -w DevWorkspace # Create workspace
rushx run-local create-account user1 -p 1234 -f John -l Appleseed # Create account
rushx run-local configure ws1 --list --enable '*' # Enable all modules, even if they are not yet intended to be used by a wide audience.
rushx run-local assign-workspace user1 ws1 # Assign workspace to user.
Expand Down
2 changes: 1 addition & 1 deletion dev/client-resources/src/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export async function connect (handler: (tx: Tx) => void): Promise<ClientConnect
}
},
defaultContentAdapter: 'default',
workspace: getWorkspaceId('')
workspace: { ...getWorkspaceId(''), workspaceUrl: '', workspaceName: '' }
}
const ctx = new MeasureMetricsContext('client', {})
const serverStorage = await createServerStorage(ctx, conf, {
Expand Down
3 changes: 2 additions & 1 deletion dev/docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ services:
links:
- mongodb
- minio
- transactor
ports:
- 3000:3000
environment:
Expand Down Expand Up @@ -136,6 +135,7 @@ services:
- elastic
- minio
- rekoni
- account
# - apm-server
ports:
- 3333:3333
Expand All @@ -154,6 +154,7 @@ services:
- FRONT_URL=http://localhost:8087
# - APM_SERVER_URL=http://apm-server:8200
- SERVER_PROVIDER=ws
- ACCOUNTS_URL=http://account:3000
restart: unless-stopped
rekoni:
image: hardcoreeng/rekoni-service
Expand Down
9 changes: 5 additions & 4 deletions dev/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
// limitations under the License.
//

import { DOMAIN_TX, getWorkspaceId, MeasureMetricsContext } from '@hcengineering/core'
import { DOMAIN_TX, MeasureMetricsContext } from '@hcengineering/core'
import { createInMemoryTxAdapter } from '@hcengineering/dev-storage'
import {
ContentTextAdapter,
Expand Down Expand Up @@ -44,7 +44,7 @@ async function createNullContentTextAdapter (): Promise<ContentTextAdapter> {
export async function start (port: number, host?: string): Promise<void> {
const ctx = new MeasureMetricsContext('server', {})
startJsonRpc(ctx, {
pipelineFactory: (ctx) => {
pipelineFactory: (ctx, workspaceId) => {
const conf: DbConfiguration = {
domains: {
[DOMAIN_TX]: 'InMemoryTx'
Expand Down Expand Up @@ -74,13 +74,14 @@ export async function start (port: number, host?: string): Promise<void> {
}
},
defaultContentAdapter: 'default',
workspace: getWorkspaceId('')
workspace: workspaceId
}
return createPipeline(ctx, conf, [], false, () => {})
},
sessionFactory: (token, pipeline, broadcast) => new ClientSession(broadcast, token, pipeline),
port,
productId: '',
serverFactory: startHttpServer
serverFactory: startHttpServer,
accountsUrl: ''
})
}
19 changes: 12 additions & 7 deletions dev/tool/src/benchmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,14 +207,19 @@ export async function benchmark (
operations = 0
requestTime = 0
transfer = 0
for (const w of workspaceId) {
const r = extract(json.metrics as Metrics, w.name, 'client', 'handleRequest', 'process', 'find-all')
operations += r?.operations ?? 0
requestTime += (r?.value ?? 0) / (((r?.operations as number) ?? 0) + 1)
const r = extract(
json.metrics as Metrics,
'🧲 session',
'client',
'handleRequest',
'process',
'find-all'
)
operations += r?.operations ?? 0
requestTime += (r?.value ?? 0) / (((r?.operations as number) ?? 0) + 1)

const tr = extract(json.metrics as Metrics, w.name, 'client', 'handleRequest', '#send-data')
transfer += tr?.value ?? 0
}
const tr = extract(json.metrics as Metrics, '🧲 session', 'client', 'handleRequest', '#send-data')
transfer += tr?.value ?? 0
})
.catch((err) => {
console.log(err)
Expand Down
34 changes: 24 additions & 10 deletions dev/tool/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,20 @@
import {
ACCOUNT_DB,
assignWorkspace,
ClientWorkspaceInfo,
confirmEmail,
createAcc,
createWorkspace,
dropAccount,
dropWorkspace,
getAccount,
getWorkspace,
getWorkspaceById,
listAccounts,
listWorkspaces,
replacePassword,
setAccountAdmin,
setRole,
upgradeWorkspace,
WorkspaceInfoOnly
upgradeWorkspace
} from '@hcengineering/account'
import { setMetadata } from '@hcengineering/platform'
import {
Expand All @@ -43,7 +43,7 @@ import {
import serverToken, { decodeToken, generateToken } from '@hcengineering/server-token'
import toolPlugin, { FileModelLogger } from '@hcengineering/server-tool'

import { program, Command } from 'commander'
import { Command, program } from 'commander'
import { Db, MongoClient } from 'mongodb'
import { clearTelegramHistory } from './telegram'
import { diffWorkspace } from './workspace'
Expand Down Expand Up @@ -155,7 +155,16 @@ export function devTool (
const { mongodbUri } = prepareTools()
await withDatabase(mongodbUri, async (db, client) => {
console.log(`assigning user ${email} to ${workspace}...`)
await assignWorkspace(db, productId, email, workspace)
const workspaceInfo = await getWorkspaceById(db, productId, workspace)
if (workspaceInfo === null) {
throw new Error(`workspace ${workspace} not found`)
}
console.log('assigning to workspace', workspaceInfo)
try {
await assignWorkspace(db, productId, email, workspaceInfo?.workspaceUrl ?? workspaceInfo.workspace)
} catch (err: any) {
console.error(err)
}
})
})

Expand Down Expand Up @@ -197,11 +206,12 @@ export function devTool (
program
.command('create-workspace <name>')
.description('create workspace')
.requiredOption('-o, --organization <organization>', 'organization name')
.requiredOption('-w, --workspaceName <workspaceName>', 'Workspace name')
.option('-e, --email <email>', 'Author email', 'platform@email.com')
.action(async (workspace, cmd) => {
const { mongodbUri, txes, version, migrateOperations } = prepareTools()
await withDatabase(mongodbUri, async (db) => {
await createWorkspace(version, txes, migrateOperations, db, productId, workspace, cmd.organization)
await createWorkspace(version, txes, migrateOperations, db, productId, cmd.email, cmd.workspaceName, workspace)
})
})

Expand Down Expand Up @@ -230,7 +240,11 @@ export function devTool (
.action(async (workspace, cmd) => {
const { mongodbUri, version, txes, migrateOperations } = prepareTools()
await withDatabase(mongodbUri, async (db) => {
await upgradeWorkspace(version, txes, migrateOperations, productId, db, workspace)
const info = await getWorkspaceById(db, productId, workspace)
if (info === null) {
throw new Error(`workspace ${workspace} not found`)
}
await upgradeWorkspace(version, txes, migrateOperations, productId, db, info.workspaceUrl ?? info.workspace)
})
})

Expand All @@ -252,7 +266,7 @@ export function devTool (
const workspaces = await listWorkspaces(db, productId)
const withError: string[] = []

async function _upgradeWorkspace (ws: WorkspaceInfoOnly): Promise<void> {
async function _upgradeWorkspace (ws: ClientWorkspaceInfo): Promise<void> {
const t = Date.now()
const logger = cmd.console
? consoleModelLogger
Expand Down Expand Up @@ -298,7 +312,7 @@ export function devTool (
.action(async (workspace, cmd) => {
const { mongodbUri } = prepareTools()
await withDatabase(mongodbUri, async (db) => {
const ws = await getWorkspace(db, productId, workspace)
const ws = await getWorkspaceById(db, productId, workspace)
if (ws === null) {
console.log('no workspace exists')
return
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ export async function createClient (
let lastTx: number

function txHandler (tx: Tx): void {
if (tx === null) {
if (tx == null) {
return
}
if (client === null) {
Expand Down
14 changes: 11 additions & 3 deletions packages/core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ function count (): string {
* @public
* @returns
*/
export function generateId<T extends Doc> (): Ref<T> {
return (timestamp() + random + count()) as Ref<T>
export function generateId<T extends Doc> (join: string = ''): Ref<T> {
return (timestamp() + join + random + join + count()) as Ref<T>
}

let currentAccount: Account
Expand Down Expand Up @@ -89,6 +89,14 @@ export interface WorkspaceId {
productId: string
}

/**
* @public
*/
export interface WorkspaceIdWithUrl extends WorkspaceId {
workspaceUrl: string
workspaceName: string
}

/**
* @public
*
Expand Down Expand Up @@ -507,7 +515,7 @@ export function cutObjectArray (obj: any): any {
for (const key of Object.keys(obj)) {
if (Array.isArray(obj[key])) {
if (obj[key].length > 3) {
Object.assign(r, { [key]: `[${obj[key].slice(0, 3)}, ... and ${obj[key].length - 3} more]` })
Object.assign(r, { [key]: [...obj[key].slice(0, 3), `... and ${obj[key].length - 3} more`] })
} else Object.assign(r, { [key]: obj[key] })
continue
}
Expand Down
61 changes: 33 additions & 28 deletions plugins/client-resources/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import core, {
AccountClient,
ClientConnectEvent,
TxHandler,
TxPersistenceStore,
TxWorkspaceEvent,
WorkspaceEvent,
createClient
Expand Down Expand Up @@ -68,34 +69,7 @@ export default async () => {
return connect(url.href, upgradeHandler, onUpgrade, onUnauthorized, onConnect)
},
filterModel ? [...getPlugins(), ...(getMetadata(clientPlugin.metadata.ExtraPlugins) ?? [])] : undefined,
{
load: async () => {
if (typeof localStorage !== 'undefined') {
const storedValue = localStorage.getItem('platform.model') ?? null
try {
const model = storedValue != null ? JSON.parse(storedValue) : undefined
if (token !== model?.token) {
return {
full: false,
transactions: [],
hash: []
}
}
return model.model
} catch {}
}
return {
full: true,
transactions: [],
hash: []
}
},
store: async (model) => {
if (typeof localStorage !== 'undefined') {
localStorage.setItem('platform.model', JSON.stringify({ token, model }))
}
}
}
createModelPersistence(token)
)
// Check if we had dev hook for client.
client = hookClient(client)
Expand All @@ -104,6 +78,37 @@ export default async () => {
}
}
}
function createModelPersistence (token: string): TxPersistenceStore | undefined {
return {
load: async () => {
if (typeof localStorage !== 'undefined') {
const storedValue = localStorage.getItem('platform.model') ?? null
try {
const model = storedValue != null ? JSON.parse(storedValue) : undefined
if (token !== model?.token) {
return {
full: false,
transactions: [],
hash: []
}
}
return model.model
} catch {}
}
return {
full: true,
transactions: [],
hash: []
}
},
store: async (model) => {
if (typeof localStorage !== 'undefined') {
localStorage.setItem('platform.model', JSON.stringify({ token, model }))
}
}
}
}

async function hookClient (client: Promise<AccountClient>): Promise<AccountClient> {
const hook = getMetadata(clientPlugin.metadata.ClientHook)
if (hook !== undefined) {
Expand Down
8 changes: 1 addition & 7 deletions plugins/login-assets/lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"Join": "Join",
"Email": "Email",
"Password": "Password",
"Workspace": "Workspace",
"Workspace": "Workspace name",
"DoNotHaveAnAccount": "Do not have an account?",
"PasswordRepeat": "Repeat password",
"HaveAccount": "Already have an account?",
Expand All @@ -27,12 +27,6 @@
"WantAnotherWorkspace": "Want to create another workspace?",
"ChangeAccount": "Change account",
"NotSeeingWorkspace": "Not seeing your workspace?",
"WorkspaceNameRule": "Workspace name cannot contain special characters except -",
"WorkspaceNameRuleCapital": "The workspace name must contain only lowercase letters",
"WorkspaceNameRuleHyphen": "The workspace name cannot start with a dash (-)",
"WorkspaceNameRuleHyphenEnd": "The workspace name cannot end with a dash (-)",
"WorkspaceNameRuleLengthLow": "Workspace name must be at least 3 characters",
"WorkspaceNameRuleLengthHigh": "Workspace name must be no longer than 63 characters",
"ForgotPassword": "Forgot your password?",
"KnowPassword": "Know your password?",
"Recover": "Recover",
Expand Down
6 changes: 0 additions & 6 deletions plugins/login-assets/lang/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,6 @@
"WantAnotherWorkspace": "Хотите создать другое рабочее пространство?",
"ChangeAccount": "Сменить пользователя",
"NotSeeingWorkspace": "Не видите ваше рабочее пространство?",
"WorkspaceNameRule": "Название рабочего пространства не может содержать специальные символы кроме -",
"WorkspaceNameRuleCapital": "Название рабочего пространства должно содержать только строчные буквы",
"WorkspaceNameRuleHyphen": "Название рабочего пространства не может начинаться с символа 'тире' (-)",
"WorkspaceNameRuleHyphenEnd": "Название рабочего пространства не может заканчиваться символом 'тире' (-)",
"WorkspaceNameRuleLengthLow": "Название рабочего пространства должно быть не короче 3 символов",
"WorkspaceNameRuleLengthHigh": "Название рабочего пространства должно быть не длиннее 63 символов",
"ForgotPassword": "Забыли пароль?",
"KnowPassword": "Знаете пароль?",
"Recover": "Восстановить",
Expand Down
5 changes: 3 additions & 2 deletions plugins/login-resources/src/components/Confirmation.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@
navigate(loc)
}

function goToLogin () {
function goToLogin (): void {
const loc = getCurrentLocation()
loc.query = undefined
loc.path[1] = 'login'
loc.path.length = 2
navigate(loc)
}

async function check () {
async function check (): Promise<void> {
const location = getCurrentLocation()
if (location.query?.id === undefined || location.query?.id === null) return
status = new Status(Severity.INFO, login.status.ConnectingToServer, {})
Expand All @@ -50,6 +50,7 @@

if (result !== undefined) {
setMetadata(presentation.metadata.Token, result.token)
setMetadataLocalStorage(login.metadata.LastToken, result.token)
setMetadataLocalStorage(login.metadata.LoginEndpoint, result.endpoint)
setMetadataLocalStorage(login.metadata.LoginEmail, result.email)
goToWorkspaces()
Expand Down
Loading
Loading