.do

API Reference

Complete API reference for Services-as-Software types, methods, and interfaces

Complete reference documentation for the Services-as-Software API, including core types, methods, properties, and usage patterns.

Overview

The Services-as-Software API provides a semantic interface for defining, discovering, ordering, and executing services. Built on the $.Subject.predicate.Object pattern, it offers an intuitive, type-safe way to work with services programmatically.

Quick Reference

Core Types

TypePurposeKey MethodsDocumentation
ServiceDefine service specifications$.Service.create(), $.Service.find()Service definitions, capabilities, pricing
ServiceOfferingPublish service offerings$.ServiceOffering.create(), $.ServiceOffering.list()Marketplace listings, pricing tiers
ServiceOrderPlace and manage orders$.ServiceOrder.create(), $.ServiceOrder.track()Order lifecycle, fulfillment
ServiceExecutionExecute service logic$.ServiceExecution.start(), $.ServiceExecution.monitor()Execution context, results

Type System

CategoryTypesDocumentation
Service TypesServiceType, ServiceCategory, ServiceCapabilityService classification and discovery
Pricing TypesPricingModel, PricingTier, BillingPeriodPricing and billing structures
Execution TypesExecutionStatus, ExecutionResult, ExecutionMetricsRuntime execution state

Getting Started with the API

Basic Service Creation

Create a new service with complete specifications:

import $ from 'sdk.do'

const service = await $.Service.create({
  // Basic info
  name: 'Document Summarizer',
  description: 'AI-powered document summarization service',
  type: $.ServiceType.ContentGeneration,

  // Input schema
  input: {
    required: ['document', 'style'],
    schema: {
      document: {
        type: 'file',
        formats: ['pdf', 'docx', 'txt'],
        maxSize: '10MB',
      },
      style: {
        type: 'enum',
        values: ['concise', 'detailed', 'bullet-points'],
      },
    },
  },

  // Output schema
  output: {
    schema: {
      summary: { type: 'string' },
      keyPoints: { type: 'array', items: 'string' },
      wordCount: { type: 'number' },
    },
  },

  // Pricing
  pricing: {
    model: 'per-use',
    rate: 0.05,
    unit: 'document',
  },
})

Service Discovery

Find services by type, capability, or tags:

// Find by type
const contentServices = await $.Service.find({
  where: {
    type: $.ServiceType.ContentGeneration,
  },
})

// Find by capability
const aiServices = await $.Service.find({
  where: {
    capabilities: { contains: 'ai-generation' },
  },
})

// Search by tags
const marketingServices = await $.Service.search({
  tags: ['marketing', 'automation'],
  sortBy: 'popularity',
})

Order and Execute

Place an order and execute a service:

// Create order
const order = await $.ServiceOrder.create({
  serviceId: service.id,
  customerId: $.User.current().id,
  inputs: {
    document: uploadedFile,
    style: 'concise',
  },
})

// Execute service
const execution = await $.ServiceExecution.start({
  orderId: order.id,
})

// Wait for completion
const result = await execution.waitForCompletion({
  timeout: 60000, // 60 seconds
})

console.log('Summary:', result.outputs.summary)
console.log('Key Points:', result.outputs.keyPoints)

Core API Types

Service

The foundational type representing a service definition.

Primary Use Cases:

  • Define new services
  • Specify input/output schemas
  • Set pricing and billing rules
  • Configure capabilities and constraints

Quick Example:

const service = await $.Service.create({
  name: 'Email Validator',
  type: $.ServiceType.DataValidation,
  pricing: { model: 'per-use', rate: 0.001 },
})

Full Service API Documentation →


ServiceOffering

Represents a published service offering in the marketplace.

Primary Use Cases:

  • Publish services to marketplace
  • Manage pricing tiers and plans
  • Control service availability
  • Track offering performance

Quick Example:

