Files
huly-platform/foundations/server/packages/middleware/src/tests/txOrdering.test.ts
T
+1 98652c6476 Include sub projects (#10201)
* Add bump-changes

* Add utility tests

* Add utility tests

* Bump to new version of esbuild and typescript

* v0.7.3

* use platform rig 0.7.10

* upgrade: memory engine optimized; change name  to  (was recommended by Copilot and Onnikov, TODO: CHANGE CLIENT TOO!!!)

Signed-off-by: Leonid Kaganov <lleo@lleo.me>

* Fix rate limits bug

* Bump versions

* Fix lock file

* Fix bug in queue cleanup

* Add more tests for queue

* Add api-test tests

* Initial commit

* Improve hierarchy + tests

Add tests for hierarchy and few performance/memory  optimizations.

* Add more hierarchy tests

* Move from Huly platform repository

* Add docker tests setup

* Fix test to be executed only once

* Add connection tests

* Fix package include source files

* More tests

* Create README.md

* Fix pnpm lock

* Fix packages publish

* Remove broken tests

* feat: adjust hulylake client for storage adapter

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Fix export

* Fix publish

* Fix message update (#114)

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* Bump version

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* Bump versions

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Fix lang store (#115)

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* update hulylake client

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Bump version

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Add hulylake storage adapter

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Bump version

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* fix validation issues

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* fix: do not fail on deseralization error and add logs

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* bump version -> 0.1.14

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* fix collaboration test

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Update prettier and new update-deps script

Prettier + svelte support

* fix unstable ydoc tests

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Add tx ordering middleware

* Fix ordering tests

* Fix Kafka close of admin

* Add tests for measurement and understand overhead

* Fix not updated lock file

* Fix update-deps

* Fix update-deps

* Use latest platform-rig

* Fix deps

* Add rush check to CI

* Use latest versions

* Bump versions

* Fix lock file

* validate json patch

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* bump version -> 0.1.15

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* fix merge unit tests

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Script to sync eslint deps

* Fix deps

* Fix tests

* Fix platform-rig detection

* Update to latest platform-rig

* Update to latest platform rig and core

* Bump typescript

* Bump typescript

* Rollback eslint plugins

* Fix lock file

* Bump platform-rig

* Update to latest platform-rig

* update to latest platform-rig

* Allow to compile svelte files

* Add ui-test component for checking compile

* Fix log levels rename compile ui -> compile ui-esbuild

* Fix build

* Bump esbuild svelte version

* Chore: use fixed versions in update-deps

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Chore: commit changes

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Update deps

* Add tests for session manager

* Fix txOrdering implementation

* Bump ordering

* Prevent metrics zero values in measure

+ Fix format svelte files

* Revert update-deps script logic

* v0.7.19

* update to latest platform-rig

* Update deps

* Fix pnpm

* Session counters

* Fix pnpm lock

* Add storage client

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Bump versions

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* fix versions

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Bump core

* Fix pnpm

* Get rid of communication dependency

* Add copilot memory file

* Use proper name for instructions file

* Fix instructions

* Use domain instead of test name in gauges

* Update instructions file

* fix front service upload

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* remove incorrect test

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Move packages to huly.core

* Move packages to core, since they are not utils

* Add global user profile

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Fix lock file

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Add support for memory limit check

* Bump version

* Fix pnpm

* report more accurate upload progress

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* fic validation issues

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Fix deps

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* Move LowLevelStorage to server

* Fix linting

* Revert "Fix linting"

This reverts commit 54631d353e.

* Revert "Move LowLevelStorage to server"

This reverts commit aafb8f6f12.

* feature: add regorus engine with permit file

Signed-off-by: Leonid Kaganov <lleo@lleo.me>

* Fix one second counters for memory usage

* Fix kafka test

* use fresh core

* Version bump

* fix: key parameter added

Signed-off-by: Leonid Kaganov <lleo@lleo.me>

* Fix readme and few author mistakes

* Export domain schemas

* Bump version

* Tests (#117)

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* Bump version

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* feat: compact compact worker (#4)

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* bump version -> 0.1.16

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Add TypeIdentifier

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Add change logs

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* rename send -> try_send

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Bump

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Fix pnpm lock

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Add identifier middleware, bump core

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Add subsciption methods to account client

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Fix lock file

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Fix reaction notification (#118)

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* Bump version

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* Improve find methods schemas to convert to valid types

Signed-off-by: Nikolay Marchuk <nikolay.marchuk@hardcoreeng.com>

* Add change description

Signed-off-by: Nikolay Marchuk <nikolay.marchuk@hardcoreeng.com>

* Do not transcode while recording

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Open telemetry support

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* use proper content type in multipart upload

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Bump versions

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* fix build (#26)

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Fix peers (#120)

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* Bump version

Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>

* Add ActivityCollaborativeChange

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Update pnpm

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Allow to suspend errors on with

* Fix pnpm cache

* update versions

* v0.7.17 for all

* v0.7.11

* v0.7.14

* remove arc from worker

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* bump version -> 0.1.17

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Rank for attributes

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Update pnpm

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Fix one second counters

* Fix withContext and allow pass options

* Fix formatting

* Use updated deps

* Bump versions

* Update deps

* Update deps to platform.core

* add support for textColor mark

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* add support for textStyle mark

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Bump versions

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Bump versions again

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Fix

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Rework on second timers

* fix merge of large blobs feched from s3

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* bump version -> 0.1.18

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* New subscription methods in account-client

* Update lock file

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Send error on find for wrong domain

* Suspend connect custom errors events in traces

* Bump client

* Bump core

* update deps

* Fix lock file

* Sorting for TypeIdentifier

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Bump version

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* add workspace usage info

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Bump versions

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>

* Improve pg security perfomance

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Fix identifier middleware

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Update TxAccessLevel interface

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Allow guest to update its identities

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Add password login locked platform status

Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>

* Fix Uptrace normalizeMarkdown errors

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Add change log

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Add txMatch to permission

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* update pnpm lock

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Bump

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Fix permission middleware

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Fix enum sorting

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Enable formatting check

Signed-off-by: Andrey Sobolev <haiodo@gmail.com>

* Enable formatting check

* Add change

Signed-off-by: Andrey Sobolev <haiodo@gmail.com>

* Fix Uptrace NaN error

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* feature: removed actors, improved performance

Signed-off-by: Leonid Kaganov <lleo@lleo.me>

* feature: ping from server to clients added

Signed-off-by: Leonid Kaganov <lleo@lleo.me>

* feature: ping from server to clients added

Signed-off-by: Leonid Kaganov <lleo@lleo.me>

* Compress kafka messages and fix exception in findAll

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Bump versions

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Bump versions

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Rush change

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Fix compression param

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Trigger change

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Clean up

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Trigger change

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Bump markdown version

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Enable sub projects

* Fix wrong double symbol scripts

* Include foundation packages

* Add support for custom exclude filters

Add support for custom exclude filters - by Andrey Sobolev - haiodo@gmail.com

Signed-off-by: Andrey Sobolev <haiodo@gmail.com>

* Bump

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>

* Fix Uptrace filter is not a function error

Signed-off-by: Artem Savchenko <armisav@gmail.com>

* Sync versions

Signed-off-by: Andrey Sobolev <haiodo@gmail.com>

---------

Signed-off-by: Leonid Kaganov <lleo@lleo.me>
Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>
Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com>
Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com>
Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>
Signed-off-by: Nikolay Marchuk <nikolay.marchuk@hardcoreeng.com>
Signed-off-by: Artem Savchenko <armisav@gmail.com>
Signed-off-by: Andrey Sobolev <haiodo@gmail.com>
Co-authored-by: Leonid Kaganov <lleo@lleo.me>
Co-authored-by: Alexander Onnikov <Alexander.Onnikov@xored.com>
Co-authored-by: Alexander Onnikov <Alexander.Onnikov@gmail.com>
Co-authored-by: Kristina <kristin.fefelova@gmail.com>
Co-authored-by: Alexey Zinoviev <alexey.zinoviev@xored.com>
Co-authored-by: Denis Bykhov <bykhov.denis@gmail.com>
Co-authored-by: Nikolay Marchuk <nikolay.marchuk@hardcoreeng.com>
Co-authored-by: Alexander Onnikov <aonnikov@hardcoreeng.com>
Co-authored-by: Artem Savchenko <armisav@gmail.com>
2025-11-26 19:15:30 +05:00

409 lines
13 KiB
TypeScript

//
// Copyright © 2025 Hardcore Engineering Inc.
//
// Licensed under the Eclipse Public License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. You may
// obtain a copy of the License at https://www.eclipse.org/legal/epl-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
/**
* Test for TxOrderingMiddleware
*
* This test verifies that the middleware ensures transactions for the same document
* are processed sequentially by waiting in the tx() method.
*/
import core, {
type Class,
type Doc,
generateId,
Hierarchy,
MeasureMetricsContext,
type MeasureContext,
ModelDb,
type Ref,
type Space,
type Tx,
TxFactory
} from '@hcengineering/core'
import type { PipelineContext, TxMiddlewareResult } from '@hcengineering/server-core'
import { TxOrderingMiddleware } from '../txOrdering'
interface TestDoc extends Doc {
name: string
counter: number
}
const testDocClass = 'test:class:TestDoc' as Ref<Class<TestDoc>>
/**
* Track broadcasted transactions to verify ordering
*/
class BroadcastTracker {
broadcasted: Tx[] = []
record (tx: Tx): void {
this.broadcasted.push(tx)
}
reset (): void {
this.broadcasted = []
}
getOrder (): number[] {
return this.broadcasted.map((tx) => tx.modifiedOn)
}
}
describe('TxOrderingMiddleware', () => {
let ctx: MeasureContext
let middleware: TxOrderingMiddleware
let tracker: BroadcastTracker
let txFactory: TxFactory
let testDoc: TestDoc
beforeEach(async () => {
ctx = new MeasureMetricsContext('test', {})
ctx.contextData = {
broadcast: {
txes: [],
queue: [],
sessions: {}
}
} as any
tracker = new BroadcastTracker()
const hierarchy = new Hierarchy()
const model = new ModelDb(hierarchy)
const pipelineContext: PipelineContext = {
workspace: { uuid: 'test-workspace' as any, url: 'test', dataId: 'test' as any },
hierarchy,
modelDb: model,
branding: null as any,
adapterManager: {} as any,
storageAdapter: {} as any,
contextVars: {},
lastTx: '',
lastHash: '',
broadcastEvent: async (ctx, txes) => {
for (const tx of txes) {
tracker.record(tx)
}
}
}
// Create a mock "next" middleware that records transactions when they're processed
const nextMiddleware = {
tx: async (ctx: MeasureContext, txes: Tx[]): Promise<TxMiddlewareResult> => {
// Record transactions as they're processed
for (const tx of txes) {
tracker.record(tx)
}
return {}
},
handleBroadcast: async (ctx: MeasureContext): Promise<void> => {
// No-op since we removed handleBroadcast from TxOrderingMiddleware
}
}
middleware = (await TxOrderingMiddleware.create()(
ctx,
pipelineContext,
nextMiddleware as any
)) as TxOrderingMiddleware
txFactory = new TxFactory(core.account.System)
testDoc = {
_id: generateId<TestDoc>(),
_class: testDocClass,
space: 'test:space' as Ref<Space>,
modifiedOn: 100,
modifiedBy: core.account.System,
name: 'Test Document',
counter: 0
}
})
it('should broadcast transactions in order by modifiedOn', async () => {
// Create 3 transactions with different modifiedOn times
const tx1 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 1 })
tx1.modifiedOn = 101
const tx2 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 2 })
tx2.modifiedOn = 102
const tx3 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 3 })
tx3.modifiedOn = 103
// Process transactions - they will be processed sequentially
// even if called in parallel
const promises = [
middleware.tx(ctx as any, [tx2]),
middleware.tx(ctx as any, [tx1]),
middleware.tx(ctx as any, [tx3])
]
await Promise.all(promises)
// Verify they were processed (tracker records them during next.tx which is called in order)
expect(tracker.broadcasted.length).toBe(3)
})
it('should handle multiple documents independently', async () => {
const testDoc2: TestDoc = {
_id: generateId<TestDoc>(),
_class: testDocClass,
space: 'test:space' as Ref<Space>,
modifiedOn: 200,
modifiedBy: core.account.System,
name: 'Test Document 2',
counter: 0
}
// Create transactions for doc1
const tx1Doc1 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 1 })
tx1Doc1.modifiedOn = 102
const tx2Doc1 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 2 })
tx2Doc1.modifiedOn = 101
// Create transactions for doc2
const tx1Doc2 = txFactory.createTxUpdateDoc(testDocClass, testDoc2.space, testDoc2._id, { counter: 1 })
tx1Doc2.modifiedOn = 202
const tx2Doc2 = txFactory.createTxUpdateDoc(testDocClass, testDoc2.space, testDoc2._id, { counter: 2 })
tx2Doc2.modifiedOn = 201
// Process all transactions - doc1 and doc2 can be processed in parallel
await Promise.all([middleware.tx(ctx as any, [tx1Doc1, tx2Doc1]), middleware.tx(ctx as any, [tx1Doc2, tx2Doc2])])
// Verify both documents were processed
expect(tracker.broadcasted.length).toBe(4)
})
it('should wait for previous transactions to complete', async () => {
// This test simulates concurrent tx() calls for the same document
const tx1 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 1 })
tx1.modifiedOn = 101
const tx2 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 2 })
tx2.modifiedOn = 102
const tx3 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 3 })
tx3.modifiedOn = 103
// Track the order of execution
const executionOrder: number[] = []
// Create a mock next middleware that tracks execution order
const trackingMiddleware = {
tx: async (ctx: MeasureContext, txes: Tx[]): Promise<TxMiddlewareResult> => {
for (const tx of txes) {
executionOrder.push(tx.modifiedOn)
// Simulate some async work
await new Promise((resolve) => setTimeout(resolve, 10))
}
return {}
},
handleBroadcast: async (ctx: MeasureContext): Promise<void> => {}
}
// Recreate middleware with tracking
const pipelineContext: PipelineContext = {
workspace: { uuid: 'test-workspace' as any, url: 'test', dataId: 'test' as any },
hierarchy: new Hierarchy(),
modelDb: new ModelDb(new Hierarchy()),
branding: null as any,
adapterManager: {} as any,
storageAdapter: {} as any,
contextVars: {},
lastTx: '',
lastHash: '',
broadcastEvent: async (ctx, txes) => {}
}
const testMiddleware = (await TxOrderingMiddleware.create()(
ctx,
pipelineContext,
trackingMiddleware as any
)) as TxOrderingMiddleware
// Start all transactions "simultaneously" (tx2 first, but should wait for tx1)
const promises = [
testMiddleware.tx(ctx as any, [tx2]),
testMiddleware.tx(ctx as any, [tx1]),
testMiddleware.tx(ctx as any, [tx3])
]
await Promise.all(promises)
// Despite being called in order [tx2, tx1, tx3], they should execute sequentially
// The order depends on which promise was awaited first, but all should complete
expect(executionOrder.length).toBe(3)
expect(new Set(executionOrder)).toEqual(new Set([101, 102, 103]))
})
it('should handle rapid sequential transactions', async () => {
// Create 10 transactions for the same document
const txes: Tx[] = []
for (let i = 1; i <= 10; i++) {
const tx = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: i })
tx.modifiedOn = 100 + i
txes.push(tx)
}
// Process all at once - they should be handled sequentially
await middleware.tx(ctx as any, txes)
// Should have processed all transactions
expect(tracker.broadcasted.length).toBe(10)
})
it('should track statistics correctly', async () => {
const tx1 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 1 })
tx1.modifiedOn = 101
const tx2 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 2 })
tx2.modifiedOn = 102
// Process transactions
await middleware.tx(ctx as any, [tx1, tx2])
// Verify transactions were processed
expect(tracker.broadcasted.length).toBe(2)
})
it('should handle already ordered transactions efficiently', async () => {
// Create transactions already in order
const tx1 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 1 })
tx1.modifiedOn = 101
const tx2 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 2 })
tx2.modifiedOn = 102
const tx3 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 3 })
tx3.modifiedOn = 103
// Process in order
await middleware.tx(ctx as any, [tx1, tx2, tx3])
// Verify all were processed
expect(tracker.broadcasted.length).toBe(3)
})
it('should release waits on exceptions', async () => {
const tx1 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 1 })
tx1.modifiedOn = 101
const tx2 = txFactory.createTxUpdateDoc(testDocClass, testDoc.space, testDoc._id, { counter: 2 })
tx2.modifiedOn = 102
// Create middleware that throws on first transaction
let shouldThrow = true
const throwingMiddleware = {
tx: async (ctx: MeasureContext, txes: Tx[]): Promise<TxMiddlewareResult> => {
if (shouldThrow) {
shouldThrow = false
throw new Error('Test error')
}
return {}
},
handleBroadcast: async (ctx: MeasureContext): Promise<void> => {}
}
const pipelineContext: PipelineContext = {
workspace: { uuid: 'test-workspace' as any, url: 'test', dataId: 'test' as any },
hierarchy: new Hierarchy(),
modelDb: new ModelDb(new Hierarchy()),
branding: null as any,
adapterManager: {} as any,
storageAdapter: {} as any,
contextVars: {},
lastTx: '',
lastHash: '',
broadcastEvent: async (ctx, txes) => {}
}
const testMiddleware = (await TxOrderingMiddleware.create()(
ctx,
pipelineContext,
throwingMiddleware as any
)) as TxOrderingMiddleware
// First transaction should throw
await expect(testMiddleware.tx(ctx as any, [tx1])).rejects.toThrow('Test error')
// Second transaction should not hang - it should be able to proceed
await expect(testMiddleware.tx(ctx as any, [tx2])).resolves.toBeDefined()
})
})
/**
* Integration test with mocked pipeline context
*/
describe('TxOrderingMiddleware Integration', () => {
it('should work with provideTx flow', async () => {
const ctx = new MeasureMetricsContext('test', {})
ctx.contextData = { broadcast: { txes: [], queue: [], sessions: {} } } as any
const hierarchy = new Hierarchy()
const model = new ModelDb(hierarchy)
const processedOrder: number[] = []
// Create middleware with next middleware mock
const nextMiddleware = {
tx: async (ctx: MeasureContext, txes: Tx[]): Promise<TxMiddlewareResult> => {
// Track processing order
for (const tx of txes) {
processedOrder.push(tx.modifiedOn)
}
return {}
},
handleBroadcast: async (ctx: MeasureContext): Promise<void> => {}
}
const pipelineContext: PipelineContext = {
workspace: { uuid: 'test-workspace' as any, url: 'test', dataId: 'test' as any },
hierarchy,
modelDb: model,
branding: null as any,
adapterManager: {} as any,
storageAdapter: {} as any,
contextVars: {},
lastTx: '',
lastHash: '',
broadcastEvent: async (ctx, txes) => {}
}
const middleware = (await TxOrderingMiddleware.create()(
ctx,
pipelineContext,
nextMiddleware as any
)) as TxOrderingMiddleware
const txFactory = new TxFactory(core.account.System)
const docId = generateId()
const tx1 = txFactory.createTxUpdateDoc('test:class' as any, 'test:space' as any, docId as any, {} as any)
tx1.modifiedOn = 102
const tx2 = txFactory.createTxUpdateDoc('test:class' as any, 'test:space' as any, docId as any, {} as any)
tx2.modifiedOn = 101
// Process in parallel - they should be serialized
await Promise.all([middleware.tx(ctx as any, [tx1]), middleware.tx(ctx as any, [tx2])])
// Verify both transactions were processed
expect(processedOrder.length).toBe(2)
expect(new Set(processedOrder)).toEqual(new Set([101, 102]))
})
})