Skip to content
Open
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
5 changes: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ jobs:
working-directory: ${{ github.workspace }}/barge
run: |
bash -x start_ocean.sh 2>&1 > start_ocean.log &

env:
NODE_VERSION: pr-1638
- name: Install deps & build
run: npm ci && npm run build:metadata
- name: Wait for node to be ready
Expand Down Expand Up @@ -141,6 +142,8 @@ jobs:
working-directory: ${{ github.workspace }}/barge
run: |
bash -x start_ocean.sh 2>&1 > start-node.log &
env:
NODE_VERSION: pr-1638
- name: Install deps & build
run: npm ci && npm run build:metadata

Expand Down
17 changes: 17 additions & 0 deletions src/@types/Services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,9 @@ export interface ServiceJob {
expiresAt: number // Unix ms timestamp
duration: number // requested seconds
exposedPorts: number[]
// Pinned host ports the caller requested, keyed by containerPort (string). Only pinned
// entries appear; auto-allocated ports are absent. Resolved host ports live in `endpoints`.
requestedHostPorts?: Record<string, number>
endpoints: ServiceJobEndpoint[]
resources: any[] // ComputeResourceRequestWithPrice[] on the node
payment: ServiceJobPayment // initial start payment
Expand Down Expand Up @@ -228,6 +231,15 @@ export interface ServicePayment {
// so a plaintext secret can never be forwarded unencrypted.
export type ServiceUserData = Record<string, unknown>

// A port the service exposes. `hostPort` omitted ⇒ the node auto-allocates a host port from
// its hostPortRange (legacy behaviour). `hostPort` set ⇒ pin that specific host port; the node
// rejects the command if it is outside hostPortRange or not free. Mirrors ocean-node's
// ServicePortRequest.
export interface ServicePortRequest {
containerPort: number // 1..65535
hostPort?: number // 1..65535; omitted = auto-allocate
}

// The container specification shared by serviceStart and serviceRestart. Every field is
// optional here; the consuming type decides which are required (serviceStart re-declares
// `image` as mandatory). `userData` is always ECIES-encrypted to the node before sending.
Expand All @@ -244,6 +256,11 @@ export interface ServiceContainerSpec {
// cap and 400s if oversized). Unlike userData it is NOT encrypted. On serviceRestart it
// replaces the stored metadata when supplied and does NOT force RESPEC mode.
metadata?: ComputeJobMetadata
// Exposed ports, optionally with a PINNED host port per entry (`hostPort` omitted =
// auto-allocate). Independent of the RESPEC rule, like `metadata`. On serviceStart `ports`
// supersedes the legacy `exposedPorts` when both are sent; on serviceRestart the node reads
// ONLY `ports` (never `exposedPorts`) and an omitted `ports` keeps the service's current ports.
ports?: ServicePortRequest[]
}

// Optional container-spec overrides for serviceRestart. The node treats the restart
Expand Down
8 changes: 6 additions & 2 deletions src/services/providers/HttpProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2218,7 +2218,8 @@ export class HttpProvider {
userData,
dockerCmd,
dockerEntrypoint,
metadata
metadata,
ports
} = params ?? {}
const route = this.baseUrl(nodeUri) + '/api/services/serviceRestart'
const authPayload = await this.getSignedCommandParams(
Expand Down Expand Up @@ -2247,7 +2248,10 @@ export class HttpProvider {
...(additionalDockerFiles !== undefined ? { additionalDockerFiles } : {}),
...(dockerCmd !== undefined ? { dockerCmd } : {}),
...(dockerEntrypoint !== undefined ? { dockerEntrypoint } : {}),
...(metadata !== undefined ? { metadata } : {})
...(metadata !== undefined ? { metadata } : {}),
// Port change — independent of REUSE/RESPEC; omitted ⇒ keep current ports. The node
// reads only `ports` on restart (never the legacy `exposedPorts`).
...(ports !== undefined ? { ports } : {})
}),
signal
})
Expand Down
8 changes: 6 additions & 2 deletions src/services/providers/P2pProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4054,7 +4054,8 @@ export class P2pProvider {
userData,
dockerCmd,
dockerEntrypoint,
metadata
metadata,
ports
} = params ?? {}
const authPayload = await this.getSignedCommandParams(
nodeUri,
Expand All @@ -4078,7 +4079,10 @@ export class P2pProvider {
...(additionalDockerFiles !== undefined ? { additionalDockerFiles } : {}),
...(dockerCmd !== undefined ? { dockerCmd } : {}),
...(dockerEntrypoint !== undefined ? { dockerEntrypoint } : {}),
...(metadata !== undefined ? { metadata } : {})
...(metadata !== undefined ? { metadata } : {}),
// Port change — independent of REUSE/RESPEC; omitted ⇒ keep current ports. The node
// reads only `ports` on restart (never the legacy `exposedPorts`).
...(ports !== undefined ? { ports } : {})
},
signerOrAuthToken,
signal
Expand Down
45 changes: 45 additions & 0 deletions test/integration/Services.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,51 @@ describe('Service on Demand flow tests', () => {
expect(after?.metadata).to.deep.equal(restartMetadata)
})

it('restart with an out-of-range pinned `ports` host port is rejected, service stays Running', async function () {
if (skipLifecycle || !serviceId) this.skip()
this.timeout(60000)
const before = (
await ProviderInstance.getServiceStatus(providerUrl, consumerAccount, serviceId)
).find((j) => j.serviceId === serviceId)
assert(before?.endpoints?.[0], 'expected the running service to have an endpoint')
const containerPort = before.endpoints[0].containerPort
const oldContainerId = before.containerId

// DISCRIMINATING check that `ports` actually reaches the node: host port 1 is below the
// node's hostPortRange floor (schema enforces >=1024), so the node MUST reject the restart.
// If the SDK silently dropped `ports`, this would instead be a no-op REUSE restart that
// succeeds — so a rejection proves the field was forwarded. The restart is rejected up front
// (before teardown), so the service keeps running on its original container/port untouched.
let restartError: Error | undefined
try {
await ProviderInstance.serviceRestart(
providerUrl,
consumerAccount,
serviceId,
{ ports: [{ containerPort, hostPort: 1 }] },
opSignal()
)
} catch (e) {
restartError = e as Error
}
// The restart MUST fail with the node's host-port range rejection specifically. Asserting on
// the error message (not merely that *something* threw) means a nonce-retrieval or
// request-delivery failure — which throws a different message — fails this test instead of
// masquerading as the expected port-range rejection.
assert(restartError, 'node should reject an out-of-range pinned host port')
expect(
restartError.message,
`expected a host-port range rejection, got: ${restartError?.message}`
).to.match(/host port|range/i)

const after = (
await ProviderInstance.getServiceStatus(providerUrl, consumerAccount, serviceId)
).find((j) => j.serviceId === serviceId)
expect(after?.status).to.equal(ServiceStatusNumber.Running)
expect(after?.containerId).to.equal(oldContainerId) // untouched: no teardown happened
expect(after?.endpoints[0].hostPort).to.equal(hostPort)
})

it('stops the service → Stopped', async function () {
if (skipLifecycle || !serviceId) this.skip()
this.timeout(120000)
Expand Down
82 changes: 82 additions & 0 deletions test/unit/Services.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,86 @@ describe('Service on Demand client wiring', () => {
)
expect(decrypted).to.deep.equal(userData)
})

describe('ports forwarding (serviceStart / serviceRestart request body)', () => {
// An "agent signature" token short-circuits getSignedCommandParams with NO network call,
// and omitting userData skips the node-public-key fetch — so stubbing global.fetch alone
// captures the exact request body the provider builds, offline.
const NODE = 'http://localhost:8000'
const token = {
consumerAddress: '0x0000000000000000000000000000000000000aBc',
nonce: '1',
signature: '0xsig'
} as any
let origFetch: typeof globalThis.fetch
let captured: any

beforeEach(() => {
origFetch = globalThis.fetch
captured = undefined
globalThis.fetch = (async (_url: string, init: any) => {
captured = JSON.parse(init.body)
return {
ok: true,
json: async () => [{ serviceId: 'svc-1' }],
text: async () => ''
} as any
}) as any
})
afterEach(() => {
globalThis.fetch = origFetch
})

it('serviceStart forwards `ports` (and still forwards legacy `exposedPorts`)', async () => {
// No `as any`: a well-typed ServiceStartParams, so this also pins that `ports` is a valid
// field on the public type (tsx does not type-check, but `npm run build` does).
await ProviderInstance.serviceStart(NODE, token, {
environment: 'env-1',
image: 'nginx',
duration: 3600,
payment: { chainId: 8996, token: '0xtoken' },
exposedPorts: [9090],
ports: [{ containerPort: 8080, hostPort: 30010 }, { containerPort: 8081 }]
})
expect(captured.ports).to.deep.equal([
{ containerPort: 8080, hostPort: 30010 },
{ containerPort: 8081 }
])
expect(captured.exposedPorts).to.deep.equal([9090]) // legacy field still passes through
})

it('serviceRestart forwards `ports` when supplied (alongside other fields)', async () => {
await ProviderInstance.serviceRestart(NODE, token, 'svc-1', {
ports: [{ containerPort: 8080, hostPort: 30011 }],
metadata: { run: 'v2' },
dockerCmd: ['nginx', '-g', 'daemon off;']
})
expect(captured.ports).to.deep.equal([{ containerPort: 8080, hostPort: 30011 }])
// the new spread must not disturb its neighbours
expect(captured.metadata).to.deep.equal({ run: 'v2' })
expect(captured.dockerCmd).to.deep.equal(['nginx', '-g', 'daemon off;'])
})

it('serviceRestart forwards an explicit empty `ports: []` (replace-with-none, not omit)', async () => {
// Contract: `[] !== undefined`, so it IS sent — the node treats it as "no ports", distinct
// from omitting `ports` (keep current). Guards against a truthiness-based simplification.
await ProviderInstance.serviceRestart(NODE, token, 'svc-1', { ports: [] })
expect(captured.ports).to.deep.equal([])
})

it('serviceRestart omits `ports` when not supplied (REUSE keeps current ports)', async () => {
await ProviderInstance.serviceRestart(NODE, token, 'svc-1', {})
expect(captured).to.not.have.property('ports')
})

it('serviceRestart never forwards the legacy `exposedPorts` (node ignores it on restart)', async () => {
// `as any`: `exposedPorts` is intentionally OFF-type for ServiceRestartParams — the SDK
// must drop it even if a caller forces it through.
await ProviderInstance.serviceRestart(NODE, token, 'svc-1', {
exposedPorts: [9090]
} as any)
expect(captured).to.not.have.property('exposedPorts')
expect(captured).to.not.have.property('ports')
})
})
})