const offering = await $.ServiceOffering.create({
  serviceId: service.id,
  status: 'active',
  tiers: [
    { name: 'basic', price: 29, features: ['feature-1'] },
    { name: 'pro', price: 99, features: ['feature-1', 'feature-2'] },
  ],
})

Full ServiceOffering API Documentation →


ServiceOrder

Represents a customer order for a service.

Primary Use Cases:

  • Place service orders
  • Track order status
  • Manage order fulfillment
  • Handle payments and billing

Quick Example:

const order = await $.ServiceOrder.create({
  offeringId: offering.id,
  tier: 'pro',
  inputs: {
    /* service inputs */
  },
})

// Track order
const status = await order.getStatus()
console.log('Order status:', status.state)

Full ServiceOrder API Documentation →


ServiceExecution

Represents the runtime execution of a service.

Primary Use Cases:

  • Execute service logic
  • Monitor execution progress
  • Handle execution results
  • Manage execution lifecycle

Quick Example:

const execution = await $.ServiceExecution.start({
  orderId: order.id,
  context: {
    /* execution context */
  },
})

// Monitor progress
execution.on('progress', (event) => {
  console.log(`Progress: ${event.percentComplete}%`)
})

// Get result
const result = await execution.waitForCompletion()

Full ServiceExecution API Documentation →

Type System Reference

Service Types

Classification system for services:

// Service type enum
enum ServiceType {
  ContentGeneration = 'content-generation',
  DataAnalysis = 'data-analysis',
  Automation = 'automation',
  Integration = 'integration',
  // ... more types
}

// Usage
const service = await $.Service.create({
  type: $.ServiceType.ContentGeneration,
})

Available Service Types:

  • Content Generation
  • Data Analysis
  • Data Transformation
  • Data Validation
  • Workflow Automation
  • Integration
  • AI/ML Services
  • Business Process Automation

Complete Service Types Reference →


Pricing Types

Pricing and billing structures:

// Pricing models
interface PricingModel {
  model: 'per-use' | 'subscription' | 'tiered' | 'hybrid'
  rate?: number
  currency: string
  // ... more options
}

// Tiered pricing
interface PricingTier {
  from: number
  to: number | null
  rate: number
}

// Usage
const service = await $.Service.create({
  pricing: {
    model: 'tiered',
    currency: 'USD',
    tiers: [
      { from: 0, to: 1000, rate: 0.01 },
      { from: 1000, to: null, rate: 0.008 },
    ],
  },
})

Pricing Model Types:

  • Per-Use: Charge per execution
  • Subscription: Recurring fees
  • Tiered: Volume-based pricing
  • Hybrid: Subscription + usage
  • Credit-Based: Pre-purchased credits

Complete Pricing Types Reference →


Execution Types

Runtime execution state and results:

// Execution status
enum ExecutionStatus {
  Pending = 'pending',
  Running = 'running',
  Completed = 'completed',
  Failed = 'failed',
  Cancelled = 'cancelled',
}

// Execution result
interface ExecutionResult {
  status: ExecutionStatus
  outputs?: Record<string, any>
  error?: string
  metrics: ExecutionMetrics
}

// Usage
const execution = await $.ServiceExecution.start({ orderId })
const result = await execution.waitForCompletion()

if (result.status === $.ExecutionStatus.Completed) {
  console.log('Outputs:', result.outputs)
}

Execution States:

  • Pending: Queued for execution
  • Running: Currently executing
  • Completed: Successfully finished
  • Failed: Execution error
  • Cancelled: User cancelled

Complete Execution Types Reference →

Common API Patterns

Pattern: Service Lifecycle

Complete service lifecycle from definition to execution:

// 1. Define service
const service = await $.Service.create({
  name: 'Content Translator',
  type: $.ServiceType.ContentGeneration,
  input: {
    /* schema */
  },
  pricing: {
    /* pricing */
  },
})

// 2. Create offering
const offering = await $.ServiceOffering.create({
  serviceId: service.id,
  status: 'active',
})

// 3. Customer places order
const order = await $.ServiceOrder.create({
  offeringId: offering.id,
  inputs: { text: 'Hello', targetLanguage: 'es' },
})

// 4. Execute service
const execution = await $.ServiceExecution.start({
  orderId: order.id,
})

// 5. Deliver results
const result = await execution.waitForCompletion()
await order.markDelivered({ outputs: result.outputs })

Pattern: Service Discovery

Find and filter services:

// Find by multiple criteria
const services = await $.Service.find({
  where: {
    type: $.ServiceType.DataAnalysis,
    status: 'active',
    pricing: {
      model: 'per-use',
      rate: { lte: 0.1 },
    },
  },
  orderBy: { popularity: 'desc' },
  limit: 10,
})

// Search with full-text
const searchResults = await $.Service.search({
  query: 'email validation',
  filters: {
    category: 'productivity',
    priceRange: { min: 0, max: 50 },
  },
})

Pattern: Event-Driven Execution

React to service events:

import { on, send } from 'sdk.do'

// Listen for order creation
on($.ServiceOrder.created, async (order) => {
  // Start execution automatically
  const execution = await $.ServiceExecution.start({
    orderId: order.id,
  })
})

// Listen for execution completion
on($.ServiceExecution.completed, async (execution) => {
  // Deliver results
  await send($.ServiceOrder.deliver, {
    orderId: execution.orderId,
    outputs: execution.result.outputs,
  })

  // Charge customer
  await send($.Payment.charge, {
    customerId: execution.order.customerId,
    amount: execution.cost,
  })
})

// Listen for execution failures
on($.ServiceExecution.failed, async (execution) => {
  // Notify customer
  await send($.Notification.send, {
    userId: execution.order.customerId,
    type: 'service-failed',
    data: { error: execution.error },
  })
})

Pattern: Service Composition

Combine multiple services:

// Chain services
const workflow = await $.Workflow.create({
  name: 'Content Pipeline',
  steps: [
    {
      service: $.Service.find({ name: 'Content Generator' }),
      inputs: { topic: '${workflow.inputs.topic}' },
    },
    {
      service: $.Service.find({ name: 'Grammar Checker' }),
      inputs: { text: '${steps[0].outputs.content}' },
    },
    {
      service: $.Service.find({ name: 'SEO Optimizer' }),
      inputs: {
        text: '${steps[1].outputs.correctedText}',
        keywords: '${workflow.inputs.keywords}',
      },
    },
  ],
})

// Execute workflow
const result = await workflow.execute({
  inputs: {
    topic: 'AI in Healthcare',
    keywords: ['AI', 'healthcare', 'automation'],
  },
})

Advanced Usage

Custom Service Types

Define custom service types:

// Extend ServiceType
const CustomServiceType = {
  ...$.ServiceType,
  CustomAnalysis: 'custom-analysis',
  SpecializedProcessing: 'specialized-processing',
}

// Use custom type
const service = await $.Service.create({
  type: CustomServiceType.CustomAnalysis,
  // ... rest of service definition
})

Dynamic Pricing

Implement dynamic pricing logic:

const service = await $.Service.create({
  name: 'Dynamic Pricing Service',
  pricing: {
    model: 'dynamic',
    calculator: async (inputs) => {
      const baseRate = 0.1
      const complexity = analyzeComplexity(inputs)
      const volumeDiscount = getVolumeDiscount(inputs.quantity)

      return {
        amount: baseRate * complexity * (1 - volumeDiscount),
        breakdown: {
          base: baseRate,
          complexityMultiplier: complexity,
          discount: volumeDiscount,
        },
      }
    },
  },
})

Execution Monitoring

Monitor and control execution:

const execution = await $.ServiceExecution.start({ orderId })

// Subscribe to events
execution.on('progress', (event) => {
  console.log(`Step ${event.step}: ${event.message}`)
})

execution.on('metric', (metric) => {
  console.log(`${metric.name}: ${metric.value}`)
})

// Set timeout
execution.setTimeout(30000) // 30 seconds

// Cancel if needed
if (shouldCancel) {
  await execution.cancel({ reason: 'User requested' })
}

// Get live metrics
const metrics = await execution.getMetrics()
console.log('CPU usage:', metrics.cpu)
console.log('Memory:', metrics.memory)

Error Handling

Common Error Types

import { ServiceError } from 'sdk.do'

try {
  const result = await $.ServiceExecution.start({ orderId })
} catch (error) {
  if (error instanceof ServiceError.ValidationError) {
    console.error('Invalid inputs:', error.validationErrors)
  } else if (error instanceof ServiceError.ExecutionError) {
    console.error('Execution failed:', error.message)
  } else if (error instanceof ServiceError.PaymentError) {
    console.error('Payment failed:', error.reason)
  } else {
    console.error('Unknown error:', error)
  }
}

Retry Logic

import { retry } from 'sdk.do'

const result = await retry(async () => $.ServiceExecution.start({ orderId }), {
  attempts: 3,
  delay: 1000,
  backoff: 'exponential',
  onRetry: (attempt, error) => {
    console.log(`Retry ${attempt}: ${error.message}`)
  },
})

Best Practices

1. Type Safety

Use TypeScript for type safety:

import type { Service, ServiceInput, ServiceOutput } from 'sdk.do'

interface TranslatorInput extends ServiceInput {
  text: string
  targetLanguage: string
}

interface TranslatorOutput extends ServiceOutput {
  translatedText: string
  sourceLanguage: string
  confidence: number
}

const service: Service<TranslatorInput, TranslatorOutput> = await $.Service.create({
  name: 'Translator',
  // ... type-safe definition
})

2. Input Validation

Always validate inputs:

const service = await $.Service.create({
  name: 'Validator',
  input: {
    schema: {
      email: {
        type: 'string',
        format: 'email',
        required: true,
      },
    },
    validator: async (inputs) => {
      if (!isValidEmail(inputs.email)) {
        throw new Error('Invalid email format')
      }
      return true
    },
  },
})

3. Error Recovery

Implement graceful error handling:

on($.ServiceExecution.failed, async (execution) => {
  // Attempt automatic recovery
  if (execution.retryCount < 3) {
    await execution.retry({
      delay: Math.pow(2, execution.retryCount) * 1000,
    })
  } else {
    // Notify customer of permanent failure
    await send($.Notification.send, {
      userId: execution.order.customerId,
      type: 'service-permanently-failed',
      data: execution.error,
    })
  }
})

4. Performance Optimization

Optimize for performance:

// Use batching
const orders = await $.ServiceOrder.findMany({
  where: { status: 'pending' },
  limit: 100,
})

// Execute in parallel
const executions = await Promise.all(orders.map((order) => $.ServiceExecution.start({ orderId: order.id })))

// Cache frequently accessed data
const cachedService = await cache.get(
  `service:${serviceId}`,
  async () => $.Service.findById(serviceId),
  { ttl: 3600 } // 1 hour
)

API Versioning

Version Compatibility

// Specify API version
import $ from 'sdk.do'

const service = await $.Service.create({
  name: 'Versioned Service',
  version: '2.0.0',
  apiVersion: 'v2',
  // ... service definition
})

// Call specific version
const result = await $.ServiceExecution.start({
  orderId,
  version: '2.0.0', // Use specific version
})

Deprecation Handling

// Mark version as deprecated
await $.Service.update(service.id, {
  version: '1.0.0',
  deprecated: true,
  deprecationDate: new Date('2025-12-31'),
  migrationGuide: 'https://docs.example.com/migration/v1-to-v2',
})

Next Steps

Explore detailed API documentation:

Or continue learning: